1pub mod broker;
17pub mod channel;
18#[cfg(unix)]
19pub mod helper_mac;
20pub mod web;
21
22use std::sync::OnceLock;
23
24use serde::{Deserialize, Serialize};
25use serde_json::{Map, Value, json};
26
27pub use broker::{Broker, Trust};
28
29pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");
32
33pub const PROOF_DOMAIN: &str = "leanctx.cloud.consent_proof.v1\n";
35pub const STATEMENT_DOMAIN: &str = "leanctx.cloud.consent.v1\n";
37pub const STATEMENT_SCHEMA: &str = "leanctx.cloud.consent.v1";
38
39pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
45#[serde(rename_all = "snake_case")]
46pub enum Kind {
47 LinkVault,
48 ApiKeySet,
49}
50
51impl Kind {
52 pub const ALL: [Kind; 2] = [Kind::LinkVault, Kind::ApiKeySet];
53
54 pub fn as_str(self) -> &'static str {
55 match self {
56 Kind::LinkVault => "link_vault",
57 Kind::ApiKeySet => "api_key_set",
58 }
59 }
60
61 pub fn parse(value: &str) -> Option<Kind> {
62 Kind::ALL.into_iter().find(|k| k.as_str() == value)
63 }
64
65 fn spec(self) -> &'static KindSpec {
66 kind_specs()
67 .iter()
68 .find(|s| s.value == self.as_str())
69 .expect("every kind is in the embedded fixture (tested)")
70 }
71
72 pub fn subject_fields(self) -> &'static [String] {
74 &self.spec().subject
75 }
76
77 pub fn answerable_on(self, channel: &str) -> bool {
79 self.spec().channels.iter().any(|c| c == channel)
80 }
81
82 pub fn typed_field(self) -> &'static str {
85 match self {
86 Kind::LinkVault => "vault",
87 Kind::ApiKeySet => "vendor",
88 }
89 }
90}
91
92impl std::fmt::Display for Kind {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 f.write_str(self.as_str())
95 }
96}
97
98#[derive(Debug, Deserialize)]
99struct KindSpec {
100 value: String,
101 channels: Vec<String>,
102 subject: Vec<String>,
103}
104
105#[derive(Debug, Deserialize)]
106struct KindList {
107 values: Vec<KindSpec>,
108}
109
110fn kind_specs() -> &'static [KindSpec] {
111 static SPECS: OnceLock<Vec<KindSpec>> = OnceLock::new();
112 SPECS.get_or_init(|| {
113 serde_json::from_str::<KindList>(KINDS_JSON)
114 .expect("embedded consent-kinds.json parses (tested)")
115 .values
116 })
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum Channel {
123 OsPresence,
124 TtyOnly,
125 Cockpit,
126 Web,
127}
128
129impl Channel {
130 pub fn as_str(self) -> &'static str {
131 match self {
132 Channel::OsPresence => "os_presence",
133 Channel::TtyOnly => "tty_only",
134 Channel::Cockpit => "cockpit",
135 Channel::Web => "web",
136 }
137 }
138
139 fn surface(self) -> &'static str {
141 match self {
142 Channel::OsPresence | Channel::TtyOnly => "cli",
143 Channel::Cockpit => "cockpit",
144 Channel::Web => "web",
145 }
146 }
147}
148
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum State {
152 Pending,
153 Approved,
154 Denied,
155 Expired,
156}
157
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160#[serde(deny_unknown_fields)]
161pub struct PresenceSignature {
162 pub key_id: String,
163 pub alg: String,
164 pub signature: String,
166}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum Proof {
172 Presence(PresenceSignature),
173 Statement(Value),
174 Mac(String),
176}
177
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(deny_unknown_fields)]
181pub struct Record {
182 pub consent_id: String,
183 pub kind: Kind,
184 pub subject: Value,
185 pub subject_digest: String,
186 pub created_at: u64,
187 pub expires_at: u64,
188 pub state: State,
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub channel: Option<Channel>,
191 #[serde(default, skip_serializing_if = "Option::is_none")]
192 pub approved_at: Option<u64>,
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub proof: Option<Proof>,
195}
196
197impl Record {
198 pub fn proof_input(&self, approved_at: u64) -> Result<Vec<u8>, ConsentError> {
200 lean_ctx_protocol::cloud::signing_input(
201 PROOF_DOMAIN,
202 &json!({
203 "consent_id": self.consent_id,
204 "kind": self.kind,
205 "subject_digest": self.subject_digest,
206 "approved_at": approved_at,
207 }),
208 )
209 .map_err(|e| ConsentError::Local(e.to_string()))
210 }
211
212 pub fn fingerprint(&self) -> &str {
214 &self.subject_digest[..16]
215 }
216
217 pub fn typed_value(&self) -> String {
219 let value = self.subject[self.kind.typed_field()]
220 .as_str()
221 .unwrap_or_default();
222 if is_uuid(value) {
224 value[..8].to_string()
225 } else {
226 value.to_string()
227 }
228 }
229}
230
231#[derive(Debug, Clone, PartialEq, Eq)]
234pub enum ConsentError {
235 Required {
237 consent_id: String,
238 kind: Kind,
239 },
240 Denied,
242 Expired,
244 RecordInvalid,
246 WebOnly {
248 consent_id: String,
249 },
250 TerminalOnly,
252 PresenceRequiredByPolicy {
254 consent_id: String,
255 },
256 ChannelRefused(String),
259 NotFound,
261 InvalidSubject(String),
263 InvalidState,
265 WebTimeout,
267 PresenceCancelled,
269 HelperMissing,
271 HelperSignature,
273 PolicyExpired(String),
276 Local(String),
277}
278
279impl ConsentError {
280 pub fn code(&self) -> &'static str {
281 match self {
282 ConsentError::Required { .. } => "consent_required",
283 ConsentError::Denied => "consent_denied",
284 ConsentError::Expired => "consent_expired",
285 ConsentError::RecordInvalid => "consent_record_invalid",
286 ConsentError::WebOnly { .. } => "consent_web_only",
287 ConsentError::TerminalOnly => "consent_terminal_only",
288 ConsentError::PresenceRequiredByPolicy { .. } => "consent_presence_required_by_policy",
289 ConsentError::ChannelRefused(_) => "consent_channel_refused",
290 ConsentError::NotFound => "not_found",
291 ConsentError::InvalidSubject(_) => "invalid_subject",
292 ConsentError::InvalidState => "invalid_state",
293 ConsentError::WebTimeout => "consent_web_timeout",
294 ConsentError::PresenceCancelled => "presence_cancelled",
295 ConsentError::HelperMissing => "helper_missing",
296 ConsentError::HelperSignature => "helper_signature",
297 ConsentError::PolicyExpired(_) => "policy_authorisation_expired",
298 ConsentError::Local(_) => "local",
299 }
300 }
301}
302
303impl std::fmt::Display for ConsentError {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 match self {
306 ConsentError::Required { .. } => {
308 f.write_str("Approve in a terminal: lean-ctx cloud consent")
309 }
310 ConsentError::Denied => f.write_str("The person declined this."),
311 ConsentError::Expired => f.write_str("This request expired; run the command again."),
312 ConsentError::RecordInvalid => {
313 f.write_str("A consent record was altered; approve again.")
314 }
315 ConsentError::WebOnly { consent_id } => write!(
316 f,
317 "Answer this one in the browser: lean-ctx cloud consent --web {consent_id}"
318 ),
319 ConsentError::TerminalOnly => {
320 f.write_str("This one is answered in the terminal only: lean-ctx cloud consent")
321 }
322 ConsentError::PresenceRequiredByPolicy { consent_id } => write!(
323 f,
324 "Your workspace requires system confirmation or the browser. Run: lean-ctx cloud consent --web {consent_id}"
325 ),
326 ConsentError::ChannelRefused(why) => write!(f, "Not approved: {why}"),
327 ConsentError::NotFound => f.write_str("No such consent request on this computer."),
328 ConsentError::InvalidSubject(why) => write!(f, "invalid consent subject: {why}"),
329 ConsentError::InvalidState => f.write_str("This request was already answered."),
330 ConsentError::WebTimeout => {
331 f.write_str("No answer in the browser within 10 minutes; run the command again.")
332 }
333 ConsentError::PresenceCancelled => {
334 f.write_str("System confirmation was cancelled. Nothing was approved.")
335 }
336 ConsentError::HelperMissing => f.write_str(
337 "LeanCTX Consent.app is not installed; run lean-ctx cloud consent-helper install.",
338 ),
339 ConsentError::HelperSignature => f.write_str(
340 "LeanCTX Consent.app signature invalid; run lean-ctx cloud consent-helper install.",
341 ),
342 ConsentError::PolicyExpired(why) => write!(f, "Refused: {why}"),
343 ConsentError::Local(why) => write!(f, "consent store: {why}"),
344 }
345 }
346}
347
348impl std::error::Error for ConsentError {}
349
350impl From<ConsentError> for crate::CloudError {
351 fn from(error: ConsentError) -> Self {
352 crate::CloudError::Refused(format!("{}: {error}", error.code()))
353 }
354}
355
356pub fn new_consent_id() -> Result<String, ConsentError> {
358 let mut bytes = [0u8; 10];
359 getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
360 Ok(format!("cns_{}", base32_lower(&bytes)))
361}
362
363pub fn is_consent_id(value: &str) -> bool {
364 value.strip_prefix("cns_").is_some_and(|rest| {
365 rest.len() == 16
366 && rest
367 .bytes()
368 .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
369 })
370}
371
372fn base32_lower(bytes: &[u8]) -> String {
373 const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
374 let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
375 let (mut buffer, mut bits) = (0u32, 0u32);
376 for &byte in bytes {
377 buffer = (buffer << 8) | u32::from(byte);
378 bits += 8;
379 while bits >= 5 {
380 bits -= 5;
381 out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
382 }
383 }
384 out
385}
386
387pub fn subject_digest(subject: &Value) -> Result<String, ConsentError> {
389 let bytes = lean_ctx_protocol::cloud::canonical_json(subject)
390 .map_err(|e| ConsentError::InvalidSubject(e.to_string()))?;
391 Ok(blake3::hash(&bytes).to_hex().to_string())
392}
393
394pub fn check_subject(kind: Kind, subject: &Value) -> Result<(), ConsentError> {
397 let bad = |why: String| Err(ConsentError::InvalidSubject(format!("{kind}: {why}")));
398 let Some(fields) = subject.as_object() else {
399 return bad("not an object".into());
400 };
401 let expected = kind.subject_fields();
402 if fields.len() != expected.len() || !expected.iter().all(|f| fields.contains_key(f)) {
403 let got: Vec<&String> = fields.keys().collect();
404 return bad(format!("fields {got:?}, expected {expected:?}"));
405 }
406 for (name, value) in fields {
407 if !field_ok(kind, name, value) {
408 return bad(format!("field {name}"));
409 }
410 }
411 Ok(())
412}
413
414fn field_ok(kind: Kind, name: &str, value: &Value) -> bool {
415 let text = value.as_str();
416 match name {
417 "link_digest" => text.is_some_and(is_hex64),
418 "vault" if kind == Kind::LinkVault => {
419 text.is_some_and(|v| crate::vault_address::VaultAddress::parse(v).is_ok())
420 }
421 "vault" => text.is_some_and(is_uuid),
422 "remote_seen" | "bound_repo" => {
423 value.is_null() || text.is_some_and(|t| (1..=500).contains(&t.chars().count()))
424 }
425 "target_vault" => value.is_null(),
426 "worker_id" => text.is_some_and(crate::bus::address::is_worker_id),
427 "cli" => text.is_some_and(|t| !t.is_empty() && t.len() <= 64),
428 "vendor" => text.is_some_and(|t| handle_like(t, 32)),
429 "requester" => text.is_some_and(|t| handle_like(t, 39)),
430 "instance_fingerprint" => text.is_some_and(|t| t.len() == 16 && is_lower_hex(t)),
431 _ => false,
432 }
433}
434
435fn handle_like(value: &str, max: usize) -> bool {
437 let bytes = value.as_bytes();
438 !bytes.is_empty()
439 && bytes.len() <= max
440 && bytes[0] != b'-'
441 && bytes
442 .iter()
443 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
444}
445
446fn is_lower_hex(value: &str) -> bool {
447 value
448 .bytes()
449 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
450}
451
452fn is_hex64(value: &str) -> bool {
453 value.len() == 64 && is_lower_hex(value)
454}
455
456fn is_uuid(value: &str) -> bool {
457 let parts: Vec<&str> = value.split('-').collect();
458 parts.len() == 5
459 && parts.iter().map(|p| p.len()).eq([8, 4, 4, 4, 12])
460 && parts.iter().all(|p| is_lower_hex(p))
461}
462
463pub fn subject(fields: &[(&str, Value)]) -> Value {
465 Value::Object(
466 fields
467 .iter()
468 .map(|(k, v)| ((*k).to_string(), v.clone()))
469 .collect::<Map<_, _>>(),
470 )
471}
472
473#[cfg(test)]
474mod tests;