use alloc::collections::VecDeque;
use alloc::sync::Arc;
use core::future::Future;
use core::net::{IpAddr, SocketAddr};
use core::pin::Pin as Pinned;
use core::task::{Context, Poll, Waker};
use core::time::Duration;
use std::collections::HashMap;
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError};
use std::time::SystemTime;
use crate::clock::{Clock, later};
use crate::error::Error;
use crate::id::PeerId;
use crate::pair::code::{CodeAlphabet, PairingCode, Pin, UserCode, below, same};
use crate::pair::{PairRefusal, PairingError};
use crate::random::Random;
use crate::store::{DEFAULT_IPV6_PREFIX, source_key};
use crate::weakening::Weakening;
const ISSUE_DRAWS: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PairingOptions {
pub invitation: bool,
pub pin: bool,
pub device: bool,
pub pin_alphabet: CodeAlphabet,
pub pin_ttl: Duration,
pub pin_attempts: u32,
pub user_code_alphabet: CodeAlphabet,
pub device_ttl: Duration,
}
impl Default for PairingOptions {
fn default() -> Self {
Self {
invitation: true,
pin: true,
device: true,
pin_alphabet: CodeAlphabet::pin(),
pin_ttl: Duration::from_secs(600),
pin_attempts: 1,
user_code_alphabet: CodeAlphabet::user_code(),
device_ttl: Duration::from_secs(600),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeskLimits {
pub pending: usize,
pub pending_per_source: usize,
pub pin_runs_per_source: usize,
pub wrong_codes_per_approver: usize,
pub approver_window: Duration,
pub wrong_codes_total: usize,
pub ipv6_prefix: u8,
}
impl Default for DeskLimits {
fn default() -> Self {
Self {
pending: 32,
pending_per_source: 4,
pin_runs_per_source: 8,
wrong_codes_per_approver: 5,
approver_window: Duration::from_secs(60),
wrong_codes_total: 60,
ipv6_prefix: DEFAULT_IPV6_PREFIX,
}
}
}
fn note(found: &mut Vec<Weakening>, setting: &str, value: String, strict: String) {
found.push(Weakening::new(setting, value, strict));
}
impl PairingOptions {
pub fn check(&self) -> Result<(), Error> {
self.pin_alphabet.check()?;
self.user_code_alphabet.check()?;
if self.pin_ttl.is_zero() || self.device_ttl.is_zero() || self.pin_attempts == 0 {
return Err(Error::InvalidOptions);
}
Ok(())
}
pub fn weakened(&self) -> Vec<Weakening> {
let default = Self::default();
let mut found = Vec::new();
if self.pin_alphabet.combinations() < default.pin_alphabet.combinations() {
note(
&mut found,
"pin_alphabet",
self.pin_alphabet.combinations().to_string(),
default.pin_alphabet.combinations().to_string(),
);
}
if self.pin_attempts > default.pin_attempts {
note(
&mut found,
"pin_attempts",
self.pin_attempts.to_string(),
default.pin_attempts.to_string(),
);
}
if self.pin_ttl > default.pin_ttl {
note(
&mut found,
"pin_ttl",
self.pin_ttl.as_secs().to_string(),
default.pin_ttl.as_secs().to_string(),
);
}
if self.user_code_alphabet.combinations() < default.user_code_alphabet.combinations() {
note(
&mut found,
"user_code_alphabet",
self.user_code_alphabet.combinations().to_string(),
default.user_code_alphabet.combinations().to_string(),
);
}
if self.device_ttl > default.device_ttl {
note(
&mut found,
"device_ttl",
self.device_ttl.as_secs().to_string(),
default.device_ttl.as_secs().to_string(),
);
}
found
}
}
impl DeskLimits {
pub fn weakened(&self) -> Vec<Weakening> {
let default = Self::default();
let mut found = Vec::new();
for (setting, value, standard) in [
("pending", self.pending, default.pending),
(
"pending_per_source",
self.pending_per_source,
default.pending_per_source,
),
(
"pin_runs_per_source",
self.pin_runs_per_source,
default.pin_runs_per_source,
),
(
"wrong_codes_per_approver",
self.wrong_codes_per_approver,
default.wrong_codes_per_approver,
),
(
"wrong_codes_total",
self.wrong_codes_total,
default.wrong_codes_total,
),
] {
if value > standard {
note(&mut found, setting, value.to_string(), standard.to_string());
}
}
if self.approver_window < default.approver_window {
note(
&mut found,
"approver_window",
self.approver_window.as_secs().to_string(),
default.approver_window.as_secs().to_string(),
);
}
if self.ipv6_prefix > default.ipv6_prefix {
note(
&mut found,
"ipv6_prefix",
self.ipv6_prefix.to_string(),
default.ipv6_prefix.to_string(),
);
}
found
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ticket(u64);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Decision {
Code(Pin),
Approved,
Denied,
Expired,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShownPin {
pub pin: Pin,
pub expires: SystemTime,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingSlot {
pub slot: u8,
pub peer: PeerId,
pub source: Option<SocketAddr>,
pub expires: SystemTime,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingDevice {
pub peer: PeerId,
pub source: Option<SocketAddr>,
pub label: String,
pub expires: SystemTime,
ticket: Ticket,
}
#[derive(Debug)]
enum Kind {
Slot(u8),
Device(UserCode),
}
#[derive(Debug)]
struct Waiting {
kind: Kind,
peer: PeerId,
source: Option<SocketAddr>,
label: String,
expires: SystemTime,
decision: Option<Decision>,
settled: bool,
waker: Option<Waker>,
}
#[derive(Debug)]
struct State {
options: PairingOptions,
limits: DeskLimits,
clock: Clock,
random: Random,
shown: Option<(ShownPin, u32)>,
gone: PairRefusal,
waiting: HashMap<u64, Waiting>,
next: u64,
pending: usize,
pending_by: HashMap<Option<IpAddr>, usize>,
runs: HashMap<Option<IpAddr>, VecDeque<SystemTime>>,
wrong_by: HashMap<String, VecDeque<SystemTime>>,
wrong_all: VecDeque<SystemTime>,
}
#[derive(Debug)]
struct Inner {
state: Mutex<State>,
changed: Condvar,
}
#[derive(Debug, Clone)]
pub struct PairingDesk {
inner: Arc<Inner>,
}
#[derive(Debug)]
pub(crate) struct Admission {
inner: Arc<Inner>,
id: u64,
bucket: Option<IpAddr>,
}
impl Admission {
pub(crate) fn ticket(&self) -> Ticket {
Ticket(self.id)
}
}
impl Drop for Admission {
fn drop(&mut self) {
let mut state = self
.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner);
state.pending = state.pending.saturating_sub(1);
if let Some(count) = state.pending_by.get_mut(&self.bucket) {
*count = count.saturating_sub(1);
if *count == 0 {
state.pending_by.remove(&self.bucket);
}
}
state.waiting.remove(&self.id);
drop(state);
self.inner.changed.notify_all();
}
}
fn prune(times: &mut VecDeque<SystemTime>, now: SystemTime, window: Duration) {
while times
.front()
.is_some_and(|at| now.duration_since(*at).unwrap_or_default() >= window)
{
times.pop_front();
}
}
impl State {
fn sweep(&mut self) -> bool {
let now = self.clock.now();
let mut changed = false;
if self
.shown
.as_ref()
.is_some_and(|(shown, _)| now >= shown.expires)
{
self.shown = None;
self.gone = PairRefusal::Expired;
changed = true;
}
for waiting in self.waiting.values_mut() {
if !waiting.settled && now >= waiting.expires {
waiting.decision = Some(Decision::Expired);
waiting.settled = true;
if let Some(waker) = waiting.waker.take() {
waker.wake();
}
changed = true;
}
}
let (ttl, window) = (self.options.pin_ttl, self.limits.approver_window);
self.runs.retain(|_, times| {
prune(times, now, ttl);
!times.is_empty()
});
self.wrong_by.retain(|_, times| {
prune(times, now, window);
!times.is_empty()
});
changed
}
fn decide(&mut self, ticket: Ticket, decision: Decision) -> Result<(), PairingError> {
let waiting = self
.waiting
.get_mut(&ticket.0)
.filter(|waiting| !waiting.settled)
.ok_or(PairingError::Refused(PairRefusal::Expired))?;
waiting.decision = Some(decision);
waiting.settled = true;
if let Some(waker) = waiting.waker.take() {
waker.wake();
}
Ok(())
}
}
impl PairingDesk {
pub fn new(random: Random) -> Self {
Self {
inner: Arc::new(Inner {
state: Mutex::new(State {
options: PairingOptions::default(),
limits: DeskLimits::default(),
clock: Clock::system(),
random,
shown: None,
gone: PairRefusal::Exhausted,
waiting: HashMap::new(),
next: 0,
pending: 0,
pending_by: HashMap::new(),
runs: HashMap::new(),
wrong_by: HashMap::new(),
wrong_all: VecDeque::new(),
}),
changed: Condvar::new(),
}),
}
}
fn state(&self) -> MutexGuard<'_, State> {
self.inner
.state
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub fn with_options(self, options: PairingOptions) -> Result<Self, Error> {
options.check()?;
self.state().options = options;
Ok(self)
}
#[must_use]
pub fn with_limits(self, limits: DeskLimits) -> Self {
self.state().limits = limits;
self
}
#[must_use]
pub fn with_clock(self, clock: Clock) -> Self {
self.state().clock = clock;
self
}
pub fn options(&self) -> PairingOptions {
self.state().options.clone()
}
pub fn limits(&self) -> DeskLimits {
self.state().limits
}
pub fn show_pin(&self) -> Result<ShownPin, Error> {
let mut state = self.state();
let pin = Pin::generate(&state.options.pin_alphabet, &state.random)?;
let shown = ShownPin {
pin,
expires: later(state.clock.now(), state.options.pin_ttl),
};
state.shown = Some((shown.clone(), state.options.pin_attempts));
Ok(shown)
}
pub fn shown_pin(&self) -> Option<ShownPin> {
let mut state = self.state();
state.sweep();
state.shown.as_ref().map(|(shown, _)| shown.clone())
}
pub fn clear_pin(&self) {
let mut state = self.state();
state.shown = None;
state.gone = PairRefusal::Exhausted;
}
pub fn slots(&self) -> Vec<PendingSlot> {
let mut state = self.state();
state.sweep();
let mut slots: Vec<PendingSlot> = state
.waiting
.values()
.filter(|waiting| !waiting.settled)
.filter_map(|waiting| match waiting.kind {
Kind::Slot(slot) => Some(PendingSlot {
slot,
peer: waiting.peer,
source: waiting.source,
expires: waiting.expires,
}),
Kind::Device(_) => None,
})
.collect();
slots.sort_by_key(|slot| slot.slot);
slots
}
pub fn submit_code(&self, code: &PairingCode) -> Result<(), PairingError> {
let mut state = self.state();
state.sweep();
let ticket = state
.waiting
.iter()
.find(|(_, waiting)| {
!waiting.settled
&& matches!(waiting.kind, Kind::Slot(slot) if Some(slot) == code.slot)
})
.map(|(id, _)| Ticket(*id))
.ok_or(PairingError::Refused(PairRefusal::WrongCode))?;
state.decide(ticket, Decision::Code(code.pin.clone()))?;
drop(state);
self.inner.changed.notify_all();
Ok(())
}
pub fn find_device(&self, approver: &str, code: &str) -> Result<PendingDevice, PairingError> {
let mut state = self.state();
state.sweep();
let entered = UserCode::parse(&state.options.user_code_alphabet, code)
.map_err(PairingError::Local)?;
let now = state.clock.now();
let (limits, ttl) = (state.limits, state.options.device_ttl);
let by = state.wrong_by.entry(approver.to_owned()).or_default();
prune(by, now, limits.approver_window);
let by_count = by.len();
prune(&mut state.wrong_all, now, ttl);
if by_count >= limits.wrong_codes_per_approver
|| state.wrong_all.len() >= limits.wrong_codes_total
{
return Err(PairingError::Refused(PairRefusal::Throttled));
}
let mut found = None;
for (id, waiting) in &state.waiting {
if let Kind::Device(issued) = &waiting.kind
&& !waiting.settled
&& same(issued.as_str(), entered.as_str())
{
found = Some(PendingDevice {
peer: waiting.peer,
source: waiting.source,
label: waiting.label.clone(),
expires: waiting.expires,
ticket: Ticket(*id),
});
}
}
match found {
Some(device) => Ok(device),
None => {
state
.wrong_by
.entry(approver.to_owned())
.or_default()
.push_back(now);
state.wrong_all.push_back(now);
Err(PairingError::Refused(PairRefusal::WrongCode))
}
}
}
pub fn approve(&self, device: &PendingDevice) -> Result<(), PairingError> {
self.settle(device.ticket, Decision::Approved)
}
pub fn deny(&self, device: &PendingDevice) -> Result<(), PairingError> {
self.settle(device.ticket, Decision::Denied)
}
fn settle(&self, ticket: Ticket, decision: Decision) -> Result<(), PairingError> {
let mut state = self.state();
state.sweep();
state.decide(ticket, decision)?;
drop(state);
self.inner.changed.notify_all();
Ok(())
}
pub fn sweep(&self) {
let changed = self.state().sweep();
if changed {
self.inner.changed.notify_all();
}
}
pub fn wait(&self, ticket: Ticket) -> Decision {
let mut state = self.state();
loop {
state.sweep();
match state.waiting.get_mut(&ticket.0) {
None => return Decision::Expired,
Some(waiting) => {
if let Some(decision) = waiting.decision.take() {
return decision;
}
}
}
state = self
.inner
.changed
.wait_timeout(state, Duration::from_secs(1))
.unwrap_or_else(PoisonError::into_inner)
.0;
}
}
pub fn decided(&self, ticket: Ticket) -> Decided {
Decided {
desk: self.clone(),
ticket,
}
}
pub(crate) fn random(&self) -> Random {
self.state().random.clone()
}
pub(crate) fn now(&self) -> SystemTime {
self.state().clock.now()
}
pub(crate) fn admit(&self, source: Option<SocketAddr>) -> Result<Admission, PairRefusal> {
let mut state = self.state();
let bucket = source.map(|s| source_key(s.ip(), state.limits.ipv6_prefix));
let from_source = state.pending_by.get(&bucket).copied().unwrap_or(0);
if state.pending >= state.limits.pending || from_source >= state.limits.pending_per_source {
return Err(PairRefusal::Throttled);
}
state.pending += 1;
*state.pending_by.entry(bucket).or_insert(0) += 1;
state.next += 1;
Ok(Admission {
inner: self.inner.clone(),
id: state.next,
bucket,
})
}
pub(crate) fn pin_run(&self, source: Option<SocketAddr>) -> Result<(), PairRefusal> {
let mut state = self.state();
let now = state.clock.now();
let (ttl, limits) = (state.options.pin_ttl, state.limits);
let bucket = source.map(|s| source_key(s.ip(), limits.ipv6_prefix));
let runs = state.runs.entry(bucket).or_default();
prune(runs, now, ttl);
if runs.len() >= limits.pin_runs_per_source {
return Err(PairRefusal::Throttled);
}
runs.push_back(now);
Ok(())
}
pub(crate) fn pin_ready(&self) -> Result<(), PairRefusal> {
let mut state = self.state();
state.sweep();
if state.shown.is_some() {
Ok(())
} else {
Err(state.gone)
}
}
pub(crate) fn take_pin(&self) -> Result<Pin, PairRefusal> {
let mut state = self.state();
state.sweep();
let gone = state.gone;
let (shown, left) = state.shown.as_mut().ok_or(gone)?;
let pin = shown.pin.clone();
*left -= 1;
if *left == 0 {
state.shown = None;
state.gone = PairRefusal::Exhausted;
}
Ok(pin)
}
pub(crate) fn open_slot(
&self,
admission: &Admission,
peer: PeerId,
source: Option<SocketAddr>,
) -> Result<u8, PairingError> {
let mut state = self.state();
state.sweep();
let used: Vec<u8> = state
.waiting
.values()
.filter_map(|waiting| match waiting.kind {
Kind::Slot(slot) => Some(slot),
Kind::Device(_) => None,
})
.collect();
let free: Vec<u8> = (0..100).filter(|slot| !used.contains(slot)).collect();
if free.is_empty() {
return Err(PairingError::Refused(PairRefusal::Throttled));
}
let slot = free[below(&state.random, free.len()).map_err(PairingError::Local)?];
let expires = later(state.clock.now(), state.options.pin_ttl);
state.waiting.insert(
admission.id,
Waiting {
kind: Kind::Slot(slot),
peer,
source,
label: String::new(),
expires,
decision: None,
settled: false,
waker: None,
},
);
Ok(slot)
}
pub(crate) fn issue(
&self,
admission: &Admission,
peer: PeerId,
source: Option<SocketAddr>,
label: &str,
) -> Result<(UserCode, SystemTime), PairingError> {
let mut state = self.state();
state.sweep();
let issued = state
.waiting
.values()
.filter(|waiting| matches!(waiting.kind, Kind::Device(_)))
.count();
if issued as u128 >= state.options.user_code_alphabet.combinations() {
return Err(PairingError::Refused(PairRefusal::Throttled));
}
let mut code = None;
for _ in 0..ISSUE_DRAWS {
let drawn = UserCode::generate(&state.options.user_code_alphabet, &state.random)
.map_err(PairingError::Local)?;
let taken = state
.waiting
.values()
.any(|waiting| matches!(&waiting.kind, Kind::Device(issued) if issued == &drawn));
if !taken {
code = Some(drawn);
break;
}
}
let code = code.ok_or(PairingError::Refused(PairRefusal::Throttled))?;
let expires = later(state.clock.now(), state.options.device_ttl);
state.waiting.insert(
admission.id,
Waiting {
kind: Kind::Device(code.clone()),
peer,
source,
label: label.to_owned(),
expires,
decision: None,
settled: false,
waker: None,
},
);
Ok((code, expires))
}
}
#[derive(Debug)]
pub struct Decided {
desk: PairingDesk,
ticket: Ticket,
}
impl Future for Decided {
type Output = Decision;
fn poll(self: Pinned<&mut Self>, context: &mut Context<'_>) -> Poll<Decision> {
let mut state = self.desk.state();
state.sweep();
match state.waiting.get_mut(&self.ticket.0) {
None => Poll::Ready(Decision::Expired),
Some(waiting) => match waiting.decision.take() {
Some(decision) => Poll::Ready(decision),
None => {
waiting.waker = Some(context.waker().clone());
Poll::Pending
}
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::sync::atomic::{AtomicU64, Ordering};
use std::time::UNIX_EPOCH;
#[test]
fn the_buckets_of_past_windows_are_dropped() {
let now = Arc::new(AtomicU64::new(1_800_000_000));
let seen = now.clone();
let clock =
Clock::from_fn(move || UNIX_EPOCH + Duration::from_secs(seen.load(Ordering::SeqCst)));
let desk = PairingDesk::new(Random::from_fn(|out| {
out.fill(7);
Ok(())
}))
.with_clock(clock)
.with_limits(DeskLimits {
wrong_codes_total: 1000,
..DeskLimits::default()
});
for host in 0..200u8 {
let source = SocketAddr::from(([192, 0, 2, host], 1000));
desk.pin_run(Some(source)).unwrap();
let _ = desk.find_device(&format!("approver {host}"), "BBBBBBBB");
}
assert_eq!(desk.state().runs.len(), 200);
assert_eq!(desk.state().wrong_by.len(), 200);
now.fetch_add(600, Ordering::SeqCst);
desk.sweep();
assert!(desk.state().runs.is_empty());
assert!(desk.state().wrong_by.is_empty());
}
}