Skip to main content

lean_ctx_cloud/consent/
web.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Web channel `lean-ctx cloud consent --web <id>` (SPEC-ENGINE §3.8.2
3//! "Web channel flow", RESOLUTIONS R49, R61, R82).
4//!
5//! 1. A pairing code (40 random bits, Crockford base32, `XXXX-XXXX`) lives
6//!    only in this process and on the terminal.
7//! 2. E35 `POST /v1/consents` carries the stored subject (canonical, so a
8//!    repeat is byte-identical) and `code_hash = hex(sha256(consent_id ‖
9//!    code))`; a repeat replaces the code.
10//! 3. One line on stdout names the URL, the code and the request
11//!    fingerprint the consent page shows too.
12//! 4. The engine waits up to 10 min: a `consent.answered` frame seen by the
13//!    relay (a marker file) or E35 `GET` every 2 s.
14//! 5. Only a Cloud-signed `leanctx.cloud.consent.v1` statement for this
15//!    request and the owner account is stored (`proof = {statement}`).
16
17use std::path::{Path, PathBuf};
18use std::time::Duration;
19
20use serde_json::{Value, json};
21use sha2::Digest as _;
22
23use super::broker::Broker;
24use super::{ConsentError, Kind, Record, State, is_consent_id};
25use crate::transport::CloudClient;
26
27/// How long a pairing code and the wait last.
28pub const CODE_TTL_MS: u64 = 10 * 60 * 1000;
29pub const POLL_EVERY: Duration = Duration::from_secs(2);
30/// The relay drops `<data>/cloud/consent_answered/<id>` on a
31/// `consent.answered` frame.
32pub(crate) const ANSWERED_DIR: &str = "consent_answered";
33const MAX_ANSWER: usize = 64 * 1024;
34
35const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
36
37/// 8 Crockford characters (40 random bits), uppercase, no dash.
38pub fn new_code() -> Result<String, ConsentError> {
39    let mut bytes = [0u8; 5];
40    getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
41    let bits = bytes.iter().fold(0u64, |acc, b| (acc << 8) | u64::from(*b));
42    Ok((0..8)
43        .rev()
44        .map(|i| CROCKFORD[((bits >> (i * 5)) & 31) as usize] as char)
45        .collect())
46}
47
48/// `XXXX-XXXX`.
49pub fn display(code: &str) -> String {
50    format!("{}-{}", &code[..4], &code[4..])
51}
52
53/// `hex(sha256(consent_id ‖ code))`, `code` uppercase without the dash.
54pub fn code_hash(consent_id: &str, code: &str) -> String {
55    let mut hasher = sha2::Sha256::new();
56    hasher.update(consent_id.as_bytes());
57    hasher.update(code.replace('-', "").to_ascii_uppercase().as_bytes());
58    hex::encode(hasher.finalize())
59}
60
61/// The E35 create body. The subject is the stored one, so its canonical
62/// form is the same on every repeat (R82).
63pub fn create_body(record: &Record, code: &str, now: u64) -> Value {
64    json!({
65        "consent_id": record.consent_id,
66        "kind": record.kind,
67        "subject": record.subject,
68        "subject_digest": record.subject_digest,
69        "expires_at": record.expires_at,
70        "code_hash": code_hash(&record.consent_id, code),
71        "code_expires_at": now + CODE_TTL_MS,
72    })
73}
74
75/// The consent page with the pairing code in its fragment: the browser
76/// fills the code in, and a fragment never reaches a server or its logs.
77pub fn link(url: &str, code: &str) -> String {
78    format!("{url}#k={}", display(code))
79}
80
81/// The stdout lines of step 3: the link to open (with the code in it) and
82/// the code itself, for a browser on another device. The request
83/// fingerprint stays on the page under "Details" and in `consent list`.
84pub fn output_line(url: &str, code: &str, record: &Record) -> String {
85    let _ = record;
86    format!(
87        "Confirm it in your browser:\n  {}\nIf the page asks for a code, it is {} (valid for 10 minutes).",
88        link(url, code),
89        display(code)
90    )
91}
92
93/// An E35 `GET` answer.
94#[derive(Debug, Clone, PartialEq)]
95pub enum Polled {
96    Pending,
97    Expired,
98    Answered(Value),
99}
100
101pub fn parse_state(answer: &Value) -> Result<Polled, ConsentError> {
102    let bad = || ConsentError::Local("unexpected consent state from the Cloud".into());
103    match answer["state"].as_str() {
104        Some("pending") => Ok(Polled::Pending),
105        Some("expired") => Ok(Polled::Expired),
106        Some("approved" | "denied") => answer
107            .get("statement")
108            .cloned()
109            .map(Polled::Answered)
110            .ok_or_else(bad),
111        _ => Err(bad()),
112    }
113}
114
115/// The marker the relay writes for a `consent.answered` frame.
116pub fn answered_marker(data_dir: &Path, consent_id: &str) -> Option<PathBuf> {
117    is_consent_id(consent_id).then(|| data_dir.join(ANSWERED_DIR).join(consent_id))
118}
119
120/// Record a `consent.answered` frame for a waiting `--web` (relay side).
121pub fn note_answered(data_dir: &Path, consent_id: &str) {
122    if let Some(path) = answered_marker(data_dir, consent_id) {
123        let _ = crate::state::write_private(path.parent().unwrap_or(data_dir), consent_id, b"");
124    }
125}
126
127/// What `--web` needs from its surroundings; tests replace the clock and
128/// the sleep.
129pub struct WebRun<'a> {
130    pub broker: &'a Broker,
131    pub data_dir: &'a Path,
132    pub now: &'a dyn Fn() -> u64,
133    pub sleep: &'a dyn Fn(Duration),
134    /// Opens the consent link in the browser (best effort; tests pass a
135    /// no-op).
136    pub open: &'a dyn Fn(&str),
137}
138
139impl WebRun<'_> {
140    /// Steps 1–7 for `consent_id`; prints the step-3 line through `print`.
141    pub fn run(
142        &self,
143        client: &CloudClient,
144        consent_id: &str,
145        print: &mut dyn FnMut(&str),
146    ) -> Result<Record, ConsentError> {
147        let record = self.broker.get(consent_id)?;
148        if record.state != State::Pending || record.expires_at <= (self.now)() {
149            return Err(if record.state == State::Pending {
150                ConsentError::Expired
151            } else {
152                ConsentError::InvalidState
153            });
154        }
155        if record.kind == Kind::ApiKeySet {
156            return Err(ConsentError::TerminalOnly);
157        }
158        let path = format!("/consents/{consent_id}");
159        // The browser may already have answered while an earlier wait was
160        // interrupted: take that signed answer instead of pairing again
161        // (Cloud refuses a new code for an answered request).
162        if let Ok(answer) = send(client, "GET", &path, None)
163            && let Polled::Answered(statement) = parse_state(&answer)?
164        {
165            return self.broker.record_web(consent_id, statement, (self.now)());
166        }
167        let code = new_code()?;
168        let started = (self.now)();
169        let body = create_body(&record, &code, started);
170        let created = send(client, "POST", "/consents", Some(&body))?;
171        let url = created["url"].as_str().ok_or_else(|| {
172            ConsentError::Local("The Cloud answered without a consent URL".into())
173        })?;
174        print(&output_line(url, &code, &record));
175        (self.open)(&link(url, &code));
176        let marker = answered_marker(self.data_dir, consent_id);
177        if let Some(m) = &marker {
178            let _ = std::fs::remove_file(m);
179        }
180        loop {
181            match parse_state(&send(client, "GET", &path, None)?)? {
182                Polled::Pending => {}
183                Polled::Expired => return Err(ConsentError::Expired),
184                Polled::Answered(statement) => {
185                    if let Some(m) = &marker {
186                        let _ = std::fs::remove_file(m);
187                    }
188                    return self.broker.record_web(consent_id, statement, (self.now)());
189                }
190            }
191            if (self.now)().saturating_sub(started) >= CODE_TTL_MS {
192                return Err(ConsentError::WebTimeout);
193            }
194            // A frame marker cuts the wait short; otherwise poll every 2 s.
195            let step = Duration::from_millis(250);
196            let mut waited = Duration::ZERO;
197            while waited < POLL_EVERY && !marker.as_ref().is_some_and(|m| m.exists()) {
198                (self.sleep)(step);
199                waited += step;
200            }
201        }
202    }
203}
204
205/// The E35 create body of a request bound to the device approval page
206/// (C0 2.1 `consent_create.device_binding.request.json`): no pairing code.
207pub fn device_body(record: &Record) -> Value {
208    json!({
209        "binding": "device",
210        "consent_id": record.consent_id,
211        "kind": record.kind,
212        "subject": record.subject,
213        "subject_digest": record.subject_digest,
214        "expires_at": record.expires_at,
215    })
216}
217
218impl WebRun<'_> {
219    /// C0 2.1: answer a first share on the device approval page that just
220    /// approved this machine. Cloud approves it at once when it is exactly
221    /// the share the page showed; anything else the person answers there,
222    /// within the page's window. `waiting` runs once if it has to wait.
223    pub fn run_device(
224        &self,
225        client: &CloudClient,
226        consent_id: &str,
227        waiting: &mut dyn FnMut(),
228    ) -> Result<Record, ConsentError> {
229        let record = self.broker.get(consent_id)?;
230        if record.state != State::Pending || record.expires_at <= (self.now)() {
231            return Err(ConsentError::InvalidState);
232        }
233        if record.kind != Kind::LinkVault {
234            return Err(ConsentError::Local(
235                "only a first share is answered on the device page".into(),
236            ));
237        }
238        let path = format!("/consents/{consent_id}");
239        send(client, "POST", "/consents", Some(&device_body(&record)))?;
240        let started = (self.now)();
241        let mut told = false;
242        loop {
243            match parse_state(&send(client, "GET", &path, None)?)? {
244                Polled::Answered(statement) => {
245                    return self.broker.record_web(consent_id, statement, (self.now)());
246                }
247                Polled::Expired => return Err(ConsentError::Expired),
248                Polled::Pending => {}
249            }
250            if !told {
251                waiting();
252                told = true;
253            }
254            if (self.now)().saturating_sub(started) >= CODE_TTL_MS {
255                return Err(ConsentError::WebTimeout);
256            }
257            (self.sleep)(POLL_EVERY);
258        }
259    }
260}
261
262/// The longest a browser-bound request waits (Cloud caps it at 15 min).
263pub const BROWSER_TTL_MS: u64 = 16 * 60 * 1000;
264
265/// The E35 create body of a request the person answers on a Cloud page
266/// opened by an app (`consent_create.browser_binding.request.json`): no
267/// pairing code; the page asks for the account's second factor, or its
268/// password or a mailed link without one.
269pub fn browser_body(record: &Record) -> Value {
270    json!({
271        "binding": "browser",
272        "consent_id": record.consent_id,
273        "kind": record.kind,
274        "subject": record.subject,
275        "subject_digest": record.subject_digest,
276        "expires_at": record.expires_at,
277    })
278}
279
280/// The poll interval Cloud names (`interval_s`), kept within 1–30 s.
281pub fn browser_interval(created: &Value) -> Duration {
282    Duration::from_secs(created["interval_s"].as_u64().unwrap_or(5).clamp(1, 30))
283}
284
285impl WebRun<'_> {
286    /// A first share answered in the browser for an app (rc3-70): create
287    /// the browser-bound request, hand Cloud's answer (`url`,
288    /// `expires_at`, `interval_s`) to `opened` once, then poll until the
289    /// person answered or the request expired. A Cloud without the browser
290    /// binding (`400 invalid_request` naming `binding`) ends it as
291    /// [`ConsentError::BrowserUnsupported`].
292    pub fn run_browser(
293        &self,
294        client: &CloudClient,
295        consent_id: &str,
296        opened: &mut dyn FnMut(&Value),
297    ) -> Result<Record, ConsentError> {
298        let record = self.broker.get(consent_id)?;
299        if record.state != State::Pending || record.expires_at <= (self.now)() {
300            return Err(ConsentError::InvalidState);
301        }
302        if record.kind != Kind::LinkVault {
303            return Err(ConsentError::Local(
304                "only a first share is answered in the browser for an app".into(),
305            ));
306        }
307        let path = format!("/consents/{consent_id}");
308        let (status, created) =
309            exchange(client, "POST", "/consents", Some(&browser_body(&record)))?;
310        if binding_refused(status, &created) {
311            return Err(ConsentError::BrowserUnsupported);
312        }
313        let created = judge(status, created)?;
314        if created["url"].as_str().is_none_or(str::is_empty) {
315            return Err(ConsentError::Local(
316                "The Cloud answered without a consent URL".into(),
317            ));
318        }
319        opened(&created);
320        let every = browser_interval(&created);
321        let started = (self.now)();
322        loop {
323            (self.sleep)(every);
324            match parse_state(&send(client, "GET", &path, None)?)? {
325                Polled::Answered(statement) => {
326                    return self.broker.record_web(consent_id, statement, (self.now)());
327                }
328                Polled::Expired => return Err(ConsentError::Expired),
329                Polled::Pending => {}
330            }
331            if (self.now)().saturating_sub(started) >= BROWSER_TTL_MS {
332                return Err(ConsentError::WebTimeout);
333            }
334        }
335    }
336}
337
338/// Withdraw a relayed request that no longer needs an answer (C0 2.1
339/// `DELETE /v1/consents/{id}`), so no page lists it as waiting. Best
340/// effort: a Cloud without the route or without the request ignores it.
341pub fn withdraw_relayed(client: &CloudClient, consent_id: &str) {
342    if let Err(error) = client.delete(&format!("/consents/{consent_id}")) {
343        tracing::info!("cloud consent withdraw {consent_id}: {error}");
344    }
345}
346
347/// A Cloud from before rc3-70 refuses the browser binding as an unknown
348/// value (`400 invalid_request` with `field: "binding"`, the consent
349/// route's `bad("enum", "binding")`); any other refusal stays what it is.
350fn binding_refused(status: u16, answer: &Value) -> bool {
351    status == 400
352        && answer["error"]["code"] == "invalid_request"
353        && answer["error"]["field"] == "binding"
354}
355
356/// One E35 call; a 1.x Cloud has no consent relay (`404`).
357fn send(
358    client: &CloudClient,
359    method: &str,
360    path: &str,
361    body: Option<&Value>,
362) -> Result<Value, ConsentError> {
363    let (status, answer) = exchange(client, method, path, body)?;
364    judge(status, answer)
365}
366
367/// One E35 call, its status and answer as sent.
368fn exchange(
369    client: &CloudClient,
370    method: &str,
371    path: &str,
372    body: Option<&Value>,
373) -> Result<(u16, Value), ConsentError> {
374    client
375        .send_answer(method, path, body, MAX_ANSWER)
376        .map_err(|e| ConsentError::Local(e.to_string()))
377}
378
379/// An E35 answer: the body on success, otherwise the refusal.
380fn judge(status: u16, answer: Value) -> Result<Value, ConsentError> {
381    match status {
382        200..=299 => Ok(answer),
383        404 => Err(ConsentError::Local(
384            "this Cloud server has no browser consent yet; approve in a terminal".into(),
385        )),
386        409 if answer["error"]["reason"] == "subject_changed" => Err(ConsentError::Local(
387            "The Cloud holds this request with another subject; nothing was approved".into(),
388        )),
389        409 if answer["error"]["code"] == "consent_terminal_only" => {
390            Err(ConsentError::TerminalOnly)
391        }
392        _ => Err(ConsentError::Local(
393            crate::CloudError::from_response(status, &answer).to_string(),
394        )),
395    }
396}
397
398#[cfg(test)]
399#[path = "web_tests.rs"]
400mod tests;