1use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10
11use base64::Engine as _;
12use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
13use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
14use serde::{Deserialize, Serialize};
15use serde_json::{Value, json};
16use sha2::Digest as _;
17
18use super::{
19 Channel, ConsentError, Kind, PresenceSignature, Proof, REQUEST_TTL_MS, Record,
20 STATEMENT_DOMAIN, STATEMENT_SCHEMA, State, check_subject, is_consent_id, new_consent_id,
21 subject_digest,
22};
23use crate::CloudStore;
24use crate::state::{lock_state, write_private};
25
26const DIR: &str = "consent";
27const KEY_FILE: &str = "consent.key";
28pub(crate) const PRESENCE_KEY_FILE: &str = "presence_key.json";
30pub(crate) const ACCOUNT_FILE: &str = "account.json";
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(deny_unknown_fields)]
37pub struct BoundPresenceKey {
38 pub alg: String,
39 pub key_id: String,
40 pub public_key: String,
42}
43
44impl BoundPresenceKey {
45 fn consistent(&self) -> bool {
47 B64URL
48 .decode(&self.public_key)
49 .is_ok_and(|bytes| hex::encode(sha2::Sha256::digest(&bytes))[..16] == self.key_id)
50 }
51
52 pub(super) fn verifies(&self, message: &[u8], signature: &str) -> bool {
53 let Ok(signature) = B64URL.decode(signature) else {
54 return false;
55 };
56 match self.alg.as_str() {
57 "ed25519" => {
58 let (Ok(public), Ok(signature)) = (
59 B64URL
60 .decode(&self.public_key)
61 .ok()
62 .and_then(|b| <[u8; 32]>::try_from(b).ok())
63 .ok_or(())
64 .and_then(|b| VerifyingKey::from_bytes(&b).map_err(|_| ())),
65 Signature::from_slice(&signature),
66 ) else {
67 return false;
68 };
69 public.verify(message, &signature).is_ok()
70 }
71 "p256_ecdsa_sha256" => {
74 use p256::ecdsa::signature::Verifier as _;
75 use p256::pkcs8::DecodePublicKey as _;
76 let (Ok(der), Ok(signature)) = (
77 B64URL.decode(&self.public_key),
78 p256::ecdsa::Signature::from_der(&signature),
79 ) else {
80 return false;
81 };
82 p256::ecdsa::VerifyingKey::from_public_key_der(&der)
83 .is_ok_and(|key| key.verify(message, &signature).is_ok())
84 }
85 _ => false,
88 }
89 }
90}
91
92#[derive(Debug, Clone, Default)]
94pub struct Trust {
95 pub presence: Option<BoundPresenceKey>,
96 pub consent_keys: BTreeMap<String, VerifyingKey>,
98 pub owner_user_id: Option<String>,
100}
101
102#[derive(Deserialize)]
103struct AccountRecord {
104 user_id: String,
105}
106
107pub fn linked_user_id(store: &CloudStore) -> Option<String> {
110 store
111 .read_config::<AccountRecord>(ACCOUNT_FILE)
112 .ok()
113 .flatten()
114 .map(|a| a.user_id)
115 .filter(|id| !id.is_empty())
116}
117
118pub fn bound_presence_key(store: &CloudStore) -> Option<BoundPresenceKey> {
120 store
121 .read_config::<BoundPresenceKey>(PRESENCE_KEY_FILE)
122 .ok()
123 .flatten()
124 .filter(BoundPresenceKey::consistent)
125}
126
127impl Trust {
128 pub fn load(store: &CloudStore, config: &crate::CloudConfig) -> Self {
132 let presence = bound_presence_key(store);
133 let owner_user_id = linked_user_id(store);
134 let consent_keys = store
135 .instance()
136 .ok()
137 .flatten()
138 .and_then(|i| crate::root_cert::trust_root(store, config, &i.url).ok())
139 .and_then(|root| crate::keyset_v3::load(store, &root))
140 .map(|set| set.keys_of(crate::keyset_v3::Purpose::Consent))
141 .unwrap_or_default();
142 Trust {
143 presence,
144 consent_keys,
145 owner_user_id,
146 }
147 }
148
149 pub fn host_channel(&self) -> Channel {
151 if self.presence.is_some() {
152 Channel::OsPresence
153 } else {
154 Channel::TtyOnly
155 }
156 }
157}
158
159#[derive(Debug, Clone)]
161pub enum Approval {
162 Presence {
164 signature: PresenceSignature,
165 approved_at: u64,
166 channel: Channel,
167 },
168 Statement(Value),
170 TtyOnly { approved_at: u64 },
172}
173
174#[derive(Debug, Clone)]
176pub struct Listed {
177 pub record: Record,
178 pub valid: bool,
179}
180
181pub struct Broker {
182 dir: PathBuf,
183 key_path: PathBuf,
184 trust: Trust,
185 cloud_data: PathBuf,
187}
188
189impl Broker {
190 pub fn open(store: &CloudStore, trust: Trust) -> Self {
191 Broker {
192 dir: store.config_dir().join(DIR),
193 key_path: store.config_dir().join(KEY_FILE),
194 trust,
195 cloud_data: store.data_dir().to_path_buf(),
196 }
197 }
198
199 pub fn trust(&self) -> &Trust {
200 &self.trust
201 }
202
203 fn policy_gate(&self, kind: Kind, now: u64) -> Result<(), ConsentError> {
206 if !crate::effective_policy::sensitive_kind(kind) {
207 return Ok(());
208 }
209 let at = i64::try_from(now)
210 .ok()
211 .and_then(lean_ctx_time::UtcDateTime::from_timestamp_millis)
212 .unwrap_or_default();
213 crate::effective_policy::sensitive_gate(&self.cloud_data, at)
214 .map_err(ConsentError::PolicyExpired)
215 }
216
217 pub fn require(&self, kind: Kind, subject: &Value, now: u64) -> Result<Record, ConsentError> {
221 self.policy_gate(kind, now)?;
222 check_subject(kind, subject)?;
223 let digest = subject_digest(subject)?;
224 let mut altered = false;
225 let mut newest: Option<Record> = None;
226 for listed in self.records()? {
227 let record = listed.record;
228 if record.kind != kind || record.subject_digest != digest {
229 continue;
230 }
231 if !listed.valid {
232 altered = true;
233 continue;
234 }
235 if record.state == State::Approved {
236 return Ok(record);
237 }
238 if newest
239 .as_ref()
240 .is_none_or(|n| record.created_at > n.created_at)
241 {
242 newest = Some(record);
243 }
244 }
245 let reuse = match &newest {
246 Some(r) if r.state == State::Pending && r.expires_at > now => {
247 Some(r.consent_id.clone())
248 }
249 Some(r) if r.state == State::Denied && r.created_at + REQUEST_TTL_MS > now => {
250 return Err(ConsentError::Denied);
251 }
252 _ => None,
253 };
254 let consent_id = match reuse {
255 Some(id) => id,
256 None => self.create(kind, subject.clone(), digest, now)?.consent_id,
257 };
258 if altered {
259 return Err(ConsentError::RecordInvalid);
260 }
261 Err(ConsentError::Required { consent_id, kind })
262 }
263
264 pub fn withdraw(
267 &self,
268 kinds: &[Kind],
269 field: &str,
270 value: &str,
271 ) -> Result<usize, ConsentError> {
272 let _lock = self.lock()?;
273 let mut removed = 0;
274 for listed in self.records()? {
275 let r = &listed.record;
276 if kinds.contains(&r.kind) && r.state == State::Approved && r.subject[field] == value {
277 std::fs::remove_file(self.path(&r.consent_id)?)
278 .map_err(|e| ConsentError::Local(e.to_string()))?;
279 removed += 1;
280 }
281 }
282 Ok(removed)
283 }
284
285 pub fn close_satisfied(
289 &self,
290 satisfied: &dyn Fn(&Record) -> bool,
291 ) -> Result<Vec<String>, ConsentError> {
292 let _lock = self.lock()?;
293 let mut closed = Vec::new();
294 for listed in self.records()? {
295 let r = &listed.record;
296 if r.state == State::Pending && satisfied(r) {
297 std::fs::remove_file(self.path(&r.consent_id)?)
298 .map_err(|e| ConsentError::Local(e.to_string()))?;
299 closed.push(r.consent_id.clone());
300 }
301 }
302 Ok(closed)
303 }
304
305 pub fn get(&self, consent_id: &str) -> Result<Record, ConsentError> {
307 let record = self.read(consent_id)?;
308 if !self.verify(&record) {
309 tracing::warn!("consent record {consent_id} failed its proof check");
310 return Err(ConsentError::RecordInvalid);
311 }
312 Ok(record)
313 }
314
315 pub fn list(&self) -> Result<Vec<Listed>, ConsentError> {
317 let mut all = self.records()?;
318 all.sort_by_key(|l| std::cmp::Reverse(l.record.created_at));
319 Ok(all)
320 }
321
322 pub fn approve(
325 &self,
326 consent_id: &str,
327 approval: Approval,
328 now: u64,
329 ) -> Result<Record, ConsentError> {
330 let _lock = self.lock()?;
331 let mut record = self.pending(consent_id, now)?;
332 let channel = match &approval {
333 Approval::Presence { channel, .. } => *channel,
334 Approval::Statement(_) => Channel::Web,
335 Approval::TtyOnly { .. } => Channel::TtyOnly,
336 };
337 channel_allowed(&record, channel)?;
338 let (approved_at, proof) = match approval {
339 Approval::Presence {
340 signature,
341 approved_at,
342 ..
343 } => (approved_at, Proof::Presence(signature)),
344 Approval::Statement(statement) => (
345 statement["answered_at"].as_u64().unwrap_or_default(),
346 Proof::Statement(statement),
347 ),
348 Approval::TtyOnly { approved_at } => {
349 if self.trust.presence.is_some() {
350 return Err(ConsentError::RecordInvalid);
352 }
353 let mut decided = record.clone();
354 decided.state = State::Approved;
355 decided.channel = Some(Channel::TtyOnly);
356 decided.approved_at = Some(approved_at);
357 (
358 approved_at,
359 Proof::Mac(mac(&self.file_key(true)?, &decided)?),
360 )
361 }
362 };
363 record.state = State::Approved;
364 record.channel = Some(channel);
365 record.approved_at = Some(approved_at);
366 record.proof = Some(proof);
367 if !self.verify(&record) {
368 return Err(ConsentError::RecordInvalid);
369 }
370 self.write(&record)?;
371 Ok(record)
372 }
373
374 pub fn record_web(
377 &self,
378 consent_id: &str,
379 statement: Value,
380 now: u64,
381 ) -> Result<Record, ConsentError> {
382 let pending = self.get(consent_id)?;
383 match verify_statement(&statement, &pending, &self.trust)? {
384 Answer::Allow => self.approve(consent_id, Approval::Statement(statement), now),
385 Answer::Deny => {
386 let _lock = self.lock()?;
387 let mut record = self.pending(consent_id, now)?;
388 record.state = State::Denied;
389 record.channel = Some(Channel::Web);
390 record.approved_at = statement["answered_at"].as_u64();
391 record.proof = Some(Proof::Statement(statement));
392 self.write(&record)?;
393 Ok(record)
394 }
395 }
396 }
397
398 pub fn deny(
400 &self,
401 consent_id: &str,
402 channel: Channel,
403 now: u64,
404 ) -> Result<Record, ConsentError> {
405 let _lock = self.lock()?;
406 let mut record = self.pending(consent_id, now)?;
407 record.state = State::Denied;
408 record.channel = Some(channel);
409 record.approved_at = Some(now);
410 record.proof = None;
411 self.write(&record)?;
412 Ok(record)
413 }
414
415 pub fn verify(&self, record: &Record) -> bool {
417 if !is_consent_id(&record.consent_id)
418 || check_subject(record.kind, &record.subject).is_err()
419 || subject_digest(&record.subject).ok().as_deref() != Some(&record.subject_digest)
420 {
421 return false;
422 }
423 match record.state {
424 State::Pending | State::Expired => record.proof.is_none(),
425 State::Denied => true,
426 State::Approved => self.approved_proof_holds(record),
427 }
428 }
429
430 fn approved_proof_holds(&self, record: &Record) -> bool {
431 let (Some(channel), Some(approved_at), Some(proof)) =
432 (record.channel, record.approved_at, &record.proof)
433 else {
434 return false;
435 };
436 if channel_allowed(record, channel).is_err() {
437 return false;
438 }
439 match proof {
440 Proof::Mac(hex) => {
441 self.trust.presence.is_none()
442 && channel == Channel::TtyOnly
443 && self
444 .file_key(false)
445 .and_then(|key| mac(&key, record))
446 .is_ok_and(|expected| constant_eq(expected.as_bytes(), hex.as_bytes()))
447 }
448 Proof::Presence(signature) => {
449 let Some(bound) = &self.trust.presence else {
450 return false;
451 };
452 matches!(channel, Channel::OsPresence | Channel::Cockpit)
453 && bound.key_id == signature.key_id
454 && bound.alg == signature.alg
455 && record
456 .proof_input(approved_at)
457 .is_ok_and(|input| bound.verifies(&input, &signature.signature))
458 }
459 Proof::Statement(statement) => {
460 channel == Channel::Web
461 && statement["answered_at"].as_u64() == Some(approved_at)
462 && verify_statement(statement, record, &self.trust) == Ok(Answer::Allow)
463 }
464 }
465 }
466
467 fn create(
468 &self,
469 kind: Kind,
470 subject: Value,
471 digest: String,
472 now: u64,
473 ) -> Result<Record, ConsentError> {
474 let _lock = self.lock()?;
475 let record = Record {
476 consent_id: new_consent_id()?,
477 kind,
478 subject,
479 subject_digest: digest,
480 created_at: now,
481 expires_at: now + REQUEST_TTL_MS,
482 state: State::Pending,
483 channel: None,
484 approved_at: None,
485 proof: None,
486 };
487 self.write(&record)?;
488 Ok(record)
489 }
490
491 fn pending(&self, consent_id: &str, now: u64) -> Result<Record, ConsentError> {
493 let mut record = self.get(consent_id)?;
494 match record.state {
495 State::Pending if record.expires_at > now => Ok(record),
496 State::Pending => {
497 record.state = State::Expired;
498 self.write(&record)?;
499 Err(ConsentError::Expired)
500 }
501 State::Expired => Err(ConsentError::Expired),
502 State::Approved | State::Denied => Err(ConsentError::InvalidState),
503 }
504 }
505
506 fn records(&self) -> Result<Vec<Listed>, ConsentError> {
507 let entries = match std::fs::read_dir(&self.dir) {
508 Ok(entries) => entries,
509 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
510 Err(e) => return Err(ConsentError::Local(e.to_string())),
511 };
512 let mut out = Vec::new();
513 for entry in entries.flatten() {
514 let name = entry.file_name();
515 let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".json")) else {
516 continue;
517 };
518 if !is_consent_id(id) {
519 continue;
520 }
521 if let Ok(record) = self.read(id) {
522 let valid = self.verify(&record);
523 if !valid {
524 tracing::warn!("consent record {id} failed its proof check");
525 }
526 out.push(Listed { record, valid });
527 } else {
528 tracing::warn!("consent record {id} is unreadable");
529 }
530 }
531 Ok(out)
532 }
533
534 fn read(&self, consent_id: &str) -> Result<Record, ConsentError> {
535 let path = self.path(consent_id)?;
536 let bytes = match std::fs::read(&path) {
537 Ok(bytes) => bytes,
538 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
539 return Err(ConsentError::NotFound);
540 }
541 Err(e) => return Err(ConsentError::Local(e.to_string())),
542 };
543 let record: Record =
544 serde_json::from_slice(&bytes).map_err(|_| ConsentError::RecordInvalid)?;
545 if record.consent_id != consent_id {
546 return Err(ConsentError::RecordInvalid);
547 }
548 Ok(record)
549 }
550
551 fn write(&self, record: &Record) -> Result<(), ConsentError> {
552 let bytes =
553 serde_json::to_vec_pretty(record).map_err(|e| ConsentError::Local(e.to_string()))?;
554 write_private(&self.dir, &format!("{}.json", record.consent_id), &bytes)
555 .map_err(|e| ConsentError::Local(e.to_string()))
556 }
557
558 fn path(&self, consent_id: &str) -> Result<PathBuf, ConsentError> {
559 if !is_consent_id(consent_id) {
560 return Err(ConsentError::NotFound);
561 }
562 Ok(self.dir.join(format!("{consent_id}.json")))
563 }
564
565 fn lock(&self) -> Result<crate::state::StateLock, ConsentError> {
566 lock_state(self.dir.parent().unwrap_or(Path::new(".")), "consent")
567 .map_err(|e| ConsentError::Local(e.to_string()))
568 }
569
570 fn file_key(&self, create: bool) -> Result<[u8; 32], ConsentError> {
572 let local = |e: &dyn std::fmt::Display| ConsentError::Local(e.to_string());
573 match std::fs::read(&self.key_path) {
574 Ok(bytes) => <[u8; 32]>::try_from(bytes).map_err(|_| ConsentError::RecordInvalid),
575 Err(e) if e.kind() == std::io::ErrorKind::NotFound && create => {
576 let mut key = [0u8; 32];
577 getrandom::fill(&mut key).map_err(|e| local(&e))?;
578 let dir = self.key_path.parent().unwrap_or(Path::new("."));
579 write_private(dir, KEY_FILE, &key).map_err(|e| local(&e))?;
580 Ok(key)
581 }
582 Err(e) => Err(local(&e)),
583 }
584 }
585}
586
587fn channel_allowed(record: &Record, channel: Channel) -> Result<(), ConsentError> {
589 match record.kind {
590 Kind::ApiKeySet if !matches!(channel, Channel::OsPresence | Channel::TtyOnly) => {
591 Err(ConsentError::TerminalOnly)
592 }
593 kind if !kind.answerable_on(channel.surface()) => Err(ConsentError::InvalidState),
594 _ => Ok(()),
595 }
596}
597
598fn mac(key: &[u8; 32], record: &Record) -> Result<String, ConsentError> {
601 let input = lean_ctx_protocol::cloud::canonical_json(&json!({
602 "consent_id": record.consent_id,
603 "kind": record.kind,
604 "subject_digest": record.subject_digest,
605 "state": record.state,
606 "channel": record.channel,
607 "approved_at": record.approved_at,
608 }))
609 .map_err(|e| ConsentError::Local(e.to_string()))?;
610 Ok(blake3::keyed_hash(key, &input).to_hex().to_string())
611}
612
613fn constant_eq(a: &[u8], b: &[u8]) -> bool {
614 a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
615}
616
617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum Answer {
620 Allow,
621 Deny,
622}
623
624const STATEMENT_FIELDS: [&str; 8] = [
625 "schema",
626 "consent_id",
627 "subject_digest",
628 "answer",
629 "answered_at",
630 "user_id",
631 "key_id",
632 "signature",
633];
634
635pub fn verify_statement(
638 statement: &Value,
639 record: &Record,
640 trust: &Trust,
641) -> Result<Answer, ConsentError> {
642 let invalid = Err(ConsentError::RecordInvalid);
643 let Some(fields) = statement.as_object() else {
644 return invalid;
645 };
646 if fields.len() != STATEMENT_FIELDS.len()
647 || !STATEMENT_FIELDS.iter().all(|f| fields.contains_key(*f))
648 || statement["schema"] != STATEMENT_SCHEMA
649 || statement["consent_id"] != record.consent_id.as_str()
650 || statement["subject_digest"] != record.subject_digest.as_str()
651 || trust
652 .owner_user_id
653 .as_deref()
654 .is_none_or(|owner| statement["user_id"].as_str() != Some(owner))
655 || statement["answered_at"]
656 .as_u64()
657 .is_none_or(|at| at >= record.expires_at)
658 {
659 return invalid;
660 }
661 let answer = match statement["answer"].as_str() {
662 Some("allow") => Answer::Allow,
663 Some("deny") => Answer::Deny,
664 _ => return invalid,
665 };
666 let key = statement["key_id"]
667 .as_str()
668 .and_then(|id| trust.consent_keys.get(id));
669 let signature = statement["signature"]
670 .as_str()
671 .and_then(|s| hex::decode(s).ok())
672 .and_then(|b| Signature::from_slice(&b).ok());
673 let input =
674 lean_ctx_protocol::cloud::signing_input_without_signature(STATEMENT_DOMAIN, statement);
675 match (key, signature, input) {
676 (Some(key), Some(signature), Ok(input)) if key.verify(&input, &signature).is_ok() => {
677 Ok(answer)
678 }
679 _ => invalid,
680 }
681}