1use 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
27pub const CODE_TTL_MS: u64 = 10 * 60 * 1000;
29pub const POLL_EVERY: Duration = Duration::from_secs(2);
30pub(crate) const ANSWERED_DIR: &str = "consent_answered";
33const MAX_ANSWER: usize = 64 * 1024;
34
35const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
36
37pub 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
48pub fn display(code: &str) -> String {
50 format!("{}-{}", &code[..4], &code[4..])
51}
52
53pub 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
61pub 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
75pub fn link(url: &str, code: &str) -> String {
78 format!("{url}#k={}", display(code))
79}
80
81pub 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#[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
115pub 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
120pub 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
127pub 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 pub open: &'a dyn Fn(&str),
137}
138
139impl WebRun<'_> {
140 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 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 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
205pub 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 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
262pub 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
271fn 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;