Skip to main content

lean_ctx_cloud/
runtime_lease.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The Cloud lease as the Intelligence runtime's licence.
3//!
4//! The runtime lease is `{"schema": "leanctx.cloud.runtime-lease/v1",
5//! "lease": <lease envelope>, "keys": <key set>}`, both exactly as Cloud sent
6//! them. The runtime verifies root → key set → lease → right `runtime` and
7//! the validity window itself, against roots compiled into it; this engine
8//! only offers the bytes while its own lease is valid or in grace and grants
9//! `runtime`.
10
11use std::sync::OnceLock;
12
13use lean_ctx_time::UtcDateTime;
14use serde_json::{Value, json};
15
16use super::auth::Session;
17use super::config::CloudConfig;
18use super::state::{CloudStore, KEYS_FILE, LEASE_FILE, LeaseRecord};
19use lean_ctx::core::intelligence_runtime::lease::{LeaseSource, RuntimeLeaseV1, set_lease_source};
20use lean_ctx_protocol::cloud::lease::{CloudRight, LeaseState};
21
22pub const RUNTIME_LEASE_SCHEMA: &str = "leanctx.cloud.runtime-lease/v1";
23/// v1 plus `root_cert` (a self-hosted Cloud); runtimes that declare
24/// `runtime_lease: "v2"` read it, v1 runtimes refuse it (hosted-only).
25pub const RUNTIME_LEASE_SCHEMA_V2: &str = "leanctx.cloud.runtime-lease/v2";
26
27/// The runtime lease of the instance in `store`, if it may run the runtime now.
28pub fn runtime_lease_bytes(store: &CloudStore, config: &CloudConfig) -> Option<Vec<u8>> {
29    if config.enabled == Some(false) {
30        return None;
31    }
32    let instance = store.instance().ok()??;
33    let session = Session::load(
34        store.clone(),
35        super::root_cert::trust_root(store, config, &instance.url).ok()?,
36    )
37    .ok()?;
38    if !matches!(
39        session.lease.state_at(UtcDateTime::now()),
40        LeaseState::Valid | LeaseState::Grace
41    ) || !session.lease.lease.grants(CloudRight::Runtime)
42    {
43        return None;
44    }
45    let record: LeaseRecord = store.read_config(LEASE_FILE).ok()??;
46    let keys: Value = store.read_config(KEYS_FILE).ok()??;
47    // A self-hosted Cloud: v2 carries the vendor certificate of its root.
48    let document = match super::root_cert::stored_certificate(store) {
49        Some(certificate) => json!({
50            "schema": RUNTIME_LEASE_SCHEMA_V2,
51            "lease": record.envelope,
52            "keys": keys,
53            "root_cert": certificate,
54        }),
55        None => json!({
56            "schema": RUNTIME_LEASE_SCHEMA,
57            "lease": record.envelope,
58            "keys": keys,
59        }),
60    };
61    serde_json::to_vec(&document).ok()
62}
63
64/// Signed in: an enrollment this machine may use (not revoked, the managed
65/// org) whose lease is valid or in grace. The managed `cloud.require` gate
66/// asks this ([`lean_ctx::core::config::managed::register_signed_in_probe`]).
67pub(crate) fn signed_in() -> bool {
68    let Ok(store) = CloudStore::open() else {
69        return false;
70    };
71    let config = lean_ctx::core::config::Config::load().cloud.clone();
72    if config.enabled == Some(false) {
73        return false;
74    }
75    let Ok(Some(instance)) = store.instance() else {
76        return false;
77    };
78    let Ok(root) = super::root_cert::trust_root(&store, &config, &instance.url) else {
79        return false;
80    };
81    Session::load(store, root).is_ok_and(|session| {
82        matches!(
83            session.lease.state_at(UtcDateTime::now()),
84            LeaseState::Valid | LeaseState::Grace
85        )
86    })
87}
88
89struct CloudLeaseSource;
90
91impl LeaseSource for CloudLeaseSource {
92    fn current(&self) -> Option<RuntimeLeaseV1> {
93        let store = CloudStore::open().ok()?;
94        let config = lean_ctx::core::config::Config::load().cloud.clone();
95        runtime_lease_bytes(&store, &config).map(RuntimeLeaseV1::from_bytes)
96    }
97}
98
99/// Register the Cloud lease as this process's runtime lease source (once).
100pub fn ensure_registered() {
101    static REGISTERED: OnceLock<()> = OnceLock::new();
102    REGISTERED.get_or_init(|| set_lease_source(Box::new(CloudLeaseSource)));
103}