Skip to main content

core_api/
runtime_space.rs

1//! Device runtime admission, independent of user permissions and Node topology.
2//!
3//! The Host supplies this policy through its trusted local runtime configuration.
4//! Discovery only advertises it; accepting a credential must always check the
5//! local policy. An unclaimed single-Space Host has no effective policy yet.
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase", deny_unknown_fields)]
10pub struct SpaceIdentity {
11    pub tenant_id: String,
12    pub scope_id: String,
13}
14
15impl SpaceIdentity {
16    pub fn validate(&self) -> Result<(), &'static str> {
17        if valid_id(&self.tenant_id) && valid_id(&self.scope_id) {
18            Ok(())
19        } else {
20            Err("invalid runtime Space identity")
21        }
22    }
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(tag = "mode", rename_all = "camelCase", deny_unknown_fields)]
27pub enum RuntimeSpacePolicy {
28    Multi {},
29    Single { space: SpaceIdentity },
30}
31
32impl RuntimeSpacePolicy {
33    /// Discovery is advisory, but missing or unknown restrictions are never
34    /// interpreted as an unrestricted device. Authentication rechecks the policy.
35    pub fn from_mdns(
36        mode: Option<&str>,
37        tenant: Option<&str>,
38        scope: Option<&str>,
39    ) -> Result<Self, &'static str> {
40        let policy = match (mode, tenant, scope) {
41            (Some("multi"), None, None) => Self::Multi {},
42            (Some("single"), Some(tenant), Some(scope)) => Self::Single {
43                space: SpaceIdentity {
44                    tenant_id: tenant.into(),
45                    scope_id: scope.into(),
46                },
47            },
48            _ => return Err("missing or invalid runtime Space discovery policy"),
49        };
50        policy.validate()?;
51        Ok(policy)
52    }
53
54    pub fn mdns_properties(&self) -> Vec<(String, String)> {
55        match self {
56            Self::Multi {} => vec![("space_mode".into(), "multi".into())],
57            Self::Single { space } => vec![
58                ("space_mode".into(), "single".into()),
59                ("space_tenant".into(), space.tenant_id.clone()),
60                ("space_id".into(), space.scope_id.clone()),
61            ],
62        }
63    }
64    pub fn validate(&self) -> Result<(), &'static str> {
65        match self {
66            Self::Multi {} => Ok(()),
67            Self::Single { space } => space.validate(),
68        }
69    }
70
71    /// Call for initial admission, persisted-identity recovery and credential
72    /// refresh. A valid credential for another Space does not override this rule.
73    pub fn admit(&self, tenant_id: &str, scope_id: &str) -> Result<(), &'static str> {
74        self.validate()?;
75        if !valid_id(tenant_id) || !valid_id(scope_id) {
76            return Err("invalid requested Space identity");
77        }
78        match self {
79            Self::Multi {} => Ok(()),
80            Self::Single { space }
81                if space.tenant_id == tenant_id && space.scope_id == scope_id =>
82            {
83                Ok(())
84            }
85            Self::Single { .. } => Err("runtime is restricted to another Space"),
86        }
87    }
88}
89
90impl std::str::FromStr for RuntimeSpacePolicy {
91    type Err = String;
92    fn from_str(value: &str) -> Result<Self, Self::Err> {
93        let policy: Self = serde_json::from_str(value).map_err(|e| e.to_string())?;
94        policy.validate().map_err(str::to_owned)?;
95        Ok(policy)
96    }
97}
98
99fn valid_id(value: &str) -> bool {
100    !value.is_empty() && value.trim() == value && value.len() <= 240
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn single_space_rejects_other_tenants_and_spaces() {
109        let policy = RuntimeSpacePolicy::Single {
110            space: SpaceIdentity {
111                tenant_id: "tenant-a".into(),
112                scope_id: "space-a".into(),
113            },
114        };
115        assert!(policy.admit("tenant-a", "space-a").is_ok());
116        assert!(policy.admit("tenant-a", "space-b").is_err());
117        assert!(policy.admit("tenant-b", "space-a").is_err());
118        assert!(policy.admit("", "space-a").is_err());
119        assert!(RuntimeSpacePolicy::Multi {}
120            .admit("tenant-b", "space-b")
121            .is_ok());
122    }
123
124    #[test]
125    fn discovery_roundtrip_and_missing_policy_fail_closed() {
126        let multi = RuntimeSpacePolicy::Multi {};
127        let single = RuntimeSpacePolicy::Single {
128            space: SpaceIdentity {
129                tenant_id: "t".into(),
130                scope_id: "s".into(),
131            },
132        };
133        for policy in [multi, single] {
134            let properties: std::collections::BTreeMap<_, _> =
135                policy.mdns_properties().into_iter().collect();
136            let get = |key| properties.get(key).map(String::as_str);
137            assert_eq!(
138                RuntimeSpacePolicy::from_mdns(
139                    get("space_mode"),
140                    get("space_tenant"),
141                    get("space_id")
142                )
143                .unwrap(),
144                policy
145            );
146        }
147        assert!(RuntimeSpacePolicy::from_mdns(None, None, None).is_err());
148        assert!(RuntimeSpacePolicy::from_mdns(Some("multi"), Some("t"), Some("s")).is_err());
149        assert!(RuntimeSpacePolicy::from_mdns(Some("single"), None, None).is_err());
150    }
151
152    #[test]
153    fn missing_or_malformed_policy_never_defaults_to_multi() {
154        for input in [
155            "{}",
156            "null",
157            r#"{"mode":"single"}"#,
158            r#"{"mode":"multi","space":{"tenantId":"t","scopeId":"s"}}"#,
159        ] {
160            assert!(
161                serde_json::from_str::<RuntimeSpacePolicy>(input).is_err(),
162                "{input}"
163            );
164        }
165        let invalid = RuntimeSpacePolicy::Single {
166            space: SpaceIdentity {
167                tenant_id: "t".into(),
168                scope_id: " ".into(),
169            },
170        };
171        assert!(invalid.validate().is_err());
172        assert!(invalid.admit("t", "s").is_err());
173    }
174}