use crate::CloudConfigExt as _;
use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
use lean_ctx_time::UtcDateTime;
use serde_json::Value;
use super::config::CloudConfig;
use super::transport::CloudClient;
use super::{CloudError, CloudStore};
use lean_ctx_protocol::cloud::lease::CloudLeaseV1;
use lean_ctx_protocol::cloud::root_cert::RootCertV1;
const CERT_FILE: &str = "root-cert.json";
const MAX_VENDOR_ROOTS: usize = 8;
fn compiled_vendor_roots() -> Vec<[u8; 32]> {
parse_vendor_roots(option_env!("LEANCTX_CLOUD_ROOT_KEYS"))
}
fn parse_vendor_roots(input: Option<&str>) -> Vec<[u8; 32]> {
let Some(input) = input.filter(|text| text.len() <= 1024) else {
return Vec::new();
};
let Ok(keys) = serde_json::from_str::<Vec<String>>(input) else {
return Vec::new();
};
if keys.len() > MAX_VENDOR_ROOTS {
return Vec::new();
}
let parsed: Option<Vec<[u8; 32]>> = keys
.iter()
.map(|key| {
let mut bytes = [0u8; 32];
hex::decode_to_slice(key, &mut bytes).ok()?;
VerifyingKey::from_bytes(&bytes)
.ok()
.filter(|parsed| !parsed.is_weak())
.map(|_| bytes)
})
.collect();
parsed.unwrap_or_default()
}
pub(crate) fn verify_with(
raw: &Value,
vendors: &[[u8; 32]],
origin: &str,
now: UtcDateTime,
) -> Result<([u8; 32], RootCertV1), String> {
let cert: RootCertV1 =
serde_json::from_value(raw.clone()).map_err(|e| format!("not a root certificate: {e}"))?;
cert.validate().map_err(|e| e.to_string())?;
let signature: [u8; 64] = base64_array(&cert.signature).ok_or("its signature is malformed")?;
let input = RootCertV1::signing_input_raw(raw).map_err(|e| e.to_string())?;
let vouched = vendors.iter().any(|vendor| {
VerifyingKey::from_bytes(vendor).is_ok_and(|key| {
key.verify(&input, &Signature::from_bytes(&signature))
.is_ok()
})
});
if !vouched {
return Err("it is not signed by a LeanCTX vendor root of this build".into());
}
if cert.cloud_origin != origin {
return Err(format!("it is for {}, not {origin}", cert.cloud_origin));
}
if !cert
.valid_at(now.fixed_offset())
.map_err(|e| e.to_string())?
{
return Err(format!(
"it is valid {} to {} only",
cert.not_before.as_str(),
cert.not_after.as_str()
));
}
let root: [u8; 32] = base64_array(&cert.root_ed25519_pub).ok_or("its root key is malformed")?;
Ok((root, cert))
}
fn base64_array<const N: usize>(text: &str) -> Option<[u8; N]> {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD
.decode(text)
.ok()?
.try_into()
.ok()
}
fn stored(store: &CloudStore) -> Option<Value> {
store.read_config(CERT_FILE).ok().flatten()
}
pub fn stored_certificate(store: &CloudStore) -> Option<Value> {
stored(store)
}
fn stored_root(
store: &CloudStore,
origin: &str,
now: UtcDateTime,
) -> Result<Option<([u8; 32], RootCertV1)>, CloudError> {
let Some(raw) = stored(store) else {
return Ok(None);
};
verify_with(&raw, &compiled_vendor_roots(), origin, now)
.map(Some)
.map_err(|reason| {
CloudError::Config(format!(
"the LeanCTX Cloud root certificate does not hold: {reason}; LeanCTX Cloud is paused until a valid one is installed"
))
})
}
pub fn trust_root(
store: &CloudStore,
config: &CloudConfig,
origin: &str,
) -> Result<[u8; 32], CloudError> {
match stored_root(store, origin, UtcDateTime::now())? {
Some((root, _)) => Ok(root),
None => config.root_key(origin),
}
}
pub fn check_lease_org(
store: &CloudStore,
origin: &str,
lease: &CloudLeaseV1,
) -> Result<(), CloudError> {
match stored_root(store, origin, UtcDateTime::now())? {
Some((_, cert)) if !cert.covers_org(&lease.org_id) => Err(CloudError::Config(format!(
"the LeanCTX Cloud root certificate does not cover workspace {}",
lease.org_id
))),
_ => Ok(()),
}
}
fn fetch(client: &CloudClient) -> Result<Option<Value>, CloudError> {
match client.get("/root-cert") {
Ok(raw) => Ok(Some(raw)),
Err(CloudError::NotFound) => Ok(None),
Err(error) => Err(error),
}
}
pub struct ConnectTrust {
pub root: [u8; 32],
pub certificate: Option<Value>,
pub unvouched: bool,
}
pub fn for_connect(
client: &CloudClient,
config: &CloudConfig,
origin: &str,
) -> Result<ConnectTrust, CloudError> {
if let Some(raw) = fetch(client)? {
let (root, _) = verify_with(&raw, &compiled_vendor_roots(), origin, UtcDateTime::now())
.map_err(|reason| {
CloudError::Config(format!(
"the LeanCTX Cloud root certificate of {origin}: {reason}"
))
})?;
return Ok(ConnectTrust {
root,
certificate: Some(raw),
unvouched: false,
});
}
let root = config.root_key(origin)?;
Ok(ConnectTrust {
root,
certificate: None,
unvouched: config.root_key.is_some(),
})
}
pub fn store_certificate(store: &CloudStore, raw: &Value) -> Result<(), CloudError> {
store.write_config(CERT_FILE, raw)
}
pub fn refresh(store: &CloudStore, client: &CloudClient, origin: &str) {
if let Ok(Some(raw)) = fetch(client)
&& verify_with(&raw, &compiled_vendor_roots(), origin, UtcDateTime::now()).is_ok()
{
let _ = store_certificate(store, &raw);
}
}
pub fn unvouched(store: &CloudStore, config: &CloudConfig) -> bool {
config.root_key.is_some() && stored(store).is_none()
}
#[cfg(test)]
mod tests {
use super::*;
use base64::Engine as _;
use ed25519_dalek::{Signer as _, SigningKey};
use lean_ctx_protocol::cloud::root_cert::ROOT_CERT_SCHEMA;
const VENDOR: [u8; 32] = [0x56; 32];
const ROOT: [u8; 32] = [0x52; 32];
fn cert(origin: &str, orgs: &[&str]) -> Value {
let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
let mut raw = serde_json::json!({
"schema": ROOT_CERT_SCHEMA, "serial": "rc-1",
"issuer_key_id": format!("key:ed25519-{}", "a".repeat(32)),
"subject": "Example Office", "cloud_origin": origin,
"root_ed25519_pub": b64(SigningKey::from_bytes(&ROOT).verifying_key().as_bytes()),
"org_ids": orgs, "plans": ["enterprise"], "max_seats": 50,
"issued_at": "2026-10-21T00:00:00Z", "not_before": "2026-10-21T00:00:00Z",
"not_after": "2027-10-21T00:00:00Z",
});
let input = RootCertV1::signing_input_raw(&raw).unwrap();
raw["signature"] = Value::from(b64(&SigningKey::from_bytes(&VENDOR)
.sign(&input)
.to_bytes()));
raw
}
fn vendor() -> [u8; 32] {
SigningKey::from_bytes(&VENDOR).verifying_key().to_bytes()
}
fn at(t: &str) -> UtcDateTime {
lean_ctx_time::OffsetDateTime::parse_from_rfc3339(t)
.unwrap()
.to_utc()
}
#[test]
fn a_vouched_certificate_names_the_root_of_its_origin_only() {
let raw = cert("https://cloud.example.test", &["org_acme"]);
let now = at("2026-11-01T00:00:00Z");
let (root, parsed) =
verify_with(&raw, &[vendor()], "https://cloud.example.test", now).unwrap();
assert_eq!(
root,
SigningKey::from_bytes(&ROOT).verifying_key().to_bytes()
);
assert!(parsed.covers_org("org_acme") && !parsed.covers_org("org_other"));
assert!(
verify_with(&raw, &[vendor()], "https://other.example.test", now)
.is_err_and(|reason| reason.contains("not https://other"))
);
assert!(
verify_with(&raw, &[], "https://cloud.example.test", now)
.is_err_and(|reason| reason.contains("vendor root"))
);
assert!(
verify_with(
&raw,
&[vendor()],
"https://cloud.example.test",
at("2027-10-22T00:00:00Z")
)
.is_err_and(|reason| reason.contains("valid"))
);
let mut forged = raw;
forged["max_seats"] = Value::from(5000);
assert!(verify_with(&forged, &[vendor()], "https://cloud.example.test", now).is_err());
}
#[test]
fn a_stored_certificate_that_does_not_hold_pauses_cloud() {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let config = CloudConfig {
root_key: Some(base64::engine::general_purpose::STANDARD.encode([7u8; 32])),
..CloudConfig::default()
};
assert_eq!(
trust_root(&store, &config, "https://cloud.example.test").unwrap(),
[7u8; 32]
);
assert!(unvouched(&store, &config));
store_certificate(&store, &cert("https://cloud.example.test", &["org_acme"])).unwrap();
assert!(
trust_root(&store, &config, "https://cloud.example.test")
.is_err_and(|e| e.to_string().contains("paused"))
);
assert!(!unvouched(&store, &config));
}
#[test]
fn vendor_roots_are_a_bounded_list_of_strong_keys() {
assert!(parse_vendor_roots(None).is_empty());
assert!(parse_vendor_roots(Some("not json")).is_empty());
let good = hex::encode(vendor());
assert_eq!(
parse_vendor_roots(Some(&format!("[\"{good}\"]"))),
vec![vendor()]
);
assert!(parse_vendor_roots(Some(&format!("[\"{}\"]", hex::encode([0u8; 32])))).is_empty());
}
}