lean-ctx-cloud 3.12.8

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! The Cloud lease as the Intelligence runtime's licence.
//!
//! The runtime lease is `{"schema": "leanctx.cloud.runtime-lease/v1",
//! "lease": <lease envelope>, "keys": <key set>}`, both exactly as Cloud sent
//! them. The runtime verifies root → key set → lease → right `runtime` and
//! the validity window itself, against roots compiled into it; this engine
//! only offers the bytes while its own lease is valid or in grace and grants
//! `runtime`.

use std::sync::OnceLock;

use lean_ctx_time::UtcDateTime;
use serde_json::{Value, json};

use super::auth::Session;
use super::config::CloudConfig;
use super::state::{CloudStore, KEYS_FILE, LEASE_FILE, LeaseRecord};
use lean_ctx::core::intelligence_runtime::lease::{LeaseSource, RuntimeLeaseV1, set_lease_source};
use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};

pub const RUNTIME_LEASE_SCHEMA: &str = "leanctx.cloud.runtime-lease/v1";
/// v1 plus `root_cert` (a self-hosted Cloud); runtimes that declare
/// `runtime_lease: "v2"` read it, v1 runtimes refuse it (hosted-only).
pub const RUNTIME_LEASE_SCHEMA_V2: &str = "leanctx.cloud.runtime-lease/v2";

/// The runtime lease of the instance in `store`, if it may run the runtime now.
pub fn runtime_lease_bytes(store: &CloudStore, config: &CloudConfig) -> Option<Vec<u8>> {
    if config.enabled == Some(false) {
        return None;
    }
    let instance = store.instance().ok()??;
    let session = Session::load(
        store.clone(),
        super::root_cert::trust_root(store, config, &instance.url).ok()?,
    )
    .ok()?;
    if !matches!(
        session.lease.state_at(UtcDateTime::now()),
        LeaseState::Valid | LeaseState::Grace
    ) || !session.lease.lease.grants(CloudRight::Runtime)
    {
        return None;
    }
    let record: LeaseRecord = store.read_config(LEASE_FILE).ok()??;
    let keys: Value = store.read_config(KEYS_FILE).ok()??;
    // A self-hosted Cloud: v2 carries the vendor certificate of its root.
    let document = match super::root_cert::stored_certificate(store) {
        Some(certificate) => json!({
            "schema": RUNTIME_LEASE_SCHEMA_V2,
            "lease": record.envelope,
            "keys": keys,
            "root_cert": certificate,
        }),
        None => json!({
            "schema": RUNTIME_LEASE_SCHEMA,
            "lease": record.envelope,
            "keys": keys,
        }),
    };
    serde_json::to_vec(&document).ok()
}

/// Signed in: an enrollment this machine may use (not revoked, the managed
/// org) whose lease is valid or in grace. The managed `cloud.require` gate
/// asks this ([`lean_ctx::core::config::managed::register_signed_in_probe`]).
pub(crate) fn signed_in() -> bool {
    let Ok(store) = CloudStore::open() else {
        return false;
    };
    let config = lean_ctx::core::config::Config::load().cloud.clone();
    if config.enabled == Some(false) {
        return false;
    }
    let Ok(Some(instance)) = store.instance() else {
        return false;
    };
    let Ok(root) = super::root_cert::trust_root(&store, &config, &instance.url) else {
        return false;
    };
    Session::load(store, root).is_ok_and(|session| {
        matches!(
            session.lease.state_at(UtcDateTime::now()),
            LeaseState::Valid | LeaseState::Grace
        )
    })
}

struct CloudLeaseSource;

impl LeaseSource for CloudLeaseSource {
    fn current(&self) -> Option<RuntimeLeaseV1> {
        let store = CloudStore::open().ok()?;
        let config = lean_ctx::core::config::Config::load().cloud.clone();
        runtime_lease_bytes(&store, &config).map(RuntimeLeaseV1::from_bytes)
    }
}

/// Register the Cloud lease as this process's runtime lease source (once).
pub fn ensure_registered() {
    static REGISTERED: OnceLock<()> = OnceLock::new();
    REGISTERED.get_or_init(|| set_lease_source(Box::new(CloudLeaseSource)));
}