Skip to main content

coqui_peer/pair/
code.rs

1use core::fmt;
2
3use subtle::ConstantTimeEq;
4
5use crate::error::Error;
6use crate::random::Random;
7
8/// The characters and length of a short code a person reads and types: a PIN or a device-flow
9/// user code.
10///
11/// The crate matches codes exactly over `chars`: it ignores no case, dash or space. Normalising
12/// what a person typed, and grouping a code for display, is the caller's. Any alphabet and
13/// length with a meaning is accepted; [`combinations`](CodeAlphabet::combinations) says how many
14/// codes there are, which is what an attacker's one guess is against.
15#[derive(Debug, Clone, PartialEq, Eq, coqui_builder::Describe)]
16#[map(deny_unknown_fields)]
17#[non_exhaustive]
18pub struct CodeAlphabet {
19    /// The characters a code is made of, each once.
20    pub chars: String,
21    /// How many characters a code has.
22    pub len: usize,
23}
24
25impl CodeAlphabet {
26    /// An alphabet of the characters `chars`, each once, and codes of `len` of them.
27    pub fn new(chars: impl Into<String>, len: usize) -> Self {
28        Self {
29            chars: chars.into(),
30            len,
31        }
32    }
33
34    /// The default PIN alphabet: `0123456789`, 6 characters (10^6 codes).
35    pub fn pin() -> Self {
36        Self {
37            chars: "0123456789".to_owned(),
38            len: 6,
39        }
40    }
41
42    /// The default user-code alphabet of RFC 8628 section 6.1: `BCDFGHJKLMNPQRSTVWXZ`, 8
43    /// characters (about 2.6 × 10^10 codes).
44    pub fn user_code() -> Self {
45        Self {
46            chars: "BCDFGHJKLMNPQRSTVWXZ".to_owned(),
47            len: 8,
48        }
49    }
50
51    /// How many distinct codes there are, saturating at `u128::MAX`.
52    pub fn combinations(&self) -> u128 {
53        let base = self.chars.chars().count() as u128;
54        u32::try_from(self.len)
55            .ok()
56            .and_then(|len| base.checked_pow(len))
57            .unwrap_or(u128::MAX)
58    }
59
60    /// Whether the alphabet has a meaning.
61    ///
62    /// # Errors
63    ///
64    /// [`Error::InvalidOptions`] when `chars` is empty, repeats a character or holds a control
65    /// character, or `len` is 0.
66    pub fn check(&self) -> Result<(), Error> {
67        let chars: Vec<char> = self.chars.chars().collect();
68        let repeated = chars
69            .iter()
70            .enumerate()
71            .any(|(index, c)| chars[..index].contains(c));
72        if chars.is_empty() || repeated || chars.iter().any(|c| c.is_control()) || self.len == 0 {
73            return Err(Error::InvalidOptions);
74        }
75        Ok(())
76    }
77
78    /// A uniformly random code.
79    ///
80    /// # Errors
81    ///
82    /// [`Error::InvalidOptions`] as [`check`](CodeAlphabet::check); [`Error::Random`] when the
83    /// source fails.
84    pub(crate) fn generate(&self, random: &Random) -> Result<String, Error> {
85        self.check()?;
86        let chars: Vec<char> = self.chars.chars().collect();
87        let mut code = String::with_capacity(self.len);
88        for _ in 0..self.len {
89            code.push(chars[below(random, chars.len())?]);
90        }
91        Ok(code)
92    }
93
94    /// `text` when it is exactly `len` characters of this alphabet.
95    ///
96    /// # Errors
97    ///
98    /// [`Error::InvalidOptions`] as [`check`](CodeAlphabet::check); [`Error::InvalidCode`]
99    /// otherwise.
100    pub(crate) fn parse(&self, text: &str) -> Result<String, Error> {
101        self.check()?;
102        if text.chars().count() != self.len || !text.chars().all(|c| self.chars.contains(c)) {
103            return Err(Error::InvalidCode);
104        }
105        Ok(text.to_owned())
106    }
107}
108
109/// A uniformly random index below `bound`, by rejection sampling of four random bytes.
110pub(crate) fn below(random: &Random, bound: usize) -> Result<usize, Error> {
111    let bound = u64::try_from(bound.max(1)).unwrap_or(u64::MAX);
112    let span = 1u64 << 32;
113    let limit = span - span % bound;
114    loop {
115        let mut bytes = [0u8; 4];
116        random.fill(&mut bytes)?;
117        let value = u64::from(u32::from_be_bytes(bytes));
118        if value < limit {
119            return Ok(usize::try_from(value % bound).unwrap_or(0));
120        }
121    }
122}
123
124/// Whether two codes are equal, in time that does not depend on where they differ.
125pub(crate) fn same(left: &str, right: &str) -> bool {
126    left.len() == right.len() && bool::from(left.as_bytes().ct_eq(right.as_bytes()))
127}
128
129/// A PIN: a short code one side shows and a person types on the other, checked by a PAKE.
130/// `Debug` does not show it.
131#[derive(Clone, PartialEq, Eq)]
132pub struct Pin(String);
133
134impl Pin {
135    /// A random PIN of `alphabet`.
136    ///
137    /// # Errors
138    ///
139    /// [`Error::InvalidOptions`] for a meaningless alphabet, [`Error::Random`].
140    pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
141        alphabet.generate(random).map(Self)
142    }
143
144    /// `text` as a PIN of `alphabet`, matched exactly.
145    ///
146    /// # Errors
147    ///
148    /// [`Error::InvalidCode`] when it is not exactly `len` characters of the alphabet.
149    pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
150        alphabet.parse(text).map(Self)
151    }
152
153    /// The characters, to show.
154    pub fn as_str(&self) -> &str {
155        &self.0
156    }
157}
158
159impl Drop for Pin {
160    fn drop(&mut self) {
161        zeroize::Zeroize::zeroize(&mut self.0);
162    }
163}
164
165impl fmt::Debug for Pin {
166    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
167        formatter.write_str("Pin(..)")
168    }
169}
170
171/// What a person types at the responder when the joiner shows its PIN: the slot the responder
172/// assigned to that joiner, and the PIN. Plain data: joining and splitting the text a person
173/// reads (`37-482913`, say) is the caller's.
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct PairingCode {
176    /// The responder's handle for the waiting joiner, 0 to 99; not secret. `None` when the
177    /// responder shows the PIN.
178    pub slot: Option<u8>,
179    /// The PIN.
180    pub pin: Pin,
181}
182
183/// A device-flow user code: the responder issues it, the joiner shows it, and the operator
184/// enters it at the responder to approve. `Debug` does not show it.
185#[derive(Clone, PartialEq, Eq)]
186pub struct UserCode(String);
187
188impl UserCode {
189    /// A code as the responder sent it; the joiner shows it as it is.
190    pub(crate) fn issued(text: String) -> Self {
191        Self(text)
192    }
193
194    /// A random user code of `alphabet`.
195    ///
196    /// # Errors
197    ///
198    /// [`Error::InvalidOptions`] for a meaningless alphabet, [`Error::Random`].
199    pub fn generate(alphabet: &CodeAlphabet, random: &Random) -> Result<Self, Error> {
200        alphabet.generate(random).map(Self)
201    }
202
203    /// `text` as a user code of `alphabet`, matched exactly.
204    ///
205    /// # Errors
206    ///
207    /// [`Error::InvalidCode`] when it is not exactly `len` characters of the alphabet.
208    pub fn parse(alphabet: &CodeAlphabet, text: &str) -> Result<Self, Error> {
209        alphabet.parse(text).map(Self)
210    }
211
212    /// The characters, to show.
213    pub fn as_str(&self) -> &str {
214        &self.0
215    }
216}
217
218impl fmt::Debug for UserCode {
219    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220        formatter.write_str("UserCode(..)")
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn codes_match_exactly_over_their_alphabet() {
230        let alphabet = CodeAlphabet::user_code();
231        assert!(UserCode::parse(&alphabet, "WDJBMJHT").is_ok());
232        for bad in [
233            "wdjbmjht",
234            "WDJB-MJHT",
235            "WDJB MJHT",
236            "WDJBMJH",
237            "WDJBMJHTA",
238            "AAAAAAAA",
239        ] {
240            assert!(matches!(
241                UserCode::parse(&alphabet, bad),
242                Err(Error::InvalidCode)
243            ));
244        }
245        assert!(Pin::parse(&CodeAlphabet::pin(), "482913").is_ok());
246        assert!(Pin::parse(&CodeAlphabet::pin(), "48291a").is_err());
247    }
248
249    #[test]
250    fn combinations_are_reported_not_refused() {
251        assert_eq!(CodeAlphabet::pin().combinations(), 1_000_000);
252        assert_eq!(CodeAlphabet::user_code().combinations(), 20u128.pow(8));
253        let tiny = CodeAlphabet::new("01", 1);
254        assert!(tiny.check().is_ok());
255        assert_eq!(tiny.combinations(), 2);
256        let huge = CodeAlphabet::new("01", 1000);
257        assert_eq!(huge.combinations(), u128::MAX);
258    }
259
260    #[test]
261    fn meaningless_alphabets_are_errors() {
262        for (chars, len) in [("", 6), ("0123", 0), ("0012", 4), ("01\n", 4)] {
263            let alphabet = CodeAlphabet {
264                chars: chars.to_owned(),
265                len,
266            };
267            assert!(matches!(alphabet.check(), Err(Error::InvalidOptions)));
268        }
269    }
270
271    #[test]
272    fn generated_codes_use_the_whole_alphabet() {
273        let counter = core::sync::atomic::AtomicU32::new(0);
274        let random = Random::from_fn(move |out| {
275            let value = counter.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
276            out.copy_from_slice(&value.to_be_bytes()[..out.len()]);
277            Ok(())
278        });
279        let alphabet = CodeAlphabet::pin();
280        let code = Pin::generate(&alphabet, &random).unwrap();
281        assert_eq!(code.as_str(), "012345");
282        assert!(Pin::parse(&alphabet, code.as_str()).is_ok());
283    }
284}