Skip to main content

lean_ctx_cloud/consent/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Out-of-band consent (SPEC-ENGINE §3.8; C0 2.0 `consent.schema.json`,
3//! `enums/consent-kinds.json`, `vectors/consent_*.vectors.json`).
4//!
5//! The engine creates every consent (RESOLUTIONS R16); a person answers it
6//! in a terminal, the Cockpit or the browser. No MCP action can approve:
7//! approval lives only in [`broker::Broker::approve`], which takes a
8//! [`Proof`] that only an approval channel produces.
9//!
10//! - [`Kind`]: the two kinds the engine uses, equal to the embedded list
11//!   (the kinds of the C0 fixture the engine knows; any other is unknown).
12//! - [`Record`]: one request with its decision and its proof, stored
13//!   `<config>/cloud/consent/<id>.json` (0600); [`broker`] verifies the
14//!   proof on every read.
15
16pub 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
29/// The C0 kind list, embedded (`crates/` is not packaged); a test keeps it
30/// equal to `tests/fixtures/cloud-v2/enums/consent-kinds.json`.
31pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");
32
33/// Domain of a presence-key signature (§3.8.1, form (b) of §3.8.3).
34pub const PROOF_DOMAIN: &str = "leanctx.cloud.consent_proof.v1\n";
35/// Domain and schema of a Cloud-signed web answer (§3.8.2 step 5).
36pub const STATEMENT_DOMAIN: &str = "leanctx.cloud.consent.v1\n";
37pub const STATEMENT_SCHEMA: &str = "leanctx.cloud.consent.v1";
38
39/// A request may be answered for 24 h.
40pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;
41
42/// The C0 consent kinds (C0 2.2): sharing a checkout into a vault and
43/// storing an API key.
44#[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    /// The subject fields, sorted (the fixture lists them so).
73    pub fn subject_fields(self) -> &'static [String] {
74        &self.spec().subject
75    }
76
77    /// Whether the person may answer it on `channel` (`cli`, `cockpit`, `web`).
78    pub fn answerable_on(self, channel: &str) -> bool {
79        self.spec().channels.iter().any(|c| c == channel)
80    }
81
82    /// The subject value the person types on the TTY to approve (§3.8.2):
83    /// the place, vendor or account it names.
84    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/// How a decision was made (`enums/consent-channels.json`).
120#[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    /// The kind-list column this channel answers in.
140    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/// The presence-key signature of an approval (§3.8.4).
159#[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    /// base64url without padding.
165    pub signature: String,
166}
167
168/// Exactly one proof per approved record (§3.8.1).
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170#[serde(rename_all = "snake_case")]
171pub enum Proof {
172    Presence(PresenceSignature),
173    Statement(Value),
174    /// hex `blake3_keyed(K_file, …)`, tty-only hosts only.
175    Mac(String),
176}
177
178/// One consent request and its decision.
179#[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    /// What the presence key signs (§3.8.1).
199    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    /// The "Request fingerprint" the terminal and the web show (R82).
213    pub fn fingerprint(&self) -> &str {
214        &self.subject_digest[..16]
215    }
216
217    /// The value the person types to approve on a TTY.
218    pub fn typed_value(&self) -> String {
219        let value = self.subject[self.kind.typed_field()]
220            .as_str()
221            .unwrap_or_default();
222        // A UUID is typed by its first block.
223        if is_uuid(value) {
224            value[..8].to_string()
225        } else {
226            value.to_string()
227        }
228    }
229}
230
231/// Why a consent-gated step did not run. `code()` is the C0/engine error
232/// code; `Display` is the person-facing text of SPEC-ENGINE §3.17.
233#[derive(Debug, Clone, PartialEq, Eq)]
234pub enum ConsentError {
235    /// A request waits for the person (`consent_required`).
236    Required {
237        consent_id: String,
238        kind: Kind,
239    },
240    /// The person declined (`consent_denied`).
241    Denied,
242    /// Older than 24 h (`consent_expired`).
243    Expired,
244    /// A record failed its proof check (`consent_record_invalid`).
245    RecordInvalid,
246    /// A proof only the web flow gives (`consent_web_only`).
247    WebOnly {
248        consent_id: String,
249    },
250    /// `api_key_set` outside the terminal (`consent_terminal_only`).
251    TerminalOnly,
252    /// Tty-only approval refused by workspace policy.
253    PresenceRequiredByPolicy {
254        consent_id: String,
255    },
256    /// The approval channel refused (no TTY, agent ancestry, wrong typed
257    /// value); nothing was stored.
258    ChannelRefused(String),
259    /// Not a request of this engine.
260    NotFound,
261    /// A subject of the wrong shape for its kind (a caller bug).
262    InvalidSubject(String),
263    /// Already answered.
264    InvalidState,
265    /// No browser answer within 10 minutes (`consent_web_timeout`).
266    WebTimeout,
267    /// The person cancelled the system dialog (`presence_cancelled`).
268    PresenceCancelled,
269    /// `LeanCTX Consent.app` is not installed (`helper_missing`).
270    HelperMissing,
271    /// The helper is not ours (`helper_signature`).
272    HelperSignature,
273    /// A sensitive operation under an expired, missing or damaged Cloud
274    /// policy (`policy_authorisation_expired`); fails closed.
275    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            // Never the id alone as something to pass back (§3.8.1).
307            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
356/// `cns_` + 16 lowercase base32 (80 random bits).
357pub 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
387/// `hex(blake3(canonical_json(subject)))`.
388pub 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
394/// The subject carries exactly the kind's fields (no `isolation`, R107),
395/// each of the type the schema gives it.
396pub 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
435/// `^[a-z0-9][a-z0-9-]{0,max-1}$`.
436fn 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
463/// Build a subject from its fields (callers name each one).
464pub 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;