Skip to main content

core_api/
ingress.rs

1//! Transport-independent ingress rules. Identity always comes from the authenticated host session.
2use crate::{
3    ErrorResponse, ExceptionCode, MwsMessage, MwsMessageType, ServiceCoreInput, ServiceCoreResponse,
4};
5use std::time::Duration;
6
7pub const CORE_REQUEST_TIMEOUT: Duration = Duration::from_secs(60);
8pub const IPC_TIMEOUT_GRACE: Duration = Duration::from_secs(5);
9
10/// Rust validation may build a bundle for 180s. Leave time for analysis and the
11/// Core -> cloud round trip; callers add their own transport grace outside this.
12pub const SCRIPT_VALIDATION_TIMEOUT: Duration = Duration::from_secs(205);
13
14/// Select a longer budget only for validation carrying companion source. This
15/// recognizes wire envelopes, not authorization: ingress still validates them.
16pub fn script_validation_timeout(target: &str, payload: &str) -> Option<Duration> {
17    let (target, forwarded) = target
18        .strip_prefix("/invoke")
19        .or_else(|| target.strip_prefix("/dispatch/agent"))
20        .or_else(|| target.strip_prefix("/dispatch"))
21        .map_or((target, false), |target| (target, true));
22    if !matches!(
23        target,
24        "/app/automation/verify"
25            | "/bridge/automation/parse"
26            | "/bridge/automation/format"
27            | "/bridge/automation/verify"
28            | "/automation/format"
29    ) {
30        return None;
31    }
32    let root: serde_json::Value = serde_json::from_str(payload).ok()?;
33    let input = if forwarded {
34        root.get("call")?.get("input")?
35    } else if target.starts_with("/app/") {
36        root.get("input")?
37    } else {
38        &root
39    };
40    let scripts = input.get("script")?.get("scripts")?.as_object()?;
41    (!scripts.is_empty()).then_some(SCRIPT_VALIDATION_TIMEOUT)
42}
43
44pub fn request_timeout(target: &str) -> Duration {
45    match target {
46        "/harness/test/session/open" => Duration::from_secs(150),
47        _ => CORE_REQUEST_TIMEOUT,
48    }
49}
50
51pub fn input_timeout(input: &ServiceCoreInput) -> Duration {
52    match input {
53        ServiceCoreInput::ClientRequest {
54            target, payload, ..
55        }
56        | ServiceCoreInput::ConversationRequest {
57            target, payload, ..
58        }
59        | ServiceCoreInput::NodeRequest {
60            target, payload, ..
61        } => script_validation_timeout(target, payload).unwrap_or_else(|| request_timeout(target)),
62        _ => CORE_REQUEST_TIMEOUT,
63    }
64}
65
66pub struct NodeSession<'a> {
67    pub connection_key: &'a str,
68    pub tenant_id: &'a str,
69    pub scope_id: &'a str,
70    pub node_type: &'a str,
71    pub node_id: &'a str,
72}
73
74pub fn node_input(
75    request: &MwsMessage,
76    session: NodeSession<'_>,
77) -> Result<ServiceCoreInput, ErrorResponse> {
78    let target = request.target.as_deref().unwrap_or_default();
79    if target.is_empty() {
80        return Err(ErrorResponse::new(
81            ExceptionCode::BadRequest,
82            "target is required",
83        ));
84    }
85    let payload = request
86        .payload
87        .as_deref()
88        .filter(|p| !p.is_empty())
89        .unwrap_or("{}");
90    if target == crate::node::status::STATUS_CHANGED_TARGET {
91        let status = serde_json::from_str(payload).map_err(|error| {
92            ErrorResponse::new(
93                ExceptionCode::BadRequest,
94                format!("invalid Node status payload: {error}"),
95            )
96        })?;
97        return Ok(ServiceCoreInput::NodeStatusObserved {
98            connection_key: session.connection_key.into(),
99            status: Box::new(status),
100        });
101    }
102    Ok(ServiceCoreInput::NodeRequest {
103        target: target.into(),
104        payload: payload.into(),
105        control: request.control.clone(),
106        tenant_id: session.tenant_id.into(),
107        scope_id: session.scope_id.into(),
108        node_type: session.node_type.into(),
109        node_id: session.node_id.into(),
110    })
111}
112
113/// Apply at the outer boundary, including authorization and validation failures.
114pub fn node_reply<T>(message_type: &str, response: Option<T>) -> Option<T> {
115    if message_type == MwsMessageType::NODE_DATA {
116        None
117    } else {
118        response
119    }
120}
121
122pub fn node_response(
123    request: &MwsMessage,
124    scope_id: &str,
125    result: Result<Option<ServiceCoreResponse>, ErrorResponse>,
126) -> Option<MwsMessage> {
127    let result = result.and_then(|response| match response {
128        Some(ServiceCoreResponse::NodeRequest { response_payload }) => {
129            Ok(response_payload.unwrap_or_else(|| "{}".into()))
130        }
131        Some(ServiceCoreResponse::Ack { handled: true })
132            if request.target.as_deref() == Some(crate::node::status::STATUS_CHANGED_TARGET) =>
133        {
134            Ok("{}".into())
135        }
136        _ => Err(ErrorResponse::new(
137            ExceptionCode::Internal,
138            "unexpected Core response for Node request",
139        )),
140    });
141    let (payload, error) = match result {
142        Ok(payload) => (Some(payload), None),
143        Err(error) => (None, Some(error)),
144    };
145    node_reply(
146        request.r#type.as_deref().unwrap_or_default(),
147        Some(MwsMessage {
148            scope_id: Some(scope_id.into()),
149            from: None,
150            target: request.target.clone(),
151            sig: request.sig.clone(),
152            r#type: Some(MwsMessageType::NODE_RESP.into()),
153            payload,
154            error,
155            control: None,
156            client_info: None,
157        }),
158    )
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    #[test]
165    fn rust_validation_budgets_follow_exact_routes_and_wire_envelopes() {
166        let input =
167            serde_json::json!({"script":{"script":"task: []","scripts":{"lighting":"source"}}});
168        let call = serde_json::json!({"control":{"mode":"direct"},"input":input});
169        for prefix in ["", "/invoke", "/dispatch", "/dispatch/agent"] {
170            let payload = if prefix.is_empty() {
171                call.clone()
172            } else {
173                serde_json::json!({"call":call})
174            };
175            assert_eq!(
176                script_validation_timeout(
177                    &format!("{prefix}/app/automation/verify"),
178                    &payload.to_string()
179                ),
180                Some(SCRIPT_VALIDATION_TIMEOUT)
181            );
182        }
183        for target in [
184            "/bridge/automation/parse",
185            "/bridge/automation/verify",
186            "/bridge/automation/format",
187            "/automation/format",
188        ] {
189            assert_eq!(
190                script_validation_timeout(target, &input.to_string()),
191                Some(SCRIPT_VALIDATION_TIMEOUT)
192            );
193        }
194        for payload in [
195            "invalid",
196            "{}",
197            r#"{"input":{"script":{"scripts":{}}}}"#,
198            r#"{"input":{"script":{"scripts":[]}}}"#,
199            r#"{"script":{"scripts":{"f":"source"}}}"#,
200        ] {
201            assert_eq!(
202                script_validation_timeout("/app/automation/verify", payload),
203                None
204            );
205        }
206        for target in [
207            "/app/automation/save",
208            "/app/automation/start",
209            "/app/automation/verify/extra",
210            "/app/room/list",
211        ] {
212            assert_eq!(script_validation_timeout(target, &call.to_string()), None);
213        }
214        let request = ServiceCoreInput::NodeRequest {
215            target: "/app/automation/verify".into(),
216            payload: call.to_string(),
217            control: None,
218            tenant_id: "tenant".into(),
219            scope_id: "scope".into(),
220            node_type: "test".into(),
221            node_id: "node".into(),
222        };
223        assert_eq!(input_timeout(&request), SCRIPT_VALIDATION_TIMEOUT);
224    }
225    fn request(target: &str, kind: &str, payload: &str) -> MwsMessage {
226        serde_json::from_value(serde_json::json!({"target":target,"type":kind,"payload":payload,"scopeId":"untrusted","sig":"s"})).unwrap()
227    }
228    fn session() -> NodeSession<'static> {
229        NodeSession {
230            connection_key: "connection",
231            tenant_id: "tenant",
232            scope_id: "scope",
233            node_type: "camera",
234            node_id: "node",
235        }
236    }
237    #[test]
238    fn regular_node_input_uses_authenticated_identity() {
239        match node_input(&request("/x", MwsMessageType::NODE_REQ, ""), session()).unwrap() {
240            ServiceCoreInput::NodeRequest {
241                tenant_id,
242                scope_id,
243                node_id,
244                payload,
245                ..
246            } => {
247                assert_eq!(
248                    (
249                        tenant_id.as_str(),
250                        scope_id.as_str(),
251                        node_id.as_str(),
252                        payload.as_str()
253                    ),
254                    ("tenant", "scope", "node", "{}")
255                );
256            }
257            _ => panic!("wrong input"),
258        }
259    }
260    #[test]
261    fn invalid_status_is_not_forwarded_as_an_ordinary_request() {
262        let error = node_input(
263            &request(
264                crate::node::status::STATUS_CHANGED_TARGET,
265                MwsMessageType::NODE_DATA,
266                "{}",
267            ),
268            session(),
269        )
270        .unwrap_err();
271        assert_eq!(error.error, ExceptionCode::BadRequest.as_str());
272    }
273    #[test]
274    fn status_uses_the_transport_connection_not_payload_identity() {
275        let payload = serde_json::json!({
276            "contract":crate::node::STATUS_CONTRACT,"serviceId":"camera","nodeType":"camera",
277            "processGeneration":"process","revision":1,"process":"running","updatedAtMs":1,
278            "instance":{"nodeId":"node","runtimeId":"r","hubId":"h","tenantId":"tenant","scopeId":"scope",
279                "identity":"commissioned","hub":"resolved","connection":"connected","runtime":"ready",
280                "runtimeGeneration":1,"connectionGeneration":1,"revision":1,"effective":"online","updatedAtMs":1},
281            "runtime":{"runtimeId":"r","runtime":"ready","generation":1,"revision":1,"updatedAtMs":1},
282            "connectionKey":"forged"
283        });
284        let request = request(
285            crate::node::status::STATUS_CHANGED_TARGET,
286            MwsMessageType::NODE_REQ,
287            &payload.to_string(),
288        );
289        match node_input(&request, session()).unwrap() {
290            ServiceCoreInput::NodeStatusObserved {
291                connection_key,
292                status,
293            } => {
294                assert_eq!(connection_key, "connection");
295                assert_eq!(status.instance.node_id, "node");
296            }
297            _ => panic!("status must use the status manager input"),
298        }
299        let response = node_response(
300            &request,
301            "scope",
302            Ok(Some(ServiceCoreResponse::Ack { handled: true })),
303        )
304        .unwrap();
305        assert_eq!(response.payload.as_deref(), Some("{}"));
306        assert!(response.error.is_none());
307    }
308    #[test]
309    fn windows_pipe_names_are_bounded_and_workdir_specific() {
310        use crate::external_core_pipe_name as name;
311        use std::path::Path;
312        assert_eq!(
313            name(Path::new("C:/Meow/dev/core.sock")),
314            name(Path::new(r"c:\meow\dev\core.sock"))
315        );
316        assert_ne!(
317            name(Path::new("C:/Meow/dev/core.sock")),
318            name(Path::new("C:/Meow/prod/core.sock"))
319        );
320        assert!(name(Path::new(&"a".repeat(5000))).len() < 256);
321    }
322    #[test]
323    fn reports_never_reply_and_requests_preserve_error_details() {
324        let error = ErrorResponse::new(ExceptionCode::PreconditionFail, "expired")
325            .with_details(serde_json::json!({"preparedActionStatus":"expired"}));
326        for target in ["", "/x", crate::node::status::STATUS_CHANGED_TARGET] {
327            assert!(node_response(
328                &request(target, MwsMessageType::NODE_DATA, "{}"),
329                "scope",
330                Err(error.clone())
331            )
332            .is_none());
333        }
334        let response = node_response(
335            &request("/x", MwsMessageType::NODE_REQ, "{}"),
336            "scope",
337            Err(error.clone()),
338        )
339        .unwrap();
340        assert_eq!(
341            serde_json::to_value(response.error.unwrap()).unwrap(),
342            serde_json::to_value(error).unwrap()
343        );
344        assert!(node_reply(MwsMessageType::NODE_DATA, Some("unauthorized")).is_none());
345    }
346    #[test]
347    fn ipc_budget_covers_core_budget_including_long_requests() {
348        assert_eq!(
349            request_timeout("/app/plugin/camera/device/settings/update").as_secs(),
350            60
351        );
352        assert_eq!(request_timeout("/harness/test/session/open").as_secs(), 150);
353        assert!(IPC_TIMEOUT_GRACE > Duration::ZERO);
354    }
355}