Skip to main content

lean_ctx_cloud/
root_cert.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Trust in a self-hosted Cloud: the vendor's root certificate (C0 1.7).
3//!
4//! The hosted Cloud is trusted through its root compiled into this build.
5//! A self-hosted Cloud is trusted when LeanCTX vouched for its root with a
6//! `RootCertV1`, signed by a vendor root compiled in at release
7//! (`LEANCTX_CLOUD_ROOT_KEYS`, a JSON array of hex Ed25519 keys; no default):
8//! the certificate names the origin, the organizations whose leases the root
9//! may sign, and its validity (no grace after `not_after`).
10//!
11//! The engine fetches the certificate on connect and at lease renewal,
12//! keeps the last verified one in `<config>/cloud/root-cert.json` (0600) and
13//! replaces it only with one that verifies. An invalid or expired stored
14//! certificate pauses Cloud, like a lapsed lease; local tools never notice.
15//! `[cloud] root_key` stays a development escape hatch ("unvouched Cloud
16//! root"); a certificate, when present, wins over it.
17
18use crate::CloudConfigExt as _;
19use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
20use lean_ctx_time::UtcDateTime;
21use serde_json::Value;
22
23use super::config::CloudConfig;
24use super::transport::CloudClient;
25use super::{CloudError, CloudStore};
26use lean_ctx_protocol::cloud::lease::CloudLeaseV1;
27use lean_ctx_protocol::cloud::root_cert::RootCertV1;
28
29pub(crate) const CERT_FILE: &str = "root-cert.json";
30const MAX_VENDOR_ROOTS: usize = 8;
31
32/// The vendor roots compiled into this build (none: no self-host trust).
33fn compiled_vendor_roots() -> Vec<[u8; 32]> {
34    parse_vendor_roots(option_env!("LEANCTX_CLOUD_ROOT_KEYS"))
35}
36
37/// The bounded JSON array of hex keys; anything malformed yields none.
38fn parse_vendor_roots(input: Option<&str>) -> Vec<[u8; 32]> {
39    let Some(input) = input.filter(|text| text.len() <= 1024) else {
40        return Vec::new();
41    };
42    let Ok(keys) = serde_json::from_str::<Vec<String>>(input) else {
43        return Vec::new();
44    };
45    if keys.len() > MAX_VENDOR_ROOTS {
46        return Vec::new();
47    }
48    let parsed: Option<Vec<[u8; 32]>> = keys
49        .iter()
50        .map(|key| {
51            let mut bytes = [0u8; 32];
52            hex::decode_to_slice(key, &mut bytes).ok()?;
53            VerifyingKey::from_bytes(&bytes)
54                .ok()
55                .filter(|parsed| !parsed.is_weak())
56                .map(|_| bytes)
57        })
58        .collect();
59    parsed.unwrap_or_default()
60}
61
62/// Verify `raw` for `origin` at `now` against `vendors`; returns the
63/// certified self-host root and the certificate.
64pub(crate) fn verify_with(
65    raw: &Value,
66    vendors: &[[u8; 32]],
67    origin: &str,
68    now: UtcDateTime,
69) -> Result<([u8; 32], RootCertV1), String> {
70    let cert: RootCertV1 =
71        serde_json::from_value(raw.clone()).map_err(|e| format!("not a root certificate: {e}"))?;
72    cert.validate().map_err(|e| e.to_string())?;
73    let signature: [u8; 64] = base64_array(&cert.signature).ok_or("its signature is malformed")?;
74    let input = RootCertV1::signing_input_raw(raw).map_err(|e| e.to_string())?;
75    let vouched = vendors.iter().any(|vendor| {
76        VerifyingKey::from_bytes(vendor).is_ok_and(|key| {
77            key.verify(&input, &Signature::from_bytes(&signature))
78                .is_ok()
79        })
80    });
81    if !vouched {
82        return Err("it is not signed by a LeanCTX vendor root of this build".into());
83    }
84    if cert.cloud_origin != origin {
85        return Err(format!("it is for {}, not {origin}", cert.cloud_origin));
86    }
87    if !cert
88        .valid_at(now.fixed_offset())
89        .map_err(|e| e.to_string())?
90    {
91        return Err(format!(
92            "it is valid {} to {} only",
93            cert.not_before.as_str(),
94            cert.not_after.as_str()
95        ));
96    }
97    let root: [u8; 32] = base64_array(&cert.root_ed25519_pub).ok_or("its root key is malformed")?;
98    Ok((root, cert))
99}
100
101fn base64_array<const N: usize>(text: &str) -> Option<[u8; N]> {
102    use base64::Engine as _;
103    base64::engine::general_purpose::STANDARD
104        .decode(text)
105        .ok()?
106        .try_into()
107        .ok()
108}
109
110/// The stored certificate, as received.
111fn stored(store: &CloudStore) -> Option<Value> {
112    store.read_config(CERT_FILE).ok().flatten()
113}
114
115/// The stored certificate for the runtime lease (the runtime verifies it).
116pub fn stored_certificate(store: &CloudStore) -> Option<Value> {
117    stored(store)
118}
119
120/// The certified root of `origin` from the stored certificate: `None` when
121/// none is stored; an error when the stored one does not hold (any more).
122fn stored_root(
123    store: &CloudStore,
124    origin: &str,
125    now: UtcDateTime,
126) -> Result<Option<([u8; 32], RootCertV1)>, CloudError> {
127    let Some(raw) = stored(store) else {
128        return Ok(None);
129    };
130    verify_with(&raw, &compiled_vendor_roots(), origin, now)
131        .map(Some)
132        .map_err(|reason| {
133            CloudError::Config(format!(
134                "the Cloud root certificate does not hold: {reason}; the Cloud is paused until a valid one is installed"
135            ))
136        })
137}
138
139/// The root that signs `origin`'s key set: a stored certificate's, else the
140/// configured or compiled one.
141pub fn trust_root(
142    store: &CloudStore,
143    config: &CloudConfig,
144    origin: &str,
145) -> Result<[u8; 32], CloudError> {
146    match stored_root(store, origin, UtcDateTime::now())? {
147        Some((root, _)) => Ok(root),
148        None => config.root_key(origin),
149    }
150}
151
152/// The organization check of a certified root: the lease's org must be one
153/// the certificate names. Without a certificate there is nothing to check.
154pub fn check_lease_org(
155    store: &CloudStore,
156    origin: &str,
157    lease: &CloudLeaseV1,
158) -> Result<(), CloudError> {
159    match stored_root(store, origin, UtcDateTime::now())? {
160        Some((_, cert)) if !cert.covers_org(&lease.org_id) => Err(CloudError::Config(format!(
161            "the Cloud root certificate does not cover workspace {}",
162            lease.org_id
163        ))),
164        _ => Ok(()),
165    }
166}
167
168/// `GET /v1/root-cert`: `None` on a Cloud without one (the hosted one).
169fn fetch(client: &CloudClient) -> Result<Option<Value>, CloudError> {
170    match client.get("/root-cert") {
171        Ok(raw) => Ok(Some(raw)),
172        Err(CloudError::NotFound) => Ok(None),
173        Err(error) => Err(error),
174    }
175}
176
177/// How this engine trusts an origin it is about to connect to.
178pub struct ConnectTrust {
179    pub root: [u8; 32],
180    /// The verified certificate to keep once the enrollment succeeded.
181    pub certificate: Option<Value>,
182    /// The root came from `[cloud] root_key`, vouched for by nobody.
183    pub unvouched: bool,
184}
185
186/// The root for a new enrollment: a certificate the origin serves wins; an
187/// explicit `[cloud] root_key` is the unvouched fallback; the hosted Cloud
188/// uses its compiled root.
189pub fn for_connect(
190    client: &CloudClient,
191    config: &CloudConfig,
192    origin: &str,
193) -> Result<ConnectTrust, CloudError> {
194    if let Some(raw) = fetch(client)? {
195        let (root, _) = verify_with(&raw, &compiled_vendor_roots(), origin, UtcDateTime::now())
196            .map_err(|reason| {
197                CloudError::Config(format!("the Cloud root certificate of {origin}: {reason}"))
198            })?;
199        return Ok(ConnectTrust {
200            root,
201            certificate: Some(raw),
202            unvouched: false,
203        });
204    }
205    let root = config.root_key(origin)?;
206    Ok(ConnectTrust {
207        root,
208        certificate: None,
209        unvouched: config.root_key.is_some(),
210    })
211}
212
213/// Keep a verified certificate (after the enrollment or a refresh).
214pub fn store_certificate(store: &CloudStore, raw: &Value) -> Result<(), CloudError> {
215    store.write_config(CERT_FILE, raw)
216}
217
218/// At lease renewal: fetch the certificate again and keep it when it
219/// verifies (a renewed one replaces the old); a failing fetch keeps the
220/// stored one, whose own validity still applies.
221pub fn refresh(store: &CloudStore, client: &CloudClient, origin: &str) {
222    if let Ok(Some(raw)) = fetch(client)
223        && verify_with(&raw, &compiled_vendor_roots(), origin, UtcDateTime::now()).is_ok()
224    {
225        let _ = store_certificate(store, &raw);
226    }
227}
228
229/// Whether the configured root is the unvouched escape hatch (for `cloud
230/// status`): a `root_key` is set and no certificate is stored.
231pub fn unvouched(store: &CloudStore, config: &CloudConfig) -> bool {
232    config.root_key.is_some() && stored(store).is_none()
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use base64::Engine as _;
239    use ed25519_dalek::{Signer as _, SigningKey};
240    use lean_ctx_protocol::cloud::root_cert::ROOT_CERT_SCHEMA;
241
242    const VENDOR: [u8; 32] = [0x56; 32];
243    const ROOT: [u8; 32] = [0x52; 32];
244
245    fn cert(origin: &str, orgs: &[&str]) -> Value {
246        let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
247        let mut raw = serde_json::json!({
248            "schema": ROOT_CERT_SCHEMA, "serial": "rc-1",
249            "issuer_key_id": format!("key:ed25519-{}", "a".repeat(32)),
250            "subject": "Example Office", "cloud_origin": origin,
251            "root_ed25519_pub": b64(SigningKey::from_bytes(&ROOT).verifying_key().as_bytes()),
252            "org_ids": orgs, "plans": ["enterprise"], "max_seats": 50,
253            "issued_at": "2026-10-21T00:00:00Z", "not_before": "2026-10-21T00:00:00Z",
254            "not_after": "2027-10-21T00:00:00Z",
255        });
256        let input = RootCertV1::signing_input_raw(&raw).unwrap();
257        raw["signature"] = Value::from(b64(&SigningKey::from_bytes(&VENDOR)
258            .sign(&input)
259            .to_bytes()));
260        raw
261    }
262
263    fn vendor() -> [u8; 32] {
264        SigningKey::from_bytes(&VENDOR).verifying_key().to_bytes()
265    }
266
267    fn at(t: &str) -> UtcDateTime {
268        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
269            .unwrap()
270            .to_utc()
271    }
272
273    #[test]
274    fn a_vouched_certificate_names_the_root_of_its_origin_only() {
275        let raw = cert("https://cloud.example.test", &["org_acme"]);
276        let now = at("2026-11-01T00:00:00Z");
277        let (root, parsed) =
278            verify_with(&raw, &[vendor()], "https://cloud.example.test", now).unwrap();
279        assert_eq!(
280            root,
281            SigningKey::from_bytes(&ROOT).verifying_key().to_bytes()
282        );
283        assert!(parsed.covers_org("org_acme") && !parsed.covers_org("org_other"));
284        assert!(
285            verify_with(&raw, &[vendor()], "https://other.example.test", now)
286                .is_err_and(|reason| reason.contains("not https://other"))
287        );
288        assert!(
289            verify_with(&raw, &[], "https://cloud.example.test", now)
290                .is_err_and(|reason| reason.contains("vendor root"))
291        );
292        assert!(
293            verify_with(
294                &raw,
295                &[vendor()],
296                "https://cloud.example.test",
297                at("2027-10-22T00:00:00Z")
298            )
299            .is_err_and(|reason| reason.contains("valid"))
300        );
301        let mut forged = raw;
302        forged["max_seats"] = Value::from(5000);
303        assert!(verify_with(&forged, &[vendor()], "https://cloud.example.test", now).is_err());
304    }
305
306    #[test]
307    fn a_stored_certificate_that_does_not_hold_pauses_cloud() {
308        let dir = tempfile::tempdir().unwrap();
309        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
310        // No certificate: the configured root applies.
311        let config = CloudConfig {
312            root_key: Some(base64::engine::general_purpose::STANDARD.encode([7u8; 32])),
313            ..CloudConfig::default()
314        };
315        assert_eq!(
316            trust_root(&store, &config, "https://cloud.example.test").unwrap(),
317            [7u8; 32]
318        );
319        assert!(unvouched(&store, &config));
320        // A stored certificate this build cannot verify (no compiled vendor
321        // root in a test build) pauses Cloud instead of falling back.
322        store_certificate(&store, &cert("https://cloud.example.test", &["org_acme"])).unwrap();
323        assert!(
324            trust_root(&store, &config, "https://cloud.example.test")
325                .is_err_and(|e| e.to_string().contains("paused"))
326        );
327        assert!(!unvouched(&store, &config));
328    }
329
330    #[test]
331    fn vendor_roots_are_a_bounded_list_of_strong_keys() {
332        assert!(parse_vendor_roots(None).is_empty());
333        assert!(parse_vendor_roots(Some("not json")).is_empty());
334        let good = hex::encode(vendor());
335        assert_eq!(
336            parse_vendor_roots(Some(&format!("[\"{good}\"]"))),
337            vec![vendor()]
338        );
339        assert!(parse_vendor_roots(Some(&format!("[\"{}\"]", hex::encode([0u8; 32])))).is_empty());
340    }
341}