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
26pub(crate) const DIR: &str = "consent";
27pub(crate) const 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 #[serde(default)]
106 email: Option<String>,
107}
108
109pub fn linked_user_id(store: &CloudStore) -> Option<String> {
112 store
113 .read_config::<AccountRecord>(ACCOUNT_FILE)
114 .ok()
115 .flatten()
116 .map(|a| a.user_id)
117 .filter(|id| !id.is_empty())
118}
119
120pub fn linked_email(store: &CloudStore) -> Option<String> {
123 store
124 .read_config::<AccountRecord>(ACCOUNT_FILE)
125 .ok()
126 .flatten()
127 .and_then(|a| a.email)
128 .map(|e| e.trim().to_string())
129 .filter(|e| e.contains('@'))
130}
131
132pub fn bound_presence_key(store: &CloudStore) -> Option<BoundPresenceKey> {
134 store
135 .read_config::<BoundPresenceKey>(PRESENCE_KEY_FILE)
136 .ok()
137 .flatten()
138 .filter(BoundPresenceKey::consistent)
139}
140
141impl Trust {
142 pub fn load(store: &CloudStore, config: &crate::CloudConfig) -> Self {
146 let presence = bound_presence_key(store);
147 let owner_user_id = linked_user_id(store);
148 let consent_keys = store
149 .instance()
150 .ok()
151 .flatten()
152 .and_then(|i| crate::root_cert::trust_root(store, config, &i.url).ok())
153 .and_then(|root| crate::keyset_v3::load(store, &root))
154 .map(|set| set.keys_of(crate::keyset_v3::Purpose::Consent))
155 .unwrap_or_default();
156 Trust {
157 presence,
158 consent_keys,
159 owner_user_id,
160 }
161 }
162
163 pub fn host_channel(&self) -> Channel {
165 if self.presence.is_some() {
166 Channel::OsPresence
167 } else {
168 Channel::TtyOnly
169 }
170 }
171}
172
173#[derive(Debug, Clone)]
175pub enum Approval {
176 Presence {
178 signature: PresenceSignature,
179 approved_at: u64,
180 channel: Channel,
181 },
182 Statement(Value),
184 TtyOnly { approved_at: u64 },
186}
187
188#[derive(Debug, Clone)]
190pub struct Listed {
191 pub record: Record,
192 pub valid: bool,
193}
194
195pub struct Broker {
196 dir: PathBuf,
197 key_path: PathBuf,
198 trust: Trust,
199 cloud_data: PathBuf,
201}
202
203impl Broker {
204 pub fn open(store: &CloudStore, trust: Trust) -> Self {
205 Broker {
206 dir: store.config_dir().join(DIR),
207 key_path: store.config_dir().join(KEY_FILE),
208 trust,
209 cloud_data: store.data_dir().to_path_buf(),
210 }
211 }
212
213 pub fn trust(&self) -> &Trust {
214 &self.trust
215 }
216
217 fn policy_gate(&self, kind: Kind, now: u64) -> Result<(), ConsentError> {
220 if !crate::effective_policy::sensitive_kind(kind) {
221 return Ok(());
222 }
223 let at = i64::try_from(now)
224 .ok()
225 .and_then(lean_ctx_time::UtcDateTime::from_timestamp_millis)
226 .unwrap_or_default();
227 crate::effective_policy::sensitive_gate(&self.cloud_data, at)
228 .map_err(ConsentError::PolicyExpired)
229 }
230
231 pub fn require(&self, kind: Kind, subject: &Value, now: u64) -> Result<Record, ConsentError> {
235 self.policy_gate(kind, now)?;
236 check_subject(kind, subject)?;
237 let digest = subject_digest(subject)?;
238 let mut altered = false;
239 let mut newest: Option<Record> = None;
240 for listed in self.records()? {
241 let record = listed.record;
242 if record.kind != kind || record.subject_digest != digest {
243 continue;
244 }
245 if !listed.valid {
246 altered = true;
247 continue;
248 }
249 if record.state == State::Approved {
250 return Ok(record);
251 }
252 if newest
253 .as_ref()
254 .is_none_or(|n| record.created_at > n.created_at)
255 {
256 newest = Some(record);
257 }
258 }
259 let reuse = match &newest {
260 Some(r) if r.state == State::Pending && r.expires_at > now => {
261 Some(r.consent_id.clone())
262 }
263 Some(r) if r.state == State::Denied && r.created_at + REQUEST_TTL_MS > now => {
264 return Err(ConsentError::Denied);
265 }
266 _ => None,
267 };
268 let consent_id = match reuse {
269 Some(id) => id,
270 None => self.create(kind, subject.clone(), digest, now)?.consent_id,
271 };
272 if altered {
273 return Err(ConsentError::RecordInvalid);
274 }
275 Err(ConsentError::Required { consent_id, kind })
276 }
277
278 pub fn withdraw(
281 &self,
282 kinds: &[Kind],
283 field: &str,
284 value: &str,
285 ) -> Result<usize, ConsentError> {
286 let _lock = self.lock()?;
287 let mut removed = 0;
288 for listed in self.records()? {
289 let r = &listed.record;
290 if kinds.contains(&r.kind) && r.state == State::Approved && r.subject[field] == value {
291 std::fs::remove_file(self.path(&r.consent_id)?)
292 .map_err(|e| ConsentError::Local(e.to_string()))?;
293 removed += 1;
294 }
295 }
296 Ok(removed)
297 }
298
299 pub fn close_satisfied(
303 &self,
304 satisfied: &dyn Fn(&Record) -> bool,
305 ) -> Result<Vec<String>, ConsentError> {
306 let _lock = self.lock()?;
307 let mut closed = Vec::new();
308 for listed in self.records()? {
309 let r = &listed.record;
310 if r.state == State::Pending && satisfied(r) {
311 std::fs::remove_file(self.path(&r.consent_id)?)
312 .map_err(|e| ConsentError::Local(e.to_string()))?;
313 closed.push(r.consent_id.clone());
314 }
315 }
316 Ok(closed)
317 }
318
319 pub fn get(&self, consent_id: &str) -> Result<Record, ConsentError> {
321 let record = self.read(consent_id)?;
322 if !self.verify(&record) {
323 tracing::warn!("consent record {consent_id} failed its proof check");
324 return Err(ConsentError::RecordInvalid);
325 }
326 Ok(record)
327 }
328
329 pub fn list(&self) -> Result<Vec<Listed>, ConsentError> {
331 let mut all = self.records()?;
332 all.sort_by_key(|l| std::cmp::Reverse(l.record.created_at));
333 Ok(all)
334 }
335
336 pub fn approve(
339 &self,
340 consent_id: &str,
341 approval: Approval,
342 now: u64,
343 ) -> Result<Record, ConsentError> {
344 let _lock = self.lock()?;
345 let mut record = self.pending(consent_id, now)?;
346 let channel = match &approval {
347 Approval::Presence { channel, .. } => *channel,
348 Approval::Statement(_) => Channel::Web,
349 Approval::TtyOnly { .. } => Channel::TtyOnly,
350 };
351 channel_allowed(&record, channel)?;
352 let (approved_at, proof) = match approval {
353 Approval::Presence {
354 signature,
355 approved_at,
356 ..
357 } => (approved_at, Proof::Presence(signature)),
358 Approval::Statement(statement) => (
359 statement["answered_at"].as_u64().unwrap_or_default(),
360 Proof::Statement(statement),
361 ),
362 Approval::TtyOnly { approved_at } => {
363 if self.trust.presence.is_some() {
364 return Err(ConsentError::RecordInvalid);
366 }
367 let mut decided = record.clone();
368 decided.state = State::Approved;
369 decided.channel = Some(Channel::TtyOnly);
370 decided.approved_at = Some(approved_at);
371 (
372 approved_at,
373 Proof::Mac(mac(&self.file_key(true)?, &decided)?),
374 )
375 }
376 };
377 record.state = State::Approved;
378 record.channel = Some(channel);
379 record.approved_at = Some(approved_at);
380 record.proof = Some(proof);
381 if !self.verify(&record) {
382 return Err(ConsentError::RecordInvalid);
383 }
384 self.write(&record)?;
385 Ok(record)
386 }
387
388 pub fn record_web(
391 &self,
392 consent_id: &str,
393 statement: Value,
394 now: u64,
395 ) -> Result<Record, ConsentError> {
396 let pending = self.get(consent_id)?;
397 match verify_statement(&statement, &pending, &self.trust)? {
398 Answer::Allow => self.approve(consent_id, Approval::Statement(statement), now),
399 Answer::Deny => {
400 let _lock = self.lock()?;
401 let mut record = self.pending(consent_id, now)?;
402 record.state = State::Denied;
403 record.channel = Some(Channel::Web);
404 record.approved_at = statement["answered_at"].as_u64();
405 record.proof = Some(Proof::Statement(statement));
406 self.write(&record)?;
407 Ok(record)
408 }
409 }
410 }
411
412 pub fn deny(
414 &self,
415 consent_id: &str,
416 channel: Channel,
417 now: u64,
418 ) -> Result<Record, ConsentError> {
419 let _lock = self.lock()?;
420 let mut record = self.pending(consent_id, now)?;
421 record.state = State::Denied;
422 record.channel = Some(channel);
423 record.approved_at = Some(now);
424 record.proof = None;
425 self.write(&record)?;
426 Ok(record)
427 }
428
429 pub fn verify(&self, record: &Record) -> bool {
431 if !is_consent_id(&record.consent_id)
432 || check_subject(record.kind, &record.subject).is_err()
433 || subject_digest(&record.subject).ok().as_deref() != Some(&record.subject_digest)
434 {
435 return false;
436 }
437 match record.state {
438 State::Pending | State::Expired => record.proof.is_none(),
439 State::Denied => true,
440 State::Approved => self.approved_proof_holds(record),
441 }
442 }
443
444 fn approved_proof_holds(&self, record: &Record) -> bool {
445 let (Some(channel), Some(approved_at), Some(proof)) =
446 (record.channel, record.approved_at, &record.proof)
447 else {
448 return false;
449 };
450 if channel_allowed(record, channel).is_err() {
451 return false;
452 }
453 match proof {
454 Proof::Mac(hex) => {
455 self.trust.presence.is_none()
456 && channel == Channel::TtyOnly
457 && self
458 .file_key(false)
459 .and_then(|key| mac(&key, record))
460 .is_ok_and(|expected| constant_eq(expected.as_bytes(), hex.as_bytes()))
461 }
462 Proof::Presence(signature) => {
463 let Some(bound) = &self.trust.presence else {
464 return false;
465 };
466 matches!(channel, Channel::OsPresence | Channel::Cockpit)
467 && bound.key_id == signature.key_id
468 && bound.alg == signature.alg
469 && record
470 .proof_input(approved_at)
471 .is_ok_and(|input| bound.verifies(&input, &signature.signature))
472 }
473 Proof::Statement(statement) => {
474 channel == Channel::Web
475 && statement["answered_at"].as_u64() == Some(approved_at)
476 && verify_statement(statement, record, &self.trust) == Ok(Answer::Allow)
477 }
478 }
479 }
480
481 fn create(
482 &self,
483 kind: Kind,
484 subject: Value,
485 digest: String,
486 now: u64,
487 ) -> Result<Record, ConsentError> {
488 let _lock = self.lock()?;
489 let record = Record {
490 consent_id: new_consent_id()?,
491 kind,
492 subject,
493 subject_digest: digest,
494 created_at: now,
495 expires_at: now + REQUEST_TTL_MS,
496 state: State::Pending,
497 channel: None,
498 approved_at: None,
499 proof: None,
500 };
501 self.write(&record)?;
502 Ok(record)
503 }
504
505 fn pending(&self, consent_id: &str, now: u64) -> Result<Record, ConsentError> {
507 let mut record = self.get(consent_id)?;
508 match record.state {
509 State::Pending if record.expires_at > now => Ok(record),
510 State::Pending => {
511 record.state = State::Expired;
512 self.write(&record)?;
513 Err(ConsentError::Expired)
514 }
515 State::Expired => Err(ConsentError::Expired),
516 State::Approved | State::Denied => Err(ConsentError::InvalidState),
517 }
518 }
519
520 fn records(&self) -> Result<Vec<Listed>, ConsentError> {
521 let entries = match std::fs::read_dir(&self.dir) {
522 Ok(entries) => entries,
523 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
524 Err(e) => return Err(ConsentError::Local(e.to_string())),
525 };
526 let mut out = Vec::new();
527 for entry in entries.flatten() {
528 let name = entry.file_name();
529 let Some(id) = name.to_str().and_then(|n| n.strip_suffix(".json")) else {
530 continue;
531 };
532 if !is_consent_id(id) {
533 continue;
534 }
535 if let Ok(record) = self.read(id) {
536 let valid = self.verify(&record);
537 if !valid {
538 tracing::warn!("consent record {id} failed its proof check");
539 }
540 out.push(Listed { record, valid });
541 } else {
542 tracing::warn!("consent record {id} is unreadable");
543 }
544 }
545 Ok(out)
546 }
547
548 fn read(&self, consent_id: &str) -> Result<Record, ConsentError> {
549 let path = self.path(consent_id)?;
550 let bytes = match std::fs::read(&path) {
551 Ok(bytes) => bytes,
552 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
553 return Err(ConsentError::NotFound);
554 }
555 Err(e) => return Err(ConsentError::Local(e.to_string())),
556 };
557 let record: Record =
558 serde_json::from_slice(&bytes).map_err(|_| ConsentError::RecordInvalid)?;
559 if record.consent_id != consent_id {
560 return Err(ConsentError::RecordInvalid);
561 }
562 Ok(record)
563 }
564
565 fn write(&self, record: &Record) -> Result<(), ConsentError> {
566 let bytes =
567 serde_json::to_vec_pretty(record).map_err(|e| ConsentError::Local(e.to_string()))?;
568 write_private(&self.dir, &format!("{}.json", record.consent_id), &bytes)
569 .map_err(|e| ConsentError::Local(e.to_string()))
570 }
571
572 fn path(&self, consent_id: &str) -> Result<PathBuf, ConsentError> {
573 if !is_consent_id(consent_id) {
574 return Err(ConsentError::NotFound);
575 }
576 Ok(self.dir.join(format!("{consent_id}.json")))
577 }
578
579 fn lock(&self) -> Result<crate::state::StateLock, ConsentError> {
580 lock_state(self.dir.parent().unwrap_or(Path::new(".")), "consent")
581 .map_err(|e| ConsentError::Local(e.to_string()))
582 }
583
584 fn file_key(&self, create: bool) -> Result<[u8; 32], ConsentError> {
586 let local = |e: &dyn std::fmt::Display| ConsentError::Local(e.to_string());
587 match std::fs::read(&self.key_path) {
588 Ok(bytes) => <[u8; 32]>::try_from(bytes).map_err(|_| ConsentError::RecordInvalid),
589 Err(e) if e.kind() == std::io::ErrorKind::NotFound && create => {
590 let mut key = [0u8; 32];
591 getrandom::fill(&mut key).map_err(|e| local(&e))?;
592 let dir = self.key_path.parent().unwrap_or(Path::new("."));
593 write_private(dir, KEY_FILE, &key).map_err(|e| local(&e))?;
594 Ok(key)
595 }
596 Err(e) => Err(local(&e)),
597 }
598 }
599}
600
601fn channel_allowed(record: &Record, channel: Channel) -> Result<(), ConsentError> {
603 match record.kind {
604 Kind::ApiKeySet if !matches!(channel, Channel::OsPresence | Channel::TtyOnly) => {
605 Err(ConsentError::TerminalOnly)
606 }
607 kind if !kind.answerable_on(channel.surface()) => Err(ConsentError::InvalidState),
608 _ => Ok(()),
609 }
610}
611
612fn mac(key: &[u8; 32], record: &Record) -> Result<String, ConsentError> {
615 let input = lean_ctx_protocol::cloud::canonical_json(&json!({
616 "consent_id": record.consent_id,
617 "kind": record.kind,
618 "subject_digest": record.subject_digest,
619 "state": record.state,
620 "channel": record.channel,
621 "approved_at": record.approved_at,
622 }))
623 .map_err(|e| ConsentError::Local(e.to_string()))?;
624 Ok(blake3::keyed_hash(key, &input).to_hex().to_string())
625}
626
627fn constant_eq(a: &[u8], b: &[u8]) -> bool {
628 a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
629}
630
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633pub enum Answer {
634 Allow,
635 Deny,
636}
637
638const STATEMENT_FIELDS: [&str; 8] = [
639 "schema",
640 "consent_id",
641 "subject_digest",
642 "answer",
643 "answered_at",
644 "user_id",
645 "key_id",
646 "signature",
647];
648
649pub fn verify_statement(
652 statement: &Value,
653 record: &Record,
654 trust: &Trust,
655) -> Result<Answer, ConsentError> {
656 let invalid = Err(ConsentError::RecordInvalid);
657 let Some(fields) = statement.as_object() else {
658 return invalid;
659 };
660 if fields.len() != STATEMENT_FIELDS.len()
661 || !STATEMENT_FIELDS.iter().all(|f| fields.contains_key(*f))
662 || statement["schema"] != STATEMENT_SCHEMA
663 || statement["consent_id"] != record.consent_id.as_str()
664 || statement["subject_digest"] != record.subject_digest.as_str()
665 || trust
666 .owner_user_id
667 .as_deref()
668 .is_none_or(|owner| statement["user_id"].as_str() != Some(owner))
669 || statement["answered_at"]
670 .as_u64()
671 .is_none_or(|at| at >= record.expires_at)
672 {
673 return invalid;
674 }
675 let answer = match statement["answer"].as_str() {
676 Some("allow") => Answer::Allow,
677 Some("deny") => Answer::Deny,
678 _ => return invalid,
679 };
680 let key = statement["key_id"]
681 .as_str()
682 .and_then(|id| trust.consent_keys.get(id));
683 let signature = statement["signature"]
684 .as_str()
685 .and_then(|s| hex::decode(s).ok())
686 .and_then(|b| Signature::from_slice(&b).ok());
687 let input =
688 lean_ctx_protocol::cloud::signing_input_without_signature(STATEMENT_DOMAIN, statement);
689 match (key, signature, input) {
690 (Some(key), Some(signature), Ok(input)) if key.verify(&input, &signature).is_ok() => {
691 Ok(answer)
692 }
693 _ => invalid,
694 }
695}