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;
18pub mod chat_key;
19#[cfg(unix)]
20pub mod helper_mac;
21pub mod optin_key;
22pub mod person_sign;
23pub mod task_key;
24pub mod web;
25
26use std::sync::OnceLock;
27
28use serde::{Deserialize, Serialize};
29use serde_json::{Map, Value, json};
30
31pub use broker::{Broker, Trust};
32
33/// The C0 kind list, embedded (`crates/` is not packaged); a test keeps it
34/// equal to `tests/fixtures/cloud-v2/enums/consent-kinds.json`.
35pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");
36
37/// Domain of a presence-key signature (§3.8.1, form (b) of §3.8.3).
38pub const PROOF_DOMAIN: &str = "leanctx.cloud.consent_proof.v1\n";
39/// Domain and schema of a Cloud-signed web answer (§3.8.2 step 5).
40pub const STATEMENT_DOMAIN: &str = "leanctx.cloud.consent.v1\n";
41pub const STATEMENT_SCHEMA: &str = "leanctx.cloud.consent.v1";
42
43/// A request may be answered for 24 h.
44pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;
45
46/// The C0 consent kinds (C0 2.2): sharing a checkout into a vault and
47/// storing an API key.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum Kind {
51    LinkVault,
52    ApiKeySet,
53}
54
55impl Kind {
56    pub const ALL: [Kind; 2] = [Kind::LinkVault, Kind::ApiKeySet];
57
58    pub fn as_str(self) -> &'static str {
59        match self {
60            Kind::LinkVault => "link_vault",
61            Kind::ApiKeySet => "api_key_set",
62        }
63    }
64
65    pub fn parse(value: &str) -> Option<Kind> {
66        Kind::ALL.into_iter().find(|k| k.as_str() == value)
67    }
68
69    fn spec(self) -> &'static KindSpec {
70        kind_specs()
71            .iter()
72            .find(|s| s.value == self.as_str())
73            .expect("every kind is in the embedded fixture (tested)")
74    }
75
76    /// The subject fields, sorted (the fixture lists them so).
77    pub fn subject_fields(self) -> &'static [String] {
78        &self.spec().subject
79    }
80
81    /// Whether the person may answer it on `channel` (`cli`, `cockpit`, `web`).
82    pub fn answerable_on(self, channel: &str) -> bool {
83        self.spec().channels.iter().any(|c| c == channel)
84    }
85
86    /// The subject value the person types on the TTY to approve (§3.8.2):
87    /// the place, vendor or account it names.
88    pub fn typed_field(self) -> &'static str {
89        match self {
90            Kind::LinkVault => "vault",
91            Kind::ApiKeySet => "vendor",
92        }
93    }
94}
95
96impl std::fmt::Display for Kind {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.write_str(self.as_str())
99    }
100}
101
102#[derive(Debug, Deserialize)]
103struct KindSpec {
104    value: String,
105    channels: Vec<String>,
106    subject: Vec<String>,
107}
108
109#[derive(Debug, Deserialize)]
110struct KindList {
111    values: Vec<KindSpec>,
112}
113
114fn kind_specs() -> &'static [KindSpec] {
115    static SPECS: OnceLock<Vec<KindSpec>> = OnceLock::new();
116    SPECS.get_or_init(|| {
117        serde_json::from_str::<KindList>(KINDS_JSON)
118            .expect("embedded consent-kinds.json parses (tested)")
119            .values
120    })
121}
122
123/// How a decision was made (`enums/consent-channels.json`).
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum Channel {
127    OsPresence,
128    TtyOnly,
129    Cockpit,
130    Web,
131}
132
133impl Channel {
134    pub fn as_str(self) -> &'static str {
135        match self {
136            Channel::OsPresence => "os_presence",
137            Channel::TtyOnly => "tty_only",
138            Channel::Cockpit => "cockpit",
139            Channel::Web => "web",
140        }
141    }
142
143    /// The kind-list column this channel answers in.
144    fn surface(self) -> &'static str {
145        match self {
146            Channel::OsPresence | Channel::TtyOnly => "cli",
147            Channel::Cockpit => "cockpit",
148            Channel::Web => "web",
149        }
150    }
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum State {
156    Pending,
157    Approved,
158    Denied,
159    Expired,
160}
161
162/// The presence-key signature of an approval (§3.8.4).
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164#[serde(deny_unknown_fields)]
165pub struct PresenceSignature {
166    pub key_id: String,
167    pub alg: String,
168    /// base64url without padding.
169    pub signature: String,
170}
171
172/// Exactly one proof per approved record (§3.8.1).
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
174#[serde(rename_all = "snake_case")]
175pub enum Proof {
176    Presence(PresenceSignature),
177    Statement(Value),
178    /// hex `blake3_keyed(K_file, …)`, tty-only hosts only.
179    Mac(String),
180}
181
182/// One consent request and its decision.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(deny_unknown_fields)]
185pub struct Record {
186    pub consent_id: String,
187    pub kind: Kind,
188    pub subject: Value,
189    pub subject_digest: String,
190    pub created_at: u64,
191    pub expires_at: u64,
192    pub state: State,
193    #[serde(default, skip_serializing_if = "Option::is_none")]
194    pub channel: Option<Channel>,
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub approved_at: Option<u64>,
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub proof: Option<Proof>,
199}
200
201impl Record {
202    /// What the presence key signs (§3.8.1).
203    pub fn proof_input(&self, approved_at: u64) -> Result<Vec<u8>, ConsentError> {
204        lean_ctx_protocol::cloud::signing_input(
205            PROOF_DOMAIN,
206            &json!({
207                "consent_id": self.consent_id,
208                "kind": self.kind,
209                "subject_digest": self.subject_digest,
210                "approved_at": approved_at,
211            }),
212        )
213        .map_err(|e| ConsentError::Local(e.to_string()))
214    }
215
216    /// The "Request fingerprint" the terminal and the web show (R82).
217    pub fn fingerprint(&self) -> &str {
218        &self.subject_digest[..16]
219    }
220
221    /// The value the person types to approve on a TTY.
222    pub fn typed_value(&self) -> String {
223        let value = self.subject[self.kind.typed_field()]
224            .as_str()
225            .unwrap_or_default();
226        // A UUID is typed by its first block.
227        if is_uuid(value) {
228            value[..8].to_string()
229        } else {
230            value.to_string()
231        }
232    }
233}
234
235/// Why a consent-gated step did not run. `code()` is the C0/engine error
236/// code; `Display` is the person-facing text of SPEC-ENGINE §3.17.
237#[derive(Debug, Clone, PartialEq, Eq)]
238pub enum ConsentError {
239    /// A request waits for the person (`consent_required`).
240    Required {
241        consent_id: String,
242        kind: Kind,
243    },
244    /// The person declined (`consent_denied`).
245    Denied,
246    /// Older than 24 h (`consent_expired`).
247    Expired,
248    /// A record failed its proof check (`consent_record_invalid`).
249    RecordInvalid,
250    /// A proof only the web flow gives (`consent_web_only`).
251    WebOnly {
252        consent_id: String,
253    },
254    /// `api_key_set` outside the terminal (`consent_terminal_only`).
255    TerminalOnly,
256    /// Tty-only approval refused by workspace policy.
257    PresenceRequiredByPolicy {
258        consent_id: String,
259    },
260    /// The approval channel refused (no TTY, agent ancestry, wrong typed
261    /// value); nothing was stored.
262    ChannelRefused(String),
263    /// Not a request of this engine.
264    NotFound,
265    /// A subject of the wrong shape for its kind (a caller bug).
266    InvalidSubject(String),
267    /// Already answered.
268    InvalidState,
269    /// No browser answer within 10 minutes (`consent_web_timeout`).
270    WebTimeout,
271    /// The person cancelled the system dialog (`presence_cancelled`).
272    PresenceCancelled,
273    /// `LeanCTX Consent.app` is not installed (`helper_missing`).
274    HelperMissing,
275    /// The helper is not ours (`helper_signature`).
276    HelperSignature,
277    /// A sensitive operation under an expired, missing or damaged Cloud
278    /// policy (`policy_authorisation_expired`); fails closed.
279    PolicyExpired(String),
280    /// The Cloud does not offer the browser binding of an app's first
281    /// share yet (`400 invalid_request` naming `binding`).
282    BrowserUnsupported,
283    Local(String),
284}
285
286impl ConsentError {
287    pub fn code(&self) -> &'static str {
288        match self {
289            ConsentError::Required { .. } => "consent_required",
290            ConsentError::Denied => "consent_denied",
291            ConsentError::Expired => "consent_expired",
292            ConsentError::RecordInvalid => "consent_record_invalid",
293            ConsentError::WebOnly { .. } => "consent_web_only",
294            ConsentError::TerminalOnly => "consent_terminal_only",
295            ConsentError::PresenceRequiredByPolicy { .. } => "consent_presence_required_by_policy",
296            ConsentError::ChannelRefused(_) => "consent_channel_refused",
297            ConsentError::NotFound => "not_found",
298            ConsentError::InvalidSubject(_) => "invalid_subject",
299            ConsentError::InvalidState => "invalid_state",
300            ConsentError::WebTimeout => "consent_web_timeout",
301            ConsentError::PresenceCancelled => "presence_cancelled",
302            ConsentError::HelperMissing => "helper_missing",
303            ConsentError::HelperSignature => "helper_signature",
304            ConsentError::PolicyExpired(_) => "policy_authorisation_expired",
305            ConsentError::BrowserUnsupported => "consent_browser_unsupported",
306            ConsentError::Local(_) => "local",
307        }
308    }
309}
310
311impl std::fmt::Display for ConsentError {
312    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313        match self {
314            // Never the id alone as something to pass back (§3.8.1).
315            ConsentError::Required { .. } => {
316                f.write_str("Approve in a terminal: lean-ctx cloud consent")
317            }
318            ConsentError::Denied => f.write_str("The person declined this."),
319            ConsentError::Expired => f.write_str("This request expired; run the command again."),
320            ConsentError::RecordInvalid => {
321                f.write_str("A consent record was altered; approve again.")
322            }
323            ConsentError::WebOnly { consent_id } => write!(
324                f,
325                "Answer this one in the browser: lean-ctx cloud consent --web {consent_id}"
326            ),
327            ConsentError::TerminalOnly => {
328                f.write_str("This one is answered in the terminal only: lean-ctx cloud consent")
329            }
330            ConsentError::PresenceRequiredByPolicy { consent_id } => write!(
331                f,
332                "Your workspace requires system confirmation or the browser. Run: lean-ctx cloud consent --web {consent_id}"
333            ),
334            ConsentError::ChannelRefused(why) => write!(f, "Not approved: {why}"),
335            ConsentError::NotFound => f.write_str("No such consent request on this computer."),
336            ConsentError::InvalidSubject(why) => write!(f, "invalid consent subject: {why}"),
337            ConsentError::InvalidState => f.write_str("This request was already answered."),
338            ConsentError::WebTimeout => {
339                f.write_str("No answer in the browser within 10 minutes; run the command again.")
340            }
341            ConsentError::PresenceCancelled => {
342                f.write_str("System confirmation was cancelled. Nothing was approved.")
343            }
344            ConsentError::HelperMissing => f.write_str(
345                "LeanCTX Consent.app is not installed; run lean-ctx cloud consent-helper install.",
346            ),
347            ConsentError::HelperSignature => f.write_str(
348                "LeanCTX Consent.app signature invalid; run lean-ctx cloud consent-helper install.",
349            ),
350            ConsentError::PolicyExpired(why) => write!(f, "Refused: {why}"),
351            ConsentError::BrowserUnsupported => f.write_str(
352                "This Cloud does not offer the confirmation in the browser yet. Try again after its next update.",
353            ),
354            ConsentError::Local(why) => write!(f, "consent store: {why}"),
355        }
356    }
357}
358
359impl std::error::Error for ConsentError {}
360
361impl From<ConsentError> for crate::CloudError {
362    fn from(error: ConsentError) -> Self {
363        crate::CloudError::Refused(format!("{}: {error}", error.code()))
364    }
365}
366
367/// `cns_` + 16 lowercase base32 (80 random bits).
368pub fn new_consent_id() -> Result<String, ConsentError> {
369    let mut bytes = [0u8; 10];
370    getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
371    Ok(format!("cns_{}", base32_lower(&bytes)))
372}
373
374pub fn is_consent_id(value: &str) -> bool {
375    value.strip_prefix("cns_").is_some_and(|rest| {
376        rest.len() == 16
377            && rest
378                .bytes()
379                .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
380    })
381}
382
383fn base32_lower(bytes: &[u8]) -> String {
384    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
385    let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
386    let (mut buffer, mut bits) = (0u32, 0u32);
387    for &byte in bytes {
388        buffer = (buffer << 8) | u32::from(byte);
389        bits += 8;
390        while bits >= 5 {
391            bits -= 5;
392            out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
393        }
394    }
395    out
396}
397
398/// `hex(blake3(canonical_json(subject)))`.
399pub fn subject_digest(subject: &Value) -> Result<String, ConsentError> {
400    let bytes = lean_ctx_protocol::cloud::canonical_json(subject)
401        .map_err(|e| ConsentError::InvalidSubject(e.to_string()))?;
402    Ok(blake3::hash(&bytes).to_hex().to_string())
403}
404
405/// The subject carries exactly the kind's fields (no `isolation`, R107),
406/// each of the type the schema gives it.
407pub fn check_subject(kind: Kind, subject: &Value) -> Result<(), ConsentError> {
408    let bad = |why: String| Err(ConsentError::InvalidSubject(format!("{kind}: {why}")));
409    let Some(fields) = subject.as_object() else {
410        return bad("not an object".into());
411    };
412    let expected = kind.subject_fields();
413    if fields.len() != expected.len() || !expected.iter().all(|f| fields.contains_key(f)) {
414        let got: Vec<&String> = fields.keys().collect();
415        return bad(format!("fields {got:?}, expected {expected:?}"));
416    }
417    for (name, value) in fields {
418        if !field_ok(kind, name, value) {
419            return bad(format!("field {name}"));
420        }
421    }
422    Ok(())
423}
424
425fn field_ok(kind: Kind, name: &str, value: &Value) -> bool {
426    let text = value.as_str();
427    match name {
428        "link_digest" => text.is_some_and(is_hex64),
429        "vault" if kind == Kind::LinkVault => {
430            text.is_some_and(|v| crate::vault_address::VaultAddress::parse(v).is_ok())
431        }
432        "vault" => text.is_some_and(is_uuid),
433        "remote_seen" | "bound_repo" => {
434            value.is_null() || text.is_some_and(|t| (1..=500).contains(&t.chars().count()))
435        }
436        "target_vault" => value.is_null(),
437        "worker_id" => text.is_some_and(crate::bus::address::is_worker_id),
438        "cli" => text.is_some_and(|t| !t.is_empty() && t.len() <= 64),
439        "vendor" => text.is_some_and(|t| handle_like(t, 32)),
440        "requester" => text.is_some_and(|t| handle_like(t, 39)),
441        "instance_fingerprint" => text.is_some_and(|t| t.len() == 16 && is_lower_hex(t)),
442        _ => false,
443    }
444}
445
446/// `^[a-z0-9][a-z0-9-]{0,max-1}$`.
447fn handle_like(value: &str, max: usize) -> bool {
448    let bytes = value.as_bytes();
449    !bytes.is_empty()
450        && bytes.len() <= max
451        && bytes[0] != b'-'
452        && bytes
453            .iter()
454            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
455}
456
457fn is_lower_hex(value: &str) -> bool {
458    value
459        .bytes()
460        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
461}
462
463fn is_hex64(value: &str) -> bool {
464    value.len() == 64 && is_lower_hex(value)
465}
466
467fn is_uuid(value: &str) -> bool {
468    let parts: Vec<&str> = value.split('-').collect();
469    parts.len() == 5
470        && parts.iter().map(|p| p.len()).eq([8, 4, 4, 4, 12])
471        && parts.iter().all(|p| is_lower_hex(p))
472}
473
474/// Build a subject from its fields (callers name each one).
475pub fn subject(fields: &[(&str, Value)]) -> Value {
476    Value::Object(
477        fields
478            .iter()
479            .map(|(k, v)| ((*k).to_string(), v.clone()))
480            .collect::<Map<_, _>>(),
481    )
482}
483
484#[cfg(test)]
485mod tests;