lean-ctx-cloud 3.12.10

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// SPDX-License-Identifier: Apache-2.0
//! Out-of-band consent (SPEC-ENGINE §3.8; C0 2.0 `consent.schema.json`,
//! `enums/consent-kinds.json`, `vectors/consent_*.vectors.json`).
//!
//! The engine creates every consent (RESOLUTIONS R16); a person answers it
//! in a terminal, the Cockpit or the browser. No MCP action can approve:
//! approval lives only in [`broker::Broker::approve`], which takes a
//! [`Proof`] that only an approval channel produces.
//!
//! - [`Kind`]: the two kinds the engine uses, equal to the embedded list
//!   (the kinds of the C0 fixture the engine knows; any other is unknown).
//! - [`Record`]: one request with its decision and its proof, stored
//!   `<config>/cloud/consent/<id>.json` (0600); [`broker`] verifies the
//!   proof on every read.

pub mod broker;
pub mod channel;
pub mod chat_key;
#[cfg(unix)]
pub mod helper_mac;
pub mod optin_key;
pub mod person_sign;
pub mod task_key;
pub mod web;

use std::sync::OnceLock;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};

pub use broker::{Broker, Trust};

/// The C0 kind list, embedded (`crates/` is not packaged); a test keeps it
/// equal to `tests/fixtures/cloud-v2/enums/consent-kinds.json`.
pub(crate) const KINDS_JSON: &str = include_str!("consent-kinds.json");

/// Domain of a presence-key signature (§3.8.1, form (b) of §3.8.3).
pub const PROOF_DOMAIN: &str = "leanctx.cloud.consent_proof.v1\n";
/// Domain and schema of a Cloud-signed web answer (§3.8.2 step 5).
pub const STATEMENT_DOMAIN: &str = "leanctx.cloud.consent.v1\n";
pub const STATEMENT_SCHEMA: &str = "leanctx.cloud.consent.v1";

/// A request may be answered for 24 h.
pub const REQUEST_TTL_MS: u64 = 24 * 60 * 60 * 1000;

/// The C0 consent kinds (C0 2.2): sharing a checkout into a vault and
/// storing an API key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    LinkVault,
    ApiKeySet,
}

impl Kind {
    pub const ALL: [Kind; 2] = [Kind::LinkVault, Kind::ApiKeySet];

    pub fn as_str(self) -> &'static str {
        match self {
            Kind::LinkVault => "link_vault",
            Kind::ApiKeySet => "api_key_set",
        }
    }

    pub fn parse(value: &str) -> Option<Kind> {
        Kind::ALL.into_iter().find(|k| k.as_str() == value)
    }

    fn spec(self) -> &'static KindSpec {
        kind_specs()
            .iter()
            .find(|s| s.value == self.as_str())
            .expect("every kind is in the embedded fixture (tested)")
    }

    /// The subject fields, sorted (the fixture lists them so).
    pub fn subject_fields(self) -> &'static [String] {
        &self.spec().subject
    }

    /// Whether the person may answer it on `channel` (`cli`, `cockpit`, `web`).
    pub fn answerable_on(self, channel: &str) -> bool {
        self.spec().channels.iter().any(|c| c == channel)
    }

    /// The subject value the person types on the TTY to approve (§3.8.2):
    /// the place, vendor or account it names.
    pub fn typed_field(self) -> &'static str {
        match self {
            Kind::LinkVault => "vault",
            Kind::ApiKeySet => "vendor",
        }
    }
}

impl std::fmt::Display for Kind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Deserialize)]
struct KindSpec {
    value: String,
    channels: Vec<String>,
    subject: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct KindList {
    values: Vec<KindSpec>,
}

fn kind_specs() -> &'static [KindSpec] {
    static SPECS: OnceLock<Vec<KindSpec>> = OnceLock::new();
    SPECS.get_or_init(|| {
        serde_json::from_str::<KindList>(KINDS_JSON)
            .expect("embedded consent-kinds.json parses (tested)")
            .values
    })
}

/// How a decision was made (`enums/consent-channels.json`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Channel {
    OsPresence,
    TtyOnly,
    Cockpit,
    Web,
}

impl Channel {
    pub fn as_str(self) -> &'static str {
        match self {
            Channel::OsPresence => "os_presence",
            Channel::TtyOnly => "tty_only",
            Channel::Cockpit => "cockpit",
            Channel::Web => "web",
        }
    }

    /// The kind-list column this channel answers in.
    fn surface(self) -> &'static str {
        match self {
            Channel::OsPresence | Channel::TtyOnly => "cli",
            Channel::Cockpit => "cockpit",
            Channel::Web => "web",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum State {
    Pending,
    Approved,
    Denied,
    Expired,
}

/// The presence-key signature of an approval (§3.8.4).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PresenceSignature {
    pub key_id: String,
    pub alg: String,
    /// base64url without padding.
    pub signature: String,
}

/// Exactly one proof per approved record (§3.8.1).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Proof {
    Presence(PresenceSignature),
    Statement(Value),
    /// hex `blake3_keyed(K_file, …)`, tty-only hosts only.
    Mac(String),
}

/// One consent request and its decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Record {
    pub consent_id: String,
    pub kind: Kind,
    pub subject: Value,
    pub subject_digest: String,
    pub created_at: u64,
    pub expires_at: u64,
    pub state: State,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel: Option<Channel>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_at: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proof: Option<Proof>,
}

impl Record {
    /// What the presence key signs (§3.8.1).
    pub fn proof_input(&self, approved_at: u64) -> Result<Vec<u8>, ConsentError> {
        lean_ctx_protocol::cloud::signing_input(
            PROOF_DOMAIN,
            &json!({
                "consent_id": self.consent_id,
                "kind": self.kind,
                "subject_digest": self.subject_digest,
                "approved_at": approved_at,
            }),
        )
        .map_err(|e| ConsentError::Local(e.to_string()))
    }

    /// The "Request fingerprint" the terminal and the web show (R82).
    pub fn fingerprint(&self) -> &str {
        &self.subject_digest[..16]
    }

    /// The value the person types to approve on a TTY.
    pub fn typed_value(&self) -> String {
        let value = self.subject[self.kind.typed_field()]
            .as_str()
            .unwrap_or_default();
        // A UUID is typed by its first block.
        if is_uuid(value) {
            value[..8].to_string()
        } else {
            value.to_string()
        }
    }
}

/// Why a consent-gated step did not run. `code()` is the C0/engine error
/// code; `Display` is the person-facing text of SPEC-ENGINE §3.17.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConsentError {
    /// A request waits for the person (`consent_required`).
    Required {
        consent_id: String,
        kind: Kind,
    },
    /// The person declined (`consent_denied`).
    Denied,
    /// Older than 24 h (`consent_expired`).
    Expired,
    /// A record failed its proof check (`consent_record_invalid`).
    RecordInvalid,
    /// A proof only the web flow gives (`consent_web_only`).
    WebOnly {
        consent_id: String,
    },
    /// `api_key_set` outside the terminal (`consent_terminal_only`).
    TerminalOnly,
    /// Tty-only approval refused by workspace policy.
    PresenceRequiredByPolicy {
        consent_id: String,
    },
    /// The approval channel refused (no TTY, agent ancestry, wrong typed
    /// value); nothing was stored.
    ChannelRefused(String),
    /// Not a request of this engine.
    NotFound,
    /// A subject of the wrong shape for its kind (a caller bug).
    InvalidSubject(String),
    /// Already answered.
    InvalidState,
    /// No browser answer within 10 minutes (`consent_web_timeout`).
    WebTimeout,
    /// The person cancelled the system dialog (`presence_cancelled`).
    PresenceCancelled,
    /// `LeanCTX Consent.app` is not installed (`helper_missing`).
    HelperMissing,
    /// The helper is not ours (`helper_signature`).
    HelperSignature,
    /// A sensitive operation under an expired, missing or damaged Cloud
    /// policy (`policy_authorisation_expired`); fails closed.
    PolicyExpired(String),
    /// The Cloud does not offer the browser binding of an app's first
    /// share yet (`400 invalid_request` naming `binding`).
    BrowserUnsupported,
    Local(String),
}

impl ConsentError {
    pub fn code(&self) -> &'static str {
        match self {
            ConsentError::Required { .. } => "consent_required",
            ConsentError::Denied => "consent_denied",
            ConsentError::Expired => "consent_expired",
            ConsentError::RecordInvalid => "consent_record_invalid",
            ConsentError::WebOnly { .. } => "consent_web_only",
            ConsentError::TerminalOnly => "consent_terminal_only",
            ConsentError::PresenceRequiredByPolicy { .. } => "consent_presence_required_by_policy",
            ConsentError::ChannelRefused(_) => "consent_channel_refused",
            ConsentError::NotFound => "not_found",
            ConsentError::InvalidSubject(_) => "invalid_subject",
            ConsentError::InvalidState => "invalid_state",
            ConsentError::WebTimeout => "consent_web_timeout",
            ConsentError::PresenceCancelled => "presence_cancelled",
            ConsentError::HelperMissing => "helper_missing",
            ConsentError::HelperSignature => "helper_signature",
            ConsentError::PolicyExpired(_) => "policy_authorisation_expired",
            ConsentError::BrowserUnsupported => "consent_browser_unsupported",
            ConsentError::Local(_) => "local",
        }
    }
}

impl std::fmt::Display for ConsentError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            // Never the id alone as something to pass back (§3.8.1).
            ConsentError::Required { .. } => {
                f.write_str("Approve in a terminal: lean-ctx cloud consent")
            }
            ConsentError::Denied => f.write_str("The person declined this."),
            ConsentError::Expired => f.write_str("This request expired; run the command again."),
            ConsentError::RecordInvalid => {
                f.write_str("A consent record was altered; approve again.")
            }
            ConsentError::WebOnly { consent_id } => write!(
                f,
                "Answer this one in the browser: lean-ctx cloud consent --web {consent_id}"
            ),
            ConsentError::TerminalOnly => {
                f.write_str("This one is answered in the terminal only: lean-ctx cloud consent")
            }
            ConsentError::PresenceRequiredByPolicy { consent_id } => write!(
                f,
                "Your workspace requires system confirmation or the browser. Run: lean-ctx cloud consent --web {consent_id}"
            ),
            ConsentError::ChannelRefused(why) => write!(f, "Not approved: {why}"),
            ConsentError::NotFound => f.write_str("No such consent request on this computer."),
            ConsentError::InvalidSubject(why) => write!(f, "invalid consent subject: {why}"),
            ConsentError::InvalidState => f.write_str("This request was already answered."),
            ConsentError::WebTimeout => {
                f.write_str("No answer in the browser within 10 minutes; run the command again.")
            }
            ConsentError::PresenceCancelled => {
                f.write_str("System confirmation was cancelled. Nothing was approved.")
            }
            ConsentError::HelperMissing => f.write_str(
                "LeanCTX Consent.app is not installed; run lean-ctx cloud consent-helper install.",
            ),
            ConsentError::HelperSignature => f.write_str(
                "LeanCTX Consent.app signature invalid; run lean-ctx cloud consent-helper install.",
            ),
            ConsentError::PolicyExpired(why) => write!(f, "Refused: {why}"),
            ConsentError::BrowserUnsupported => f.write_str(
                "This Cloud does not offer the confirmation in the browser yet. Try again after its next update.",
            ),
            ConsentError::Local(why) => write!(f, "consent store: {why}"),
        }
    }
}

impl std::error::Error for ConsentError {}

impl From<ConsentError> for crate::CloudError {
    fn from(error: ConsentError) -> Self {
        crate::CloudError::Refused(format!("{}: {error}", error.code()))
    }
}

/// `cns_` + 16 lowercase base32 (80 random bits).
pub fn new_consent_id() -> Result<String, ConsentError> {
    let mut bytes = [0u8; 10];
    getrandom::fill(&mut bytes).map_err(|e| ConsentError::Local(e.to_string()))?;
    Ok(format!("cns_{}", base32_lower(&bytes)))
}

pub fn is_consent_id(value: &str) -> bool {
    value.strip_prefix("cns_").is_some_and(|rest| {
        rest.len() == 16
            && rest
                .bytes()
                .all(|b| b.is_ascii_lowercase() || (b'2'..=b'7').contains(&b))
    })
}

fn base32_lower(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
    let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
    let (mut buffer, mut bits) = (0u32, 0u32);
    for &byte in bytes {
        buffer = (buffer << 8) | u32::from(byte);
        bits += 8;
        while bits >= 5 {
            bits -= 5;
            out.push(ALPHABET[((buffer >> bits) & 31) as usize] as char);
        }
    }
    out
}

/// `hex(blake3(canonical_json(subject)))`.
pub fn subject_digest(subject: &Value) -> Result<String, ConsentError> {
    let bytes = lean_ctx_protocol::cloud::canonical_json(subject)
        .map_err(|e| ConsentError::InvalidSubject(e.to_string()))?;
    Ok(blake3::hash(&bytes).to_hex().to_string())
}

/// The subject carries exactly the kind's fields (no `isolation`, R107),
/// each of the type the schema gives it.
pub fn check_subject(kind: Kind, subject: &Value) -> Result<(), ConsentError> {
    let bad = |why: String| Err(ConsentError::InvalidSubject(format!("{kind}: {why}")));
    let Some(fields) = subject.as_object() else {
        return bad("not an object".into());
    };
    let expected = kind.subject_fields();
    if fields.len() != expected.len() || !expected.iter().all(|f| fields.contains_key(f)) {
        let got: Vec<&String> = fields.keys().collect();
        return bad(format!("fields {got:?}, expected {expected:?}"));
    }
    for (name, value) in fields {
        if !field_ok(kind, name, value) {
            return bad(format!("field {name}"));
        }
    }
    Ok(())
}

fn field_ok(kind: Kind, name: &str, value: &Value) -> bool {
    let text = value.as_str();
    match name {
        "link_digest" => text.is_some_and(is_hex64),
        "vault" if kind == Kind::LinkVault => {
            text.is_some_and(|v| crate::vault_address::VaultAddress::parse(v).is_ok())
        }
        "vault" => text.is_some_and(is_uuid),
        "remote_seen" | "bound_repo" => {
            value.is_null() || text.is_some_and(|t| (1..=500).contains(&t.chars().count()))
        }
        "target_vault" => value.is_null(),
        "worker_id" => text.is_some_and(crate::bus::address::is_worker_id),
        "cli" => text.is_some_and(|t| !t.is_empty() && t.len() <= 64),
        "vendor" => text.is_some_and(|t| handle_like(t, 32)),
        "requester" => text.is_some_and(|t| handle_like(t, 39)),
        "instance_fingerprint" => text.is_some_and(|t| t.len() == 16 && is_lower_hex(t)),
        _ => false,
    }
}

/// `^[a-z0-9][a-z0-9-]{0,max-1}$`.
fn handle_like(value: &str, max: usize) -> bool {
    let bytes = value.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= max
        && bytes[0] != b'-'
        && bytes
            .iter()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
}

fn is_lower_hex(value: &str) -> bool {
    value
        .bytes()
        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn is_hex64(value: &str) -> bool {
    value.len() == 64 && is_lower_hex(value)
}

fn is_uuid(value: &str) -> bool {
    let parts: Vec<&str> = value.split('-').collect();
    parts.len() == 5
        && parts.iter().map(|p| p.len()).eq([8, 4, 4, 4, 12])
        && parts.iter().all(|p| is_lower_hex(p))
}

/// Build a subject from its fields (callers name each one).
pub fn subject(fields: &[(&str, Value)]) -> Value {
    Value::Object(
        fields
            .iter()
            .map(|(k, v)| ((*k).to_string(), v.clone()))
            .collect::<Map<_, _>>(),
    )
}

#[cfg(test)]
mod tests;