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
// SPDX-License-Identifier: Apache-2.0
//! What the computer reports about itself besides the meter: its SSH host
//! key fingerprints (shown next to the computer in the cloud, so a grantee
//! can check the first login) and whether anyone is active on it (holds off
//! the idle stop). Both read only world-readable system files.

use std::path::Path;

use base64::Engine as _;
use sha2::{Digest, Sha256};

/// The host keys the cloud accepts at most.
const MAX_HOST_KEYS: usize = 8;

/// `SHA256:<base64, no padding>` of an OpenSSH public key line, as
/// `ssh-keygen -l` prints it; `None` for anything that is not a key.
pub(crate) fn fingerprint(public_key: &str) -> Option<String> {
    let canonical = super::grants::canonical_key(public_key)?;
    let blob = canonical.split(' ').nth(1)?;
    let raw = base64::engine::general_purpose::STANDARD
        .decode(blob)
        .ok()?;
    let digest = Sha256::digest(&raw);
    Some(format!(
        "SHA256:{}",
        base64::engine::general_purpose::STANDARD_NO_PAD.encode(digest)
    ))
}

/// The fingerprints of `dir/ssh_host_*_key.pub`, sorted, at most eight.
pub(crate) fn host_key_fingerprints(dir: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut out: Vec<String> = entries
        .filter_map(Result::ok)
        .filter(|e| {
            let name = e.file_name();
            let name = name.to_string_lossy();
            name.starts_with("ssh_host_") && name.ends_with("_key.pub")
        })
        .filter_map(|e| {
            let meta = std::fs::symlink_metadata(e.path()).ok()?;
            if !meta.is_file() || meta.len() > 16 * 1024 {
                return None;
            }
            fingerprint(&std::fs::read_to_string(e.path()).ok()?)
        })
        .collect();
    out.sort();
    out.dedup();
    out.truncate(MAX_HOST_KEYS);
    out
}

/// The uids of `lc-…` users in a `/etc/passwd` text.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn grantee_uids(passwd: &str) -> std::collections::BTreeSet<u32> {
    passwd
        .lines()
        .filter_map(|line| {
            let mut fields = line.split(':');
            let name = fields.next()?;
            let uid = fields.nth(1)?.parse::<u32>().ok()?;
            (super::grants::valid_unix_user(name) && uid != 0).then_some(uid)
        })
        .collect()
}

/// Whether any process of a grantee runs: an SSH session, or a job or agent
/// a grantee left running. Unknown counts as idle.
#[cfg(target_os = "linux")]
pub(crate) fn grantee_active() -> bool {
    use std::os::unix::fs::MetadataExt;
    let Ok(passwd) = std::fs::read_to_string("/etc/passwd") else {
        return false;
    };
    let uids = grantee_uids(&passwd);
    if uids.is_empty() {
        return false;
    }
    let Ok(procs) = std::fs::read_dir("/proc") else {
        return false;
    };
    procs.filter_map(Result::ok).any(|e| {
        e.file_name()
            .to_string_lossy()
            .bytes()
            .all(|b| b.is_ascii_digit())
            && e.metadata().is_ok_and(|m| uids.contains(&m.uid()))
    })
}

#[cfg(not(target_os = "linux"))]
pub(crate) fn grantee_active() -> bool {
    false
}

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

    const ED: &str =
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl root@x";

    #[test]
    fn fingerprints_match_ssh_keygen() {
        // `ssh-keygen -lf` of the same key.
        assert_eq!(
            fingerprint(ED).as_deref(),
            Some("SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU")
        );
        assert_eq!(fingerprint("not a key"), None);
    }

    #[test]
    fn host_keys_are_read_from_their_files_only() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("ssh_host_ed25519_key.pub"), ED).unwrap();
        std::fs::write(dir.path().join("ssh_host_ed25519_key"), "PRIVATE").unwrap();
        std::fs::write(dir.path().join("ssh_host_rsa_key.pub"), "garbage").unwrap();
        std::fs::write(dir.path().join("other.pub"), ED).unwrap();
        assert_eq!(
            host_key_fingerprints(dir.path()),
            vec!["SHA256:+DiY3wvvV6TuJJhbpZisF/zLDA0zPMSvHdkr4UvCOqU".to_string()]
        );
        assert!(host_key_fingerprints(&dir.path().join("missing")).is_empty());
    }

    #[test]
    fn only_grantees_count_as_activity() {
        let passwd = "root:x:0:0:root:/root:/bin/bash\n\
            leanctx:x:998:998::/var/lib/leanctx:/usr/sbin/nologin\n\
            lc-0123456789ab:x:1001:1001:LeanCTX:/home/lc-0123456789ab:/bin/bash\n\
            lc-ROOT:x:1002:1002::/home/x:/bin/sh\n\
            lc-0000000000ff:x:0:0::/home/x:/bin/sh\n";
        assert_eq!(
            grantee_uids(passwd).into_iter().collect::<Vec<_>>(),
            vec![1001]
        );
    }
}