lean-ctx 3.12.11

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported proxy integrations.
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
//! Access grants → Unix users: the pure half of the key sync.
//!
//! The cloud answers the granted public keys of this computer (design
//! §2.3a, `GET /v1/me/computer/authorized-keys`, instance token):
//! `{"keys":[{"public_key","fingerprint","user_id","unix_user","admin"}]}`.
//! [`desired`] turns that answer into one key set per Unix user, dropping
//! every entry whose user name or key is not of the strict form (a dropped
//! entry grants nothing, so a malformed answer can only take access away).
//! [`diff`] compares it with the users this daemon created and names the
//! steps; `users.rs` carries them out.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use super::config::Role;

/// The group every grantee's user is in (sshd `AllowGroups lc-users`).
#[cfg(target_os = "linux")]
pub(crate) const GROUP_USERS: &str = "lc-users";
/// The extra group of a `weave_host` grantee (sshd `Match Group lc-diag`
/// forces the diagnostic menu).
#[cfg(target_os = "linux")]
pub(crate) const GROUP_DIAG: &str = "lc-diag";
/// The forced command of every key on a `weave_host` computer.
pub(crate) const DIAG_COMMAND: &str = "lean-ctx computer diag";

/// `lc-` and 8 to 16 lowercase letters or digits: the cloud's `unix_user`
/// column check (API §22 issues `lc-` and 12 hex digits).
pub(crate) fn valid_unix_user(name: &str) -> bool {
    name.strip_prefix("lc-").is_some_and(|rest| {
        (8..=16).contains(&rest.len())
            && rest
                .bytes()
                .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
    })
}

/// The key types sshd accepts here.
const KEY_TYPES: &[&str] = &[
    "ssh-ed25519",
    "sk-ssh-ed25519@openssh.com",
    "ecdsa-sha2-nistp256",
    "ecdsa-sha2-nistp384",
    "ecdsa-sha2-nistp521",
    "sk-ecdsa-sha2-nistp256@openssh.com",
    "ssh-rsa",
];

/// The longest base64 key blob accepted (an RSA-16384 key is ~2.8 KB).
const MAX_BLOB: usize = 4096;

/// `<type> <base64>` of a public key, its comment dropped; `None` for
/// anything else (options, several lines, an unknown type).
pub(crate) fn canonical_key(public_key: &str) -> Option<String> {
    let mut parts = public_key.trim().split(' ');
    let kind = parts.next()?;
    let blob = parts.next()?;
    if !KEY_TYPES.contains(&kind) {
        return None;
    }
    let body = blob.trim_end_matches('=');
    if body.is_empty()
        || blob.len() > MAX_BLOB
        || blob.len() - body.len() > 2
        || !body
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
    {
        return None;
    }
    // A comment may follow; it is dropped, but must stay printable ASCII.
    let rest: Vec<&str> = parts.collect();
    if rest
        .iter()
        .any(|p| !p.bytes().all(|b| b.is_ascii_graphic()))
    {
        return None;
    }
    Some(format!("{kind} {blob}"))
}

#[derive(Deserialize)]
struct Answer {
    keys: Vec<Entry>,
}

#[derive(Deserialize)]
struct Entry {
    public_key: String,
    unix_user: String,
}

/// The users and keys an answer grants, plus how many entries were dropped.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Desired {
    pub users: BTreeMap<String, Vec<String>>,
    pub dropped: usize,
}

/// Parse the authorized-keys answer.
pub(crate) fn desired(body: &[u8]) -> Result<Desired, String> {
    let answer: Answer =
        serde_json::from_slice(body).map_err(|e| format!("authorized keys answer: {e}"))?;
    let mut out = Desired::default();
    for entry in answer.keys {
        match (
            valid_unix_user(&entry.unix_user),
            canonical_key(&entry.public_key),
        ) {
            (true, Some(key)) => {
                let keys = out.users.entry(entry.unix_user).or_default();
                if !keys.contains(&key) {
                    keys.push(key);
                }
            }
            _ => out.dropped += 1,
        }
    }
    for keys in out.users.values_mut() {
        keys.sort();
    }
    Ok(out)
}

/// The hand-off from the unprivileged agent to the root user sync: the
/// checked grants in the cloud's own answer shape, so the root side parses
/// them again with [`desired`] and trusts nothing the agent wrote.
pub(crate) fn handoff(desired: &Desired) -> Vec<u8> {
    let keys: Vec<serde_json::Value> = desired
        .users
        .iter()
        .flat_map(|(user, keys)| {
            keys.iter()
                .map(move |key| serde_json::json!({"public_key": key, "unix_user": user}))
        })
        .collect();
    serde_json::json!({ "keys": keys }).to_string().into_bytes()
}

/// The `authorized_keys` file of a user with `keys` on a computer of `role`.
pub(crate) fn render_keys(role: Role, keys: &[String]) -> String {
    let mut out = String::new();
    for key in keys {
        if role == Role::WeaveHost {
            out.push_str("restrict,command=\"");
            out.push_str(DIAG_COMMAND);
            out.push_str("\" ");
        }
        out.push_str(key);
        out.push('\n');
    }
    out
}

/// The digest of a rendered `authorized_keys`, to skip unchanged rewrites.
pub(crate) fn keys_digest(rendered: &str) -> String {
    blake3::hash(rendered.as_bytes()).to_hex().to_string()
}

/// One user this daemon created, as recorded in its state file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Managed {
    /// Whether the user currently has a grant (else locked, home kept).
    pub active: bool,
    /// [`keys_digest`] of the keys last written; empty while none are (a
    /// user recorded before `useradd`, or one whose revoke began), so a
    /// grant for it unlocks the account again before writing keys.
    pub keys: String,
}

impl Managed {
    /// The record written before `useradd`: a crash or a failed
    /// `useradd` leaves a record, never an unrecorded user the sync would
    /// then refuse to touch.
    #[cfg(any(target_os = "linux", test))]
    pub(crate) fn pending() -> Self {
        Self {
            active: true,
            keys: String::new(),
        }
    }

    /// Record a revoke attempt. The user counts as revoked only when its
    /// keys were emptied *and* its account expired; otherwise it stays
    /// active, so the next sync plans the revoke again.
    #[cfg(any(target_os = "linux", test))]
    pub(crate) fn record_revoke(&mut self, emptied: bool, expired: bool) {
        if emptied || expired {
            self.keys.clear();
        }
        if emptied && expired {
            self.active = false;
        }
    }
}

/// The state file: every user this daemon created. Only these are ever
/// changed; a user the daemon did not create is never touched.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ManagedUsers {
    pub users: BTreeMap<String, Managed>,
}

/// One step of a sync.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Step {
    /// Create the user, then write its keys.
    Create { user: String, keys: String },
    /// Unlock a user whose grant came back, then write its keys.
    Reactivate { user: String, keys: String },
    /// Rewrite the keys of an active user.
    SetKeys { user: String, keys: String },
    /// Lock the user, empty its keys, end its sessions; keep its home.
    Revoke { user: String },
}

/// The steps that take `managed` to `desired` on a computer of `role`.
pub(crate) fn diff(role: Role, desired: &Desired, managed: &ManagedUsers) -> Vec<Step> {
    let mut steps = Vec::new();
    for (user, keys) in &desired.users {
        let rendered = render_keys(role, keys);
        match managed.users.get(user) {
            None => steps.push(Step::Create {
                user: user.clone(),
                keys: rendered,
            }),
            Some(m) if !m.active || m.keys.is_empty() => steps.push(Step::Reactivate {
                user: user.clone(),
                keys: rendered,
            }),
            Some(m) if m.keys != keys_digest(&rendered) => steps.push(Step::SetKeys {
                user: user.clone(),
                keys: rendered,
            }),
            Some(_) => {}
        }
    }
    for (user, m) in &managed.users {
        if m.active && !desired.users.contains_key(user) {
            steps.push(Step::Revoke { user: user.clone() });
        }
    }
    steps
}

#[cfg(test)]
mod tests {
    use super::*;

    const ED: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl";
    const ED2: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBc8nTy6vxDLkLs0yX7oQ1VWm3qzqv1h3dpdX6oJp9Ab";

    fn answer(entries: &[(&str, &str)]) -> Vec<u8> {
        let keys: Vec<_> = entries
            .iter()
            .map(|(user, key)| {
                serde_json::json!({"public_key": key, "fingerprint": "SHA256:x",
                    "user_id": "u", "unix_user": user, "admin": false})
            })
            .collect();
        serde_json::json!({ "keys": keys }).to_string().into_bytes()
    }

    #[test]
    fn unix_user_names_are_strict() {
        for good in ["lc-0123456789ab", "lc-abcdefgh", "lc-0123456789abcdef"] {
            assert!(valid_unix_user(good), "{good}");
        }
        for bad in [
            "root",
            "lc-",
            "lc-weave",
            "lc-users",
            "lc-diag",
            "lc-ABCDEF012345",
            "lc-0123456789abcdef0",
            "lc-0123-56789ab",
            "lc-01234567../",
            "xlc-0123456789ab",
            "lc-0123456789ab\n",
            "lc-01234567 9ab",
            "-lc-0123456789",
        ] {
            assert!(!valid_unix_user(bad), "{bad:?}");
        }
    }

    #[test]
    fn keys_are_reduced_to_type_and_blob() {
        assert_eq!(canonical_key(&format!("{ED} anna@laptop")).unwrap(), ED);
        assert_eq!(canonical_key(ED).unwrap(), ED);
        for bad in [
            format!("command=\"sh\" {ED}"),
            format!("restrict {ED}"),
            format!("{ED}\nssh-ed25519 AAAA"),
            "ssh-dss AAAAB3NzaC1kc3M=".to_string(),
            "ssh-ed25519".to_string(),
            "ssh-ed25519 AAA$AAA".to_string(),
            "ssh-ed25519 AAAA===".to_string(),
            format!("{ED} comment\twith tab"),
            String::new(),
        ] {
            assert!(canonical_key(&bad).is_none(), "{bad:?}");
        }
    }

    #[test]
    fn an_answer_groups_keys_per_user_and_drops_bad_entries() {
        let body = answer(&[
            ("lc-0123456789ab", ED2),
            ("lc-0123456789ab", ED),
            ("lc-0123456789ab", ED),
            ("root", ED),
            ("lc-ffffffffffff", "command=\"sh\" ssh-ed25519 AAAA"),
        ]);
        let d = desired(&body).unwrap();
        assert_eq!(d.dropped, 2);
        assert_eq!(d.users.len(), 1);
        // Keys come back deduplicated and sorted, independent of answer order.
        let mut want = vec![ED.to_string(), ED2.to_string()];
        want.sort();
        assert_eq!(d.users["lc-0123456789ab"], want);
        assert!(desired(b"{\"keys\":null}").is_err());
        assert!(desired(b"[]").is_err());
        assert_eq!(desired(b"{\"keys\":[]}").unwrap(), Desired::default());
    }

    #[test]
    fn a_weave_host_key_carries_the_forced_diag_command() {
        let keys = vec![ED.to_string()];
        assert_eq!(
            render_keys(Role::WeaveHost, &keys),
            format!("restrict,command=\"lean-ctx computer diag\" {ED}\n")
        );
        assert_eq!(render_keys(Role::General, &keys), format!("{ED}\n"));
    }

    fn managed(entries: &[(&str, bool, &str)]) -> ManagedUsers {
        ManagedUsers {
            users: entries
                .iter()
                .map(|(u, active, keys)| {
                    (
                        (*u).to_string(),
                        Managed {
                            active: *active,
                            keys: (*keys).to_string(),
                        },
                    )
                })
                .collect(),
        }
    }

    #[test]
    fn grants_diff_into_create_reactivate_rekey_and_revoke() {
        let role = Role::WeaveHost;
        let d = desired(&answer(&[
            ("lc-aaaaaaaaaaaa", ED),
            ("lc-bbbbbbbbbbbb", ED),
            ("lc-cccccccccccc", ED2),
            ("lc-dddddddddddd", ED),
        ]))
        .unwrap();
        let same = keys_digest(&render_keys(role, &[ED.to_string()]));
        let state = managed(&[
            ("lc-bbbbbbbbbbbb", false, &same),
            ("lc-cccccccccccc", true, &same),
            ("lc-dddddddddddd", true, &same),
            ("lc-eeeeeeeeeeee", true, &same),
            ("lc-ffffffffffff", false, &same),
        ]);
        let steps = diff(role, &d, &state);
        let rendered = |k: &str| render_keys(role, &[k.to_string()]);
        assert_eq!(
            steps,
            vec![
                Step::Create {
                    user: "lc-aaaaaaaaaaaa".into(),
                    keys: rendered(ED)
                },
                Step::Reactivate {
                    user: "lc-bbbbbbbbbbbb".into(),
                    keys: rendered(ED)
                },
                Step::SetKeys {
                    user: "lc-cccccccccccc".into(),
                    keys: rendered(ED2)
                },
                Step::Revoke {
                    user: "lc-eeeeeeeeeeee".into()
                },
            ]
        );
    }

    #[test]
    fn an_empty_answer_revokes_every_active_managed_user_and_nothing_else() {
        let state = managed(&[
            ("lc-aaaaaaaaaaaa", true, "x"),
            ("lc-bbbbbbbbbbbb", false, "x"),
        ]);
        assert_eq!(
            diff(Role::General, &Desired::default(), &state),
            vec![Step::Revoke {
                user: "lc-aaaaaaaaaaaa".into()
            }]
        );
        // Unmanaged users never appear: the diff only knows managed ones.
        assert!(diff(Role::General, &Desired::default(), &ManagedUsers::default()).is_empty());
    }

    #[test]
    fn a_revoke_that_failed_in_part_is_planned_again() {
        let user = "lc-aaaaaaaaaaaa";
        let none = Desired::default();
        let revoke = vec![Step::Revoke { user: user.into() }];
        for (emptied, expired) in [(false, false), (true, false), (false, true)] {
            let mut state = managed(&[(user, true, "digest")]);
            state
                .users
                .get_mut(user)
                .unwrap()
                .record_revoke(emptied, expired);
            assert!(state.users[user].active, "{emptied} {expired}");
            assert_eq!(diff(Role::General, &none, &state), revoke);
        }
        let mut state = managed(&[(user, true, "digest")]);
        state.users.get_mut(user).unwrap().record_revoke(true, true);
        assert_eq!(
            state.users[user],
            Managed {
                active: false,
                keys: String::new()
            }
        );
        assert!(diff(Role::General, &none, &state).is_empty());
    }

    #[test]
    fn a_grant_after_a_partial_revoke_or_a_pending_create_unlocks_first() {
        let role = Role::General;
        let user = "lc-aaaaaaaaaaaa";
        let d = desired(&answer(&[(user, ED)])).unwrap();
        let reactivate = vec![Step::Reactivate {
            user: user.into(),
            keys: render_keys(role, &[ED.to_string()]),
        }];
        // The account expired but the keys could not be emptied.
        let mut state = managed(&[(user, true, "digest")]);
        state
            .users
            .get_mut(user)
            .unwrap()
            .record_revoke(false, true);
        assert_eq!(diff(role, &d, &state), reactivate);
        // Recorded before a useradd that failed or never finished.
        let mut state = ManagedUsers::default();
        state.users.insert(user.into(), Managed::pending());
        assert_eq!(diff(role, &d, &state), reactivate);
    }

    #[test]
    fn the_handoff_reads_back_as_the_same_grants() {
        let body = serde_json::json!({"keys": [
            {"public_key": ED, "unix_user": "lc-0123456789ab", "admin": true},
            {"public_key": ED2, "unix_user": "lc-0123456789ab"},
            {"public_key": ED, "unix_user": "lc-aaaabbbbcccc"},
            {"public_key": ED, "unix_user": "root"},
        ]});
        let first = desired(body.to_string().as_bytes()).unwrap();
        let again = desired(&handoff(&first)).unwrap();
        assert_eq!(again.users, first.users);
        assert_eq!(again.dropped, 0);
        assert_eq!(
            desired(&handoff(&Desired::default())).unwrap(),
            Desired::default()
        );
    }
}