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 LeanCTX Cloud root certificate does not hold: {reason}; LeanCTX 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 LeanCTX 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!(
198                    "the LeanCTX Cloud root certificate of {origin}: {reason}"
199                ))
200            })?;
201        return Ok(ConnectTrust {
202            root,
203            certificate: Some(raw),
204            unvouched: false,
205        });
206    }
207    let root = config.root_key(origin)?;
208    Ok(ConnectTrust {
209        root,
210        certificate: None,
211        unvouched: config.root_key.is_some(),
212    })
213}
214
215/// Keep a verified certificate (after the enrollment or a refresh).
216pub fn store_certificate(store: &CloudStore, raw: &Value) -> Result<(), CloudError> {
217    store.write_config(CERT_FILE, raw)
218}
219
220/// At lease renewal: fetch the certificate again and keep it when it
221/// verifies (a renewed one replaces the old); a failing fetch keeps the
222/// stored one, whose own validity still applies.
223pub fn refresh(store: &CloudStore, client: &CloudClient, origin: &str) {
224    if let Ok(Some(raw)) = fetch(client)
225        && verify_with(&raw, &compiled_vendor_roots(), origin, UtcDateTime::now()).is_ok()
226    {
227        let _ = store_certificate(store, &raw);
228    }
229}
230
231/// Whether the configured root is the unvouched escape hatch (for `cloud
232/// status`): a `root_key` is set and no certificate is stored.
233pub fn unvouched(store: &CloudStore, config: &CloudConfig) -> bool {
234    config.root_key.is_some() && stored(store).is_none()
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use base64::Engine as _;
241    use ed25519_dalek::{Signer as _, SigningKey};
242    use lean_ctx_protocol::cloud::root_cert::ROOT_CERT_SCHEMA;
243
244    const VENDOR: [u8; 32] = [0x56; 32];
245    const ROOT: [u8; 32] = [0x52; 32];
246
247    fn cert(origin: &str, orgs: &[&str]) -> Value {
248        let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
249        let mut raw = serde_json::json!({
250            "schema": ROOT_CERT_SCHEMA, "serial": "rc-1",
251            "issuer_key_id": format!("key:ed25519-{}", "a".repeat(32)),
252            "subject": "Example Office", "cloud_origin": origin,
253            "root_ed25519_pub": b64(SigningKey::from_bytes(&ROOT).verifying_key().as_bytes()),
254            "org_ids": orgs, "plans": ["enterprise"], "max_seats": 50,
255            "issued_at": "2026-10-21T00:00:00Z", "not_before": "2026-10-21T00:00:00Z",
256            "not_after": "2027-10-21T00:00:00Z",
257        });
258        let input = RootCertV1::signing_input_raw(&raw).unwrap();
259        raw["signature"] = Value::from(b64(&SigningKey::from_bytes(&VENDOR)
260            .sign(&input)
261            .to_bytes()));
262        raw
263    }
264
265    fn vendor() -> [u8; 32] {
266        SigningKey::from_bytes(&VENDOR).verifying_key().to_bytes()
267    }
268
269    fn at(t: &str) -> UtcDateTime {
270        lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
271            .unwrap()
272            .to_utc()
273    }
274
275    #[test]
276    fn a_vouched_certificate_names_the_root_of_its_origin_only() {
277        let raw = cert("https://cloud.example.test", &["org_acme"]);
278        let now = at("2026-11-01T00:00:00Z");
279        let (root, parsed) =
280            verify_with(&raw, &[vendor()], "https://cloud.example.test", now).unwrap();
281        assert_eq!(
282            root,
283            SigningKey::from_bytes(&ROOT).verifying_key().to_bytes()
284        );
285        assert!(parsed.covers_org("org_acme") && !parsed.covers_org("org_other"));
286        assert!(
287            verify_with(&raw, &[vendor()], "https://other.example.test", now)
288                .is_err_and(|reason| reason.contains("not https://other"))
289        );
290        assert!(
291            verify_with(&raw, &[], "https://cloud.example.test", now)
292                .is_err_and(|reason| reason.contains("vendor root"))
293        );
294        assert!(
295            verify_with(
296                &raw,
297                &[vendor()],
298                "https://cloud.example.test",
299                at("2027-10-22T00:00:00Z")
300            )
301            .is_err_and(|reason| reason.contains("valid"))
302        );
303        let mut forged = raw;
304        forged["max_seats"] = Value::from(5000);
305        assert!(verify_with(&forged, &[vendor()], "https://cloud.example.test", now).is_err());
306    }
307
308    #[test]
309    fn a_stored_certificate_that_does_not_hold_pauses_cloud() {
310        let dir = tempfile::tempdir().unwrap();
311        let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
312        // No certificate: the configured root applies.
313        let config = CloudConfig {
314            root_key: Some(base64::engine::general_purpose::STANDARD.encode([7u8; 32])),
315            ..CloudConfig::default()
316        };
317        assert_eq!(
318            trust_root(&store, &config, "https://cloud.example.test").unwrap(),
319            [7u8; 32]
320        );
321        assert!(unvouched(&store, &config));
322        // A stored certificate this build cannot verify (no compiled vendor
323        // root in a test build) pauses Cloud instead of falling back.
324        store_certificate(&store, &cert("https://cloud.example.test", &["org_acme"])).unwrap();
325        assert!(
326            trust_root(&store, &config, "https://cloud.example.test")
327                .is_err_and(|e| e.to_string().contains("paused"))
328        );
329        assert!(!unvouched(&store, &config));
330    }
331
332    #[test]
333    fn vendor_roots_are_a_bounded_list_of_strong_keys() {
334        assert!(parse_vendor_roots(None).is_empty());
335        assert!(parse_vendor_roots(Some("not json")).is_empty());
336        let good = hex::encode(vendor());
337        assert_eq!(
338            parse_vendor_roots(Some(&format!("[\"{good}\"]"))),
339            vec![vendor()]
340        );
341        assert!(parse_vendor_roots(Some(&format!("[\"{}\"]", hex::encode([0u8; 32])))).is_empty());
342    }
343}