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