teter-core 26.11.7

What teter's clients share without I/O: end-to-end encryption, account crypto, signed commands
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
//! The client side of accounts: the keys derived from the password, the
//! account's key pairs, their wrapping, and the requests to the relay's
//! account service (`teter_common::account`).
//!
//! From the password and the account's salt, Argon2id gives a master key;
//! HKDF-SHA256 over it gives an auth key (presented to the relay, which keeps
//! only its hash) and a wrapping key (which never leaves the client). The
//! account has two key pairs: X25519, to receive session keys sealed to it
//! (#87), and Ed25519, to sign commands to its machines (#88). Their private
//! halves reach the relay only wrapped, with XChaCha20-Poly1305 under the
//! wrapping key, bound to the account's name.
//!
//! No I/O here: the requests to the relay are `teter_client::account`'s.

use std::io;

use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use hkdf::Hkdf;
use sha2::Sha256;
use zeroize::Zeroizing;

pub use teter_common::account::{DEFAULT_KDF, KdfParams, salt_blob};
use teter_common::account::{SALT_RANDOM_LEN, acceptable_kdf, parse_salt};

/// The nonce of a wrapping, before its ciphertext.
const NONCE_LEN: usize = 24;

/// What can go wrong with an account's keys.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum AccountError {
    /// A salt this build cannot read (another version, or damaged).
    #[error("the account's salt is not one this version of teter reads")]
    BadSalt,
    /// The key derivation failed (parameters out of range).
    #[error("deriving the account's keys: {0}")]
    Kdf(String),
    /// The wrapped keys do not open: another password, or altered.
    #[error("the account's keys do not open with this password")]
    WrongKeys,
    /// The relay's account service refused, or answered out of turn.
    #[error("{0}")]
    Refused(String),
    /// The connection, or the system's random source, failed.
    #[error(transparent)]
    Io(#[from] io::Error),
}

/// A new salt for `params`, with fresh random bytes.
///
/// # Errors
///
/// When the system's random source fails.
pub fn new_salt(params: KdfParams) -> io::Result<Vec<u8>> {
    let mut random = [0_u8; SALT_RANDOM_LEN];
    getrandom::fill(&mut random).map_err(io::Error::other)?;
    Ok(salt_blob(params, &random))
}

/// The two keys derived from the password.
pub struct Derived {
    /// Presented to the relay, which keeps its hash.
    pub auth_key: Zeroizing<[u8; 32]>,
    /// Wraps the account's private keys; never leaves the client.
    wrap_key: Zeroizing<[u8; 32]>,
}

/// Derives the auth and wrapping keys from `password` and the account's
/// `salt`.
///
/// # Errors
///
/// A salt this build cannot read, or parameters Argon2 refuses.
pub fn derive(password: &str, salt: &[u8]) -> Result<Derived, AccountError> {
    let (params, random) = parse_salt(salt).ok_or(AccountError::BadSalt)?;
    // The relay chose these (it is not trusted): too cheap would make the
    // auth key a cheap way to the password, too dear would exhaust the
    // client.
    if !acceptable_kdf(params) {
        return Err(AccountError::Kdf(format!(
            "the account's key derivation ({} KiB, {} passes, {} lanes) is outside what teter accepts",
            params.memory_kib, params.passes, params.lanes
        )));
    }
    let argon_params =
        argon2::Params::new(params.memory_kib, params.passes, params.lanes, Some(32))
            .map_err(|e| AccountError::Kdf(e.to_string()))?;
    let argon = argon2::Argon2::new(
        argon2::Algorithm::Argon2id,
        argon2::Version::V0x13,
        argon_params,
    );
    let mut master = Zeroizing::new([0_u8; 32]);
    argon
        .hash_password_into(password.as_bytes(), random, master.as_mut())
        .map_err(|e| AccountError::Kdf(e.to_string()))?;
    let hkdf =
        Hkdf::<Sha256>::from_prk(master.as_ref()).map_err(|e| AccountError::Kdf(e.to_string()))?;
    let key = |info: &[u8]| -> Result<Zeroizing<[u8; 32]>, AccountError> {
        let mut key = Zeroizing::new([0_u8; 32]);
        hkdf.expand(info, key.as_mut())
            .map_err(|e| AccountError::Kdf(e.to_string()))?;
        Ok(key)
    };
    Ok(Derived {
        auth_key: key(b"teter-account-v1 auth")?,
        wrap_key: key(b"teter-account-v1 wrap")?,
    })
}

/// The account's key pairs: X25519 (to receive sealed session keys) and
/// Ed25519 (to sign commands). Its `Debug` hides the private halves.
pub struct AccountKeys {
    x25519: x25519_dalek::StaticSecret,
    ed25519: ed25519_dalek::SigningKey,
}

impl std::fmt::Debug for AccountKeys {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AccountKeys").finish_non_exhaustive()
    }
}

impl AccountKeys {
    /// New key pairs.
    ///
    /// # Errors
    ///
    /// When the system's random source fails.
    pub fn generate() -> io::Result<Self> {
        let mut bytes = Zeroizing::new([0_u8; 64]);
        getrandom::fill(bytes.as_mut()).map_err(io::Error::other)?;
        Ok(Self::from_private(&bytes))
    }

    /// The key pairs from their private halves (X25519, then the Ed25519
    /// seed, 32 bytes each).
    fn from_private(bytes: &[u8; 64]) -> Self {
        let (x, e) = bytes.split_at(32);
        let mut x_bytes = [0_u8; 32];
        x_bytes.copy_from_slice(x);
        let mut e_bytes = [0_u8; 32];
        e_bytes.copy_from_slice(e);
        let keys = Self {
            x25519: x25519_dalek::StaticSecret::from(x_bytes),
            ed25519: ed25519_dalek::SigningKey::from_bytes(&e_bytes),
        };
        zeroize::Zeroize::zeroize(&mut x_bytes);
        zeroize::Zeroize::zeroize(&mut e_bytes);
        keys
    }

    /// The private halves, as [`AccountKeys::from_private`] takes them.
    pub fn private_bytes(&self) -> Zeroizing<[u8; 64]> {
        let mut bytes = Zeroizing::new([0_u8; 64]);
        let (x, e) = bytes.split_at_mut(32);
        x.copy_from_slice(self.x25519.as_bytes());
        e.copy_from_slice(self.ed25519.as_bytes());
        bytes
    }

    /// The key pairs from their private halves, if `bytes` holds 64.
    pub fn from_private_bytes(bytes: &[u8]) -> Option<Self> {
        let bytes: &[u8; 64] = bytes.try_into().ok()?;
        Some(Self::from_private(bytes))
    }

    /// The public halves: X25519, then Ed25519, 32 bytes each.
    pub fn public_keys(&self) -> Vec<u8> {
        let mut public = Vec::with_capacity(64);
        public.extend_from_slice(x25519_dalek::PublicKey::from(&self.x25519).as_bytes());
        public.extend_from_slice(self.ed25519.verifying_key().as_bytes());
        public
    }

    /// The private halves wrapped under `derived`'s wrapping key, bound to
    /// account `name`: a nonce, then the ciphertext.
    ///
    /// # Errors
    ///
    /// When the system's random source fails.
    pub fn wrap(&self, derived: &Derived, name: &str) -> io::Result<Vec<u8>> {
        let mut nonce = [0_u8; NONCE_LEN];
        getrandom::fill(&mut nonce).map_err(io::Error::other)?;
        let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
        let private = self.private_bytes();
        let sealed = cipher
            .encrypt(
                XNonce::from_slice(&nonce),
                Payload {
                    msg: private.as_ref(),
                    aad: &wrap_aad(name),
                },
            )
            .map_err(|_opaque| io::Error::other("wrapping the account's keys failed"))?;
        let mut wrapped = nonce.to_vec();
        wrapped.extend_from_slice(&sealed);
        Ok(wrapped)
    }

    /// The key pairs `wrapped` holds, for account `name`, under `derived`'s
    /// wrapping key; they must match `public_keys`.
    ///
    /// # Errors
    ///
    /// [`AccountError::WrongKeys`] when they do not open or do not match.
    pub fn unwrap(
        derived: &Derived,
        name: &str,
        wrapped: &[u8],
        public_keys: &[u8],
    ) -> Result<Self, AccountError> {
        let (nonce, sealed) = wrapped
            .split_at_checked(NONCE_LEN)
            .ok_or(AccountError::WrongKeys)?;
        let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
        let private = Zeroizing::new(
            cipher
                .decrypt(
                    XNonce::from_slice(nonce),
                    Payload {
                        msg: sealed,
                        aad: &wrap_aad(name),
                    },
                )
                .map_err(|_opaque| AccountError::WrongKeys)?,
        );
        let keys = Self::from_private_bytes(&private).ok_or(AccountError::WrongKeys)?;
        if keys.public_keys() != public_keys {
            return Err(AccountError::WrongKeys);
        }
        Ok(keys)
    }
}

impl AccountKeys {
    /// The account's Ed25519 signature of `message` (#88).
    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
        use ed25519_dalek::Signer as _;
        self.ed25519.sign(message).to_bytes().to_vec()
    }

    /// What [`seal_to`] sealed to this account, for `info`.
    ///
    /// # Errors
    ///
    /// [`AccountError::WrongKeys`] when it does not open: sealed to another
    /// account, for another `info`, or altered.
    pub fn open_sealed(
        &self,
        info: &[u8],
        sealed: &[u8],
    ) -> Result<Zeroizing<Vec<u8>>, AccountError> {
        let (ephemeral, rest) = sealed.split_at_checked(32).ok_or(AccountError::WrongKeys)?;
        let (nonce, ciphertext) = rest
            .split_at_checked(NONCE_LEN)
            .ok_or(AccountError::WrongKeys)?;
        let ephemeral: [u8; 32] = ephemeral
            .try_into()
            .map_err(|_opaque| AccountError::WrongKeys)?;
        let shared = self
            .x25519
            .diffie_hellman(&x25519_dalek::PublicKey::from(ephemeral));
        let recipient = *x25519_dalek::PublicKey::from(&self.x25519).as_bytes();
        let key = sealing_key(shared.as_bytes(), &ephemeral, &recipient, info)?;
        XChaCha20Poly1305::new(key.as_ref().into())
            .decrypt(XNonce::from_slice(nonce), ciphertext)
            .map(Zeroizing::new)
            .map_err(|_opaque| AccountError::WrongKeys)
    }
}

/// What a wrapping is bound to.
fn wrap_aad(name: &str) -> Vec<u8> {
    let mut aad = b"teter-account-v1 keys ".to_vec();
    aad.extend_from_slice(name.as_bytes());
    aad
}

/// Seals `plaintext` to the account whose public keys are `public_keys`
/// (its X25519 key, the first 32 bytes), for `info` (what it is, bound in
/// the key): an ephemeral X25519 key agreed with the account's, HKDF-SHA256
/// over the shared secret, XChaCha20-Poly1305. Only the account's private
/// key opens it ([`AccountKeys::open_sealed`]). The result: the ephemeral
/// public key, the nonce, the ciphertext.
///
/// # Errors
///
/// Public keys that hold no X25519 key, or a random source that fails.
pub fn seal_to(public_keys: &[u8], info: &[u8], plaintext: &[u8]) -> io::Result<Vec<u8>> {
    let recipient: [u8; 32] = public_keys
        .get(..32)
        .and_then(|key| key.try_into().ok())
        .ok_or_else(|| io::Error::other("the account's public keys hold no X25519 key"))?;
    let mut ephemeral = Zeroizing::new([0_u8; 32]);
    getrandom::fill(ephemeral.as_mut()).map_err(io::Error::other)?;
    let ephemeral = x25519_dalek::StaticSecret::from(*ephemeral);
    let ephemeral_public = x25519_dalek::PublicKey::from(&ephemeral);
    let shared = ephemeral.diffie_hellman(&x25519_dalek::PublicKey::from(recipient));
    let key = sealing_key(
        shared.as_bytes(),
        ephemeral_public.as_bytes(),
        &recipient,
        info,
    )?;
    let mut nonce = [0_u8; NONCE_LEN];
    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
    let sealed = XChaCha20Poly1305::new(key.as_ref().into())
        .encrypt(XNonce::from_slice(&nonce), plaintext)
        .map_err(|_opaque| io::Error::other("sealing failed"))?;
    let mut out = ephemeral_public.as_bytes().to_vec();
    out.extend_from_slice(&nonce);
    out.extend_from_slice(&sealed);
    Ok(out)
}

/// The key a sealing to `recipient` from `ephemeral` uses, for `info`.
fn sealing_key(
    shared: &[u8; 32],
    ephemeral: &[u8; 32],
    recipient: &[u8; 32],
    info: &[u8],
) -> io::Result<Zeroizing<[u8; 32]>> {
    let mut salt = ephemeral.to_vec();
    salt.extend_from_slice(recipient);
    let hkdf = Hkdf::<Sha256>::new(Some(&salt), shared);
    let mut full_info = b"teter-seal-v1 ".to_vec();
    full_info.extend_from_slice(info);
    let mut key = Zeroizing::new([0_u8; 32]);
    hkdf.expand(&full_info, key.as_mut())
        .map_err(|_opaque| io::Error::other("deriving the sealing key failed"))?;
    Ok(key)
}

/// Whether `signature` is the Ed25519 signature of `message` by
/// `public_key` (32 bytes).
pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
    let (Ok(key), Ok(signature)) = (
        <&[u8; 32]>::try_from(public_key),
        <&[u8; 64]>::try_from(signature),
    ) else {
        return false;
    };
    let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
        return false;
    };
    key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature))
        .is_ok()
}

/// A machine's key pair (Ed25519): it authenticates the machine to the
/// relay. Its `Debug` hides the private half.
pub struct MachineKey(ed25519_dalek::SigningKey);

impl std::fmt::Debug for MachineKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MachineKey").finish_non_exhaustive()
    }
}

impl MachineKey {
    /// A new key pair.
    ///
    /// # Errors
    ///
    /// When the system's random source fails.
    pub fn generate() -> io::Result<Self> {
        let mut seed = Zeroizing::new([0_u8; 32]);
        getrandom::fill(seed.as_mut()).map_err(io::Error::other)?;
        Ok(Self(ed25519_dalek::SigningKey::from_bytes(&seed)))
    }

    /// The key pair from its 32-byte private seed, if `seed` holds 32 bytes.
    pub fn from_seed(seed: &[u8]) -> Option<Self> {
        let seed: &[u8; 32] = seed.try_into().ok()?;
        Some(Self(ed25519_dalek::SigningKey::from_bytes(seed)))
    }

    /// The private seed.
    pub fn seed(&self) -> Zeroizing<[u8; 32]> {
        Zeroizing::new(*self.0.as_bytes())
    }

    /// The public key, 32 bytes.
    pub fn public_key(&self) -> Vec<u8> {
        self.0.verifying_key().as_bytes().to_vec()
    }

    /// The signature of `message`, 64 bytes.
    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
        ed25519_dalek::Signer::sign(&self.0, message)
            .to_bytes()
            .to_vec()
    }
}

/// A device's key pair (#158), the same kind as a machine's: each login is
/// bound to the public half, and every request with its token is signed
/// ([`prove`]).
pub type DeviceKey = MachineKey;

/// `request` (one with a login token), signed by `device` at `at` (Unix
/// seconds) with a fresh nonce: what the relay takes for it (#158).
///
/// # Errors
///
/// When the request does not serialize or the random source fails.
pub fn prove(
    device: &DeviceKey,
    request: &teter_common::account::AccountRequest,
    at: i64,
) -> io::Result<teter_common::account::AccountRequest> {
    let request = serde_json::to_string(request).map_err(io::Error::other)?;
    let mut nonce = vec![0_u8; teter_common::account::PROOF_NONCE_LEN];
    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
    let signature = device.sign(&teter_common::account::proof_bytes(&request, at, &nonce));
    Ok(teter_common::account::AccountRequest::Proven {
        request,
        at,
        nonce,
        signature,
    })
}

/// The fingerprint of an account's public keys: the first 16 bytes of their
/// SHA-256. A registration token carries it, and the machine checks the
/// keys the relay gives it against it (#86).
pub fn fingerprint(public_keys: &[u8]) -> [u8; 16] {
    let digest = <Sha256 as sha2::Digest>::digest(public_keys);
    let mut fingerprint = [0_u8; 16];
    fingerprint.copy_from_slice(digest.get(..16).unwrap_or_default());
    fingerprint
}

/// The hash of a registration token's enrollment secret, which is all the
/// relay keeps of it.
pub fn secret_hash(secret: &[u8]) -> Vec<u8> {
    <Sha256 as sha2::Digest>::digest(secret).to_vec()
}

/// What of a registration token's secret goes to the relay (#133): a key
/// derived from it, so the relay never learns the [`registration_binding`]
/// key, which proves to the account's device that the machine held the
/// token.
pub fn registration_auth(secret: &[u8]) -> Zeroizing<[u8; 32]> {
    registration_key(secret, b"teter-reg-v1 auth")
}

/// The key a machine proves with that it held the registration token
/// (#133); never sent anywhere.
pub fn registration_binding(secret: &[u8]) -> Zeroizing<[u8; 32]> {
    registration_key(secret, b"teter-reg-v1 bind")
}

fn registration_key(secret: &[u8], info: &[u8]) -> Zeroizing<[u8; 32]> {
    let mut key = Zeroizing::new([0_u8; 32]);
    // 32 bytes is always a valid HKDF-SHA256 length: the error never comes.
    if Hkdf::<Sha256>::new(None, secret)
        .expand(info, key.as_mut())
        .is_err()
    {
        key.fill(0);
    }
    key
}

/// The machine's proof it held the token whose secret is `secret`, for its
/// key and sealed name: HMAC-SHA256 (HKDF-Extract) under the binding key.
pub fn binding_proof(secret: &[u8], machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
    let key = registration_binding(secret);
    let (prk, _) = Hkdf::<Sha256>::extract(
        Some(key.as_ref()),
        &teter_common::account::binding_bytes(machine_key, sealed_name),
    );
    prk.to_vec()
}

/// The account keys `pinned` leads to through `rotations` (#89): each one
/// from the keys reached so far, signed by their signing key, moves on to its
/// new keys; any other is skipped (a relay cannot forge one).
pub fn follow_rotations(
    pinned: &[u8],
    rotations: &[teter_common::account::KeyRotation],
) -> Vec<u8> {
    let mut keys = pinned.to_vec();
    for rotation in rotations {
        let signed = rotation.old_keys == keys
            && rotation.new_keys.len() == 64
            && keys.get(32..64).is_some_and(|signing| {
                verify(
                    signing,
                    &teter_common::account::rotation_bytes(
                        &rotation.old_keys,
                        &rotation.new_keys,
                        rotation.at,
                    ),
                    &rotation.signature,
                )
            });
        if signed {
            keys.clone_from(&rotation.new_keys);
        }
    }
    keys
}

/// A rotation from `old` to `new`, signed by `old` (#89).
pub fn rotation(
    old: &AccountKeys,
    new: &AccountKeys,
    at: i64,
) -> teter_common::account::KeyRotation {
    let (old_keys, new_keys) = (old.public_keys(), new.public_keys());
    teter_common::account::KeyRotation {
        signature: old.sign(&teter_common::account::rotation_bytes(
            &old_keys, &new_keys, at,
        )),
        old_keys,
        new_keys,
        at,
    }
}

/// Whether `cert` is the account's approval of machine `id` with
/// `machine_key` and `sealed_name`, checked against `account_public` (the
/// account's public keys as the device knows them from its own private
/// keys, never as a relay gives them).
pub fn cert_holds(
    account_public: &[u8],
    id: &str,
    machine_key: &[u8],
    sealed_name: &[u8],
    cert: &[u8],
) -> bool {
    // A key of its exact length: the signed bytes join it and the name.
    machine_key.len() == 32
        && account_public.get(32..64).is_some_and(|signing| {
            verify(
                signing,
                &teter_common::account::cert_bytes(id, machine_key, sealed_name),
                cert,
            )
        })
}

#[cfg(test)]
mod tests {
    use super::{
        AccountError, AccountKeys, KdfParams, derive, follow_rotations, new_salt, rotation,
        salt_blob,
    };

    #[test]
    fn a_machine_follows_only_rotations_signed_from_the_keys_it_holds() {
        let first = AccountKeys::generate().unwrap();
        let second = AccountKeys::generate().unwrap();
        let third = AccountKeys::generate().unwrap();
        let stranger = AccountKeys::generate().unwrap();
        let one = rotation(&first, &second, 10);
        let two = rotation(&second, &third, 20);
        // A chain, in order, leads to its end; from the middle, the rest.
        assert_eq!(
            follow_rotations(&first.public_keys(), &[one.clone(), two.clone()]),
            third.public_keys()
        );
        assert_eq!(
            follow_rotations(&second.public_keys(), &[one.clone(), two.clone()]),
            third.public_keys()
        );
        // One signed by other keys, or altered, is skipped.
        let forged = rotation(&stranger, &stranger, 30);
        let mut moved = one.clone();
        moved.old_keys = stranger.public_keys();
        let mut altered = one.clone();
        altered.new_keys = stranger.public_keys();
        let mut later = one.clone();
        later.at += 1;
        for skipped in [forged, moved, altered, later] {
            assert_eq!(
                follow_rotations(&first.public_keys(), &[skipped]),
                first.public_keys()
            );
        }
        // Keys no rotation starts from stay.
        assert_eq!(
            follow_rotations(&stranger.public_keys(), &[one, two]),
            stranger.public_keys()
        );
    }

    use teter_common::account::{DEFAULT_KDF, MAX_KDF};

    /// The parameters new accounts get (fast in tests: Argon2 is built
    /// optimized in the dev profile).
    const CHEAP: KdfParams = DEFAULT_KDF;

    #[test]
    fn the_same_password_and_salt_give_the_same_keys_and_another_password_others() {
        let salt = new_salt(CHEAP).unwrap();
        let one = derive("correct horse", &salt).unwrap();
        let again = derive("correct horse", &salt).unwrap();
        let other = derive("correct horsf", &salt).unwrap();
        assert_eq!(*one.auth_key, *again.auth_key);
        assert_ne!(*one.auth_key, *other.auth_key);
        assert_ne!(*one.auth_key, *one.wrap_key);
        // Another salt, other keys.
        let elsewhere = derive("correct horse", &new_salt(CHEAP).unwrap()).unwrap();
        assert_ne!(*one.auth_key, *elsewhere.auth_key);
    }

    #[test]
    fn wrapped_keys_open_with_the_password_and_name_only() {
        let salt = new_salt(CHEAP).unwrap();
        let derived = derive("correct horse", &salt).unwrap();
        let keys = AccountKeys::generate().unwrap();
        let wrapped = keys.wrap(&derived, "ana").unwrap();
        let public = keys.public_keys();
        let opened = AccountKeys::unwrap(&derived, "ana", &wrapped, &public).unwrap();
        assert_eq!(*opened.private_bytes(), *keys.private_bytes());
        let wrong = derive("wrong", &salt).unwrap();
        assert!(matches!(
            AccountKeys::unwrap(&wrong, "ana", &wrapped, &public),
            Err(AccountError::WrongKeys)
        ));
        assert!(matches!(
            AccountKeys::unwrap(&derived, "bia", &wrapped, &public),
            Err(AccountError::WrongKeys)
        ));
        // Keys that open but are not the account's public ones.
        let other = AccountKeys::generate().unwrap().public_keys();
        assert!(AccountKeys::unwrap(&derived, "ana", &wrapped, &other).is_err());
        // Nothing private in Debug.
        assert_eq!(format!("{keys:?}"), "AccountKeys { .. }");
    }

    #[test]
    fn a_salt_of_another_version_is_refused() {
        let mut salt = new_salt(CHEAP).unwrap();
        salt[0] = 9;
        assert!(matches!(derive("x", &salt), Err(AccountError::BadSalt)));
        assert!(matches!(
            derive("x", &salt[..10]),
            Err(AccountError::BadSalt)
        ));
    }

    #[test]
    fn a_salt_whose_cost_is_too_low_or_too_high_is_refused() {
        let random = [7_u8; 16];
        for params in [
            KdfParams {
                memory_kib: 8,
                passes: 1,
                lanes: 1,
            },
            KdfParams {
                passes: 1,
                ..DEFAULT_KDF
            },
            KdfParams {
                memory_kib: MAX_KDF.memory_kib + 1,
                ..DEFAULT_KDF
            },
            KdfParams {
                passes: u32::MAX,
                ..DEFAULT_KDF
            },
            KdfParams {
                lanes: 0,
                ..DEFAULT_KDF
            },
        ] {
            assert!(
                matches!(
                    derive("x", &salt_blob(params, &random)),
                    Err(AccountError::Kdf(_))
                ),
                "{params:?}"
            );
        }
    }

    #[test]
    fn what_is_sealed_to_an_account_opens_with_its_keys_and_info_only() {
        use super::{MachineKey, seal_to};

        let keys = AccountKeys::generate().unwrap();
        let sealed = seal_to(&keys.public_keys(), b"machine name", b"jupiter").unwrap();
        assert_eq!(
            keys.open_sealed(b"machine name", &sealed)
                .unwrap()
                .as_slice(),
            b"jupiter"
        );
        assert!(keys.open_sealed(b"session key", &sealed).is_err());
        let other = AccountKeys::generate().unwrap();
        assert!(other.open_sealed(b"machine name", &sealed).is_err());
        // A machine key signs, and keeps its seed.
        let machine = MachineKey::generate().unwrap();
        let again = MachineKey::from_seed(machine.seed().as_ref()).unwrap();
        assert_eq!(machine.public_key(), again.public_key());
        assert_eq!(machine.sign(b"x").len(), 64);
        assert_eq!(format!("{machine:?}"), "MachineKey { .. }");
    }

    #[test]
    fn a_proven_request_carries_the_request_and_verifies_under_the_device_key() {
        use super::{DeviceKey, prove, verify};
        use teter_common::account::{AccountRequest, proof_bytes};

        let device = DeviceKey::generate().unwrap();
        let inner = AccountRequest::MachineList {
            login: "tok".into(),
        };
        let AccountRequest::Proven {
            request,
            at,
            nonce,
            signature,
        } = prove(&device, &inner, 42).unwrap()
        else {
            panic!("not proven");
        };
        assert_eq!(at, 42);
        assert_eq!(
            serde_json::from_str::<AccountRequest>(&request).unwrap(),
            inner
        );
        let bytes = proof_bytes(&request, at, &nonce);
        assert!(verify(&device.public_key(), &bytes, &signature));
        let other = DeviceKey::generate().unwrap();
        assert!(!verify(&other.public_key(), &bytes, &signature));
        // Each proof has its own nonce.
        let AccountRequest::Proven { nonce: again, .. } = prove(&device, &inner, 42).unwrap()
        else {
            panic!("not proven");
        };
        assert_ne!(nonce, again);
    }
}