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 LeanCTX 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("LeanCTX 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/// Withdraw a relayed request that no longer needs an answer (C0 2.1
263/// `DELETE /v1/consents/{id}`), so no page lists it as waiting. Best
264/// effort: a Cloud without the route or without the request ignores it.
265pub fn withdraw_relayed(client: &CloudClient, consent_id: &str) {
266    if let Err(error) = client.delete(&format!("/consents/{consent_id}")) {
267        tracing::info!("cloud consent withdraw {consent_id}: {error}");
268    }
269}
270
271/// One E35 call; a 1.x Cloud has no consent relay (`404`).
272fn send(
273    client: &CloudClient,
274    method: &str,
275    path: &str,
276    body: Option<&Value>,
277) -> Result<Value, ConsentError> {
278    let (status, answer) = client
279        .send_answer(method, path, body, MAX_ANSWER)
280        .map_err(|e| ConsentError::Local(e.to_string()))?;
281    match status {
282        200..=299 => Ok(answer),
283        404 => Err(ConsentError::Local(
284            "this LeanCTX Cloud server has no browser consent yet; approve in a terminal".into(),
285        )),
286        409 if answer["error"]["reason"] == "subject_changed" => Err(ConsentError::Local(
287            "LeanCTX Cloud holds this request with another subject; nothing was approved".into(),
288        )),
289        409 if answer["error"]["code"] == "consent_terminal_only" => {
290            Err(ConsentError::TerminalOnly)
291        }
292        _ => Err(ConsentError::Local(
293            crate::CloudError::from_response(status, &answer).to_string(),
294        )),
295    }
296}
297
298#[cfg(test)]
299#[path = "web_tests.rs"]
300mod tests;