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            // A self-hosted key with the hosted origin: `[cloud] url` (or
60            // `--url`) is missing, and the hosted key set would never verify.
61            (Some(key), true)
62                if !compiled_root_keys(HOSTED_ROOT_KEYS)
63                    .contains(&decode_key(key.trim(), "root_key")?) =>
64            {
65                return Err(CloudError::Config(format!(
66                    "`[cloud] root_key` is not a key of {origin}; set `[cloud] url` \
67                     (or pass --url) to the Cloud this key belongs to"
68                )));
69            }
70            (Some(key), _) => key.as_str(),
71            (None, true) => HOSTED_ROOT_KEYS.first().copied().ok_or_else(|| {
72                CloudError::Config(
73                    "this build has no hosted LeanCTX Cloud root key; set `[cloud] root_key`"
74                        .into(),
75                )
76            })?,
77            (None, false) => {
78                return Err(CloudError::Config(format!(
79                    "{origin} needs its root public key: set `root_key` in the `[cloud]` \
80                     section of config.toml (`lean-ctx config path` shows the file) to the \
81                     base64 key that {origin}'s operator gives you"
82                )));
83            }
84        };
85        decode_key(encoded.trim(), "root_key")
86    }
87}
88
89/// A managed carrier that exists but was refused stops every Cloud call.
90fn managed_carrier_ok() -> Result<(), CloudError> {
91    match lean_ctx::core::config::managed::current().as_deref() {
92        Some(managed) => match &managed.config {
93            Ok(_) => Ok(()),
94            Err(error) => Err(CloudError::Config(format!(
95                "the managed configuration ({}) is refused: {error}",
96                managed.location
97            ))),
98        },
99        None => Ok(()),
100    }
101}
102
103/// Why this machine's managed configuration forbids an enrollment with
104/// `org_id` at `origin` (`cloud.org`, `cloud.url`), if it does.
105pub fn managed_enrollment_refusal(org_id: &str, origin: &str) -> Option<CloudError> {
106    let managed = lean_ctx::core::config::managed::current()?;
107    enrollment_refusal(&managed, org_id, origin)
108}
109
110pub(crate) fn enrollment_refusal(
111    managed: &lean_ctx::core::config::managed::Managed,
112    org_id: &str,
113    origin: &str,
114) -> Option<CloudError> {
115    if let Some(refusal) = managed.org_refusal(org_id) {
116        return Some(CloudError::Config(refusal));
117    }
118    let url = managed.config.as_ref().ok()?.cloud_url.as_deref()?;
119    match normalize_origin(url) {
120        Ok(managed_origin) if same_cloud_origin(&managed_origin, origin) => None,
121        Ok(managed_origin) => Some(CloudError::Config(format!(
122            "{}: it connects only to {managed_origin}, not {origin}. Run `lean-ctx cloud connect` again",
123            managed.manager()
124        ))),
125        Err(error) => Some(error),
126    }
127}
128
129/// Decode a base64 Ed25519 public key.
130pub(crate) fn decode_key(encoded: &str, what: &str) -> Result<[u8; 32], CloudError> {
131    B64.decode(encoded)
132        .ok()
133        .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
134        .ok_or_else(|| CloudError::Config(format!("{what} must be base64 of 32 bytes")))
135}
136
137/// `https://host[:port]` (or `http://localhost|127.0.0.1[:port]`), no path,
138/// query, fragment or credentials, no trailing slash.
139pub fn normalize_origin(url: &str) -> Result<String, CloudError> {
140    let url = url.trim().trim_end_matches('/');
141    let (scheme, rest) = url
142        .split_once("://")
143        .ok_or_else(|| CloudError::Config(format!("{url:?} is not a URL")))?;
144    if rest.is_empty()
145        || rest.contains(['/', '?', '#', '@'])
146        || rest.chars().any(char::is_whitespace)
147    {
148        return Err(CloudError::Config(
149            "the LeanCTX Cloud URL is an origin only: scheme, host and optional port".into(),
150        ));
151    }
152    let host = rest.rsplit_once(':').map_or(rest, |(host, port)| {
153        if port.bytes().all(|b| b.is_ascii_digit()) {
154            host
155        } else {
156            rest
157        }
158    });
159    match scheme.to_ascii_lowercase().as_str() {
160        "https" => Ok(format!("https://{rest}")),
161        "http" if matches!(host, "localhost" | "127.0.0.1" | "[::1]") => {
162            Ok(format!("http://{rest}"))
163        }
164        _ => Err(CloudError::Config(
165            "LeanCTX Cloud is reached over https (http only on localhost)".into(),
166        )),
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn origins_are_https_or_loopback_http() {
176        assert_eq!(
177            normalize_origin("https://cloud.example.com/").unwrap(),
178            "https://cloud.example.com"
179        );
180        assert_eq!(
181            normalize_origin("http://127.0.0.1:8100").unwrap(),
182            "http://127.0.0.1:8100"
183        );
184        assert!(normalize_origin("http://cloud.example.com").is_err());
185        assert!(normalize_origin("http://localhost.evil.com").is_err());
186        assert!(normalize_origin("https://user:pw@cloud.example.com").is_err());
187        assert!(normalize_origin("https://cloud.example.com/v1").is_err());
188        assert!(normalize_origin("ftp://cloud.example.com").is_err());
189    }
190
191    #[test]
192    fn a_managed_machine_refuses_a_foreign_org_or_cloud() {
193        use lean_ctx::core::config::managed::Managed;
194        use lean_ctx_protocol::cloud::managed::{ManagedCarrierKindV1, ManagedConfigV1};
195        let managed = |members: serde_json::Value| Managed {
196            carrier: ManagedCarrierKindV1::LinuxFile,
197            location: "/etc/lean-ctx/managed.toml".into(),
198            config: ManagedConfigV1::from_members(members.as_object().expect("object"))
199                .map_err(|error| error.to_string()),
200        };
201        let refused = |managed: &Managed, org: &str, origin: &str| {
202            enrollment_refusal(managed, org, origin).map(|error| error.to_string())
203        };
204        let acme = managed(serde_json::json!({
205            "cloud": {"org": "org_acme", "url": "https://cloud.acme.example"}
206        }));
207        assert!(refused(&acme, "org_acme", "https://cloud.acme.example").is_none());
208        let org = refused(&acme, "org_other", "https://cloud.acme.example").expect("other org");
209        assert!(org.contains("managed by org_acme"), "{org}");
210        let cloud =
211            refused(&acme, "org_acme", "https://cloud.other.example").expect("other LeanCTX Cloud");
212        assert!(
213            cloud.contains("connects only to https://cloud.acme.example"),
214            "{cloud}"
215        );
216
217        // Only the org is managed: any Cloud of that org.
218        let org_only = managed(serde_json::json!({"cloud": {"org": "org_acme"}}));
219        assert!(refused(&org_only, "org_acme", "https://cloud.other.example").is_none());
220
221        // A refused carrier refuses every enrollment.
222        let broken = Managed {
223            config: Err("cloud.require: not a boolean".into()),
224            ..org_only
225        };
226        let error = refused(&broken, "org_acme", "https://cloud.acme.example").expect("refused");
227        assert!(error.contains("is refused"), "{error}");
228    }
229
230    #[test]
231    fn self_hosted_cloud_needs_its_root_key() {
232        let config = CloudConfig {
233            url: Some("https://cloud.acme.internal".into()),
234            ..CloudConfig::default()
235        };
236        let origin = config.origin().unwrap();
237        // rc4-120: the refusal says where the key goes and who has it.
238        let error = config.root_key(&origin).unwrap_err().to_string();
239        for part in [
240            "`[cloud]`",
241            "config.toml",
242            "lean-ctx config path",
243            "operator",
244        ] {
245            assert!(error.contains(part), "{part}: {error}");
246        }
247        let config = CloudConfig {
248            root_key: Some(B64.encode([7u8; 32])),
249            ..config
250        };
251        assert_eq!(config.root_key(&origin).unwrap(), [7u8; 32]);
252    }
253
254    #[test]
255    fn a_self_hosted_root_key_without_its_url_names_the_missing_url() {
256        // rc4-47: root_key of another Cloud, no url → the hosted origin.
257        let config = CloudConfig {
258            root_key: Some(B64.encode([7u8; 32])),
259            ..CloudConfig::default()
260        };
261        let origin = config.origin().unwrap();
262        let error = config.root_key(&origin).unwrap_err().to_string();
263        assert!(error.contains("set `[cloud] url`"), "{error}");
264        // The hosted key itself stays accepted for the hosted origin.
265        let hosted = CloudConfig {
266            root_key: Some(HOSTED_ROOT_KEYS[0].into()),
267            ..CloudConfig::default()
268        };
269        assert_eq!(
270            hosted.root_key(&origin).unwrap(),
271            compiled_root_keys(HOSTED_ROOT_KEYS)[0]
272        );
273    }
274
275    #[test]
276    fn compiled_roots_match_the_contract_vectors() {
277        let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../..")).join(
278            "crates/lean-ctx-protocol/tests/fixtures/cloud-v2/vectors/root_keys.vectors.json",
279        );
280        let v: serde_json::Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
281        let listed = |name: &str| -> Vec<(String, String)> {
282            v[name]
283                .as_array()
284                .unwrap()
285                .iter()
286                .map(|e| {
287                    let (id, pk) = (&e["key_id"], &e["public_key"]);
288                    (id.as_str().unwrap().into(), pk.as_str().unwrap().into())
289                })
290                .collect()
291        };
292        let compiled = |list: &[&str]| -> Vec<(String, String)> {
293            let keys = compiled_root_keys(list);
294            assert_eq!(keys.len(), list.len(), "every compiled root decodes");
295            keys.iter()
296                .map(|k| {
297                    let id = blake3::hash(k).to_hex()[..16].to_string();
298                    (id, B64.encode(k))
299                })
300                .collect()
301        };
302        assert!(!HOSTED_ROOT_KEYS.is_empty(), "3.12.0 refuses an empty list");
303        assert_eq!(compiled(HOSTED_ROOT_KEYS), listed("hosted"));
304        assert_eq!(compiled(RETIRED_ROOT_KEYS), listed("retired"));
305        assert_eq!(PRE_ROTATION_ROOT_KEY_ID, v["pre_rotation"].as_str());
306        let origin = CloudConfig::default().origin().unwrap();
307        assert_eq!(
308            CloudConfig::default().root_key(&origin).unwrap(),
309            compiled_root_keys(HOSTED_ROOT_KEYS)[0]
310        );
311    }
312
313    #[test]
314    fn defaults_match_the_documented_section() {
315        let parsed: CloudConfig = toml::from_str("").unwrap();
316        assert_eq!(parsed, CloudConfig::default());
317        assert_eq!(parsed.pull_interval_minutes, 5);
318        assert!(parsed.auto_capture);
319        assert_eq!(parsed.bus, CloudBusMode::Auto);
320    }
321
322    #[test]
323    fn the_pull_interval_is_clamped_to_its_bounds() {
324        let at = |minutes| {
325            CloudConfig {
326                pull_interval_minutes: minutes,
327                ..CloudConfig::default()
328            }
329            .pull_interval()
330        };
331        assert_eq!(at(0), 1);
332        assert_eq!(at(15), 15);
333        assert_eq!(at(600), 60);
334    }
335}