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
20const ISSUE_DRAWS: usize = 64;
22
23#[derive(Debug, Clone, PartialEq, Eq, coqui_builder::Describe)]
29#[map(deny_unknown_fields)]
30#[non_exhaustive]
31pub struct PairingOptions {
32 #[map(default = PairingOptions::default().invitation)]
34 pub invitation: bool,
35 #[map(default = PairingOptions::default().pin)]
37 pub pin: bool,
38 #[map(default = PairingOptions::default().pin_shown)]
42 pub pin_shown: bool,
43 #[map(default = PairingOptions::default().device)]
45 pub device: bool,
46 #[map(default = PairingOptions::default().pin_alphabet)]
48 pub pin_alphabet: CodeAlphabet,
49 #[map(default = PairingOptions::default().pin_ttl, none = "never")]
53 pub pin_ttl: Option<Duration>,
54 #[map(default = PairingOptions::default().pin_attempts)]
57 pub pin_attempts: u32,
58 #[map(default = PairingOptions::default().user_code_alphabet)]
61 pub user_code_alphabet: CodeAlphabet,
62 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, coqui_builder::Describe)]
88#[map(deny_unknown_fields)]
89#[non_exhaustive]
90pub struct DeskLimits {
91 #[map(default = DeskLimits::default().pending)]
93 pub pending: usize,
94 #[map(default = DeskLimits::default().pending_per_source)]
97 pub pending_per_source: usize,
98 #[map(default = DeskLimits::default().pin_runs_per_source)]
101 pub pin_runs_per_source: usize,
102 #[map(default = DeskLimits::default().wrong_codes_per_approver)]
105 pub wrong_codes_per_approver: usize,
106 #[map(default = DeskLimits::default().approver_window)]
109 pub approver_window: Duration,
110 #[map(default = DeskLimits::default().wrong_codes_total)]
113 pub wrong_codes_total: usize,
114 #[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 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 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
154 coqui_builder::non_defaults(self)
155 }
156}
157
158impl DeskLimits {
159 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
161 coqui_builder::non_defaults(self)
162 }
163}
164
165#[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 #[map(default = PairingDeskSettings::default().options)]
178 pub options: PairingOptions,
179 #[map(default = PairingDeskSettings::default().limits)]
181 pub limits: DeskLimits,
182}
183
184impl PairingDeskSettings {
185 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
187 coqui_builder::non_defaults(self)
188 }
189}
190
191#[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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226pub struct Ticket(u64);
227
228#[derive(Debug, Clone, PartialEq, Eq)]
230#[non_exhaustive]
231pub enum Decision {
232 Code(Pin),
234 Approved,
236 Denied,
238 Expired,
240}
241
242#[derive(Debug, Clone, PartialEq, Eq)]
244#[non_exhaustive]
245pub struct ShownPin {
246 pub pin: Pin,
248 pub expires: SystemTime,
250}
251
252#[derive(Debug, Clone, PartialEq, Eq)]
254#[non_exhaustive]
255pub struct PendingSlot {
256 pub slot: u8,
258 pub peer: PeerId,
260 pub source: Option<SocketAddr>,
262 pub expires: SystemTime,
264}
265
266#[derive(Debug, Clone, PartialEq, Eq)]
269#[non_exhaustive]
270pub struct PendingDevice {
271 pub peer: PeerId,
273 pub source: Option<SocketAddr>,
275 pub label: String,
277 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 decision: Option<Decision>,
297 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#[derive(Debug, Clone)]
341pub struct PairingDesk {
342 inner: Arc<Inner>,
343}
344
345#[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
380fn 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 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 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 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 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 pub fn non_defaults(&self) -> Vec<coqui_builder::NonDefault> {
493 self.settings().non_defaults()
494 }
495
496 pub fn options(&self) -> PairingOptions {
498 self.state().options.clone()
499 }
500
501 pub fn limits(&self) -> DeskLimits {
503 self.state().limits
504 }
505
506 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 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 pub fn clear_pin(&self) {
532 let mut state = self.state();
533 state.shown = None;
534 state.gone = PairRefusal::Exhausted;
535 }
536
537 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 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 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 pub fn approve(&self, device: &PendingDevice) -> Result<(), PairingError> {
651 self.settle(device.ticket, Decision::Approved)
652 }
653
654 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 pub fn sweep(&self) {
675 let changed = self.state().sweep();
676 if changed {
677 self.inner.changed.notify_all();
678 }
679 }
680
681 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 pub fn decided(&self, ticket: Ticket) -> Decided {
707 Decided {
708 desk: self.clone(),
709 ticket,
710 }
711 }
712
713 pub(crate) fn random(&self) -> Random {
715 self.state().random.clone()
716 }
717
718 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 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 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 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 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#[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}