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