Skip to main content

spoolframe_protocol/
pairing.rs

1//! Pairing a device with a portable identity (P7-03, ARCHITECTURE §47):
2//! the link a device shows as a QR code, and the frames the identity's
3//! phone and the device then exchange over a direct Iroh connection on
4//! [`PAIR_ALPN`]. No Spoolframe server takes part.
5//!
6//! A TV has no camera, so the QR code goes one way, device to phone:
7//!
8//! `spoolframe://pair?e=<endpoint id>&c=<code>&n=<name>&a=<ip:port>&r=<relay url>`
9//!
10//! - `e`, the device's `EndpointId` as 64 hex digits, and `c`, the
11//!   one-time [`PairingCode`] as 43 base64url characters (no padding),
12//!   are required. The phone dials `e` and nothing else, and Iroh's TLS
13//!   proves the key, so the phone pairs with the device that showed the
14//!   code or with nothing.
15//! - `n` is the device's name, for "Pairing with …" while the phone
16//!   dials; cut to [`MAX_NAME`] characters.
17//! - `a` (repeated, at most [`MAX_ADDRS`]) and `r` (repeated, at most
18//!   [`MAX_RELAYS`]) are where the device may be reached. Hints: the key
19//!   is still proved whatever path is taken.
20//!
21//! Values are percent-encoded as in an invite link ([`crate::invite`]).
22//! A parameter this build does not know is ignored; a second `e` or `c`
23//! is not (the link is refused), nor is one that cannot be read.
24//!
25//! Then, on one bidirectional stream, each frame a [`crate::codec`] frame
26//! (big-endian `u32` length, CBOR) of at most [`MAX_FRAME`] bytes:
27//!
28//! 1. phone → device: [`PhoneFrame::Hello`], the code and the identity
29//!    the phone wants this device to act as;
30//! 2. device → phone: [`DeviceFrame::Key`], the device's key for that
31//!    identity and its name, or [`DeviceFrame::Refused`];
32//! 3. phone → device: [`PhoneFrame::Credential`], the root's credential
33//!    for that key, the identity's newest state and the servers it signs
34//!    in to (P7-06), or [`PhoneFrame::Declined`];
35//! 4. device → phone: [`DeviceFrame::Done`], or [`DeviceFrame::Refused`].
36
37use std::fmt;
38use std::net::SocketAddr;
39
40use base64::Engine;
41use base64::engine::general_purpose::URL_SAFE_NO_PAD;
42use serde::{Deserialize, Serialize};
43
44use crate::invite::{decode, encode, is_relay_url};
45use crate::portable::{
46    DevicePublicKey, PortableIdentityState, PortableUserId, UserDeviceCredential,
47};
48
49/// The ALPN of pairing, version 1. A device accepts it only while it
50/// shows a pairing code; at any other time a connection on it fails its
51/// handshake.
52pub const PAIR_ALPN: &[u8] = b"spoolframe/pair/1";
53
54/// Bytes in a [`PairingCode`]: 256 bits, out of reach of guessing within
55/// its five minutes whatever the rate.
56pub const CODE_LEN: usize = 32;
57
58/// How long a code is good for, from when the device shows it.
59pub const CODE_TTL_SECS: u64 = 5 * 60;
60
61/// The longest link read, in bytes. A link this build writes fits with
62/// every hint at its limit, the name in characters of three bytes each;
63/// a usual one (a LAN address or two, a short name) is under 250, a QR
64/// code of version 10 or so.
65pub const MAX_LINK: usize = 1024;
66
67/// The most `a` hints a link is written or read with.
68pub const MAX_ADDRS: usize = 8;
69
70/// The most `r` hints a link is written or read with.
71pub const MAX_RELAYS: usize = 2;
72
73/// The most characters of the device's name a link carries.
74pub const MAX_NAME: usize = 32;
75
76/// The largest pairing frame either side reads: room for an identity
77/// state at its limit of revoked keys, 1024 of about 90 bytes each.
78pub const MAX_FRAME: u32 = 256 << 10;
79
80const LINK_PREFIX: &str = "spoolframe://pair?";
81
82/// A one-time pairing code: 32 random bytes the device made, shown only in
83/// its QR code. Compared in constant time; [`fmt::Debug`] does not show
84/// it.
85#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
86#[serde(transparent)]
87pub struct PairingCode(#[serde(with = "serde_bytes")] [u8; CODE_LEN]);
88
89impl PairingCode {
90    pub fn from_bytes(bytes: [u8; CODE_LEN]) -> Self {
91        Self(bytes)
92    }
93
94    pub fn as_bytes(&self) -> &[u8; CODE_LEN] {
95        &self.0
96    }
97
98    /// Whether `other` is this code, in time that does not depend on
99    /// where they differ: every byte is looked at, whatever the first.
100    pub fn matches(&self, other: &PairingCode) -> bool {
101        let diff = self
102            .0
103            .iter()
104            .zip(other.0.iter())
105            .fold(0u8, |acc, (a, b)| acc | (a ^ b));
106        std::hint::black_box(diff) == 0
107    }
108
109    /// The code as the link writes it: base64url, no padding.
110    pub fn to_text(&self) -> String {
111        URL_SAFE_NO_PAD.encode(self.0)
112    }
113
114    /// The code `text` writes, as [`Self::to_text`] gives it; `None` if
115    /// it is not one.
116    pub fn from_text(text: &str) -> Option<Self> {
117        if text.len() != 43 {
118            return None;
119        }
120        let bytes = URL_SAFE_NO_PAD.decode(text).ok()?;
121        Some(Self(bytes.try_into().ok()?))
122    }
123}
124
125impl fmt::Debug for PairingCode {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str("PairingCode(<redacted>)")
128    }
129}
130
131/// What a pairing link holds.
132#[derive(Clone, PartialEq, Eq)]
133pub struct PairingLink {
134    /// The device's `EndpointId`.
135    pub endpoint: [u8; 32],
136    pub code: PairingCode,
137    /// What the device calls itself.
138    pub name: String,
139    /// Addresses it may be reached at.
140    pub addrs: Vec<SocketAddr>,
141    /// The URLs of relays it may be reached through.
142    pub relays: Vec<String>,
143}
144
145impl fmt::Debug for PairingLink {
146    // The code pairs: keep it out of logs.
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.debug_struct("PairingLink")
149            .field("endpoint", &hex(&self.endpoint))
150            .field("name", &self.name)
151            .field("addrs", &self.addrs)
152            .field("relays", &self.relays)
153            .finish_non_exhaustive()
154    }
155}
156
157impl PairingLink {
158    /// The link: what the QR code carries. The name is cut to
159    /// [`MAX_NAME`] characters, the hints to their limits, so what is
160    /// written reads back the same.
161    pub fn link(&self) -> String {
162        let mut link = format!(
163            "{LINK_PREFIX}e={}&c={}",
164            hex(&self.endpoint),
165            self.code.to_text()
166        );
167        let mut add = |key: &str, value: &str| {
168            link.push('&');
169            link.push_str(key);
170            link.push('=');
171            link.push_str(&encode(value));
172        };
173        add("n", &cut(&self.name));
174        for addr in self.addrs.iter().take(MAX_ADDRS) {
175            add("a", &addr.to_string());
176        }
177        for relay in self.relays.iter().take(MAX_RELAYS) {
178            add("r", relay);
179        }
180        link
181    }
182}
183
184/// Why a text is not a pairing link.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
186pub enum LinkError {
187    #[error("not a Spoolframe pairing code")]
188    NotALink,
189    #[error("the pairing code is longer than any device shows")]
190    TooLong,
191    #[error("the pairing code is damaged: {0}")]
192    Damaged(&'static str),
193}
194
195/// The pairing link `text` holds.
196pub fn parse_link(text: &str) -> Result<PairingLink, LinkError> {
197    let text = text.trim();
198    if text.len() > MAX_LINK {
199        return Err(LinkError::TooLong);
200    }
201    let query = text.strip_prefix(LINK_PREFIX).ok_or(LinkError::NotALink)?;
202    let mut endpoint = None;
203    let mut code = None;
204    let mut name = String::new();
205    let mut addrs = Vec::new();
206    let mut relays = Vec::new();
207    for pair in query.split('&').filter(|p| !p.is_empty()) {
208        let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
209        match key {
210            "e" => {
211                if endpoint.is_some() {
212                    return Err(LinkError::Damaged("two endpoints"));
213                }
214                endpoint = Some(unhex(raw).ok_or(LinkError::Damaged("not an endpoint id"))?);
215            }
216            "c" => {
217                if code.is_some() {
218                    return Err(LinkError::Damaged("two codes"));
219                }
220                code = Some(PairingCode::from_text(raw).ok_or(LinkError::Damaged("not a code"))?);
221            }
222            "n" => name = cut(&decode(raw).ok_or(LinkError::Damaged("the name"))?),
223            "a" if addrs.len() < MAX_ADDRS => {
224                if let Some(addr) = decode(raw).and_then(|a| a.parse().ok()) {
225                    addrs.push(addr);
226                }
227            }
228            "r" if relays.len() < MAX_RELAYS => {
229                if let Some(relay) = decode(raw).filter(|r| is_relay_url(r)) {
230                    relays.push(relay);
231                }
232            }
233            // A parameter a newer device added, or a hint past the limit.
234            _ => {}
235        }
236    }
237    Ok(PairingLink {
238        endpoint: endpoint.ok_or(LinkError::Damaged("no endpoint id"))?,
239        code: code.ok_or(LinkError::Damaged("no code"))?,
240        name,
241        addrs,
242        relays,
243    })
244}
245
246/// What the phone sends.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(tag = "type", rename_all = "snake_case")]
249pub enum PhoneFrame {
250    /// The code from the QR code, and the identity the device is to act
251    /// as. First, and only once.
252    Hello {
253        code: PairingCode,
254        identity: PortableUserId,
255    },
256    /// The root's credential for the key [`DeviceFrame::Key`] gave, the
257    /// identity's newest state if the phone has one, and the servers the
258    /// identity signs in to (P7-06), for the device to save and sign in
259    /// to.
260    Credential {
261        credential: Box<UserDeviceCredential>,
262        state: Option<Box<PortableIdentityState>>,
263        servers: Vec<PairedServer>,
264    },
265    /// The person on the phone said no.
266    Declined,
267}
268
269/// The most servers a [`PhoneFrame::Credential`] carries; a device reads
270/// no more.
271pub const MAX_PAIRED_SERVERS: usize = 16;
272
273/// A server the paired identity signs in to, as the phone has it saved
274/// (P7-06): enough for the device to pin and reach it. The phone vouches
275/// for it as the invite that brought it there did; the device dials the
276/// key and nothing else, and Iroh proves it.
277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct PairedServer {
279    /// Its `EndpointId`, 64 hex digits.
280    pub endpoint_id: String,
281    /// The server id pinned with the key (PX-14).
282    pub server_id: String,
283    pub name: String,
284    /// Where it may be reached, at most [`MAX_ADDRS`]: hints. As text,
285    /// as `ServerAddresses` sends them.
286    #[serde(with = "crate::messages::socket_addrs_as_text")]
287    pub addrs: Vec<SocketAddr>,
288    /// Its relays' URLs, at most [`MAX_RELAYS`]: hints.
289    pub relays: Vec<String>,
290}
291
292impl PairedServer {
293    /// This server held to what a device keeps of one: `None` if its key
294    /// is not one; its name cut, and its hints to their limits, a relay
295    /// that is not a relay's URL left out.
296    pub fn within_bounds(mut self) -> Option<Self> {
297        let key = &self.endpoint_id;
298        if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) {
299            return None;
300        }
301        self.endpoint_id = key.to_ascii_lowercase();
302        if self.server_id.is_empty() || self.server_id.len() > 128 {
303            return None;
304        }
305        crate::messages::cut(&mut self.name);
306        self.addrs.truncate(MAX_ADDRS);
307        self.relays.retain(|r| is_relay_url(r));
308        self.relays.truncate(MAX_RELAYS);
309        Some(self)
310    }
311}
312
313/// What the device sends.
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[serde(tag = "type", rename_all = "snake_case")]
316pub enum DeviceFrame {
317    /// The device's key for the identity [`PhoneFrame::Hello`] named, and
318    /// what the device calls itself.
319    Key {
320        device_key: DevicePublicKey,
321        name: String,
322    },
323    /// The credential is installed.
324    Done,
325    /// The pairing is over, refused for `reason`.
326    Refused { reason: Refusal },
327}
328
329/// Why a device refused a pairing. The device's pairing ends with each
330/// of them: it shows a new code to try again.
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
332#[serde(rename_all = "snake_case")]
333pub enum Refusal {
334    /// The device does not take portable sign-ins (its policy is off).
335    #[error("this device does not allow sign-ins from other people's accounts")]
336    NotAllowed,
337    /// The code is not the one shown.
338    #[error("the pairing code does not match")]
339    WrongCode,
340    /// The code was shown more than [`CODE_TTL_SECS`] ago.
341    #[error("the pairing code has expired")]
342    Expired,
343    /// The credential does not hold, is for another identity or key, or
344    /// the state revokes the key.
345    #[error("the device did not accept the credential")]
346    CredentialRefused,
347    /// Something else went wrong on the device: its storage, most likely.
348    #[error("the device could not finish pairing")]
349    Failed,
350}
351
352fn cut(name: &str) -> String {
353    name.chars().take(MAX_NAME).collect()
354}
355
356fn hex(bytes: &[u8; 32]) -> String {
357    bytes.iter().map(|b| format!("{b:02x}")).collect()
358}
359
360fn unhex(text: &str) -> Option<[u8; 32]> {
361    if text.len() != 64 || !text.is_ascii() {
362        return None;
363    }
364    let mut bytes = [0u8; 32];
365    for (i, byte) in bytes.iter_mut().enumerate() {
366        *byte = u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok()?;
367    }
368    Some(bytes)
369}
370
371/// Characters in a [`RelayCode`]: 10 of Crockford's base32, 50 bits.
372/// Typed by a person, so short; guessed only at the rate the server lets
373/// a stranger try, against a code that lives [`RELAY_TTL_SECS`].
374pub const RELAY_CODE_LEN: usize = 10;
375
376/// How long a server holds a relayed pairing (P7-08), from its offer.
377pub const RELAY_TTL_SECS: u64 = 5 * 60;
378
379/// Crockford's base32 alphabet: no I, L, O or U.
380const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
381
382/// The short code a device shows beside its QR code, for a root terminal
383/// with no camera to pair it through a server both reach (P7-08): 10
384/// characters of Crockford's base32, written in two groups of five.
385#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
386#[serde(try_from = "String", into = "String")]
387pub struct RelayCode(String);
388
389impl RelayCode {
390    /// The code `bytes` make: each of the first 10 taken mod 32.
391    pub fn from_random(bytes: [u8; RELAY_CODE_LEN]) -> Self {
392        Self(
393            bytes
394                .iter()
395                .map(|b| CROCKFORD[usize::from(b % 32)] as char)
396                .collect(),
397        )
398    }
399
400    /// The code a person typed: case, spaces and dashes ignored; I and L
401    /// read as 1, O as 0, as Crockford's base32 reads them. `None` if it
402    /// is not 10 such characters.
403    pub fn parse(text: &str) -> Option<Self> {
404        let code: String = text
405            .chars()
406            .filter(|c| !c.is_whitespace() && *c != '-')
407            .map(|c| match c.to_ascii_uppercase() {
408                'I' | 'L' => '1',
409                'O' => '0',
410                c => c,
411            })
412            .collect();
413        (code.len() == RELAY_CODE_LEN && code.bytes().all(|b| CROCKFORD.contains(&b)))
414            .then_some(Self(code))
415    }
416
417    /// As a person reads it: `ABCDE-FGHJK`.
418    pub fn display(&self) -> String {
419        format!("{}-{}", &self.0[..5], &self.0[5..])
420    }
421
422    pub fn as_str(&self) -> &str {
423        &self.0
424    }
425}
426
427impl fmt::Debug for RelayCode {
428    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429        f.write_str("RelayCode(<redacted>)")
430    }
431}
432
433impl TryFrom<String> for RelayCode {
434    type Error = &'static str;
435
436    fn try_from(text: String) -> Result<Self, Self::Error> {
437        Self::parse(&text).ok_or("a relay code is 10 characters of Crockford's base32")
438    }
439}
440
441impl From<RelayCode> for String {
442    fn from(code: RelayCode) -> Self {
443        code.0
444    }
445}
446
447/// A device's pairing request, held on a server under a [`RelayCode`]
448/// for a root terminal to fetch (P7-08): the key the root is to vouch for
449/// and the device's name. Public data: whoever has the code may read it.
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
451pub struct PairingOffer {
452    pub code: RelayCode,
453    /// The device's key for the identity it is to act as.
454    pub device_key: DevicePublicKey,
455    /// Cut to [`MAX_NAME`] characters.
456    pub name: String,
457}
458
459/// The root terminal's answer to a [`PairingOffer`]: what
460/// [`PhoneFrame::Credential`] carries on a direct pairing. The server only
461/// carries it: the device checks the credential names its own key and
462/// shows whose identity it is before it keeps it.
463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
464pub struct PairingAnswer {
465    pub credential: Box<UserDeviceCredential>,
466    pub state: Option<Box<PortableIdentityState>>,
467    /// At most [`MAX_PAIRED_SERVERS`].
468    pub servers: Vec<PairedServer>,
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    fn sample() -> PairingLink {
476        PairingLink {
477            endpoint: [0xab; 32],
478            code: PairingCode::from_bytes([7; 32]),
479            name: "Living room TV & co".into(),
480            addrs: vec![
481                "192.168.1.20:51234".parse().unwrap(),
482                "[fe80::1]:51234".parse().unwrap(),
483            ],
484            relays: vec!["https://relay.example.org/".into()],
485        }
486    }
487
488    #[test]
489    fn a_link_reads_back_as_written() {
490        let link = sample();
491        let text = link.link();
492        assert!(text.starts_with("spoolframe://pair?e=abab"), "{text}");
493        assert_eq!(parse_link(&text).unwrap(), link);
494    }
495
496    #[test]
497    fn a_link_at_every_limit_fits() {
498        let link = PairingLink {
499            name: "名".repeat(200),
500            addrs: (0..20)
501                .map(|n| {
502                    format!("[fd12:3456:789a:1:2:3:4:{n:x}]:65535")
503                        .parse()
504                        .unwrap()
505                })
506                .collect(),
507            relays: (0..5)
508                .map(|n| format!("https://relay-{n}.some-long-domain-name.example.org/"))
509                .collect(),
510            ..sample()
511        };
512        let text = link.link();
513        assert!(text.len() <= MAX_LINK, "{} bytes", text.len());
514        let read = parse_link(&text).unwrap();
515        assert_eq!(read.name.chars().count(), MAX_NAME);
516        assert_eq!(
517            (read.addrs.len(), read.relays.len()),
518            (MAX_ADDRS, MAX_RELAYS)
519        );
520    }
521
522    #[test]
523    fn what_is_not_a_link_is_refused() {
524        let good = sample().link();
525        assert_eq!(parse_link("https://example.org"), Err(LinkError::NotALink));
526        assert_eq!(
527            parse_link(&good.replace("spoolframe://pair?", "spoolframe://invite?")),
528            Err(LinkError::NotALink)
529        );
530        assert_eq!(
531            parse_link(&format!("{good}&x={}", "y".repeat(MAX_LINK))),
532            Err(LinkError::TooLong)
533        );
534        let code = PairingCode::from_bytes([7; 32]).to_text();
535        for (damaged, why) in [
536            (good.replace(&code, ""), "not a code"),
537            (good.replace(&code, &code[..42]), "not a code"),
538            (good.replace(&format!("c={code}"), "x=1"), "no code"),
539            (good.replace("e=abab", "e=zzab"), "not an endpoint id"),
540            (
541                good.replace(&format!("e={}", "ab".repeat(32)), ""),
542                "no endpoint id",
543            ),
544            (format!("{good}&c={code}"), "two codes"),
545            (format!("{good}&e={}", "cd".repeat(32)), "two endpoints"),
546            (format!("{good}&n=%ZZ"), "the name"),
547        ] {
548            assert_eq!(
549                parse_link(&damaged),
550                Err(LinkError::Damaged(why)),
551                "{damaged}"
552            );
553        }
554    }
555
556    #[test]
557    fn unknown_parameters_and_unreadable_hints_are_ignored() {
558        let text = format!(
559            "{}&v=2&a=not-an-address&r=ftp%3A%2F%2Fnope",
560            sample().link()
561        );
562        assert_eq!(parse_link(&text).unwrap(), sample());
563    }
564
565    #[test]
566    fn the_code_is_kept_out_of_debug() {
567        let link = sample();
568        let shown = format!("{link:?} {:?}", link.code);
569        assert!(!shown.contains(&link.code.to_text()), "{shown}");
570        assert!(!shown.contains("7, 7"), "{shown}");
571    }
572
573    #[test]
574    fn codes_match_only_themselves() {
575        let code = PairingCode::from_bytes([7; 32]);
576        assert!(code.matches(&PairingCode::from_bytes([7; 32])));
577        let mut last = [7; 32];
578        last[31] = 8;
579        assert!(!code.matches(&PairingCode::from_bytes(last)));
580        let mut first = [7; 32];
581        first[0] = 0;
582        assert!(!code.matches(&PairingCode::from_bytes(first)));
583    }
584
585    /// Damaged links, from a fixed seed: none panics, and what reads as a
586    /// link writes back to one that reads the same.
587    #[test]
588    fn mangled_links_never_panic_and_what_reads_round_trips() {
589        let base = sample().link().into_bytes();
590        let mut state = 0x9e37_79b9_7f4a_7c15u64;
591        let mut next = move || {
592            state ^= state << 13;
593            state ^= state >> 7;
594            state ^= state << 17;
595            state
596        };
597        for _ in 0..20_000 {
598            let mut bytes = base.clone();
599            for _ in 0..(next() % 6 + 1) {
600                let at = (next() as usize) % bytes.len();
601                match next() % 3 {
602                    0 => bytes[at] = next() as u8,
603                    1 => {
604                        bytes.remove(at);
605                    }
606                    _ => bytes.insert(at, b"&=%:[]"[(next() % 6) as usize]),
607                }
608                if bytes.is_empty() {
609                    break;
610                }
611            }
612            let Ok(text) = std::str::from_utf8(&bytes) else {
613                continue;
614            };
615            if let Ok(link) = parse_link(text) {
616                assert_eq!(parse_link(&link.link()), Ok(link));
617            }
618        }
619    }
620
621    #[test]
622    fn frames_are_tagged_by_type() {
623        let declined = crate::codec::encode(&PhoneFrame::Declined).unwrap();
624        let read: PhoneFrame = crate::codec::decode(&declined).unwrap();
625        assert_eq!(read, PhoneFrame::Declined);
626        let refused = DeviceFrame::Refused {
627            reason: Refusal::NotAllowed,
628        };
629        let json = serde_json::to_string(&refused).unwrap();
630        assert_eq!(json, r#"{"type":"refused","reason":"not_allowed"}"#);
631    }
632
633    /// A credential frame for user 7's device 9, with `servers`.
634    fn credential_frame(servers: Vec<PairedServer>) -> PhoneFrame {
635        use ed25519_dalek::{Signer, SigningKey};
636        let root = SigningKey::from_bytes(&[7; 32]);
637        let device = SigningKey::from_bytes(&[9; 32]);
638        let credential = UserDeviceCredential::new(
639            PortableUserId::from_bytes(root.verifying_key().to_bytes()).unwrap(),
640            DevicePublicKey::from_bytes(device.verifying_key().to_bytes()).unwrap(),
641            1,
642            1_791_504_000,
643            1_791_504_000 + 3600,
644            |m| root.sign(m),
645        );
646        PhoneFrame::Credential {
647            credential: Box::new(credential),
648            state: None,
649            servers,
650        }
651    }
652
653    fn home() -> PairedServer {
654        PairedServer {
655            endpoint_id: "ab".repeat(32),
656            server_id: "q7k3mpa9trdwf2h".into(),
657            name: "Home Media".into(),
658            addrs: vec![
659                "192.168.1.10:7420".parse().unwrap(),
660                "[2001:db8::1]:7420".parse().unwrap(),
661            ],
662            relays: vec!["https://relay.example.org/".into()],
663        }
664    }
665
666    /// P7-06: the servers ride the credential frame, their addresses as
667    /// text (a tagged frame cannot carry serde's own form through CBOR).
668    #[test]
669    fn a_credential_frame_carries_its_servers() {
670        let frame = credential_frame(vec![home()]);
671        let read: PhoneFrame =
672            crate::codec::decode(&crate::codec::encode(&frame).unwrap()).unwrap();
673        assert_eq!(read, frame);
674        let json = serde_json::to_value(&frame).unwrap();
675        assert_eq!(json["servers"][0]["addrs"][1], "[2001:db8::1]:7420");
676    }
677
678    /// A credential frame without its servers, as a phone before P7-06
679    /// sent it, is refused: an empty list is sent as one.
680    #[test]
681    fn a_credential_frame_without_servers_is_refused() {
682        let mut json = serde_json::to_value(credential_frame(vec![home()])).unwrap();
683        json.as_object_mut().unwrap().remove("servers");
684        let error = serde_json::from_value::<PhoneFrame>(json).unwrap_err();
685        assert!(
686            error.to_string().contains("missing field `servers`"),
687            "{error}"
688        );
689    }
690
691    #[test]
692    fn a_paired_server_is_held_to_bounds() {
693        assert_eq!(home().within_bounds(), Some(home()));
694        let loud = PairedServer {
695            endpoint_id: "AB".repeat(32),
696            name: "x".repeat(500),
697            addrs: (0..20)
698                .map(|n| format!("10.0.0.{n}:7420").parse().unwrap())
699                .collect(),
700            relays: vec![
701                "ftp://nope".into(),
702                "https://a.example/".into(),
703                "https://b.example/".into(),
704                "https://c.example/".into(),
705            ],
706            ..home()
707        };
708        let held = loud.within_bounds().unwrap();
709        assert_eq!(held.endpoint_id, "ab".repeat(32));
710        assert_eq!(held.name.chars().count(), crate::MAX_HELLO_TEXT);
711        assert_eq!(held.addrs.len(), MAX_ADDRS);
712        assert_eq!(held.relays, ["https://a.example/", "https://b.example/"]);
713        for bad in [
714            PairedServer {
715                endpoint_id: "not a key".into(),
716                ..home()
717            },
718            PairedServer {
719                server_id: String::new(),
720                ..home()
721            },
722        ] {
723            assert_eq!(bad.within_bounds(), None);
724        }
725    }
726}