Skip to main content

coqui_peer/pair/
desk.rs

1use alloc::collections::VecDeque;
2use alloc::sync::Arc;
3use core::future::Future;
4use core::net::{IpAddr, SocketAddr};
5use core::pin::Pin as Pinned;
6use core::task::{Context, Poll, Waker};
7use core::time::Duration;
8use std::collections::HashMap;
9use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
10use std::time::SystemTime;
11
12use crate::clock::{Clock, later};
13use crate::error::Error;
14use crate::id::PeerId;
15use crate::pair::code::{CodeAlphabet, PairingCode, Pin, UserCode, below, same};
16use crate::pair::{PairRefusal, PairingError};
17use crate::random::Random;
18use crate::store::{DEFAULT_IPV6_PREFIX, source_key};
19
20/// Draws of a user code that is not already pending before the desk gives up.
21const ISSUE_DRAWS: usize = 64;
22
23/// What a responder offers and how its codes are made. Every field has a default; any value
24/// with a meaning is accepted, and [`non_defaults`](PairingOptions::non_defaults) lists the ones that
25/// differ from their default. Every key is optional and an unknown key is refused; a duration
26/// reads as `600`, `90s` or `250ms`, and `pin_ttl` and `device_ttl` also read `never`.
27/// `#[non_exhaustive]`: start from [`Default`] and assign the fields.
28#[derive(Debug, Clone, PartialEq, Eq, coqui_builder::Describe)]
29#[map(deny_unknown_fields)]
30#[non_exhaustive]
31pub struct PairingOptions {
32    /// Whether joiners may pair with an invitation. Default `true`.
33    #[map(default = PairingOptions::default().invitation)]
34    pub invitation: bool,
35    /// Whether joiners may pair with a PIN (needs the `pin` feature). Default `true`.
36    #[map(default = PairingOptions::default().pin)]
37    pub pin: bool,
38    /// Whether a joiner may show a PIN for an operator to type into this side, which holds its
39    /// run until the operator answers or `pin_ttl` passes. Turn it off where nobody is there
40    /// to answer. Default `true`.
41    #[map(default = PairingOptions::default().pin_shown)]
42    pub pin_shown: bool,
43    /// Whether joiners may pair by the device flow. Default `true`.
44    #[map(default = PairingOptions::default().device)]
45    pub device: bool,
46    /// The alphabet and length of a PIN the desk shows. Default `0123456789` × 6.
47    #[map(default = PairingOptions::default().pin_alphabet)]
48    pub pin_alphabet: CodeAlphabet,
49    /// How long a shown PIN, or a slot waiting for a joiner's PIN, lasts; `None` (the text
50    /// `never`) lasts for good. Default 10 minutes; it is also the window of
51    /// [`DeskLimits::pin_runs_per_source`].
52    #[map(default = PairingOptions::default().pin_ttl, none = "never")]
53    pub pin_ttl: Option<Duration>,
54    /// How many runs may try a shown PIN before it is burned; a run counts once it is past
55    /// the first PAKE message, whatever its outcome. Default 1.
56    #[map(default = PairingOptions::default().pin_attempts)]
57    pub pin_attempts: u32,
58    /// The alphabet and length of a device-flow user code. Default RFC 8628's
59    /// `BCDFGHJKLMNPQRSTVWXZ` × 8.
60    #[map(default = PairingOptions::default().user_code_alphabet)]
61    pub user_code_alphabet: CodeAlphabet,
62    /// How long a user code waits for approval; `None` (the text `never`) waits for good.
63    /// Default 10 minutes; it is also the window of [`DeskLimits::wrong_codes_total`].
64    #[map(default = PairingOptions::default().device_ttl, none = "never")]
65    pub device_ttl: Option<Duration>,
66}
67
68impl Default for PairingOptions {
69    fn default() -> Self {
70        Self {
71            invitation: true,
72            pin: true,
73            pin_shown: true,
74            device: true,
75            pin_alphabet: CodeAlphabet::pin(),
76            pin_ttl: Some(Duration::from_secs(600)),
77            pin_attempts: 1,
78            user_code_alphabet: CodeAlphabet::user_code(),
79            device_ttl: Some(Duration::from_secs(600)),
80        }
81    }
82}
83
84/// Bounds on a desk's pending work and on guessing. Every field has a default; any value is
85/// accepted, and [`non_defaults`](DeskLimits::non_defaults) lists the ones that differ from
86/// their default. Read like [`PairingOptions`]; `#[non_exhaustive]`.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, coqui_builder::Describe)]
88#[map(deny_unknown_fields)]
89#[non_exhaustive]
90pub struct DeskLimits {
91    /// Pairing exchanges in progress at once. Default 32.
92    #[map(default = DeskLimits::default().pending)]
93    pub pending: usize,
94    /// Pairing exchanges in progress at once from one source (every mode). A source is an IPv4
95    /// address or an IPv6 prefix of [`ipv6_prefix`](DeskLimits::ipv6_prefix) bits. Default 4.
96    #[map(default = DeskLimits::default().pending_per_source)]
97    pub pending_per_source: usize,
98    /// PIN runs one source may start per [`PairingOptions::pin_ttl`]. A source is an IPv4
99    /// address or an IPv6 prefix of [`ipv6_prefix`](DeskLimits::ipv6_prefix) bits. Default 8.
100    #[map(default = DeskLimits::default().pin_runs_per_source)]
101    pub pin_runs_per_source: usize,
102    /// Wrong user codes one approver may enter per
103    /// [`approver_window`](DeskLimits::approver_window). Default 5.
104    #[map(default = DeskLimits::default().wrong_codes_per_approver)]
105    pub wrong_codes_per_approver: usize,
106    /// The window of [`wrong_codes_per_approver`](DeskLimits::wrong_codes_per_approver).
107    /// Default 1 minute.
108    #[map(default = DeskLimits::default().approver_window)]
109    pub approver_window: Duration,
110    /// Wrong user codes all approvers together may enter per
111    /// [`PairingOptions::device_ttl`]. Default 60.
112    #[map(default = DeskLimits::default().wrong_codes_total)]
113    pub wrong_codes_total: usize,
114    /// The IPv6 prefix length sources are grouped by. Default 64.
115    #[map(default = DeskLimits::default().ipv6_prefix)]
116    pub ipv6_prefix: u8,
117}
118
119impl Default for DeskLimits {
120    fn default() -> Self {
121        Self {
122            pending: 32,
123            pending_per_source: 4,
124            pin_runs_per_source: 8,
125            wrong_codes_per_approver: 5,
126            approver_window: Duration::from_secs(60),
127            wrong_codes_total: 60,
128            ipv6_prefix: DEFAULT_IPV6_PREFIX,
129        }
130    }
131}
132
133impl PairingOptions {
134    /// Whether every option has a meaning.
135    ///
136    /// # Errors
137    ///
138    /// [`Error::InvalidOptions`] for a meaningless alphabet, a zero TTL or zero attempts.
139    pub fn check(&self) -> Result<(), Error> {
140        self.pin_alphabet.check()?;
141        self.user_code_alphabet.check()?;
142        if self.pin_ttl == Some(Duration::ZERO)
143            || self.device_ttl == Some(Duration::ZERO)
144            || self.pin_attempts == 0
145        {
146            return Err(Error::InvalidOptions);
147        }
148        Ok(())
149    }
150
151    /// Every option that differs from its default, named by key path (`pin_attempts`,
152    /// `pin_alphabet.len`).
153    pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
154        coqui_builder::non_defaults(self)
155    }
156}
157
158impl DeskLimits {
159    /// Every limit that differs from its default, named by key path.
160    pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
161        coqui_builder::non_defaults(self)
162    }
163}
164
165/// What a [`PairingDesk`] is built from, besides its random source and clock, in the form a
166/// file, a form or a peer fills.
167///
168/// Every key is optional (an absent one is its default) and an unknown key is refused. The type
169/// is `Describe`, so a `Partial<PairingDeskSettings>` is filled from text and built, and it is
170/// `#[non_exhaustive]`: start from [`Default`] and assign the fields.
171#[derive(Debug, Clone, PartialEq, Eq, Default, coqui_builder::Describe)]
172#[builder(setters_on = PairingDeskBuilder)]
173#[map(deny_unknown_fields)]
174#[non_exhaustive]
175pub struct PairingDeskSettings {
176    /// What the desk offers and how its codes are made.
177    #[map(default = PairingDeskSettings::default().options)]
178    pub options: PairingOptions,
179    /// The bounds on pending work and on guessing.
180    #[map(default = PairingDeskSettings::default().limits)]
181    pub limits: DeskLimits,
182}
183
184impl PairingDeskSettings {
185    /// Every setting that differs from its default, named by key path (`limits.pending`).
186    pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
187        coqui_builder::non_defaults(self)
188    }
189}
190
191/// What a [`PairingDeskBuilder`] collects: the settings, the random source and the clock.
192///
193/// The random source is required, the clock is the system clock unless given. Build the desk with
194/// [`PairingDesk::builder`].
195#[derive(coqui_builder::Builder, Debug)]
196#[builder(build = PairingDesk, fallible)]
197pub struct PairingDeskParts {
198    settings: PairingDeskSettings,
199    #[builder(input)]
200    random: Random,
201    #[builder(input)]
202    clock: Option<Clock>,
203}
204
205impl TryFrom<PairingDeskParts> for PairingDesk {
206    type Error = Error;
207
208    /// The desk.
209    ///
210    /// # Errors
211    ///
212    /// [`Error::InvalidOptions`] as [`PairingOptions::check`].
213    fn try_from(parts: PairingDeskParts) -> Result<Self, Error> {
214        parts.settings.options.check()?;
215        Ok(PairingDesk::from_parts(
216            parts.random,
217            parts.clock.unwrap_or_default(),
218            parts.settings,
219        ))
220    }
221}
222
223/// A responder's handle on a decision it waits for: a joiner's PIN typed by the operator, or
224/// the approval of a device-flow joiner.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226pub struct Ticket(u64);
227
228/// How a waiting exchange is settled.
229#[derive(Debug, Clone, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum Decision {
232    /// The operator typed this PIN for a joiner that shows its own.
233    Code(Pin),
234    /// The operator approved a device-flow joiner.
235    Approved,
236    /// The operator denied a device-flow joiner.
237    Denied,
238    /// Nobody decided before the code expired.
239    Expired,
240}
241
242/// A PIN the desk shows, for the caller to display.
243#[derive(Debug, Clone, PartialEq, Eq)]
244#[non_exhaustive]
245pub struct ShownPin {
246    /// The PIN.
247    pub pin: Pin,
248    /// When it stops being accepted.
249    pub expires: SystemTime,
250}
251
252/// A joiner that shows its own PIN and waits for the operator to type it.
253#[derive(Debug, Clone, PartialEq, Eq)]
254#[non_exhaustive]
255pub struct PendingSlot {
256    /// The slot the desk assigned, which the joiner shows with its PIN.
257    pub slot: u8,
258    /// The joiner's id.
259    pub peer: PeerId,
260    /// Where it connected from, when known.
261    pub source: Option<SocketAddr>,
262    /// When the slot expires.
263    pub expires: SystemTime,
264}
265
266/// A device-flow joiner found by its user code: what an app may show before it approves or
267/// denies.
268#[derive(Debug, Clone, PartialEq, Eq)]
269#[non_exhaustive]
270pub struct PendingDevice {
271    /// The joiner's id.
272    pub peer: PeerId,
273    /// Where it connected from, when known.
274    pub source: Option<SocketAddr>,
275    /// The label the joiner sent; the joiner chose it, so it proves nothing.
276    pub label: String,
277    /// When its user code expires.
278    pub expires: SystemTime,
279    ticket: Ticket,
280}
281
282#[derive(Debug)]
283enum Kind {
284    Slot(u8),
285    Device(UserCode),
286}
287
288#[derive(Debug)]
289struct Waiting {
290    kind: Kind,
291    peer: PeerId,
292    source: Option<SocketAddr>,
293    label: String,
294    expires: SystemTime,
295    /// The decision, until the responder takes it.
296    decision: Option<Decision>,
297    /// Whether a decision was made: a settled entry is listed and decided no more, even after
298    /// its decision was taken.
299    settled: bool,
300    waker: Option<Waker>,
301}
302
303#[derive(Debug)]
304struct State {
305    options: PairingOptions,
306    limits: DeskLimits,
307    clock: Clock,
308    random: Random,
309    shown: Option<(ShownPin, u32)>,
310    gone: PairRefusal,
311    waiting: HashMap<u64, Waiting>,
312    next: u64,
313    pending: usize,
314    pending_by: HashMap<Option<IpAddr>, usize>,
315    runs: HashMap<Option<IpAddr>, VecDeque<SystemTime>>,
316    wrong_by: HashMap<String, VecDeque<SystemTime>>,
317    wrong_all: VecDeque<SystemTime>,
318}
319
320#[derive(Debug)]
321struct Inner {
322    state: Mutex<State>,
323    changed: Condvar,
324}
325
326/// The responder's side of pairing that involves the operator: the PIN it shows, joiners that
327/// wait for a typed PIN or an approval, and the throttles. Clone it to share it between the
328/// connections and the app's own surface.
329///
330/// The desk shows nothing and asks nobody: the caller displays [`show_pin`]'s PIN, lists
331/// [`slots`], passes what the operator typed to [`submit_code`] or [`find_device`], and calls
332/// [`approve`] or [`deny`].
333///
334/// [`show_pin`]: PairingDesk::show_pin
335/// [`slots`]: PairingDesk::slots
336/// [`submit_code`]: PairingDesk::submit_code
337/// [`find_device`]: PairingDesk::find_device
338/// [`approve`]: PairingDesk::approve
339/// [`deny`]: PairingDesk::deny
340#[derive(Debug, Clone)]
341pub struct PairingDesk {
342    inner: Arc<Inner>,
343}
344
345/// A pairing exchange in progress, counted against [`DeskLimits::pending`] until dropped; its
346/// waiting entry goes with it.
347#[derive(Debug)]
348pub(crate) struct Admission {
349    inner: Arc<Inner>,
350    id: u64,
351    bucket: Option<IpAddr>,
352}
353
354impl Admission {
355    pub(crate) fn ticket(&self) -> Ticket {
356        Ticket(self.id)
357    }
358}
359
360impl Drop for Admission {
361    fn drop(&mut self) {
362        let mut state = self
363            .inner
364            .state
365            .lock()
366            .unwrap_or_else(PoisonError::into_inner);
367        state.pending = state.pending.saturating_sub(1);
368        if let Some(count) = state.pending_by.get_mut(&self.bucket) {
369            *count = count.saturating_sub(1);
370            if *count == 0 {
371                state.pending_by.remove(&self.bucket);
372            }
373        }
374        state.waiting.remove(&self.id);
375        drop(state);
376        self.inner.changed.notify_all();
377    }
378}
379
380/// Drops the times older than `window` before `now`.
381fn prune(times: &mut VecDeque<SystemTime>, now: SystemTime, window: Duration) {
382    while times
383        .front()
384        .is_some_and(|at| now.duration_since(*at).unwrap_or_default() >= window)
385    {
386        times.pop_front();
387    }
388}
389
390impl State {
391    /// Expires the shown PIN and waiting entries by the clock; whether anything changed.
392    fn sweep(&mut self) -> bool {
393        let now = self.clock.now();
394        let mut changed = false;
395        if self
396            .shown
397            .as_ref()
398            .is_some_and(|(shown, _)| now >= shown.expires)
399        {
400            self.shown = None;
401            self.gone = PairRefusal::Expired;
402            changed = true;
403        }
404        for waiting in self.waiting.values_mut() {
405            if !waiting.settled && now >= waiting.expires {
406                waiting.decision = Some(Decision::Expired);
407                waiting.settled = true;
408                if let Some(waker) = waiting.waker.take() {
409                    waker.wake();
410                }
411                changed = true;
412            }
413        }
414        // Buckets of past windows go, so the maps stay as large as the recent traffic.
415        let (ttl, window) = (
416            self.options.pin_ttl.unwrap_or(Duration::MAX),
417            self.limits.approver_window,
418        );
419        self.runs.retain(|_, times| {
420            prune(times, now, ttl);
421            !times.is_empty()
422        });
423        self.wrong_by.retain(|_, times| {
424            prune(times, now, window);
425            !times.is_empty()
426        });
427        changed
428    }
429
430    fn decide(&mut self, ticket: Ticket, decision: Decision) -> Result<(), PairingError> {
431        let waiting = self
432            .waiting
433            .get_mut(&ticket.0)
434            .filter(|waiting| !waiting.settled)
435            .ok_or(PairingError::Refused(PairRefusal::Expired))?;
436        waiting.decision = Some(decision);
437        waiting.settled = true;
438        if let Some(waker) = waiting.waker.take() {
439            waker.wake();
440        }
441        Ok(())
442    }
443}
444
445impl PairingDesk {
446    /// A desk with the default options and limits, the system clock, and `random` for PINs,
447    /// slots and user codes: `PairingDesk::builder().random(random).build()`.
448    pub fn new(random: Random) -> Self {
449        Self::from_parts(random, Clock::system(), PairingDeskSettings::default())
450    }
451
452    fn from_parts(random: Random, clock: Clock, settings: PairingDeskSettings) -> Self {
453        Self {
454            inner: Arc::new(Inner {
455                state: Mutex::new(State {
456                    options: settings.options,
457                    limits: settings.limits,
458                    clock,
459                    random,
460                    shown: None,
461                    gone: PairRefusal::Exhausted,
462                    waiting: HashMap::new(),
463                    next: 0,
464                    pending: 0,
465                    pending_by: HashMap::new(),
466                    runs: HashMap::new(),
467                    wrong_by: HashMap::new(),
468                    wrong_all: VecDeque::new(),
469                }),
470                changed: Condvar::new(),
471            }),
472        }
473    }
474
475    fn state(&self) -> MutexGuard<'_, State> {
476        self.inner
477            .state
478            .lock()
479            .unwrap_or_else(PoisonError::into_inner)
480    }
481
482    /// The settings in force.
483    pub fn settings(&self) -> PairingDeskSettings {
484        let state = self.state();
485        PairingDeskSettings {
486            options: state.options.clone(),
487            limits: state.limits,
488        }
489    }
490
491    /// Every setting that differs from its default, named by key path.
492    pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
493        self.settings().non_defaults()
494    }
495
496    /// The options in force.
497    pub fn options(&self) -> PairingOptions {
498        self.state().options.clone()
499    }
500
501    /// The limits in force.
502    pub fn limits(&self) -> DeskLimits {
503        self.state().limits
504    }
505
506    /// Makes a new PIN for joiners to type, replacing the one shown before, and returns it for
507    /// the caller to display.
508    ///
509    /// # Errors
510    ///
511    /// [`Error::Random`] when the random source fails.
512    pub fn show_pin(&self) -> Result<ShownPin, Error> {
513        let mut state = self.state();
514        let pin = Pin::generate(&state.options.pin_alphabet, &state.random)?;
515        let shown = ShownPin {
516            pin,
517            expires: later(state.clock.now(), state.options.pin_ttl),
518        };
519        state.shown = Some((shown.clone(), state.options.pin_attempts));
520        Ok(shown)
521    }
522
523    /// The PIN shown now, while it lasts and has attempts left.
524    pub fn shown_pin(&self) -> Option<ShownPin> {
525        let mut state = self.state();
526        state.sweep();
527        state.shown.as_ref().map(|(shown, _)| shown.clone())
528    }
529
530    /// Withdraws the shown PIN.
531    pub fn clear_pin(&self) {
532        let mut state = self.state();
533        state.shown = None;
534        state.gone = PairRefusal::Exhausted;
535    }
536
537    /// The joiners that show their own PIN and wait for it to be typed, by slot.
538    pub fn slots(&self) -> Vec<PendingSlot> {
539        let mut state = self.state();
540        state.sweep();
541        let mut slots: Vec<PendingSlot> = state
542            .waiting
543            .values()
544            .filter(|waiting| !waiting.settled)
545            .filter_map(|waiting| match waiting.kind {
546                Kind::Slot(slot) => Some(PendingSlot {
547                    slot,
548                    peer: waiting.peer,
549                    source: waiting.source,
550                    expires: waiting.expires,
551                }),
552                Kind::Device(_) => None,
553            })
554            .collect();
555        slots.sort_by_key(|slot| slot.slot);
556        slots
557    }
558
559    /// Hands the PIN the operator typed to the joiner waiting in `code.slot`. Whether it is
560    /// right is found by the PAKE; the slot is used either way.
561    ///
562    /// # Errors
563    ///
564    /// [`PairingError::Refused`] with [`PairRefusal::WrongCode`] when no joiner waits in that
565    /// slot (or `slot` is `None`).
566    pub fn submit_code(&self, code: &PairingCode) -> Result<(), PairingError> {
567        let mut state = self.state();
568        state.sweep();
569        let ticket = state
570            .waiting
571            .iter()
572            .find(|(_, waiting)| {
573                !waiting.settled
574                    && matches!(waiting.kind, Kind::Slot(slot) if Some(slot) == code.slot)
575            })
576            .map(|(id, _)| Ticket(*id))
577            .ok_or(PairingError::Refused(PairRefusal::WrongCode))?;
578        state.decide(ticket, Decision::Code(code.pin.clone()))?;
579        drop(state);
580        self.inner.changed.notify_all();
581        Ok(())
582    }
583
584    /// The device-flow joiner whose user code the operator entered, for the caller to approve
585    /// or deny. `approver` names who entered it (an account, a session), for the per-approver
586    /// throttle.
587    ///
588    /// The code is matched exactly over the user-code alphabet, in constant time against every
589    /// pending code.
590    ///
591    /// # Errors
592    ///
593    /// [`PairingError::Local`] with [`Error::InvalidCode`] when `code` is not of the alphabet
594    /// (not counted as a wrong entry); [`PairRefusal::Throttled`] when the approver or all
595    /// approvers entered too many wrong codes recently; [`PairRefusal::WrongCode`] when no
596    /// pending joiner has it (counted).
597    pub fn find_device(&self, approver: &str, code: &str) -> Result<PendingDevice, PairingError> {
598        let mut state = self.state();
599        state.sweep();
600        let entered = UserCode::parse(&state.options.user_code_alphabet, code)
601            .map_err(PairingError::Local)?;
602        let now = state.clock.now();
603        let (limits, ttl) = (
604            state.limits,
605            state.options.device_ttl.unwrap_or(Duration::MAX),
606        );
607        let by = state.wrong_by.entry(approver.to_owned()).or_default();
608        prune(by, now, limits.approver_window);
609        let by_count = by.len();
610        prune(&mut state.wrong_all, now, ttl);
611        if by_count >= limits.wrong_codes_per_approver
612            || state.wrong_all.len() >= limits.wrong_codes_total
613        {
614            return Err(PairingError::Refused(PairRefusal::Throttled));
615        }
616        let mut found = None;
617        for (id, waiting) in &state.waiting {
618            if let Kind::Device(issued) = &waiting.kind
619                && !waiting.settled
620                && same(issued.as_str(), entered.as_str())
621            {
622                found = Some(PendingDevice {
623                    peer: waiting.peer,
624                    source: waiting.source,
625                    label: waiting.label.clone(),
626                    expires: waiting.expires,
627                    ticket: Ticket(*id),
628                });
629            }
630        }
631        match found {
632            Some(device) => Ok(device),
633            None => {
634                state
635                    .wrong_by
636                    .entry(approver.to_owned())
637                    .or_default()
638                    .push_back(now);
639                state.wrong_all.push_back(now);
640                Err(PairingError::Refused(PairRefusal::WrongCode))
641            }
642        }
643    }
644
645    /// Approves a device-flow joiner: its responder accepts its key and tells it so.
646    ///
647    /// # Errors
648    ///
649    /// [`PairRefusal::Expired`] when it expired, was decided, or disconnected.
650    pub fn approve(&self, device: &PendingDevice) -> Result<(), PairingError> {
651        self.settle(device.ticket, Decision::Approved)
652    }
653
654    /// Denies a device-flow joiner: its responder refuses it and tells it so.
655    ///
656    /// # Errors
657    ///
658    /// As [`approve`](PairingDesk::approve).
659    pub fn deny(&self, device: &PendingDevice) -> Result<(), PairingError> {
660        self.settle(device.ticket, Decision::Denied)
661    }
662
663    fn settle(&self, ticket: Ticket, decision: Decision) -> Result<(), PairingError> {
664        let mut state = self.state();
665        state.sweep();
666        state.decide(ticket, decision)?;
667        drop(state);
668        self.inner.changed.notify_all();
669        Ok(())
670    }
671
672    /// Expires the shown PIN and the waiting joiners by the clock, waking their responders.
673    /// The waits below also do it; call it when the clock is not the system's.
674    pub fn sweep(&self) {
675        let changed = self.state().sweep();
676        if changed {
677            self.inner.changed.notify_all();
678        }
679    }
680
681    /// Blocks until `ticket` is decided or expires. Under the system clock it rechecks expiry
682    /// every second; under another clock, [`sweep`](PairingDesk::sweep) wakes it.
683    pub fn wait(&self, ticket: Ticket) -> Decision {
684        let mut state = self.state();
685        loop {
686            state.sweep();
687            match state.waiting.get_mut(&ticket.0) {
688                None => return Decision::Expired,
689                Some(waiting) => {
690                    if let Some(decision) = waiting.decision.take() {
691                        return decision;
692                    }
693                }
694            }
695            state = self
696                .inner
697                .changed
698                .wait_timeout(state, Duration::from_secs(1))
699                .unwrap_or_else(PoisonError::into_inner)
700                .0;
701        }
702    }
703
704    /// A future of [`wait`](PairingDesk::wait)'s decision. It is woken by a decision or by
705    /// [`sweep`](PairingDesk::sweep); an async caller that relies on expiry sweeps now and then.
706    pub fn decided(&self, ticket: Ticket) -> Decided {
707        Decided {
708            desk: self.clone(),
709            ticket,
710        }
711    }
712
713    /// The random source PINs, slots and codes are drawn from.
714    pub(crate) fn random(&self) -> Random {
715        self.state().random.clone()
716    }
717
718    /// The time on the desk's clock.
719    pub(crate) fn now(&self) -> SystemTime {
720        self.state().clock.now()
721    }
722
723    pub(crate) fn admit(&self, source: Option<SocketAddr>) -> Result<Admission, PairRefusal> {
724        let mut state = self.state();
725        let bucket = source.map(|s| source_key(s.ip(), state.limits.ipv6_prefix));
726        let from_source = state.pending_by.get(&bucket).copied().unwrap_or(0);
727        if state.pending >= state.limits.pending || from_source >= state.limits.pending_per_source {
728            return Err(PairRefusal::Throttled);
729        }
730        state.pending += 1;
731        *state.pending_by.entry(bucket).or_insert(0) += 1;
732        state.next += 1;
733        Ok(Admission {
734            inner: self.inner.clone(),
735            id: state.next,
736            bucket,
737        })
738    }
739
740    /// Counts a PIN run from `source`, or refuses it past the per-source limit.
741    pub(crate) fn pin_run(&self, source: Option<SocketAddr>) -> Result<(), PairRefusal> {
742        let mut state = self.state();
743        let now = state.clock.now();
744        let (ttl, limits) = (state.options.pin_ttl.unwrap_or(Duration::MAX), state.limits);
745        let bucket = source.map(|s| source_key(s.ip(), limits.ipv6_prefix));
746        let runs = state.runs.entry(bucket).or_default();
747        prune(runs, now, ttl);
748        if runs.len() >= limits.pin_runs_per_source {
749            return Err(PairRefusal::Throttled);
750        }
751        runs.push_back(now);
752        Ok(())
753    }
754
755    /// Whether a shown PIN is there to try; why not, when not.
756    pub(crate) fn pin_ready(&self) -> Result<(), PairRefusal> {
757        let mut state = self.state();
758        state.sweep();
759        if state.shown.is_some() {
760            Ok(())
761        } else {
762            Err(state.gone)
763        }
764    }
765
766    /// Takes one attempt at the shown PIN, burning it after the last.
767    pub(crate) fn take_pin(&self) -> Result<Pin, PairRefusal> {
768        let mut state = self.state();
769        state.sweep();
770        let gone = state.gone;
771        let (shown, left) = state.shown.as_mut().ok_or(gone)?;
772        let pin = shown.pin.clone();
773        *left -= 1;
774        if *left == 0 {
775            state.shown = None;
776            state.gone = PairRefusal::Exhausted;
777        }
778        Ok(pin)
779    }
780
781    pub(crate) fn open_slot(
782        &self,
783        admission: &Admission,
784        peer: PeerId,
785        source: Option<SocketAddr>,
786    ) -> Result<u8, PairingError> {
787        let mut state = self.state();
788        state.sweep();
789        let used: Vec<u8> = state
790            .waiting
791            .values()
792            .filter_map(|waiting| match waiting.kind {
793                Kind::Slot(slot) => Some(slot),
794                Kind::Device(_) => None,
795            })
796            .collect();
797        let free: Vec<u8> = (0..100).filter(|slot| !used.contains(slot)).collect();
798        if free.is_empty() {
799            return Err(PairingError::Refused(PairRefusal::Throttled));
800        }
801        let slot = free[below(&state.random, free.len()).map_err(PairingError::Local)?];
802        let expires = later(state.clock.now(), state.options.pin_ttl);
803        state.waiting.insert(
804            admission.id,
805            Waiting {
806                kind: Kind::Slot(slot),
807                peer,
808                source,
809                label: String::new(),
810                expires,
811                decision: None,
812                settled: false,
813                waker: None,
814            },
815        );
816        Ok(slot)
817    }
818
819    pub(crate) fn issue(
820        &self,
821        admission: &Admission,
822        peer: PeerId,
823        source: Option<SocketAddr>,
824        label: &str,
825    ) -> Result<(UserCode, SystemTime), PairingError> {
826        let mut state = self.state();
827        state.sweep();
828        let issued = state
829            .waiting
830            .values()
831            .filter(|waiting| matches!(waiting.kind, Kind::Device(_)))
832            .count();
833        // A small alphabet can run out of distinct codes, so drawing is bounded.
834        if issued as u128 >= state.options.user_code_alphabet.combinations() {
835            return Err(PairingError::Refused(PairRefusal::Throttled));
836        }
837        let mut code = None;
838        for _ in 0..ISSUE_DRAWS {
839            let drawn = UserCode::generate(&state.options.user_code_alphabet, &state.random)
840                .map_err(PairingError::Local)?;
841            let taken = state
842                .waiting
843                .values()
844                .any(|waiting| matches!(&waiting.kind, Kind::Device(issued) if issued == &drawn));
845            if !taken {
846                code = Some(drawn);
847                break;
848            }
849        }
850        let code = code.ok_or(PairingError::Refused(PairRefusal::Throttled))?;
851        let expires = later(state.clock.now(), state.options.device_ttl);
852        state.waiting.insert(
853            admission.id,
854            Waiting {
855                kind: Kind::Device(code.clone()),
856                peer,
857                source,
858                label: label.to_owned(),
859                expires,
860                decision: None,
861                settled: false,
862                waker: None,
863            },
864        );
865        Ok((code, expires))
866    }
867}
868
869/// The future of [`PairingDesk::decided`].
870#[derive(Debug)]
871pub struct Decided {
872    desk: PairingDesk,
873    ticket: Ticket,
874}
875
876impl Future for Decided {
877    type Output = Decision;
878
879    fn poll(self: Pinned<&mut Self>, context: &mut Context<'_>) -> Poll<Decision> {
880        let mut state = self.desk.state();
881        state.sweep();
882        match state.waiting.get_mut(&self.ticket.0) {
883            None => Poll::Ready(Decision::Expired),
884            Some(waiting) => match waiting.decision.take() {
885                Some(decision) => Poll::Ready(decision),
886                None => {
887                    waiting.waker = Some(context.waker().clone());
888                    Poll::Pending
889                }
890            },
891        }
892    }
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898    use core::sync::atomic::{AtomicU64, Ordering};
899    use std::time::UNIX_EPOCH;
900
901    #[test]
902    fn the_buckets_of_past_windows_are_dropped() {
903        let now = Arc::new(AtomicU64::new(1_800_000_000));
904        let seen = now.clone();
905        let clock =
906            Clock::from_fn(move || UNIX_EPOCH + Duration::from_secs(seen.load(Ordering::SeqCst)));
907        let limits = DeskLimits {
908            wrong_codes_total: 1000,
909            ..DeskLimits::default()
910        };
911        let desk = PairingDesk::builder()
912            .random(Random::from_fn(|out| {
913                out.fill(7);
914                Ok(())
915            }))
916            .clock(clock)
917            .limits(limits)
918            .build()
919            .unwrap();
920        for host in 0..200u8 {
921            let source = SocketAddr::from(([192, 0, 2, host], 1000));
922            desk.pin_run(Some(source)).unwrap();
923            let _ = desk.find_device(&format!("approver {host}"), "BBBBBBBB");
924        }
925        assert_eq!(desk.state().runs.len(), 200);
926        assert_eq!(desk.state().wrong_by.len(), 200);
927        now.fetch_add(600, Ordering::SeqCst);
928        desk.sweep();
929        assert!(desk.state().runs.is_empty());
930        assert!(desk.state().wrong_by.is_empty());
931    }
932}