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 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
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("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 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 const BROWSER_TTL_MS: u64 = 16 * 60 * 1000;
264
265pub 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
280pub 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 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
338pub 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
347fn binding_refused(status: u16, answer: &Value) -> bool {
351 status == 400
352 && answer["error"]["code"] == "invalid_request"
353 && answer["error"]["field"] == "binding"
354}
355
356fn 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
367fn 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
379fn 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;