Skip to main content

core_api/node/
plugin.rs

1//! Space-scoped Plugin routing. Business payloads belong to the destination Plugin.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::HashSet;
5
6pub const REQUEST_TARGET: &str = "/plugin/request";
7pub const EVENT_TARGET: &str = "/plugin/event";
8pub const INSTANCE_LIST_TARGET: &str = "/plugin/instance/list";
9pub const ACCESS_DETAIL: &str = "pluginAccess";
10pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
11pub const MAX_TIMEOUT_MS: u64 = 60_000;
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase", deny_unknown_fields)]
15pub struct PluginAddress {
16    pub node_type: String,
17    pub node_id: String,
18}
19
20impl PluginAddress {
21    pub fn validate(&self) -> Result<(), &'static str> {
22        if self.node_type.is_empty()
23            || self.node_type.len() > 128
24            || !self
25                .node_type
26                .bytes()
27                .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_'))
28            || self.node_id.is_empty()
29            || self.node_id.len() > 256
30            || self
31                .node_id
32                .chars()
33                .any(|c| c.is_control() || c.is_whitespace())
34        {
35            return Err("Invalid Plugin instance address");
36        }
37        Ok(())
38    }
39}
40
41pub fn validate_target(target: &str) -> Result<(), &'static str> {
42    if !target.starts_with("/plugin/")
43        || target.len() > 512
44        || target[1..].split('/').any(|s| {
45            s.is_empty()
46                || s == "."
47                || s == ".."
48                || !s
49                    .bytes()
50                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_'))
51        })
52    {
53        return Err("Invalid Plugin route");
54    }
55    Ok(())
56}
57
58#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase", deny_unknown_fields)]
60pub struct PluginAccess {
61    #[serde(default)]
62    pub requests: Vec<String>,
63    #[serde(default)]
64    pub events: Vec<String>,
65}
66
67impl PluginAccess {
68    /// A typed, optional extension of the existing authenticated Node description.
69    pub fn from_description(description: &crate::NodeDescription) -> Result<Self, String> {
70        let access: Self = description
71            .details
72            .get(ACCESS_DETAIL)
73            .cloned()
74            .map(serde_json::from_value)
75            .transpose()
76            .map_err(|e| format!("Invalid Plugin access: {e}"))?
77            .unwrap_or_default();
78        for routes in [&access.requests, &access.events] {
79            if routes.len() > 256 {
80                return Err("Too many Plugin routes".into());
81            }
82            let mut seen = HashSet::new();
83            for route in routes {
84                validate_target(route).map_err(str::to_owned)?;
85                if !seen.insert(route) || !description.routes.contains(route) {
86                    return Err(format!(
87                        "Plugin access route is duplicated or unadvertised: {route}"
88                    ));
89                }
90            }
91        }
92        Ok(access)
93    }
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase", deny_unknown_fields)]
98pub struct PluginRequest {
99    pub to: PluginAddress,
100    pub target: String,
101    pub version: String,
102    pub payload: Value,
103    #[serde(default = "default_timeout")]
104    pub timeout_ms: u64,
105}
106
107fn default_timeout() -> u64 {
108    DEFAULT_TIMEOUT_MS
109}
110
111impl PluginRequest {
112    pub fn validate(&self) -> Result<(), &'static str> {
113        self.to.validate()?;
114        validate_target(&self.target)?;
115        validate_version(&self.version)?;
116        if self.timeout_ms == 0 || self.timeout_ms > MAX_TIMEOUT_MS {
117            return Err("Plugin timeout must be between 1 and 60000 milliseconds");
118        }
119        Ok(())
120    }
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase", deny_unknown_fields)]
125pub struct PluginEvent {
126    pub to: PluginAddress,
127    pub target: String,
128    pub version: String,
129    pub payload: Value,
130}
131
132impl PluginEvent {
133    pub fn validate(&self) -> Result<(), &'static str> {
134        self.to.validate()?;
135        validate_target(&self.target)?;
136        validate_version(&self.version)
137    }
138}
139
140pub fn validate_version(version: &str) -> Result<(), &'static str> {
141    if version.is_empty()
142        || version.len() > 64
143        || !version
144            .bytes()
145            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_'))
146    {
147        return Err("Invalid Plugin protocol version");
148    }
149    Ok(())
150}
151
152#[derive(Debug, Clone, Default, Serialize, Deserialize)]
153#[serde(rename_all = "camelCase", deny_unknown_fields)]
154pub struct PluginInstanceListRequest {
155    pub node_type: Option<String>,
156}
157
158#[derive(Debug, Clone, Serialize, Deserialize)]
159#[serde(rename_all = "camelCase", deny_unknown_fields)]
160pub struct PluginInstance {
161    pub address: PluginAddress,
162    pub access: PluginAccess,
163}
164
165#[derive(Debug, Clone, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase", deny_unknown_fields)]
167pub struct PluginInstanceList {
168    pub instances: Vec<PluginInstance>,
169}
170
171/// Core-authenticated metadata, outside the business payload. Never accepted from a sender.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(rename_all = "camelCase", deny_unknown_fields)]
174pub struct PluginCallContext {
175    pub space_id: String,
176    pub from: PluginAddress,
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub timeout_ms: Option<u64>,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
182#[serde(tag = "kind", rename_all = "camelCase")]
183pub enum PluginControl {
184    PluginCall(PluginCallContext),
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use serde_json::json;
191
192    #[test]
193    fn request_rejects_spoofed_context_and_invalid_routing() {
194        let input = json!({"to":{"nodeType":"dev.example.matter","nodeId":"matter-1"},
195            "target":"/plugin/camera/source/list","version":"v1","payload":{"nested":[0,false,null]}});
196        let request: PluginRequest = serde_json::from_value(input.clone()).unwrap();
197        request.validate().unwrap();
198        assert_eq!(request.timeout_ms, DEFAULT_TIMEOUT_MS);
199        for key in ["from", "spaceId", "context", "control"] {
200            let mut bad = input.clone();
201            bad[key] = json!({});
202            assert!(
203                serde_json::from_value::<PluginRequest>(bad).is_err(),
204                "{key}"
205            );
206        }
207        for target in [
208            "/app/plugin/remove",
209            "/plugin/../remove",
210            "/plugin//list",
211            "/plugin/list?x=1",
212            "/plugin/",
213        ] {
214            let mut bad = request.clone();
215            bad.target = target.into();
216            assert!(bad.validate().is_err(), "{target}");
217        }
218        for timeout in [0, MAX_TIMEOUT_MS + 1] {
219            let mut bad = request.clone();
220            bad.timeout_ms = timeout;
221            assert!(bad.validate().is_err());
222        }
223    }
224
225    #[test]
226    fn directed_events_have_no_request_timeout_or_sender_identity() {
227        let input = json!({"to":{"nodeType":"camera","nodeId":"c"},"target":"/plugin/source/changed","version":"v1","payload":{"revision":8}});
228        serde_json::from_value::<PluginEvent>(input.clone())
229            .unwrap()
230            .validate()
231            .unwrap();
232        let mut bad = input;
233        bad["timeoutMs"] = json!(1000);
234        assert!(serde_json::from_value::<PluginEvent>(bad).is_err());
235    }
236
237    #[test]
238    fn access_is_explicit_typed_and_bound_to_advertised_routes() {
239        let mut description: crate::NodeDescription = serde_json::from_value(json!({
240            "schemaVersion":crate::NODE_DESCRIBE_SCHEMA_VERSION,"nodeType":"example",
241            "serviceId":"example","serviceVersion":"1.0.0","instancePolicy":"multiple",
242            "routes":["/plugin/source/list","/plugin/source/changed"],"appAccess":{},
243            "capabilities":[],"details":{}
244        }))
245        .unwrap();
246        assert_eq!(
247            PluginAccess::from_description(&description).unwrap(),
248            PluginAccess::default()
249        );
250        description.details.insert(
251            ACCESS_DETAIL.into(),
252            json!({"requests":["/plugin/source/list"],"events":["/plugin/source/changed"]}),
253        );
254        let access = PluginAccess::from_description(&description).unwrap();
255        assert_eq!(access.requests, ["/plugin/source/list"]);
256        assert_eq!(access.events, ["/plugin/source/changed"]);
257        for bad in [
258            json!({"requests":["/plugin/missing"]}),
259            json!({"requests":["/plugin/source/list","/plugin/source/list"]}),
260            json!({"requests":["/app/plugin/remove"]}),
261            json!({"request":[]}),
262            Value::Null,
263        ] {
264            description
265                .details
266                .insert(ACCESS_DETAIL.into(), bad.clone());
267            assert!(
268                PluginAccess::from_description(&description).is_err(),
269                "{bad}"
270            );
271        }
272    }
273}