Skip to main content

lean_ctx_cloud/
config.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `[cloud]` configuration: the section's types come from
3//! [`lean_ctx::core::config::cloud`]; this module adds the Cloud's origin and
4//! root-key rules.
5
6use base64::Engine as _;
7use base64::engine::general_purpose::STANDARD as B64;
8
9use super::CloudError;
10use lean_ctx_protocol::cloud::{CLOUD_DEFAULT_URL, is_hosted_origin, same_cloud_origin};
11
12pub use lean_ctx::core::config::cloud::{
13    CloudBusMode, CloudConfig, DEFAULT_PULL_INTERVAL_MINUTES, PULL_INTERVAL_BOUNDS, schema_section,
14};
15
16/// Root public keys of the hosted service (`cloud.leanctx.com`, alias
17/// `cloud.leanctx.com`), base64
18/// Ed25519, the one that signs today first (C0 `root_keys.vectors.json`
19/// `hosted`, RESOLUTIONS R55). Any other Cloud needs `[cloud] root_key`.
20pub const HOSTED_ROOT_KEYS: &[&str] = &["gu/tH0HqqDVcjm+fbHoS05NodwN7eWqQ5N4qAxq+cV8="];
21
22/// Hosted roots that no longer sign a key set (`retired`): a set signed
23/// only by one of them is refused as `retired_root`.
24pub const RETIRED_ROOT_KEYS: &[&str] = &[];
25
26/// Key id (`hex(blake3(pk))[..16]`) of the hosted root while the offline
27/// rotation V15.O9 is open (`pre_rotation`); `None` once it is done.
28pub const PRE_ROTATION_ROOT_KEY_ID: Option<&str> = Some("b5406e1db468082e");
29
30/// The compiled keys of `list`, decoded (a malformed entry fails the
31/// vector test, never a connect).
32pub fn compiled_root_keys(list: &[&str]) -> Vec<[u8; 32]> {
33    list.iter()
34        .filter_map(|k| decode_key(k, "root_key").ok())
35        .collect()
36}
37
38/// The Cloud's origin and root key of a `[cloud]` section (the section type
39/// lives in the engine; these rules are the connector's).
40pub trait CloudConfigExt {
41    /// The configured origin, normalized and checked.
42    fn origin(&self) -> Result<String, CloudError>;
43
44    /// The root key that signs this Cloud's key set.
45    fn root_key(&self, origin: &str) -> Result<[u8; 32], CloudError>;
46}
47
48impl CloudConfigExt for CloudConfig {
49    /// The managed `cloud.url` already overlays `url` on every config load
50    /// (`lean_ctx::core::config::managed`); a refused managed carrier refuses here.
51    fn origin(&self) -> Result<String, CloudError> {
52        managed_carrier_ok()?;
53        normalize_origin(self.url.as_deref().unwrap_or(CLOUD_DEFAULT_URL))
54    }
55
56    fn root_key(&self, origin: &str) -> Result<[u8; 32], CloudError> {
57        managed_carrier_ok()?;
58        let encoded = match (&self.root_key, is_hosted_origin(origin)) {
59            (Some(key), _) => key.as_str(),
60            (None, true) => HOSTED_ROOT_KEYS.first().copied().ok_or_else(|| {
61                CloudError::Config(
62                    "this build has no hosted LeanCTX Cloud root key; set `[cloud] root_key`"
63                        .into(),
64                )
65            })?,
66            (None, false) => {
67                return Err(CloudError::Config(format!(
68                    "set `[cloud] root_key` to the root public key of {origin}"
69                )));
70            }
71        };
72        decode_key(encoded.trim(), "root_key")
73    }
74}
75
76/// A managed carrier that exists but was refused stops every Cloud call.
77fn managed_carrier_ok() -> Result<(), CloudError> {
78    match lean_ctx::core::config::managed::current().as_deref() {
79        Some(managed) => match &managed.config {
80            Ok(_) => Ok(()),
81            Err(error) => Err(CloudError::Config(format!(
82                "the managed configuration ({}) is refused: {error}",
83                managed.location
84            ))),
85        },
86        None => Ok(()),
87    }
88}
89
90/// Why this machine's managed configuration forbids an enrollment with
91/// `org_id` at `origin` (`cloud.org`, `cloud.url`), if it does.
92pub fn managed_enrollment_refusal(org_id: &str, origin: &str) -> Option<CloudError> {
93    let managed = lean_ctx::core::config::managed::current()?;
94    enrollment_refusal(&managed, org_id, origin)
95}
96
97pub(crate) fn enrollment_refusal(
98    managed: &lean_ctx::core::config::managed::Managed,
99    org_id: &str,
100    origin: &str,
101) -> Option<CloudError> {
102    if let Some(refusal) = managed.org_refusal(org_id) {
103        return Some(CloudError::Config(refusal));
104    }
105    let url = managed.config.as_ref().ok()?.cloud_url.as_deref()?;
106    match normalize_origin(url) {
107        Ok(managed_origin) if same_cloud_origin(&managed_origin, origin) => None,
108        Ok(managed_origin) => Some(CloudError::Config(format!(
109            "{}: it connects only to {managed_origin}, not {origin}. Run `lean-ctx cloud connect` again",
110            managed.manager()
111        ))),
112        Err(error) => Some(error),
113    }
114}
115
116/// Decode a base64 Ed25519 public key.
117pub(crate) fn decode_key(encoded: &str, what: &str) -> Result<[u8; 32], CloudError> {
118    B64.decode(encoded)
119        .ok()
120        .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
121        .ok_or_else(|| CloudError::Config(format!("{what} must be base64 of 32 bytes")))
122}
123
124/// `https://host[:port]` (or `http://localhost|127.0.0.1[:port]`), no path,
125/// query, fragment or credentials, no trailing slash.
126pub fn normalize_origin(url: &str) -> Result<String, CloudError> {
127    let url = url.trim().trim_end_matches('/');
128    let (scheme, rest) = url
129        .split_once("://")
130        .ok_or_else(|| CloudError::Config(format!("{url:?} is not a URL")))?;
131    if rest.is_empty()
132        || rest.contains(['/', '?', '#', '@'])
133        || rest.chars().any(char::is_whitespace)
134    {
135        return Err(CloudError::Config(
136            "the LeanCTX Cloud URL is an origin only: scheme, host and optional port".into(),
137        ));
138    }
139    let host = rest.rsplit_once(':').map_or(rest, |(host, port)| {
140        if port.bytes().all(|b| b.is_ascii_digit()) {
141            host
142        } else {
143            rest
144        }
145    });
146    match scheme.to_ascii_lowercase().as_str() {
147        "https" => Ok(format!("https://{rest}")),
148        "http" if matches!(host, "localhost" | "127.0.0.1" | "[::1]") => {
149            Ok(format!("http://{rest}"))
150        }
151        _ => Err(CloudError::Config(
152            "LeanCTX Cloud is reached over https (http only on localhost)".into(),
153        )),
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn origins_are_https_or_loopback_http() {
163        assert_eq!(
164            normalize_origin("https://cloud.example.com/").unwrap(),
165            "https://cloud.example.com"
166        );
167        assert_eq!(
168            normalize_origin("http://127.0.0.1:8100").unwrap(),
169            "http://127.0.0.1:8100"
170        );
171        assert!(normalize_origin("http://cloud.example.com").is_err());
172        assert!(normalize_origin("http://localhost.evil.com").is_err());
173        assert!(normalize_origin("https://user:pw@cloud.example.com").is_err());
174        assert!(normalize_origin("https://cloud.example.com/v1").is_err());
175        assert!(normalize_origin("ftp://cloud.example.com").is_err());
176    }
177
178    #[test]
179    fn a_managed_machine_refuses_a_foreign_org_or_cloud() {
180        use lean_ctx::core::config::managed::Managed;
181        use lean_ctx_protocol::cloud::managed::{ManagedCarrierKindV1, ManagedConfigV1};
182        let managed = |members: serde_json::Value| Managed {
183            carrier: ManagedCarrierKindV1::LinuxFile,
184            location: "/etc/lean-ctx/managed.toml".into(),
185            config: ManagedConfigV1::from_members(members.as_object().expect("object"))
186                .map_err(|error| error.to_string()),
187        };
188        let refused = |managed: &Managed, org: &str, origin: &str| {
189            enrollment_refusal(managed, org, origin).map(|error| error.to_string())
190        };
191        let acme = managed(serde_json::json!({
192            "cloud": {"org": "org_acme", "url": "https://cloud.acme.example"}
193        }));
194        assert!(refused(&acme, "org_acme", "https://cloud.acme.example").is_none());
195        let org = refused(&acme, "org_other", "https://cloud.acme.example").expect("other org");
196        assert!(org.contains("managed by org_acme"), "{org}");
197        let cloud =
198            refused(&acme, "org_acme", "https://cloud.other.example").expect("other LeanCTX Cloud");
199        assert!(
200            cloud.contains("connects only to https://cloud.acme.example"),
201            "{cloud}"
202        );
203
204        // Only the org is managed: any Cloud of that org.
205        let org_only = managed(serde_json::json!({"cloud": {"org": "org_acme"}}));
206        assert!(refused(&org_only, "org_acme", "https://cloud.other.example").is_none());
207
208        // A refused carrier refuses every enrollment.
209        let broken = Managed {
210            config: Err("cloud.require: not a boolean".into()),
211            ..org_only
212        };
213        let error = refused(&broken, "org_acme", "https://cloud.acme.example").expect("refused");
214        assert!(error.contains("is refused"), "{error}");
215    }
216
217    #[test]
218    fn self_hosted_cloud_needs_its_root_key() {
219        let config = CloudConfig {
220            url: Some("https://cloud.acme.internal".into()),
221            ..CloudConfig::default()
222        };
223        let origin = config.origin().unwrap();
224        assert!(config.root_key(&origin).is_err());
225        let config = CloudConfig {
226            root_key: Some(B64.encode([7u8; 32])),
227            ..config
228        };
229        assert_eq!(config.root_key(&origin).unwrap(), [7u8; 32]);
230    }
231
232    #[test]
233    fn compiled_roots_match_the_contract_vectors() {
234        let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")).join(
235            "crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/root_keys.vectors.json",
236        );
237        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
238        let listed = |name: &str| -> Vec<(String, String)> {
239            v[name]
240                .as_array()
241                .unwrap()
242                .iter()
243                .map(|e| {
244                    let (id, pk) = (&e["key_id"], &e["public_key"]);
245                    (id.as_str().unwrap().into(), pk.as_str().unwrap().into())
246                })
247                .collect()
248        };
249        let compiled = |list: &[&str]| -> Vec<(String, String)> {
250            let keys = compiled_root_keys(list);
251            assert_eq!(keys.len(), list.len(), "every compiled root decodes");
252            keys.iter()
253                .map(|k| {
254                    let id = blake3::hash(k).to_hex()[..16].to_string();
255                    (id, B64.encode(k))
256                })
257                .collect()
258        };
259        assert!(!HOSTED_ROOT_KEYS.is_empty(), "3.12.0 refuses an empty list");
260        assert_eq!(compiled(HOSTED_ROOT_KEYS), listed("hosted"));
261        assert_eq!(compiled(RETIRED_ROOT_KEYS), listed("retired"));
262        assert_eq!(PRE_ROTATION_ROOT_KEY_ID, v["pre_rotation"].as_str());
263        let origin = CloudConfig::default().origin().unwrap();
264        assert_eq!(
265            CloudConfig::default().root_key(&origin).unwrap(),
266            compiled_root_keys(HOSTED_ROOT_KEYS)[0]
267        );
268    }
269
270    #[test]
271    fn defaults_match_the_documented_section() {
272        let parsed: CloudConfig = toml::from_str("").unwrap();
273        assert_eq!(parsed, CloudConfig::default());
274        assert_eq!(parsed.pull_interval_minutes, 5);
275        assert!(parsed.auto_capture);
276        assert_eq!(parsed.bus, CloudBusMode::Auto);
277    }
278
279    #[test]
280    fn the_pull_interval_is_clamped_to_its_bounds() {
281        let at = |minutes| {
282            CloudConfig {
283                pull_interval_minutes: minutes,
284                ..CloudConfig::default()
285            }
286            .pull_interval()
287        };
288        assert_eq!(at(0), 1);
289        assert_eq!(at(15), 15);
290        assert_eq!(at(600), 60);
291    }
292}