lean-ctx 3.12.12

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
//! `/etc/leanctx/computer.json`, written by the computer's cloud-init: one
//! JSON object `{"computer_id","role","cloud_url"}`. Parsed strictly: an
//! unknown field, a non-canonical id, an unknown role or a URL that is not an
//! HTTPS origin refuses the whole file.

use serde::Deserialize;

/// What the computer is for (`role` of the cloud's computer row).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
    /// A computer people log in to with their own Unix user.
    General,
    /// A locked-down appliance for one hosted service; grantees get the diagnostic
    /// login only.
    WeaveHost,
}

impl Role {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Role::General => "general",
            Role::WeaveHost => "weave_host",
        }
    }
}

/// The parsed `computer.json`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ComputerConfig {
    /// The computer's id: the meter routes and the cloud's computer row.
    pub computer_id: String,
    pub role: Role,
    /// The LeanCTX Cloud origin (`https://host[:port]`, no path).
    pub origin: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Raw {
    computer_id: String,
    role: String,
    cloud_url: String,
}

/// Parse the bytes of `computer.json`.
pub(crate) fn parse(bytes: &[u8]) -> Result<ComputerConfig, String> {
    let raw: Raw = serde_json::from_slice(bytes)
        .map_err(|e| format!("computer.json is not the expected object: {e}"))?;
    let id = uuid::Uuid::parse_str(&raw.computer_id)
        .map_err(|_| "computer.json: computer_id is not a UUID".to_string())?;
    // Only the canonical lowercase hyphenated form: the id goes into a URL path.
    if id.hyphenated().to_string() != raw.computer_id {
        return Err("computer.json: computer_id is not a lowercase hyphenated UUID".into());
    }
    let role = match raw.role.as_str() {
        "general" => Role::General,
        "weave_host" => Role::WeaveHost,
        _ => return Err("computer.json: role is neither general nor weave_host".into()),
    };
    let origin = lean_ctx_cloud::config::normalize_origin(&raw.cloud_url)
        .map_err(|e| format!("computer.json: cloud_url: {e}"))?;
    if !origin.starts_with("https://") {
        return Err("computer.json: cloud_url must be an https:// origin".into());
    }
    Ok(ComputerConfig {
        computer_id: raw.computer_id,
        role,
        origin,
    })
}

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

    const ID: &str = "0b7a3f4e-9c1d-4e2a-8f00-1234567890ab";

    fn doc(id: &str, role: &str, url: &str) -> Vec<u8> {
        format!(r#"{{"computer_id":"{id}","role":"{role}","cloud_url":"{url}"}}"#).into_bytes()
    }

    #[test]
    fn the_cloud_init_file_parses() {
        let mut bytes = doc(ID, "weave_host", "https://cloud.leanctx.com");
        bytes.push(b'\n');
        let config = parse(&bytes).expect("valid");
        assert_eq!(config.computer_id, ID);
        assert_eq!(config.role, Role::WeaveHost);
        assert_eq!(config.origin, "https://cloud.leanctx.com");
        let general = parse(&doc(ID, "general", "https://staging.example.ch:8443/")).unwrap();
        assert_eq!(general.role, Role::General);
        assert_eq!(general.origin, "https://staging.example.ch:8443");
    }

    #[test]
    fn anything_unexpected_refuses_the_file() {
        let refused = [
            doc(ID, "admin", "https://cloud.leanctx.com"),
            doc(&ID.to_uppercase(), "general", "https://cloud.leanctx.com"),
            doc(
                "{0b7a3f4e-9c1d-4e2a-8f00-1234567890ab}",
                "general",
                "https://x.ch",
            ),
            doc(
                "0b7a3f4e9c1d4e2a8f001234567890ab",
                "general",
                "https://x.ch",
            ),
            doc("../../etc", "general", "https://x.ch"),
            doc(ID, "general", "http://cloud.leanctx.com"),
            doc(ID, "general", "http://127.0.0.1:4100"),
            doc(ID, "general", "https://cloud.leanctx.com/api"),
            doc(ID, "general", "https://user@cloud.leanctx.com"),
            doc(ID, "general", "file:///etc/passwd"),
            format!(
                r#"{{"computer_id":"{ID}","role":"general","cloud_url":"https://x.ch","extra":1}}"#
            )
            .into_bytes(),
            format!(r#"{{"computer_id":"{ID}","role":"general"}}"#).into_bytes(),
            b"not json".to_vec(),
        ];
        for bytes in refused {
            assert!(
                parse(&bytes).is_err(),
                "accepted {}",
                String::from_utf8_lossy(&bytes)
            );
        }
    }
}