Skip to main content

coqui_peer/
store.rs

1use alloc::collections::VecDeque;
2use alloc::sync::Arc;
3use core::fmt;
4use core::net::{IpAddr, Ipv6Addr, SocketAddr};
5use core::str::FromStr;
6use core::time::Duration;
7use std::fs::{self, OpenOptions};
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::{Mutex, PoisonError};
11use std::time::{Instant, SystemTime};
12
13use data_encoding::{HEXLOWER, HEXLOWER_PERMISSIVE};
14use sha2::{Digest as _, Sha256};
15
16use crate::clock::{Clock, from_unix_seconds, unix_seconds};
17use crate::error::Error;
18use crate::file::{self, Access};
19use crate::id::PeerId;
20use crate::key::KeyMaterial;
21use crate::pem;
22use crate::random::Random;
23use crate::waiting::WaitingQueue;
24
25/// The version of the on-disk format [`TrustStore`] writes and reads.
26pub const FORMAT_VERSION: u32 = 1;
27
28/// The longest invitation label, in bytes.
29pub const MAX_LABEL: usize = 128;
30
31/// Rotation events kept for [`TrustStore::take_rotation_events`]; older ones are dropped.
32const MAX_EVENTS: usize = 1024;
33
34/// The IPv6 prefix length a waiting source is grouped by, unless the store is given another:
35/// one /64 is the usual end-site subnet, and its holder can use any address in it.
36pub(crate) const DEFAULT_IPV6_PREFIX: u8 = 64;
37
38/// Bounds on the waiting queue.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct WaitingLimits {
41    /// Entries one source may hold; the oldest of its own is replaced. A source is an IPv4
42    /// address, or an IPv6 prefix ([`TrustStore::with_ipv6_prefix`], /64 by default).
43    pub per_source: usize,
44    /// Entries the whole directory may hold; past it nothing is recorded.
45    pub total: usize,
46    /// How long the same peer from the same source is not recorded again.
47    pub rerecord: Duration,
48}
49
50impl Default for WaitingLimits {
51    fn default() -> Self {
52        Self {
53            per_source: 16,
54            total: 1_000,
55            rerecord: Duration::from_secs(60),
56        }
57    }
58}
59
60/// How an accepted peer's key is replaced by its successor.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct RotationOptions {
63    /// How long the old key stays accepted once its successor is promoted. Default 24 hours.
64    pub retire_after: Duration,
65    /// Whether a successor waits for [`TrustStore::promote_successor`] instead of being
66    /// promoted by the method the first time the peer proves it. Default `false`.
67    pub require_approval: bool,
68    /// Whether [`TrustStore::promote_successor`] promotes a successor nobody proved
69    /// ([`TrustStore::prove_successor`]): the old key's holder then vouches alone for a key
70    /// that may not be its own. Default `false`.
71    pub allow_unproven: bool,
72}
73
74impl Default for RotationOptions {
75    fn default() -> Self {
76        Self {
77            retire_after: Duration::from_secs(24 * 3600),
78            require_approval: false,
79            allow_unproven: false,
80        }
81    }
82}
83
84/// How [`TrustStore::invite`] makes an invitation.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct InvitationOptions {
87    /// How long the invitation can be redeemed, in whole seconds. Default 24 hours; zero is an
88    /// error.
89    pub valid_for: Duration,
90    /// How many times it can be redeemed. Default 1; zero is an error.
91    pub uses: u32,
92}
93
94impl Default for InvitationOptions {
95    fn default() -> Self {
96        Self {
97            valid_for: Duration::from_secs(24 * 3600),
98            uses: 1,
99        }
100    }
101}
102
103/// A peer waiting for acceptance.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub struct WaitingEntry {
106    /// The peer's id.
107    pub id: PeerId,
108    /// The address the handshake came from; `None` when the caller did not know it.
109    pub source: Option<SocketAddr>,
110}
111
112/// The id of an invitation: the SHA-256 of its secret, and the name of its file. Knowing it
113/// does not let anyone redeem the invitation.
114#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
115pub struct InvitationId([u8; 32]);
116
117impl InvitationId {
118    /// The id of the invitation whose secret is `secret`.
119    pub fn of(secret: &[u8; 32]) -> Self {
120        Self(Sha256::digest(secret).into())
121    }
122
123    /// 64 lowercase hexadecimal characters.
124    pub fn hex(&self) -> String {
125        HEXLOWER.encode(&self.0)
126    }
127}
128
129impl fmt::Display for InvitationId {
130    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
131        formatter.write_str(&self.hex())
132    }
133}
134
135impl fmt::Debug for InvitationId {
136    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
137        write!(formatter, "InvitationId({})", self.hex())
138    }
139}
140
141impl FromStr for InvitationId {
142    type Err = Error;
143
144    /// 64 hexadecimal characters.
145    fn from_str(text: &str) -> Result<Self, Error> {
146        let text = text.trim();
147        let mut bytes = [0u8; 32];
148        if text.len() != 64 {
149            return Err(Error::InvalidId);
150        }
151        HEXLOWER_PERMISSIVE
152            .decode_mut(text.as_bytes(), &mut bytes)
153            .map_err(|_| Error::InvalidId)?;
154        Ok(Self(bytes))
155    }
156}
157
158/// A one-time pairing secret: whoever presents it may pair, until it expires or its uses run
159/// out.
160///
161/// The store keeps only the [`id`](Invitation::id), never the secret: the caller hands the
162/// secret to the joiner (a link or QR code, with the inviter's id). `Debug` does not show it.
163#[derive(Clone, PartialEq, Eq)]
164pub struct Invitation {
165    /// The secret, 32 random bytes.
166    pub secret: [u8; 32],
167    /// When it stops being redeemable.
168    pub expires: SystemTime,
169    /// Redemptions left: as made by [`TrustStore::invite`], or after this one by
170    /// [`TrustStore::redeem`].
171    pub uses: u32,
172    /// The inviter's note on whom it is for, one line of at most [`MAX_LABEL`] bytes.
173    pub label: String,
174}
175
176impl Invitation {
177    /// The invitation's id.
178    pub fn id(&self) -> InvitationId {
179        InvitationId::of(&self.secret)
180    }
181}
182
183impl Drop for Invitation {
184    fn drop(&mut self) {
185        zeroize::Zeroize::zeroize(&mut self.secret);
186    }
187}
188
189impl fmt::Debug for Invitation {
190    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
191        formatter
192            .debug_struct("Invitation")
193            .field("id", &self.id())
194            .field("expires", &self.expires)
195            .field("uses", &self.uses)
196            .field("label", &self.label)
197            .finish_non_exhaustive()
198    }
199}
200
201/// An open invitation, as listed: everything but the secret.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct InvitationEntry {
204    /// Its id.
205    pub id: InvitationId,
206    /// When it stops being redeemable.
207    pub expires: SystemTime,
208    /// Redemptions left.
209    pub uses: u32,
210    /// The inviter's note.
211    pub label: String,
212}
213
214/// A pending successor: `new` was announced by the peer accepted as `old`, and is accepted once
215/// the peer proves it (or the caller promotes it).
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217pub struct Successor {
218    /// The accepted key that announced it.
219    pub old: PeerId,
220    /// The announced key.
221    pub new: PeerId,
222    /// When its holder proved it in a handshake ([`TrustStore::prove_successor`]), if yet.
223    pub proven: Option<SystemTime>,
224}
225
226/// An accepted key with a retirement time: it is refused from `retires` on.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub struct Retiring {
229    /// The retiring key.
230    pub id: PeerId,
231    /// The key that replaced it, when it was replaced by rotation.
232    pub successor: Option<PeerId>,
233    /// When it stops being accepted.
234    pub retires: SystemTime,
235}
236
237/// A change of a peer's key, for the caller to report as it chooses.
238#[derive(Debug, Clone, Copy, PartialEq, Eq)]
239#[non_exhaustive]
240pub enum RotationEvent {
241    /// The peer accepted as `old` announced `new` as its successor.
242    Announced {
243        /// The announcing key.
244        old: PeerId,
245        /// The announced key.
246        new: PeerId,
247    },
248    /// `new` was promoted: it is accepted, and `old` retires at `retires`.
249    Promoted {
250        /// The replaced key.
251        old: PeerId,
252        /// The key now accepted.
253        new: PeerId,
254        /// When `old` stops being accepted.
255        retires: SystemTime,
256    },
257}
258
259/// Persistent trust: peers an operator accepted, peers that were turned away and wait to be
260/// accepted (pairing), open invitations, and announced successor keys.
261///
262/// # Pairing
263///
264/// 1. A server turns away a peer it does not trust, **after the peer proved it holds the
265///    key it presented**, and records its key with [`record_waiting`](TrustStore::record_waiting).
266/// 2. The operator lists [`waiting`](TrustStore::waiting) and either
267///    [`accept`](TrustStore::accept)s an entry by id or [`remove`](TrustStore::remove)s it.
268/// 3. The next handshake finds the peer [`is_accepted`](TrustStore::is_accepted).
269///
270/// **Every method must meet this contract:** nothing is recorded as waiting until the peer
271/// has shown, inside the handshake, that it holds the private key of the public key it
272/// presents (a signature over the handshake transcript, a key exchange that only the key's
273/// holder can complete, ...). Presenting a key proves nothing: anyone can copy a public
274/// certificate, and a store that records unproven keys lets a stranger fill the queue with
275/// somebody else's identity, or put a real peer's id in front of the operator under a source
276/// address that is not theirs. A handshake that fails to prove the key records nothing.
277///
278/// An [`invitation`](TrustStore::invite) lets a joiner pair without waiting: it presents the
279/// secret over a channel that proves its key, and the inviter [`redeem`](TrustStore::redeem)s
280/// it and accepts the key.
281///
282/// # Rotation
283///
284/// A peer accepted as key A announces its successor B over a session A authenticated
285/// ([`announce_successor`](TrustStore::announce_successor)). The first time the peer proves B
286/// in a handshake, the method [`promote_successor`](TrustStore::promote_successor)s it, unless
287/// [`RotationOptions::require_approval`] leaves that to the caller; A is then accepted until
288/// [`RotationOptions::retire_after`] has passed, and refused from then on. Removing A removes
289/// its pending successor. Each step is queued as a [`RotationEvent`].
290///
291/// # Key material and methods
292///
293/// The store keeps the bytes a method hands it as a [`KeyMaterial`] and never interprets
294/// them: a PEM certificate for `tls`, another method's own key for it. Each file records the
295/// method name, so a store can hold the keys of several methods side by side, and a method
296/// reads only the entries that name it. The id of an entry is the SHA-256 of its bytes; the
297/// store checks that when it reads a file.
298///
299/// # On-disk format (version 1)
300///
301/// Under `<state_dir>/peers/`:
302///
303/// ```text
304/// accepted/<64 lowercase hex>.pem     one PEM block; the name is the peer's id
305/// waiting/<64 lowercase hex>.pem      the same, for a peer that proved its key and was refused
306/// successors/<64 lowercase hex>.pem   an announced successor key, named by its id
307/// invitations/<64 lowercase hex>.inv  an open invitation, named by the SHA-256 of its secret
308/// ```
309///
310/// Before the PEM block a file may hold header lines (PEM allows explanatory text there):
311/// `Method: <name>`; in a waiting file `Source: <ip>:<port>` (IPv6 as `[addr]:port`), the
312/// address the handshake came from; in an accepted file `Successor: <64 hex>` (the announced
313/// or promoting successor) and `Retires: <unix seconds>`; in a successor file
314/// `Predecessor: <64 hex>`. An invitation file is header lines only: `Expires: <unix
315/// seconds>`, `Uses: <count>` and, when not empty, `Label: <text>`; it never holds the
316/// secret. A key file without a `Method:` line, or named otherwise, is not read. Accepting moves a file from `waiting/` to
317/// `accepted/`, rewritten without the `Source:` line.
318#[derive(Debug, Clone)]
319pub struct TrustStore {
320    root: PathBuf,
321    waiting: Arc<Mutex<WaitingQueue>>,
322    events: Arc<Mutex<VecDeque<RotationEvent>>>,
323    clock: Clock,
324    rotation: RotationOptions,
325}
326
327/// What a store file holds.
328struct Entry {
329    key: KeyMaterial,
330    source: Option<SocketAddr>,
331    successor: Option<PeerId>,
332    retires: Option<u64>,
333    predecessor: Option<PeerId>,
334    proven: Option<u64>,
335}
336
337impl TrustStore {
338    /// Opens (creating when absent) the store under `<state_dir>/peers`.
339    ///
340    /// # Errors
341    ///
342    /// [`Error::Io`] when the directories cannot be created.
343    pub fn open(state_dir: &Path) -> Result<Self, Error> {
344        let root = state_dir.join("peers");
345        fs::create_dir_all(root.join("accepted")).map_err(Error::Io)?;
346        fs::create_dir_all(root.join("waiting")).map_err(Error::Io)?;
347        Ok(Self {
348            root,
349            waiting: Arc::new(Mutex::new(WaitingQueue::new(WaitingLimits::default()))),
350            events: Arc::default(),
351            clock: Clock::system(),
352            rotation: RotationOptions::default(),
353        })
354    }
355
356    /// This store with other bounds on its waiting queue (the default: 16 per source, 1000 in
357    /// all, 60 seconds).
358    #[must_use]
359    pub fn with_limits(mut self, limits: WaitingLimits) -> Self {
360        let prefix = self.queue().ipv6_prefix();
361        self.waiting = Arc::new(Mutex::new(
362            WaitingQueue::new(limits).with_ipv6_prefix(prefix),
363        ));
364        self
365    }
366
367    /// This store with IPv6 sources grouped by their first `bits` bits for the per-source
368    /// limits (64 unless set). 128 counts each address alone, which lets the holder of a
369    /// subnet fill the queue; values above 128 are 128. IPv4 sources, IPv4-mapped IPv6 ones
370    /// included, always count per address.
371    #[must_use]
372    pub fn with_ipv6_prefix(mut self, bits: u8) -> Self {
373        let limits = self.queue().limits();
374        self.waiting = Arc::new(Mutex::new(WaitingQueue::new(limits).with_ipv6_prefix(bits)));
375        self
376    }
377
378    /// The waiting queue's bounds and what this process recorded.
379    fn queue(&self) -> std::sync::MutexGuard<'_, WaitingQueue> {
380        self.waiting.lock().unwrap_or_else(PoisonError::into_inner)
381    }
382
383    /// This store reading `clock` for invitation expiry and key retirement (the system clock
384    /// unless set).
385    #[must_use]
386    pub fn with_clock(mut self, clock: Clock) -> Self {
387        self.clock = clock;
388        self
389    }
390
391    /// This store rotating keys by `options` (24 hours, automatic, unless set).
392    #[must_use]
393    pub fn with_rotation(mut self, options: RotationOptions) -> Self {
394        self.rotation = options;
395        self
396    }
397
398    /// The rotation options in force.
399    pub fn rotation(&self) -> RotationOptions {
400        self.rotation
401    }
402
403    /// The clock in force.
404    pub fn clock(&self) -> &Clock {
405        &self.clock
406    }
407
408    /// Peers awaiting operator acceptance, sorted by id, each with the address it connected
409    /// from. Every entry proved it holds its key.
410    ///
411    /// # Errors
412    ///
413    /// [`Error::Io`] when the directory cannot be read.
414    pub fn waiting(&self) -> Result<Vec<WaitingEntry>, Error> {
415        Ok(self
416            .list("waiting")?
417            .into_iter()
418            .map(|id| WaitingEntry {
419                id,
420                source: self.read("waiting", &id).and_then(|entry| entry.source),
421            })
422            .collect())
423    }
424
425    /// Accepted ids, sorted; a key past its retirement time is not listed.
426    ///
427    /// # Errors
428    ///
429    /// [`Error::Io`] when the directory cannot be read.
430    pub fn accepted(&self) -> Result<Vec<PeerId>, Error> {
431        Ok(self
432            .list("accepted")?
433            .into_iter()
434            .filter(|id| self.current(id).is_some())
435            .collect())
436    }
437
438    /// The key material of an accepted peer, when it is accepted, not retired, and its file is
439    /// sound.
440    pub fn accepted_key(&self, id: &PeerId) -> Option<KeyMaterial> {
441        self.current(id).map(|entry| entry.key)
442    }
443
444    /// The key material of a waiting peer, when it is waiting and its file is sound.
445    pub fn waiting_key(&self, id: &PeerId) -> Option<KeyMaterial> {
446        self.read("waiting", id).map(|entry| entry.key)
447    }
448
449    /// Accepts a waiting peer by its id.
450    ///
451    /// # Errors
452    ///
453    /// [`Error::NotWaiting`], [`Error::AlreadyAccepted`], or [`Error::Material`] when the
454    /// stored key does not hash to the name.
455    pub fn accept(&self, id: &PeerId) -> Result<(), Error> {
456        if self.is_accepted(id) {
457            return Err(Error::AlreadyAccepted);
458        }
459        let path = self.existing("waiting", id).ok_or(Error::NotWaiting)?;
460        let text = fs::read_to_string(&path).map_err(|error| {
461            if error.kind() == io::ErrorKind::NotFound {
462                Error::NotWaiting
463            } else {
464                Error::Io(error)
465            }
466        })?;
467        let entry = parse(&text).ok_or(Error::Material)?;
468        if entry.key.id() != *id {
469            return Err(Error::Material);
470        }
471        self.write_current(&entry.key)?;
472        let _ = fs::remove_file(path);
473        Ok(())
474    }
475
476    /// Accepts a key directly, without it having waited.
477    ///
478    /// # Errors
479    ///
480    /// [`Error::Material`] when the key is not valid, [`Error::AlreadyAccepted`] when it is
481    /// accepted and current, [`Error::Io`] on write failure. A key past its retirement time is
482    /// accepted again, its file rewritten without `Successor:` and `Retires:`.
483    pub fn accept_key(&self, key: &KeyMaterial) -> Result<PeerId, Error> {
484        key.check()?;
485        let id = key.id();
486        self.write_current(key)?;
487        let _ = fs::remove_file(self.path("waiting", &id));
488        Ok(id)
489    }
490
491    /// Removes an accepted, waiting or pending-successor peer, and the pending successor an
492    /// accepted one announced; `true` when something was removed.
493    ///
494    /// # Errors
495    ///
496    /// [`Error::Io`] when a file cannot be removed.
497    pub fn remove(&self, id: &PeerId) -> Result<bool, Error> {
498        let mut removed = false;
499        if let Some(successor) = self.read("accepted", id).and_then(|entry| entry.successor)
500            && self
501                .read("successors", &successor)
502                .is_some_and(|entry| entry.predecessor == Some(*id))
503        {
504            fs::remove_file(self.path("successors", &successor)).map_err(Error::Io)?;
505        }
506        for section in ["accepted", "waiting", "successors"] {
507            if let Some(path) = self.existing(section, id) {
508                fs::remove_file(path).map_err(Error::Io)?;
509                removed = true;
510            }
511        }
512        Ok(removed)
513    }
514
515    /// Whether `id` is accepted, not past its retirement time, and its stored key really hashes
516    /// to it.
517    pub fn is_accepted(&self, id: &PeerId) -> bool {
518        self.current(id).is_some()
519    }
520
521    /// Records a turned-away peer's key as waiting. Failures are not reported to the peer.
522    ///
523    /// **Call this only after the peer proved it holds the key** (see the
524    /// [pairing contract](TrustStore#pairing)).
525    ///
526    /// Bounded: invalid keys are ignored; one source holds at most
527    /// [`per_source`](WaitingLimits::per_source) entries (its oldest is replaced); the same
528    /// peer from the same source is recorded at most once per
529    /// [`rerecord`](WaitingLimits::rerecord); the directory holds at most
530    /// [`total`](WaitingLimits::total). A source is an IPv4 address (IPv4-mapped IPv6 included)
531    /// or an IPv6 prefix of [`with_ipv6_prefix`](TrustStore::with_ipv6_prefix) bits, /64 by
532    /// default. The full `source` address is stored with the entry. `None` is the source of
533    /// callers that do not know it, which share one bucket.
534    pub fn record_waiting(&self, key: &KeyMaterial, source: Option<SocketAddr>) {
535        if key.check().is_err() {
536            return;
537        }
538        let id = key.id();
539        if self.existing("waiting", &id).is_some() {
540            return;
541        }
542        let Ok(stored) = self.list("waiting") else {
543            return;
544        };
545        let now = Instant::now();
546        let mut queue = self.queue();
547        // Another process (an operator's command) may have accepted or removed entries.
548        queue.prune(now, |had| stored.binary_search(had).is_ok());
549        let admission = queue.admit(id, source, stored.len(), now);
550        if !admission.record {
551            return;
552        }
553        for old in &admission.evict {
554            let _ = fs::remove_file(self.path("waiting", old));
555        }
556        let mut text = source.map_or_else(String::new, |s| format!("Source: {s}\n"));
557        text.push_str(&format!("Method: {}\n", key.method));
558        text.push_str(&pem::encode(&key.label, &key.bytes));
559        let _ = write_new(&self.path("waiting", &id), &text);
560    }
561
562    /// Makes an invitation with a secret from `random` and records it (without the secret).
563    ///
564    /// # Errors
565    ///
566    /// [`Error::InvalidOptions`] when `label` is not one line of at most [`MAX_LABEL`]
567    /// bytes without surrounding spaces, `uses` is 0 or `valid_for` is zero;
568    /// [`Error::Random`] when `random` fails; [`Error::Io`] when the file cannot be written.
569    pub fn invite(
570        &self,
571        random: &Random,
572        options: InvitationOptions,
573        label: &str,
574    ) -> Result<Invitation, Error> {
575        let label_ok = label.len() <= MAX_LABEL
576            && label.trim() == label
577            && !label.chars().any(char::is_control);
578        if !label_ok || options.uses == 0 || options.valid_for.is_zero() {
579            return Err(Error::InvalidOptions);
580        }
581        let mut secret = [0u8; 32];
582        random.fill(&mut secret)?;
583        let expires = from_unix_seconds(
584            unix_seconds(self.clock.now()).saturating_add(options.valid_for.as_secs()),
585        );
586        let invitation = Invitation {
587            secret,
588            expires,
589            uses: options.uses,
590            label: label.to_owned(),
591        };
592        fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
593        write_new(
594            &self.invitation_path(&invitation.id()),
595            &invitation_text(expires, options.uses, label),
596        )
597        .map_err(Error::Io)?;
598        Ok(invitation)
599    }
600
601    /// Redeems an invitation by its secret, using one of its uses: the invitation with the uses
602    /// left after this one. The last use removes it.
603    ///
604    /// Atomic: of concurrent redemptions of a single-use invitation exactly one succeeds. An
605    /// expired invitation is removed.
606    ///
607    /// # Errors
608    ///
609    /// [`Error::NotInvited`] when no open invitation has this secret, [`Error::Expired`] when
610    /// it expired, [`Error::Io`] when its file cannot be read or moved.
611    pub fn redeem(&self, secret: &[u8; 32]) -> Result<Invitation, Error> {
612        let path = self.invitation_path(&InvitationId::of(secret));
613        let claimed = file::temporary_path(&path);
614        // Renaming is the claim: only one redeemer can move the file away.
615        if let Err(error) = fs::rename(&path, &claimed) {
616            return Err(if error.kind() == io::ErrorKind::NotFound {
617                Error::NotInvited
618            } else {
619                Error::Io(error)
620            });
621        }
622        let text = fs::read_to_string(&claimed).ok();
623        // Removing the claimed file decides the claim. A rename is not enough: on Windows a
624        // redeemer that opened the file before another moved it can still move it again, but a
625        // file is removed only once.
626        if file::retried(|| fs::remove_file(&claimed)).is_err() {
627            return Err(Error::NotInvited);
628        }
629        let (expires, uses, label) = text
630            .as_deref()
631            .and_then(parse_invitation)
632            .ok_or(Error::NotInvited)?;
633        let revoked = self.revoked_path(&InvitationId::of(secret));
634        if revoked.exists() {
635            return Err(Error::NotInvited);
636        }
637        if self.clock.now() >= from_unix_seconds(expires) {
638            return Err(Error::Expired);
639        }
640        let left = uses - 1;
641        if left > 0 {
642            // Losing the remaining uses on a write failure fails closed.
643            let _ = write_new(
644                &path,
645                &invitation_text(from_unix_seconds(expires), left, &label),
646            );
647            // A revocation that came while the file was claimed wins: either it sees this
648            // file and removes it, or this sees its record and does.
649            if revoked.exists() {
650                let _ = fs::remove_file(&path);
651                return Err(Error::NotInvited);
652            }
653        }
654        Ok(Invitation {
655            secret: *secret,
656            expires: from_unix_seconds(expires),
657            uses: left,
658            label,
659        })
660    }
661
662    /// The open invitations, sorted by id, expired ones included until redeemed or revoked.
663    ///
664    /// # Errors
665    ///
666    /// [`Error::Io`] when the directory cannot be read.
667    pub fn invitations(&self) -> Result<Vec<InvitationEntry>, Error> {
668        let directory = self.root.join("invitations");
669        let entries = match fs::read_dir(&directory) {
670            Ok(entries) => entries,
671            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
672            Err(error) => return Err(Error::Io(error)),
673        };
674        let mut found = Vec::new();
675        for entry in entries {
676            let path = entry.map_err(Error::Io)?.path();
677            let Some(id) = path
678                .extension()
679                .filter(|extension| *extension == "inv")
680                .and_then(|_| path.file_stem())
681                .and_then(|stem| stem.to_str())
682                .filter(|stem| is_hex_name(stem))
683                .and_then(|stem| stem.parse::<InvitationId>().ok())
684            else {
685                continue;
686            };
687            if let Some((expires, uses, label)) = fs::read_to_string(&path)
688                .ok()
689                .as_deref()
690                .and_then(parse_invitation)
691            {
692                found.push(InvitationEntry {
693                    id,
694                    expires: from_unix_seconds(expires),
695                    uses,
696                    label,
697                });
698            }
699        }
700        found.sort_by_key(|entry| entry.id);
701        Ok(found)
702    }
703
704    /// Revokes an invitation; `true` when it was open. A redemption in flight when it is
705    /// revoked fails, and its remaining uses are not restored: a `<64 hex>.revoked` file
706    /// records the revocation before the invitation file goes.
707    ///
708    /// # Errors
709    ///
710    /// [`Error::Io`] when the revocation cannot be recorded or the file removed.
711    pub fn revoke_invitation(&self, id: &InvitationId) -> Result<bool, Error> {
712        fs::create_dir_all(self.root.join("invitations")).map_err(Error::Io)?;
713        OpenOptions::new()
714            .create(true)
715            .truncate(false)
716            .write(true)
717            .open(self.revoked_path(id))
718            .map_err(Error::Io)?;
719        match file::retried(|| fs::remove_file(self.invitation_path(id))) {
720            Ok(()) => Ok(true),
721            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(false),
722            Err(error) => Err(Error::Io(error)),
723        }
724    }
725
726    /// Records `new` as the pending successor of the accepted key `old`, replacing a successor
727    /// `old` announced before. Call it only with a key the holder of `old` sent over a session
728    /// `old` authenticated.
729    ///
730    /// # Errors
731    ///
732    /// [`Error::NotAccepted`] when `old` is not accepted or is already retiring;
733    /// [`Error::AlreadyAccepted`] when `new` is accepted; [`Error::SuccessorTaken`] when `new` is
734    /// the pending successor of another key that is still accepted; [`Error::Material`] when `new` is not
735    /// valid or is `old`; [`Error::Io`] on write failure.
736    pub fn announce_successor(&self, old: &PeerId, new: &KeyMaterial) -> Result<(), Error> {
737        new.check()?;
738        let new_id = new.id();
739        if new_id == *old {
740            return Err(Error::Material);
741        }
742        let entry = self
743            .current(old)
744            .filter(|entry| entry.retires.is_none())
745            .ok_or(Error::NotAccepted)?;
746        if self.existing("accepted", &new_id).is_some() {
747            return Err(Error::AlreadyAccepted);
748        }
749        // Another accepted key that announced `new` keeps it: overwriting would let a peer that
750        // learned someone else's successor claim it, and promoting it would retire the wrong key.
751        if self.successor_key(&new_id).is_some()
752            && self
753                .read("successors", &new_id)
754                .and_then(|pending| pending.predecessor)
755                .is_some_and(|predecessor| predecessor != *old)
756        {
757            return Err(Error::SuccessorTaken);
758        }
759        if let Some(previous) = entry.successor
760            && previous != new_id
761            && self
762                .read("successors", &previous)
763                .is_some_and(|pending| pending.predecessor == Some(*old))
764        {
765            let _ = fs::remove_file(self.path("successors", &previous));
766        }
767        fs::create_dir_all(self.root.join("successors")).map_err(Error::Io)?;
768        let text = format!(
769            "Predecessor: {}\nMethod: {}\n{}",
770            old.hex(),
771            new.method,
772            pem::encode(&new.label, &new.bytes)
773        );
774        replace(&self.path("successors", &new_id), &text).map_err(Error::Io)?;
775        let path = self.existing("accepted", old).ok_or(Error::NotAccepted)?;
776        replace(&path, &accepted_text(&entry.key, Some(&new_id), None)).map_err(Error::Io)?;
777        self.push_event(RotationEvent::Announced {
778            old: *old,
779            new: new_id,
780        });
781        Ok(())
782    }
783
784    /// The key of `new` when it is the pending successor of a key that is still accepted, not
785    /// retiring, and names it.
786    pub fn successor_key(&self, new: &PeerId) -> Option<KeyMaterial> {
787        let pending = self.read("successors", new)?;
788        let old = pending.predecessor?;
789        self.current(&old)
790            .filter(|entry| entry.retires.is_none() && entry.successor == Some(*new))
791            .map(|_| pending.key)
792    }
793
794    /// Records that the holder of the pending successor `new` proved it in a handshake (a
795    /// `Proven:` line with the time). A method calls it after the handshake signature verifies,
796    /// whether or not it then promotes. The first proof's time is kept.
797    ///
798    /// # Errors
799    ///
800    /// [`Error::NoSuccessor`] when `new` is not the pending successor of an accepted key;
801    /// [`Error::Io`] on write failure.
802    pub fn prove_successor(&self, new: &PeerId) -> Result<(), Error> {
803        let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
804        let pending = self.read("successors", new).ok_or(Error::NoSuccessor)?;
805        if pending.proven.is_some() {
806            return Ok(());
807        }
808        let old = pending.predecessor.ok_or(Error::NoSuccessor)?;
809        let text = format!(
810            "Predecessor: {}
811Method: {}
812Proven: {}
813{}",
814            old.hex(),
815            key.method,
816            unix_seconds(self.clock.now()),
817            pem::encode(&key.label, &key.bytes)
818        );
819        replace(&self.path("successors", new), &text).map_err(Error::Io)
820    }
821
822    /// Accepts the pending successor `new` and gives its predecessor a retirement time
823    /// ([`RotationOptions::retire_after`] from now). Returns the predecessor's id. A method calls
824    /// it once the peer proved `new`, unless [`RotationOptions::require_approval`] is set; the
825    /// caller calls it to approve.
826    ///
827    /// # Errors
828    ///
829    /// [`Error::NoSuccessor`] when `new` is not the pending successor of an accepted key;
830    /// [`Error::NotProven`] when nobody proved it and [`RotationOptions::allow_unproven`] is not
831    /// set; [`Error::Io`] on write failure.
832    pub fn promote_successor(&self, new: &PeerId) -> Result<PeerId, Error> {
833        let key = self.successor_key(new).ok_or(Error::NoSuccessor)?;
834        if !self.rotation.allow_unproven
835            && self
836                .read("successors", new)
837                .is_none_or(|pending| pending.proven.is_none())
838        {
839            return Err(Error::NotProven);
840        }
841        let old = self
842            .read("successors", new)
843            .and_then(|entry| entry.predecessor)
844            .ok_or(Error::NoSuccessor)?;
845        let old_entry = self.current(&old).ok_or(Error::NoSuccessor)?;
846        match self.write_accepted(&key) {
847            Ok(()) | Err(Error::AlreadyAccepted) => {}
848            Err(error) => return Err(error),
849        }
850        let retires =
851            unix_seconds(self.clock.now()).saturating_add(self.rotation.retire_after.as_secs());
852        let path = self.existing("accepted", &old).ok_or(Error::NoSuccessor)?;
853        replace(
854            &path,
855            &accepted_text(&old_entry.key, Some(new), Some(retires)),
856        )
857        .map_err(Error::Io)?;
858        let _ = fs::remove_file(self.path("successors", new));
859        self.push_event(RotationEvent::Promoted {
860            old,
861            new: *new,
862            retires: from_unix_seconds(retires),
863        });
864        Ok(old)
865    }
866
867    /// The pending successors, sorted by the new key's id.
868    ///
869    /// # Errors
870    ///
871    /// [`Error::Io`] when the directory cannot be read.
872    pub fn successors(&self) -> Result<Vec<Successor>, Error> {
873        Ok(self
874            .list("successors")?
875            .into_iter()
876            .filter(|new| self.successor_key(new).is_some())
877            .filter_map(|new| {
878                let pending = self.read("successors", &new)?;
879                Some(Successor {
880                    old: pending.predecessor?,
881                    new,
882                    proven: pending.proven.map(from_unix_seconds),
883                })
884            })
885            .collect())
886    }
887
888    /// Accepted keys with a retirement time, sorted by id, those already retired included.
889    ///
890    /// # Errors
891    ///
892    /// [`Error::Io`] when the directory cannot be read.
893    pub fn retiring(&self) -> Result<Vec<Retiring>, Error> {
894        Ok(self
895            .list("accepted")?
896            .into_iter()
897            .filter_map(|id| {
898                let entry = self.read("accepted", &id)?;
899                Some(Retiring {
900                    id,
901                    successor: entry.successor,
902                    retires: from_unix_seconds(entry.retires?),
903                })
904            })
905            .collect())
906    }
907
908    /// The rotation events since the last call, oldest first. Only events of this process are
909    /// kept, at most 1024; the on-disk state is in [`successors`](TrustStore::successors) and
910    /// [`retiring`](TrustStore::retiring).
911    pub fn take_rotation_events(&self) -> Vec<RotationEvent> {
912        self.events
913            .lock()
914            .unwrap_or_else(PoisonError::into_inner)
915            .drain(..)
916            .collect()
917    }
918
919    fn push_event(&self, event: RotationEvent) {
920        let mut events = self.events.lock().unwrap_or_else(PoisonError::into_inner);
921        if events.len() >= MAX_EVENTS {
922            events.pop_front();
923        }
924        events.push_back(event);
925    }
926
927    /// Writes `key` as accepted and current: new, or over a retired file.
928    fn write_current(&self, key: &KeyMaterial) -> Result<(), Error> {
929        if self.is_accepted(&key.id()) {
930            return Err(Error::AlreadyAccepted);
931        }
932        match self.existing("accepted", &key.id()) {
933            Some(path) => replace(&path, &accepted_text(key, None, None)).map_err(Error::Io),
934            None => self.write_accepted(key),
935        }
936    }
937
938    fn write_accepted(&self, key: &KeyMaterial) -> Result<(), Error> {
939        match write_new(
940            &self.path("accepted", &key.id()),
941            &accepted_text(key, None, None),
942        ) {
943            Ok(()) => Ok(()),
944            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
945                Err(Error::AlreadyAccepted)
946            }
947            Err(error) => Err(Error::Io(error)),
948        }
949    }
950
951    /// The accepted entry for `id` when it is sound and not past its retirement time.
952    fn current(&self, id: &PeerId) -> Option<Entry> {
953        let entry = self.read("accepted", id)?;
954        match entry.retires {
955            Some(retires) if self.clock.now() >= from_unix_seconds(retires) => None,
956            _ => Some(entry),
957        }
958    }
959
960    /// The sound entry for `id` in `section`: its file parses and its key hashes to `id`.
961    fn read(&self, section: &str, id: &PeerId) -> Option<Entry> {
962        let text = fs::read_to_string(self.existing(section, id)?).ok()?;
963        parse(&text).filter(|entry| entry.key.id() == *id)
964    }
965
966    fn list(&self, section: &str) -> Result<Vec<PeerId>, Error> {
967        let entries = match fs::read_dir(self.root.join(section)) {
968            Ok(entries) => entries,
969            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
970            Err(error) => return Err(Error::Io(error)),
971        };
972        let mut ids = Vec::new();
973        for entry in entries {
974            let path = entry.map_err(Error::Io)?.path();
975            if path.extension().is_some_and(|extension| extension == "pem")
976                && let Some(Ok(id)) = path
977                    .file_stem()
978                    .and_then(|stem| stem.to_str())
979                    .filter(|stem| is_hex_name(stem))
980                    .map(str::parse::<PeerId>)
981                && !ids.contains(&id)
982            {
983                ids.push(id);
984            }
985        }
986        ids.sort();
987        Ok(ids)
988    }
989
990    fn path(&self, section: &str, id: &PeerId) -> PathBuf {
991        self.root.join(section).join(format!("{}.pem", id.hex()))
992    }
993
994    fn revoked_path(&self, id: &InvitationId) -> PathBuf {
995        self.root
996            .join("invitations")
997            .join(format!("{}.revoked", id.hex()))
998    }
999
1000    fn invitation_path(&self, id: &InvitationId) -> PathBuf {
1001        self.root
1002            .join("invitations")
1003            .join(format!("{}.inv", id.hex()))
1004    }
1005
1006    /// The file for `id` in `section`, when it exists.
1007    fn existing(&self, section: &str, id: &PeerId) -> Option<PathBuf> {
1008        let path = self.path(section, id);
1009        path.is_file().then_some(path)
1010    }
1011}
1012
1013/// Whether `stem` is a file name this store writes: 64 lowercase hexadecimal characters.
1014fn is_hex_name(stem: &str) -> bool {
1015    stem.len() == 64 && HEXLOWER.decode_mut(stem.as_bytes(), &mut [0u8; 32]).is_ok()
1016}
1017
1018/// The source an address counts against: IPv4 as it is, IPv4-mapped IPv6 as the IPv4 address,
1019/// other IPv6 cut to its first `prefix` bits.
1020pub(crate) fn source_key(address: IpAddr, prefix: u8) -> IpAddr {
1021    match address {
1022        IpAddr::V4(_) => address,
1023        IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
1024            Some(v4) => IpAddr::V4(v4),
1025            None => {
1026                let mask = u128::MAX
1027                    .checked_shl(128 - u32::from(prefix.min(128)))
1028                    .unwrap_or(0);
1029                IpAddr::V6(Ipv6Addr::from(u128::from(v6) & mask))
1030            }
1031        },
1032    }
1033}
1034
1035/// An accepted file: `Method:`, then `Successor:` and `Retires:` when set, then the PEM block.
1036fn accepted_text(key: &KeyMaterial, successor: Option<&PeerId>, retires: Option<u64>) -> String {
1037    let mut text = format!("Method: {}\n", key.method);
1038    if let Some(successor) = successor {
1039        text.push_str(&format!("Successor: {}\n", successor.hex()));
1040    }
1041    if let Some(retires) = retires {
1042        text.push_str(&format!("Retires: {retires}\n"));
1043    }
1044    text.push_str(&pem::encode(&key.label, &key.bytes));
1045    text
1046}
1047
1048fn invitation_text(expires: SystemTime, uses: u32, label: &str) -> String {
1049    let mut text = format!("Expires: {}\nUses: {uses}\n", unix_seconds(expires));
1050    if !label.is_empty() {
1051        text.push_str(&format!("Label: {label}\n"));
1052    }
1053    text
1054}
1055
1056/// `(expires, uses, label)` of an invitation file; `None` unless `Expires:` and a positive
1057/// `Uses:` are present.
1058fn parse_invitation(text: &str) -> Option<(u64, u32, String)> {
1059    let (mut expires, mut uses, mut label) = (None, None, String::new());
1060    for line in text.lines() {
1061        if let Some(value) = line.strip_prefix("Expires: ") {
1062            expires = value.trim().parse().ok();
1063        } else if let Some(value) = line.strip_prefix("Uses: ") {
1064            uses = value.trim().parse::<u32>().ok().filter(|uses| *uses > 0);
1065        } else if let Some(value) = line.strip_prefix("Label: ") {
1066            value.trim().clone_into(&mut label);
1067        }
1068    }
1069    Some((expires?, uses?, label))
1070}
1071
1072/// Reads a store file: header lines, then one PEM block.
1073fn parse(text: &str) -> Option<Entry> {
1074    let pem::Block {
1075        headers,
1076        label,
1077        bytes,
1078        ..
1079    } = pem::decode(text)?;
1080    let mut method = None;
1081    let (mut source, mut successor, mut retires) = (None, None, None);
1082    let (mut predecessor, mut proven) = (None, None);
1083    for line in headers {
1084        if let Some(value) = line.strip_prefix("Method: ") {
1085            method = Some(value.trim());
1086        } else if let Some(value) = line.strip_prefix("Source: ") {
1087            source = value.trim().parse().ok();
1088        } else if let Some(value) = line.strip_prefix("Successor: ") {
1089            successor = Some(value.trim().parse().ok()?);
1090        } else if let Some(value) = line.strip_prefix("Retires: ") {
1091            retires = Some(value.trim().parse().ok()?);
1092        } else if let Some(value) = line.strip_prefix("Predecessor: ") {
1093            predecessor = Some(value.trim().parse().ok()?);
1094        } else if let Some(value) = line.strip_prefix("Proven: ") {
1095            proven = Some(value.trim().parse().ok()?);
1096        }
1097    }
1098    Some(Entry {
1099        key: KeyMaterial::new(method?, label, bytes).ok()?,
1100        source,
1101        successor,
1102        retires,
1103        predecessor,
1104        proven,
1105    })
1106}
1107
1108/// Writes `text` to `path` unless it exists, atomically.
1109fn write_new(path: &Path, text: &str) -> io::Result<()> {
1110    file::write_new(path, text.as_bytes(), Access::Default)
1111}
1112
1113/// Writes `text` to `path`, replacing what is there, atomically.
1114fn replace(path: &Path, text: &str) -> io::Result<()> {
1115    file::replace(path, text.as_bytes(), Access::Default)
1116}