Skip to main content

teter_core/
account.rs

1//! The client side of accounts: the keys derived from the password, the
2//! account's key pairs, their wrapping, and the requests to the relay's
3//! account service (`teter_common::account`).
4//!
5//! From the password and the account's salt, Argon2id gives a master key;
6//! HKDF-SHA256 over it gives an auth key (presented to the relay, which keeps
7//! only its hash) and a wrapping key (which never leaves the client). The
8//! account has two key pairs: X25519, to receive session keys sealed to it
9//! (#87), and Ed25519, to sign commands to its machines (#88). Their private
10//! halves reach the relay only wrapped, with XChaCha20-Poly1305 under the
11//! wrapping key, bound to the account's name.
12//!
13//! No I/O here: the requests to the relay are `teter_client::account`'s.
14
15use std::io;
16
17use chacha20poly1305::aead::{Aead, KeyInit, Payload};
18use chacha20poly1305::{XChaCha20Poly1305, XNonce};
19use hkdf::Hkdf;
20use sha2::Sha256;
21use zeroize::Zeroizing;
22
23pub use teter_common::account::{DEFAULT_KDF, KdfParams, salt_blob};
24use teter_common::account::{SALT_RANDOM_LEN, acceptable_kdf, parse_salt};
25
26/// The nonce of a wrapping, before its ciphertext.
27const NONCE_LEN: usize = 24;
28
29/// What can go wrong with an account's keys.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum AccountError {
33    /// A salt this build cannot read (another version, or damaged).
34    #[error("the account's salt is not one this version of teter reads")]
35    BadSalt,
36    /// The key derivation failed (parameters out of range).
37    #[error("deriving the account's keys: {0}")]
38    Kdf(String),
39    /// The wrapped keys do not open: another password, or altered.
40    #[error("the account's keys do not open with this password")]
41    WrongKeys,
42    /// The relay's account service refused, or answered out of turn.
43    #[error("{0}")]
44    Refused(String),
45    /// The connection, or the system's random source, failed.
46    #[error(transparent)]
47    Io(#[from] io::Error),
48}
49
50/// A new salt for `params`, with fresh random bytes.
51///
52/// # Errors
53///
54/// When the system's random source fails.
55pub fn new_salt(params: KdfParams) -> io::Result<Vec<u8>> {
56    let mut random = [0_u8; SALT_RANDOM_LEN];
57    getrandom::fill(&mut random).map_err(io::Error::other)?;
58    Ok(salt_blob(params, &random))
59}
60
61/// The two keys derived from the password.
62pub struct Derived {
63    /// Presented to the relay, which keeps its hash.
64    pub auth_key: Zeroizing<[u8; 32]>,
65    /// Wraps the account's private keys; never leaves the client.
66    wrap_key: Zeroizing<[u8; 32]>,
67}
68
69/// Derives the auth and wrapping keys from `password` and the account's
70/// `salt`.
71///
72/// # Errors
73///
74/// A salt this build cannot read, or parameters Argon2 refuses.
75pub fn derive(password: &str, salt: &[u8]) -> Result<Derived, AccountError> {
76    let (params, random) = parse_salt(salt).ok_or(AccountError::BadSalt)?;
77    // The relay chose these (it is not trusted): too cheap would make the
78    // auth key a cheap way to the password, too dear would exhaust the
79    // client.
80    if !acceptable_kdf(params) {
81        return Err(AccountError::Kdf(format!(
82            "the account's key derivation ({} KiB, {} passes, {} lanes) is outside what teter accepts",
83            params.memory_kib, params.passes, params.lanes
84        )));
85    }
86    let argon_params =
87        argon2::Params::new(params.memory_kib, params.passes, params.lanes, Some(32))
88            .map_err(|e| AccountError::Kdf(e.to_string()))?;
89    let argon = argon2::Argon2::new(
90        argon2::Algorithm::Argon2id,
91        argon2::Version::V0x13,
92        argon_params,
93    );
94    let mut master = Zeroizing::new([0_u8; 32]);
95    argon
96        .hash_password_into(password.as_bytes(), random, master.as_mut())
97        .map_err(|e| AccountError::Kdf(e.to_string()))?;
98    let hkdf =
99        Hkdf::<Sha256>::from_prk(master.as_ref()).map_err(|e| AccountError::Kdf(e.to_string()))?;
100    let key = |info: &[u8]| -> Result<Zeroizing<[u8; 32]>, AccountError> {
101        let mut key = Zeroizing::new([0_u8; 32]);
102        hkdf.expand(info, key.as_mut())
103            .map_err(|e| AccountError::Kdf(e.to_string()))?;
104        Ok(key)
105    };
106    Ok(Derived {
107        auth_key: key(b"teter-account-v1 auth")?,
108        wrap_key: key(b"teter-account-v1 wrap")?,
109    })
110}
111
112/// The account's key pairs: X25519 (to receive sealed session keys) and
113/// Ed25519 (to sign commands). Its `Debug` hides the private halves.
114pub struct AccountKeys {
115    x25519: x25519_dalek::StaticSecret,
116    ed25519: ed25519_dalek::SigningKey,
117}
118
119impl std::fmt::Debug for AccountKeys {
120    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121        f.debug_struct("AccountKeys").finish_non_exhaustive()
122    }
123}
124
125impl AccountKeys {
126    /// New key pairs.
127    ///
128    /// # Errors
129    ///
130    /// When the system's random source fails.
131    pub fn generate() -> io::Result<Self> {
132        let mut bytes = Zeroizing::new([0_u8; 64]);
133        getrandom::fill(bytes.as_mut()).map_err(io::Error::other)?;
134        Ok(Self::from_private(&bytes))
135    }
136
137    /// The key pairs from their private halves (X25519, then the Ed25519
138    /// seed, 32 bytes each).
139    fn from_private(bytes: &[u8; 64]) -> Self {
140        let (x, e) = bytes.split_at(32);
141        let mut x_bytes = [0_u8; 32];
142        x_bytes.copy_from_slice(x);
143        let mut e_bytes = [0_u8; 32];
144        e_bytes.copy_from_slice(e);
145        let keys = Self {
146            x25519: x25519_dalek::StaticSecret::from(x_bytes),
147            ed25519: ed25519_dalek::SigningKey::from_bytes(&e_bytes),
148        };
149        zeroize::Zeroize::zeroize(&mut x_bytes);
150        zeroize::Zeroize::zeroize(&mut e_bytes);
151        keys
152    }
153
154    /// The private halves, as [`AccountKeys::from_private`] takes them.
155    pub fn private_bytes(&self) -> Zeroizing<[u8; 64]> {
156        let mut bytes = Zeroizing::new([0_u8; 64]);
157        let (x, e) = bytes.split_at_mut(32);
158        x.copy_from_slice(self.x25519.as_bytes());
159        e.copy_from_slice(self.ed25519.as_bytes());
160        bytes
161    }
162
163    /// The key pairs from their private halves, if `bytes` holds 64.
164    pub fn from_private_bytes(bytes: &[u8]) -> Option<Self> {
165        let bytes: &[u8; 64] = bytes.try_into().ok()?;
166        Some(Self::from_private(bytes))
167    }
168
169    /// The public halves: X25519, then Ed25519, 32 bytes each.
170    pub fn public_keys(&self) -> Vec<u8> {
171        let mut public = Vec::with_capacity(64);
172        public.extend_from_slice(x25519_dalek::PublicKey::from(&self.x25519).as_bytes());
173        public.extend_from_slice(self.ed25519.verifying_key().as_bytes());
174        public
175    }
176
177    /// The private halves wrapped under `derived`'s wrapping key, bound to
178    /// account `name`: a nonce, then the ciphertext.
179    ///
180    /// # Errors
181    ///
182    /// When the system's random source fails.
183    pub fn wrap(&self, derived: &Derived, name: &str) -> io::Result<Vec<u8>> {
184        let mut nonce = [0_u8; NONCE_LEN];
185        getrandom::fill(&mut nonce).map_err(io::Error::other)?;
186        let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
187        let private = self.private_bytes();
188        let sealed = cipher
189            .encrypt(
190                XNonce::from_slice(&nonce),
191                Payload {
192                    msg: private.as_ref(),
193                    aad: &wrap_aad(name),
194                },
195            )
196            .map_err(|_opaque| io::Error::other("wrapping the account's keys failed"))?;
197        let mut wrapped = nonce.to_vec();
198        wrapped.extend_from_slice(&sealed);
199        Ok(wrapped)
200    }
201
202    /// The key pairs `wrapped` holds, for account `name`, under `derived`'s
203    /// wrapping key; they must match `public_keys`.
204    ///
205    /// # Errors
206    ///
207    /// [`AccountError::WrongKeys`] when they do not open or do not match.
208    pub fn unwrap(
209        derived: &Derived,
210        name: &str,
211        wrapped: &[u8],
212        public_keys: &[u8],
213    ) -> Result<Self, AccountError> {
214        let (nonce, sealed) = wrapped
215            .split_at_checked(NONCE_LEN)
216            .ok_or(AccountError::WrongKeys)?;
217        let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
218        let private = Zeroizing::new(
219            cipher
220                .decrypt(
221                    XNonce::from_slice(nonce),
222                    Payload {
223                        msg: sealed,
224                        aad: &wrap_aad(name),
225                    },
226                )
227                .map_err(|_opaque| AccountError::WrongKeys)?,
228        );
229        let keys = Self::from_private_bytes(&private).ok_or(AccountError::WrongKeys)?;
230        if keys.public_keys() != public_keys {
231            return Err(AccountError::WrongKeys);
232        }
233        Ok(keys)
234    }
235}
236
237impl AccountKeys {
238    /// The account's Ed25519 signature of `message` (#88).
239    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
240        use ed25519_dalek::Signer as _;
241        self.ed25519.sign(message).to_bytes().to_vec()
242    }
243
244    /// What [`seal_to`] sealed to this account, for `info`.
245    ///
246    /// # Errors
247    ///
248    /// [`AccountError::WrongKeys`] when it does not open: sealed to another
249    /// account, for another `info`, or altered.
250    pub fn open_sealed(
251        &self,
252        info: &[u8],
253        sealed: &[u8],
254    ) -> Result<Zeroizing<Vec<u8>>, AccountError> {
255        let (ephemeral, rest) = sealed.split_at_checked(32).ok_or(AccountError::WrongKeys)?;
256        let (nonce, ciphertext) = rest
257            .split_at_checked(NONCE_LEN)
258            .ok_or(AccountError::WrongKeys)?;
259        let ephemeral: [u8; 32] = ephemeral
260            .try_into()
261            .map_err(|_opaque| AccountError::WrongKeys)?;
262        let shared = self
263            .x25519
264            .diffie_hellman(&x25519_dalek::PublicKey::from(ephemeral));
265        let recipient = *x25519_dalek::PublicKey::from(&self.x25519).as_bytes();
266        let key = sealing_key(shared.as_bytes(), &ephemeral, &recipient, info)?;
267        XChaCha20Poly1305::new(key.as_ref().into())
268            .decrypt(XNonce::from_slice(nonce), ciphertext)
269            .map(Zeroizing::new)
270            .map_err(|_opaque| AccountError::WrongKeys)
271    }
272}
273
274/// What a wrapping is bound to.
275fn wrap_aad(name: &str) -> Vec<u8> {
276    let mut aad = b"teter-account-v1 keys ".to_vec();
277    aad.extend_from_slice(name.as_bytes());
278    aad
279}
280
281/// Seals `plaintext` to the account whose public keys are `public_keys`
282/// (its X25519 key, the first 32 bytes), for `info` (what it is, bound in
283/// the key): an ephemeral X25519 key agreed with the account's, HKDF-SHA256
284/// over the shared secret, XChaCha20-Poly1305. Only the account's private
285/// key opens it ([`AccountKeys::open_sealed`]). The result: the ephemeral
286/// public key, the nonce, the ciphertext.
287///
288/// # Errors
289///
290/// Public keys that hold no X25519 key, or a random source that fails.
291pub fn seal_to(public_keys: &[u8], info: &[u8], plaintext: &[u8]) -> io::Result<Vec<u8>> {
292    let recipient: [u8; 32] = public_keys
293        .get(..32)
294        .and_then(|key| key.try_into().ok())
295        .ok_or_else(|| io::Error::other("the account's public keys hold no X25519 key"))?;
296    let mut ephemeral = Zeroizing::new([0_u8; 32]);
297    getrandom::fill(ephemeral.as_mut()).map_err(io::Error::other)?;
298    let ephemeral = x25519_dalek::StaticSecret::from(*ephemeral);
299    let ephemeral_public = x25519_dalek::PublicKey::from(&ephemeral);
300    let shared = ephemeral.diffie_hellman(&x25519_dalek::PublicKey::from(recipient));
301    let key = sealing_key(
302        shared.as_bytes(),
303        ephemeral_public.as_bytes(),
304        &recipient,
305        info,
306    )?;
307    let mut nonce = [0_u8; NONCE_LEN];
308    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
309    let sealed = XChaCha20Poly1305::new(key.as_ref().into())
310        .encrypt(XNonce::from_slice(&nonce), plaintext)
311        .map_err(|_opaque| io::Error::other("sealing failed"))?;
312    let mut out = ephemeral_public.as_bytes().to_vec();
313    out.extend_from_slice(&nonce);
314    out.extend_from_slice(&sealed);
315    Ok(out)
316}
317
318/// The key a sealing to `recipient` from `ephemeral` uses, for `info`.
319fn sealing_key(
320    shared: &[u8; 32],
321    ephemeral: &[u8; 32],
322    recipient: &[u8; 32],
323    info: &[u8],
324) -> io::Result<Zeroizing<[u8; 32]>> {
325    let mut salt = ephemeral.to_vec();
326    salt.extend_from_slice(recipient);
327    let hkdf = Hkdf::<Sha256>::new(Some(&salt), shared);
328    let mut full_info = b"teter-seal-v1 ".to_vec();
329    full_info.extend_from_slice(info);
330    let mut key = Zeroizing::new([0_u8; 32]);
331    hkdf.expand(&full_info, key.as_mut())
332        .map_err(|_opaque| io::Error::other("deriving the sealing key failed"))?;
333    Ok(key)
334}
335
336/// Whether `signature` is the Ed25519 signature of `message` by
337/// `public_key` (32 bytes).
338pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
339    let (Ok(key), Ok(signature)) = (
340        <&[u8; 32]>::try_from(public_key),
341        <&[u8; 64]>::try_from(signature),
342    ) else {
343        return false;
344    };
345    let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
346        return false;
347    };
348    key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature))
349        .is_ok()
350}
351
352/// A machine's key pair (Ed25519): it authenticates the machine to the
353/// relay. Its `Debug` hides the private half.
354pub struct MachineKey(ed25519_dalek::SigningKey);
355
356impl std::fmt::Debug for MachineKey {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        f.debug_struct("MachineKey").finish_non_exhaustive()
359    }
360}
361
362impl MachineKey {
363    /// A new key pair.
364    ///
365    /// # Errors
366    ///
367    /// When the system's random source fails.
368    pub fn generate() -> io::Result<Self> {
369        let mut seed = Zeroizing::new([0_u8; 32]);
370        getrandom::fill(seed.as_mut()).map_err(io::Error::other)?;
371        Ok(Self(ed25519_dalek::SigningKey::from_bytes(&seed)))
372    }
373
374    /// The key pair from its 32-byte private seed, if `seed` holds 32 bytes.
375    pub fn from_seed(seed: &[u8]) -> Option<Self> {
376        let seed: &[u8; 32] = seed.try_into().ok()?;
377        Some(Self(ed25519_dalek::SigningKey::from_bytes(seed)))
378    }
379
380    /// The private seed.
381    pub fn seed(&self) -> Zeroizing<[u8; 32]> {
382        Zeroizing::new(*self.0.as_bytes())
383    }
384
385    /// The public key, 32 bytes.
386    pub fn public_key(&self) -> Vec<u8> {
387        self.0.verifying_key().as_bytes().to_vec()
388    }
389
390    /// The signature of `message`, 64 bytes.
391    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
392        ed25519_dalek::Signer::sign(&self.0, message)
393            .to_bytes()
394            .to_vec()
395    }
396}
397
398/// A device's key pair (#158), the same kind as a machine's: each login is
399/// bound to the public half, and every request with its token is signed
400/// ([`prove`]).
401pub type DeviceKey = MachineKey;
402
403/// `request` (one with a login token), signed by `device` at `at` (Unix
404/// seconds) with a fresh nonce: what the relay takes for it (#158).
405///
406/// # Errors
407///
408/// When the request does not serialize or the random source fails.
409pub fn prove(
410    device: &DeviceKey,
411    request: &teter_common::account::AccountRequest,
412    at: i64,
413) -> io::Result<teter_common::account::AccountRequest> {
414    let request = serde_json::to_string(request).map_err(io::Error::other)?;
415    let mut nonce = vec![0_u8; teter_common::account::PROOF_NONCE_LEN];
416    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
417    let signature = device.sign(&teter_common::account::proof_bytes(&request, at, &nonce));
418    Ok(teter_common::account::AccountRequest::Proven {
419        request,
420        at,
421        nonce,
422        signature,
423    })
424}
425
426/// The fingerprint of an account's public keys: the first 16 bytes of their
427/// SHA-256. A registration token carries it, and the machine checks the
428/// keys the relay gives it against it (#86).
429pub fn fingerprint(public_keys: &[u8]) -> [u8; 16] {
430    let digest = <Sha256 as sha2::Digest>::digest(public_keys);
431    let mut fingerprint = [0_u8; 16];
432    fingerprint.copy_from_slice(digest.get(..16).unwrap_or_default());
433    fingerprint
434}
435
436/// The hash of a registration token's enrollment secret, which is all the
437/// relay keeps of it.
438pub fn secret_hash(secret: &[u8]) -> Vec<u8> {
439    <Sha256 as sha2::Digest>::digest(secret).to_vec()
440}
441
442/// What of a registration token's secret goes to the relay (#133): a key
443/// derived from it, so the relay never learns the [`registration_binding`]
444/// key, which proves to the account's device that the machine held the
445/// token.
446pub fn registration_auth(secret: &[u8]) -> Zeroizing<[u8; 32]> {
447    registration_key(secret, b"teter-reg-v1 auth")
448}
449
450/// The key a machine proves with that it held the registration token
451/// (#133); never sent anywhere.
452pub fn registration_binding(secret: &[u8]) -> Zeroizing<[u8; 32]> {
453    registration_key(secret, b"teter-reg-v1 bind")
454}
455
456fn registration_key(secret: &[u8], info: &[u8]) -> Zeroizing<[u8; 32]> {
457    let mut key = Zeroizing::new([0_u8; 32]);
458    // 32 bytes is always a valid HKDF-SHA256 length: the error never comes.
459    if Hkdf::<Sha256>::new(None, secret)
460        .expand(info, key.as_mut())
461        .is_err()
462    {
463        key.fill(0);
464    }
465    key
466}
467
468/// The machine's proof it held the token whose secret is `secret`, for its
469/// key and sealed name: HMAC-SHA256 (HKDF-Extract) under the binding key.
470pub fn binding_proof(secret: &[u8], machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
471    let key = registration_binding(secret);
472    let (prk, _) = Hkdf::<Sha256>::extract(
473        Some(key.as_ref()),
474        &teter_common::account::binding_bytes(machine_key, sealed_name),
475    );
476    prk.to_vec()
477}
478
479/// The account keys `pinned` leads to through `rotations` (#89): each one
480/// from the keys reached so far, signed by their signing key, moves on to its
481/// new keys; any other is skipped (a relay cannot forge one).
482pub fn follow_rotations(
483    pinned: &[u8],
484    rotations: &[teter_common::account::KeyRotation],
485) -> Vec<u8> {
486    let mut keys = pinned.to_vec();
487    for rotation in rotations {
488        let signed = rotation.old_keys == keys
489            && rotation.new_keys.len() == 64
490            && keys.get(32..64).is_some_and(|signing| {
491                verify(
492                    signing,
493                    &teter_common::account::rotation_bytes(
494                        &rotation.old_keys,
495                        &rotation.new_keys,
496                        rotation.at,
497                    ),
498                    &rotation.signature,
499                )
500            });
501        if signed {
502            keys.clone_from(&rotation.new_keys);
503        }
504    }
505    keys
506}
507
508/// A rotation from `old` to `new`, signed by `old` (#89).
509pub fn rotation(
510    old: &AccountKeys,
511    new: &AccountKeys,
512    at: i64,
513) -> teter_common::account::KeyRotation {
514    let (old_keys, new_keys) = (old.public_keys(), new.public_keys());
515    teter_common::account::KeyRotation {
516        signature: old.sign(&teter_common::account::rotation_bytes(
517            &old_keys, &new_keys, at,
518        )),
519        old_keys,
520        new_keys,
521        at,
522    }
523}
524
525/// Whether `cert` is the account's approval of machine `id` with
526/// `machine_key` and `sealed_name`, checked against `account_public` (the
527/// account's public keys as the device knows them from its own private
528/// keys, never as a relay gives them).
529pub fn cert_holds(
530    account_public: &[u8],
531    id: &str,
532    machine_key: &[u8],
533    sealed_name: &[u8],
534    cert: &[u8],
535) -> bool {
536    // A key of its exact length: the signed bytes join it and the name.
537    machine_key.len() == 32
538        && account_public.get(32..64).is_some_and(|signing| {
539            verify(
540                signing,
541                &teter_common::account::cert_bytes(id, machine_key, sealed_name),
542                cert,
543            )
544        })
545}
546
547#[cfg(test)]
548mod tests {
549    use super::{
550        AccountError, AccountKeys, KdfParams, derive, follow_rotations, new_salt, rotation,
551        salt_blob,
552    };
553
554    #[test]
555    fn a_machine_follows_only_rotations_signed_from_the_keys_it_holds() {
556        let first = AccountKeys::generate().unwrap();
557        let second = AccountKeys::generate().unwrap();
558        let third = AccountKeys::generate().unwrap();
559        let stranger = AccountKeys::generate().unwrap();
560        let one = rotation(&first, &second, 10);
561        let two = rotation(&second, &third, 20);
562        // A chain, in order, leads to its end; from the middle, the rest.
563        assert_eq!(
564            follow_rotations(&first.public_keys(), &[one.clone(), two.clone()]),
565            third.public_keys()
566        );
567        assert_eq!(
568            follow_rotations(&second.public_keys(), &[one.clone(), two.clone()]),
569            third.public_keys()
570        );
571        // One signed by other keys, or altered, is skipped.
572        let forged = rotation(&stranger, &stranger, 30);
573        let mut moved = one.clone();
574        moved.old_keys = stranger.public_keys();
575        let mut altered = one.clone();
576        altered.new_keys = stranger.public_keys();
577        let mut later = one.clone();
578        later.at += 1;
579        for skipped in [forged, moved, altered, later] {
580            assert_eq!(
581                follow_rotations(&first.public_keys(), &[skipped]),
582                first.public_keys()
583            );
584        }
585        // Keys no rotation starts from stay.
586        assert_eq!(
587            follow_rotations(&stranger.public_keys(), &[one, two]),
588            stranger.public_keys()
589        );
590    }
591
592    use teter_common::account::{DEFAULT_KDF, MAX_KDF};
593
594    /// The parameters new accounts get (fast in tests: Argon2 is built
595    /// optimized in the dev profile).
596    const CHEAP: KdfParams = DEFAULT_KDF;
597
598    #[test]
599    fn the_same_password_and_salt_give_the_same_keys_and_another_password_others() {
600        let salt = new_salt(CHEAP).unwrap();
601        let one = derive("correct horse", &salt).unwrap();
602        let again = derive("correct horse", &salt).unwrap();
603        let other = derive("correct horsf", &salt).unwrap();
604        assert_eq!(*one.auth_key, *again.auth_key);
605        assert_ne!(*one.auth_key, *other.auth_key);
606        assert_ne!(*one.auth_key, *one.wrap_key);
607        // Another salt, other keys.
608        let elsewhere = derive("correct horse", &new_salt(CHEAP).unwrap()).unwrap();
609        assert_ne!(*one.auth_key, *elsewhere.auth_key);
610    }
611
612    #[test]
613    fn wrapped_keys_open_with_the_password_and_name_only() {
614        let salt = new_salt(CHEAP).unwrap();
615        let derived = derive("correct horse", &salt).unwrap();
616        let keys = AccountKeys::generate().unwrap();
617        let wrapped = keys.wrap(&derived, "ana").unwrap();
618        let public = keys.public_keys();
619        let opened = AccountKeys::unwrap(&derived, "ana", &wrapped, &public).unwrap();
620        assert_eq!(*opened.private_bytes(), *keys.private_bytes());
621        let wrong = derive("wrong", &salt).unwrap();
622        assert!(matches!(
623            AccountKeys::unwrap(&wrong, "ana", &wrapped, &public),
624            Err(AccountError::WrongKeys)
625        ));
626        assert!(matches!(
627            AccountKeys::unwrap(&derived, "bia", &wrapped, &public),
628            Err(AccountError::WrongKeys)
629        ));
630        // Keys that open but are not the account's public ones.
631        let other = AccountKeys::generate().unwrap().public_keys();
632        assert!(AccountKeys::unwrap(&derived, "ana", &wrapped, &other).is_err());
633        // Nothing private in Debug.
634        assert_eq!(format!("{keys:?}"), "AccountKeys { .. }");
635    }
636
637    #[test]
638    fn a_salt_of_another_version_is_refused() {
639        let mut salt = new_salt(CHEAP).unwrap();
640        salt[0] = 9;
641        assert!(matches!(derive("x", &salt), Err(AccountError::BadSalt)));
642        assert!(matches!(
643            derive("x", &salt[..10]),
644            Err(AccountError::BadSalt)
645        ));
646    }
647
648    #[test]
649    fn a_salt_whose_cost_is_too_low_or_too_high_is_refused() {
650        let random = [7_u8; 16];
651        for params in [
652            KdfParams {
653                memory_kib: 8,
654                passes: 1,
655                lanes: 1,
656            },
657            KdfParams {
658                passes: 1,
659                ..DEFAULT_KDF
660            },
661            KdfParams {
662                memory_kib: MAX_KDF.memory_kib + 1,
663                ..DEFAULT_KDF
664            },
665            KdfParams {
666                passes: u32::MAX,
667                ..DEFAULT_KDF
668            },
669            KdfParams {
670                lanes: 0,
671                ..DEFAULT_KDF
672            },
673        ] {
674            assert!(
675                matches!(
676                    derive("x", &salt_blob(params, &random)),
677                    Err(AccountError::Kdf(_))
678                ),
679                "{params:?}"
680            );
681        }
682    }
683
684    #[test]
685    fn what_is_sealed_to_an_account_opens_with_its_keys_and_info_only() {
686        use super::{MachineKey, seal_to};
687
688        let keys = AccountKeys::generate().unwrap();
689        let sealed = seal_to(&keys.public_keys(), b"machine name", b"jupiter").unwrap();
690        assert_eq!(
691            keys.open_sealed(b"machine name", &sealed)
692                .unwrap()
693                .as_slice(),
694            b"jupiter"
695        );
696        assert!(keys.open_sealed(b"session key", &sealed).is_err());
697        let other = AccountKeys::generate().unwrap();
698        assert!(other.open_sealed(b"machine name", &sealed).is_err());
699        // A machine key signs, and keeps its seed.
700        let machine = MachineKey::generate().unwrap();
701        let again = MachineKey::from_seed(machine.seed().as_ref()).unwrap();
702        assert_eq!(machine.public_key(), again.public_key());
703        assert_eq!(machine.sign(b"x").len(), 64);
704        assert_eq!(format!("{machine:?}"), "MachineKey { .. }");
705    }
706
707    #[test]
708    fn a_proven_request_carries_the_request_and_verifies_under_the_device_key() {
709        use super::{DeviceKey, prove, verify};
710        use teter_common::account::{AccountRequest, proof_bytes};
711
712        let device = DeviceKey::generate().unwrap();
713        let inner = AccountRequest::MachineList {
714            login: "tok".into(),
715        };
716        let AccountRequest::Proven {
717            request,
718            at,
719            nonce,
720            signature,
721        } = prove(&device, &inner, 42).unwrap()
722        else {
723            panic!("not proven");
724        };
725        assert_eq!(at, 42);
726        assert_eq!(
727            serde_json::from_str::<AccountRequest>(&request).unwrap(),
728            inner
729        );
730        let bytes = proof_bytes(&request, at, &nonce);
731        assert!(verify(&device.public_key(), &bytes, &signature));
732        let other = DeviceKey::generate().unwrap();
733        assert!(!verify(&other.public_key(), &bytes, &signature));
734        // Each proof has its own nonce.
735        let AccountRequest::Proven { nonce: again, .. } = prove(&device, &inner, 42).unwrap()
736        else {
737            panic!("not proven");
738        };
739        assert_ne!(nonce, again);
740    }
741}