Skip to main content

brep_plm/
desktop_link.rs

1//! Signing the desktop app in through the user's browser: a device
2//! authorization flow in the spirit of RFC 8628.
3//!
4//! 1. The app registers ([`DesktopLinks::register`]) with no credential and
5//!    gets three things back: a **link token** (the only one that goes in a
6//!    URL), a **poll secret** (never in a URL), and a short **code** it shows.
7//! 2. The app opens `/desktop-link?token=<link token>` in the default browser.
8//!    Signed out, the page signs in first and comes back to the link.
9//! 3. A signed-in person sees what asked (host, OS, address) and the code, and
10//!    clicks Approve or Deny ([`DesktopLinks::decide`]). Nothing is approved by
11//!    opening the page: a link someone else registered and sent to a victim
12//!    must not hand the sender the victim's account.
13//! 4. The app polls with its secret ([`DesktopLinks::poll`]); once approved,
14//!    the handler mints an API token for the approver and hands it over, once.
15//!
16//! A decision kills the link token, so a URL read later decides nothing; the
17//! link token never polls, so a URL read early collects nothing. Pending links
18//! live in memory for [`TTL`] seconds: a restart forgets them, which costs a
19//! user one more click. Only SHA-256 hashes of the token and the secret are
20//! kept, and they are compared in constant time.
21
22use std::collections::HashMap;
23use std::sync::Mutex;
24
25use serde::{Deserialize, Serialize};
26
27use crate::model::{Actor, Timestamp};
28use crate::security::{same_secret, token_hash};
29use crate::Error;
30
31/// How long a link waits for a decision and then for the app to collect it.
32pub const TTL: u64 = 10 * 60;
33/// How often the app should poll, in seconds.
34pub const INTERVAL: u64 = 2;
35/// Registrations one address may make in a minute.
36pub const REGISTER_PER_MINUTE: usize = 10;
37/// Links pending at once, all addresses together.
38const MAX_PENDING: usize = 1000;
39/// The longest host / OS / version text kept, in characters.
40const MAX_TEXT: usize = 64;
41/// The code's alphabet: no 0/O, 1/I/L, so it reads aloud and copies right.
42const CODE_ALPHABET: &[u8] = b"ABCDEFGHJKMNPQRSTUVWXYZ23456789";
43
44/// What the app says about itself, shown to the person deciding.
45#[derive(Debug, Clone, Default, Deserialize, Serialize)]
46pub struct Asker {
47    #[serde(default)]
48    pub host: String,
49    #[serde(default)]
50    pub os: String,
51    #[serde(default)]
52    pub app_version: String,
53}
54
55impl Asker {
56    /// Trimmed, one line, at most [`MAX_TEXT`] characters each.
57    fn tidy(self) -> Self {
58        let tidy = |text: String| -> String {
59            text.chars().map(|c| if c.is_control() { ' ' } else { c }).collect::<String>().trim().chars().take(MAX_TEXT).collect()
60        };
61        Self { host: tidy(self.host), os: tidy(self.os), app_version: tidy(self.app_version) }
62    }
63}
64
65/// A registration's answer: the secrets exist only here, never in the store.
66#[derive(Debug, Clone, Serialize)]
67pub struct Registered {
68    pub link_token: String,
69    pub poll_secret: String,
70    pub code: String,
71    /// The link page, relative to the server: the app joins it to its URL.
72    pub path: String,
73    pub expires_in: u64,
74    pub interval: u64,
75}
76
77/// A pending link as the confirm page sees it.
78#[derive(Debug, Clone, Serialize)]
79pub struct LinkView {
80    pub code: String,
81    pub host: String,
82    pub os: String,
83    pub app_version: String,
84    /// The address the registration came from.
85    pub ip: String,
86    pub expires_in: u64,
87}
88
89/// What a poll finds.
90#[derive(Debug, Clone)]
91pub enum Poll {
92    Pending,
93    Denied,
94    /// Approved by this person; the link is gone now, the handler mints.
95    Approved { by: Actor, asker: Asker },
96    /// No link with that secret: never was, expired, or already collected.
97    Unknown,
98}
99
100#[derive(Clone)]
101enum Decision {
102    Pending,
103    Denied,
104    Approved(Actor),
105}
106
107#[derive(Clone)]
108struct Link {
109    /// Hash of the link token; empty once decided, so it matches nothing.
110    token_hash: String,
111    secret_hash: String,
112    code: String,
113    asker: Asker,
114    ip: String,
115    expires_at: Timestamp,
116    decision: Decision,
117}
118
119/// Every pending link, and the registration counts per address.
120#[derive(Default)]
121pub struct DesktopLinks {
122    links: Mutex<Vec<Link>>,
123    registrations: Mutex<HashMap<String, Vec<Timestamp>>>,
124}
125
126impl std::fmt::Debug for DesktopLinks {
127    /// Counts only: a link's hashes are no one's business in a log.
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        let pending = self.links.lock().map(|l| l.len()).unwrap_or(0);
130        f.debug_struct("DesktopLinks").field("pending", &pending).finish()
131    }
132}
133
134impl DesktopLinks {
135    fn links(&self) -> std::sync::MutexGuard<'_, Vec<Link>> {
136        self.links.lock().unwrap_or_else(|e| e.into_inner())
137    }
138
139    /// Register a link for `asker`, from `ip`. Refused with `429` past
140    /// [`REGISTER_PER_MINUTE`] from one address, or `MAX_PENDING` in all.
141    pub fn register(&self, asker: Asker, ip: Option<String>, now: Timestamp) -> Result<Registered, Error> {
142        let ip = ip.unwrap_or_default();
143        {
144            let mut counts = self.registrations.lock().unwrap_or_else(|e| e.into_inner());
145            counts.retain(|_, times| {
146                times.retain(|&t| now.saturating_sub(t) < 60);
147                !times.is_empty()
148            });
149            let times = counts.entry(ip.clone()).or_default();
150            if times.len() >= REGISTER_PER_MINUTE {
151                return Err(Error::too_many("too many sign-in requests from this address — wait a minute and try again"));
152            }
153            times.push(now);
154        }
155        let mut links = self.links();
156        links.retain(|link| link.expires_at > now);
157        if links.len() >= MAX_PENDING {
158            return Err(Error::too_many("too many sign-in requests are waiting — try again in a few minutes"));
159        }
160        let link_token = crate::auth::random_token(32);
161        let poll_secret = crate::auth::random_token(32);
162        let code = new_code();
163        links.push(Link {
164            token_hash: token_hash(&link_token),
165            secret_hash: token_hash(&poll_secret),
166            code: code.clone(),
167            asker: asker.tidy(),
168            ip,
169            expires_at: now + TTL,
170            decision: Decision::Pending,
171        });
172        Ok(Registered {
173            path: format!("/desktop-link?token={link_token}"),
174            link_token,
175            poll_secret,
176            code,
177            expires_in: TTL,
178            interval: INTERVAL,
179        })
180    }
181
182    /// The undecided, unexpired link `token` opens, for the confirm page.
183    pub fn inspect(&self, token: &str, now: Timestamp) -> Option<LinkView> {
184        let hash = token_hash(token);
185        let links = self.links();
186        let link = links.iter().find(|l| l.expires_at > now && !l.token_hash.is_empty() && same_secret(&l.token_hash, &hash))?;
187        Some(LinkView {
188            code: link.code.clone(),
189            host: link.asker.host.clone(),
190            os: link.asker.os.clone(),
191            app_version: link.asker.app_version.clone(),
192            ip: link.ip.clone(),
193            expires_in: link.expires_at - now,
194        })
195    }
196
197    /// Decide the link `token` opens: approve as `by`, or deny with `None`.
198    /// The token is dead afterwards either way. Returns the asker, for the
199    /// audit entry.
200    pub fn decide(&self, token: &str, by: Option<Actor>, now: Timestamp) -> Result<Asker, Error> {
201        let hash = token_hash(token);
202        let mut links = self.links();
203        let link = links
204            .iter_mut()
205            .find(|l| l.expires_at > now && !l.token_hash.is_empty() && same_secret(&l.token_hash, &hash))
206            .ok_or_else(gone)?;
207        link.token_hash.clear();
208        link.decision = match by {
209            Some(actor) => Decision::Approved(actor),
210            None => Decision::Denied,
211        };
212        Ok(link.asker.clone())
213    }
214
215    /// What the app holding `secret` finds. An approval is handed out once:
216    /// the link is removed as it is read.
217    pub fn poll(&self, secret: &str, now: Timestamp) -> Poll {
218        let hash = token_hash(secret);
219        let mut links = self.links();
220        links.retain(|link| link.expires_at > now);
221        let Some(at) = links.iter().position(|l| same_secret(&l.secret_hash, &hash)) else {
222            return Poll::Unknown;
223        };
224        match &links[at].decision {
225            Decision::Pending => Poll::Pending,
226            Decision::Denied => Poll::Denied,
227            Decision::Approved(_) => {
228                let link = links.remove(at);
229                let Decision::Approved(by) = link.decision else { unreachable!() };
230                Poll::Approved { by, asker: link.asker }
231            }
232        }
233    }
234}
235
236/// The one refusal for a link token that opens nothing: never existed,
237/// expired, or already decided. Which one is no business of a URL holder.
238pub fn gone() -> Error {
239    Error {
240        status: axum::http::StatusCode::NOT_FOUND,
241        message: "this sign-in link has expired or was already used — start the sign-in again from BREP".into(),
242    }
243}
244
245fn new_code() -> String {
246    // Uniform over the alphabet: a byte at or above the largest multiple of
247    // its length is drawn again (rejection sampling), so no letter is likelier
248    // than another, as with `gen_range`.
249    let len = CODE_ALPHABET.len();
250    let limit = 256 - 256 % len;
251    let mut code = String::with_capacity(6);
252    let mut byte = [0u8; 1];
253    while code.len() < 6 {
254        crate::auth::fill_random(&mut byte);
255        if (byte[0] as usize) < limit {
256            code.push(CODE_ALPHABET[byte[0] as usize % len] as char);
257        }
258    }
259    code
260}