1use 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
32fn compiled_vendor_roots() -> Vec<[u8; 32]> {
34 parse_vendor_roots(option_env!("LEANCTX_CLOUD_ROOT_KEYS"))
35}
36
37fn 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
62pub(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
110fn stored(store: &CloudStore) -> Option<Value> {
112 store.read_config(CERT_FILE).ok().flatten()
113}
114
115pub fn stored_certificate(store: &CloudStore) -> Option<Value> {
117 stored(store)
118}
119
120fn 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
139pub 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
152pub 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
168fn 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
177pub struct ConnectTrust {
179 pub root: [u8; 32],
180 pub certificate: Option<Value>,
182 pub unvouched: bool,
184}
185
186pub 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
215pub fn store_certificate(store: &CloudStore, raw: &Value) -> Result<(), CloudError> {
217 store.write_config(CERT_FILE, raw)
218}
219
220pub 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
231pub 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 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 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}