Skip to main content

lean_ctx_protocol/cloud/
managed.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! `leanctx.managed-config/v1`: what an organisation preconfigures on a
4//! machine through MDM (contract: `docs/contracts/managed-config-v1.md`).
5//!
6//! The carrier (a macOS profile, the Windows policy key, or
7//! `/etc/lean-ctx/managed.toml`) delivers members either nested
8//! (`{"cloud": {"url": …}}`) or dotted (`{"cloud.url": …}`, the natural form of
9//! a registry value name); [`ManagedConfigV1::from_members`] accepts both.
10//! The configuration names the Cloud, the org, the IdP hint and the update
11//! mode. It carries no secret and no policy content. Every member is
12//! optional; an unknown member, a wrong type or a value out of shape refuses
13//! the whole configuration, and the engine then fails closed.
14//!
15//! Precedence: managed > Cloud floor > the user's `config.toml` > defaults.
16//! `telemetry.*` members only tighten: `false` turns an upload off, `true`
17//! changes nothing.
18
19use serde::{Deserialize, Serialize};
20use serde_json::{Map, Value};
21
22use super::effective_policy::policy_digest;
23use crate::ValidationError;
24
25pub const MANAGED_CONFIG_SCHEMA: &str = "leanctx.managed-config/v1";
26
27/// The update channel an organisation chose (`updates.mode`).
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum ManagedUpdateModeV1 {
31    /// The MDM ships updates; the engine never updates itself.
32    Mdm,
33    /// The Cloud names the version.
34    Cloud,
35    /// The user decides (the unmanaged behaviour).
36    User,
37}
38
39/// A validated managed configuration. `None`/empty: not managed.
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(deny_unknown_fields)]
42pub struct ManagedConfigV1 {
43    /// Cloud web origin; wins over `[cloud] url`.
44    #[serde(default, skip_serializing_if = "Option::is_none", rename = "cloud_url")]
45    pub cloud_url: Option<String>,
46    /// Base64 Ed25519 root key; wins over `[cloud] root_key`.
47    #[serde(
48        default,
49        skip_serializing_if = "Option::is_none",
50        rename = "cloud_root_key"
51    )]
52    pub cloud_root_key: Option<String>,
53    /// The only org this machine may connect to (org wire id).
54    #[serde(default, skip_serializing_if = "Option::is_none", rename = "cloud_org")]
55    pub cloud_org: Option<String>,
56    /// Identity-provider hint for sign-in.
57    #[serde(
58        default,
59        skip_serializing_if = "Option::is_none",
60        rename = "cloud_idp_hint"
61    )]
62    pub cloud_idp_hint: Option<String>,
63    /// Tools refuse until this machine is signed in with a live lease and
64    /// a policy floor is installed.
65    #[serde(
66        default,
67        skip_serializing_if = "Option::is_none",
68        rename = "cloud_require"
69    )]
70    pub cloud_require: Option<bool>,
71    #[serde(default, skip_serializing_if = "Vec::is_empty")]
72    pub workspace_vaults: Vec<String>,
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub updates_mode: Option<ManagedUpdateModeV1>,
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub updates_feed_base: Option<String>,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub telemetry_metrics_upload: Option<bool>,
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub telemetry_receipts_upload: Option<bool>,
81}
82
83#[derive(Clone, Copy)]
84enum Kind {
85    Text,
86    Origin,
87    Https,
88    RootKey,
89    Id,
90    Bool,
91    List,
92    Mode,
93}
94
95/// Every member of v1, by its dotted name.
96const MEMBERS: &[(&str, Kind)] = &[
97    ("cloud.url", Kind::Origin),
98    ("cloud.root_key", Kind::RootKey),
99    ("cloud.org", Kind::Id),
100    ("cloud.idp_hint", Kind::Text),
101    ("cloud.require", Kind::Bool),
102    ("workspace.vaults", Kind::List),
103    ("updates.mode", Kind::Mode),
104    ("updates.feed_base", Kind::Https),
105    ("telemetry.metrics_upload", Kind::Bool),
106    ("telemetry.receipts_upload", Kind::Bool),
107];
108
109impl ManagedConfigV1 {
110    /// Parse the members a carrier holds. `schema`, when present, must be
111    /// [`MANAGED_CONFIG_SCHEMA`].
112    pub fn from_members(members: &Map<String, Value>) -> Result<Self, ValidationError> {
113        let mut flat = Map::new();
114        for (key, value) in members {
115            if key == "schema" {
116                if value.as_str() != Some(MANAGED_CONFIG_SCHEMA) {
117                    return Err(ValidationError::new(format!(
118                        "schema must be \"{MANAGED_CONFIG_SCHEMA}\""
119                    )));
120                }
121                continue;
122            }
123            flatten(key, value, &mut flat)?;
124        }
125        let mut out = Map::new();
126        let mut named = Map::new();
127        for (name, value) in flat {
128            if named.insert(name.clone(), value).is_some() {
129                return Err(ValidationError::new(format!(
130                    "member `{name}` is set twice"
131                )));
132            }
133        }
134        for (name, value) in named {
135            let Some((_, kind)) = MEMBERS.iter().find(|(member, _)| *member == name) else {
136                return Err(ValidationError::new(format!("unknown member `{name}`")));
137            };
138            let value = coerce(&name, *kind, value)?;
139            out.insert(serde_key(&name), value);
140        }
141        serde_json::from_value(Value::Object(out))
142            .map_err(|error| ValidationError::new(format!("managed configuration: {error}")))
143    }
144
145    /// No member is set.
146    pub fn is_empty(&self) -> bool {
147        self == &Self::default()
148    }
149
150    /// The members that are set, by dotted name, with their value as text
151    /// (lists joined by `, `), in schema order.
152    pub fn members(&self) -> Vec<(&'static str, String)> {
153        let Ok(Value::Object(map)) = serde_json::to_value(self) else {
154            return Vec::new();
155        };
156        MEMBERS
157            .iter()
158            .filter_map(|(name, _)| {
159                let value = map.get(&serde_key(name))?;
160                let text = match value {
161                    Value::String(text) => text.clone(),
162                    Value::Array(items) => items
163                        .iter()
164                        .filter_map(Value::as_str)
165                        .collect::<Vec<_>>()
166                        .join(", "),
167                    other => other.to_string(),
168                };
169                Some((*name, text))
170            })
171            .collect()
172    }
173
174    /// Whether `member` (dotted, e.g. `cloud.url`) is set.
175    pub fn sets(&self, member: &str) -> bool {
176        self.members().iter().any(|(name, _)| *name == member)
177    }
178
179    /// `managed_digest`: `"sha256:" + hex(sha256(canonical_json))` of the
180    /// configuration with its schema, for the audit trail.
181    pub fn digest(&self) -> String {
182        let mut value = serde_json::to_value(self).unwrap_or(Value::Null);
183        if let Value::Object(map) = &mut value {
184            map.insert("schema".into(), Value::from(MANAGED_CONFIG_SCHEMA));
185        }
186        policy_digest(&value).unwrap_or_default()
187    }
188}
189
190/// The serde field of member `name`.
191fn serde_key(name: &str) -> String {
192    name.replace('.', "_")
193}
194
195/// Nested objects become dotted names; a name may already be dotted.
196fn flatten(
197    prefix: &str,
198    value: &Value,
199    out: &mut Map<String, Value>,
200) -> Result<(), ValidationError> {
201    match value {
202        Value::Object(inner) => {
203            for (key, value) in inner {
204                flatten(&format!("{prefix}.{key}"), value, out)?;
205            }
206            Ok(())
207        }
208        other => {
209            if out.insert(prefix.to_string(), other.clone()).is_some() {
210                return Err(ValidationError::new(format!(
211                    "member `{prefix}` is set twice"
212                )));
213            }
214            Ok(())
215        }
216    }
217}
218
219fn coerce(name: &str, kind: Kind, value: Value) -> Result<Value, ValidationError> {
220    let refuse = |what: &str| ValidationError::new(format!("member `{name}` must be {what}"));
221    let text = |value: &Value| -> Result<String, ValidationError> {
222        match value.as_str().map(str::trim) {
223            Some(text) if !text.is_empty() && text.len() <= 512 => Ok(text.to_string()),
224            _ => Err(refuse("a non-empty string")),
225        }
226    };
227    Ok(match kind {
228        Kind::Text => Value::from(text(&value)?),
229        Kind::Origin => {
230            let url = text(&value)?;
231            if !is_origin(&url) {
232                return Err(refuse(
233                    "an https origin (http only for loopback), without path or query",
234                ));
235            }
236            Value::from(url)
237        }
238        Kind::Https => {
239            let url = text(&value)?;
240            if !url.starts_with("https://") || url.len() <= "https://".len() {
241                return Err(refuse("an https URL"));
242            }
243            Value::from(url)
244        }
245        Kind::RootKey => {
246            let key = text(&value)?;
247            let base64 = |c: char| c.is_ascii_alphanumeric() || c == '+' || c == '/';
248            if key.len() != 44 || !key.ends_with('=') || !key[..43].chars().all(base64) {
249                return Err(refuse(
250                    "a standard base64 Ed25519 public key (44 characters)",
251                ));
252            }
253            Value::from(key)
254        }
255        Kind::Id => {
256            let id = text(&value)?;
257            if id.len() > 128 || id.chars().any(char::is_whitespace) {
258                return Err(refuse("an org id without whitespace"));
259            }
260            Value::from(id)
261        }
262        Kind::Bool => Value::from(match &value {
263            Value::Bool(flag) => *flag,
264            Value::Number(number) if number.as_u64() == Some(0) => false,
265            Value::Number(number) if number.as_u64() == Some(1) => true,
266            Value::String(text) if matches!(text.trim(), "true" | "1") => true,
267            Value::String(text) if matches!(text.trim(), "false" | "0") => false,
268            _ => return Err(refuse("true or false (or 1/0)")),
269        }),
270        Kind::List => {
271            let items: Vec<Value> = match &value {
272                Value::Array(items) => items.clone(),
273                Value::String(joined) => joined
274                    .split([',', '\n'])
275                    .filter(|part| !part.trim().is_empty())
276                    .map(|part| Value::from(part.trim()))
277                    .collect(),
278                _ => return Err(refuse("a list of strings")),
279            };
280            let items = items.iter().map(text).collect::<Result<Vec<_>, _>>()?;
281            Value::from(items)
282        }
283        Kind::Mode => {
284            let mode = text(&value)?;
285            if !matches!(mode.as_str(), "mdm" | "cloud" | "user") {
286                return Err(refuse("one of mdm, cloud, user"));
287            }
288            Value::from(mode)
289        }
290    })
291}
292
293/// `https://host[:port]` (or `http://` for loopback), an optional trailing
294/// `/`, nothing else.
295fn is_origin(url: &str) -> bool {
296    let (scheme, rest) = match url.split_once("://") {
297        Some(parts) => parts,
298        None => return false,
299    };
300    let authority = rest.strip_suffix('/').unwrap_or(rest);
301    if authority.is_empty() || authority.contains(['/', '?', '#', '@', ' ']) {
302        return false;
303    }
304    let host = authority
305        .rsplit_once(':')
306        .filter(|(_, port)| port.chars().all(|c| c.is_ascii_digit()) && !authority.ends_with(']'))
307        .map_or(authority, |(host, _)| host);
308    match scheme {
309        "https" => true,
310        "http" => matches!(host, "localhost" | "127.0.0.1" | "[::1]"),
311        _ => false,
312    }
313}
314
315/// Where a managed configuration came from (`cloud status`).
316#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
317#[serde(rename_all = "snake_case")]
318pub enum ManagedCarrierKindV1 {
319    MacosProfile,
320    WindowsPolicy,
321    LinuxFile,
322    #[serde(other)]
323    Unknown,
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use serde_json::json;
330
331    fn parse(value: Value) -> Result<ManagedConfigV1, ValidationError> {
332        match value {
333            Value::Object(map) => ManagedConfigV1::from_members(&map),
334            _ => unreachable!(),
335        }
336    }
337
338    const KEY: &str = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
339
340    #[test]
341    fn nested_and_dotted_carriers_mean_the_same_configuration() {
342        let nested = parse(json!({
343            "schema": MANAGED_CONFIG_SCHEMA,
344            "cloud": {"url": "https://cloud.acme.example", "root_key": KEY, "org": "org_1", "require": true},
345            "workspace": {"vaults": ["acme/main"]},
346            "updates": {"mode": "mdm"},
347            "telemetry": {"metrics_upload": false},
348        }))
349        .expect("valid");
350        // Registry shape: dotted names, DWORD booleans, a joined list.
351        let dotted = parse(json!({
352            "cloud.url": "https://cloud.acme.example",
353            "cloud.root_key": KEY,
354            "cloud.org": "org_1",
355            "cloud.require": 1,
356            "workspace.vaults": "acme/main",
357            "updates.mode": "mdm",
358            "telemetry.metrics_upload": 0,
359        }))
360        .expect("valid");
361        assert_eq!(nested, dotted);
362        assert_eq!(nested.digest(), dotted.digest());
363        assert!(nested.digest().starts_with("sha256:"));
364        assert!(nested.sets("cloud.require") && !nested.sets("cloud.idp_hint"));
365        assert_eq!(
366            nested.members()[0],
367            ("cloud.url", "https://cloud.acme.example".into())
368        );
369    }
370
371    #[test]
372    fn a_configuration_out_of_shape_is_refused_whole() {
373        for bad in [
374            json!({"schema": "leanctx.managed-config/v2"}),
375            json!({"cloud": {"rquire": true}}),
376            json!({"cloud.url": "http://cloud.acme.example"}),
377            json!({"cloud.url": "https://cloud.acme.example/v1"}),
378            json!({"cloud.root_key": "not-a-key"}),
379            json!({"cloud.require": "yes"}),
380            json!({"cloud": {"org": "a"}, "cloud.org": "b"}),
381            json!({"updates.mode": "auto"}),
382            json!({"updates.feed_base": "http://feed.example"}),
383            json!({"cloud.org": "org 1"}),
384        ] {
385            assert!(parse(bad.clone()).is_err(), "accepted {bad}");
386        }
387        assert!(parse(json!({"cloud.url": "http://127.0.0.1:8080"})).is_ok());
388        assert!(parse(json!({})).expect("empty").is_empty());
389    }
390}