scxml 0.2.0

W3C SCXML statechart library — parse, validate, export, and simulate Harel statecharts. Framework-agnostic, WASM-ready, rkyv zero-copy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Input sanitization and limits for untrusted SCXML.
//!
//! When accepting SCXML from external sources (PUT endpoints, file uploads,
//! admin editors), use [`parse_untrusted`](crate::parse::sanitize::parse_untrusted) instead of `parse_xml` to
//! enforce size limits and reject potentially dangerous content.

use crate::error::{Result, ScxmlError};
use crate::model::Statechart;

/// Limits for untrusted SCXML input.
#[derive(Debug, Clone)]
pub struct InputLimits {
    /// Maximum input size in bytes (default: 1 MB).
    pub max_input_bytes: usize,
    /// Maximum total number of states (default: 10,000).
    pub max_states: usize,
    /// Maximum nesting depth (default: 20).
    pub max_depth: usize,
    /// Maximum number of transitions (default: 100,000).
    pub max_transitions: usize,
    /// Maximum total number of actions across all states (default: 100,000).
    pub max_actions: usize,
}

impl Default for InputLimits {
    fn default() -> Self {
        Self {
            max_input_bytes: 1_048_576, // 1 MB
            max_states: 10_000,
            max_depth: 20,
            max_transitions: 100_000,
            max_actions: 100_000,
        }
    }
}

/// Parse and validate SCXML from an untrusted source with input limits.
///
/// ```rust
/// use scxml::sanitize::{parse_untrusted, InputLimits};
///
/// let xml = r#"
///     <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
///         <state id="a"><transition event="go" target="b"/></state>
///         <final id="b"/>
///     </scxml>
/// "#;
/// let chart = parse_untrusted(xml, &InputLimits::default()).unwrap();
/// assert_eq!(chart.initial.as_str(), "a");
/// ```
///
/// Checks:
/// 1. Input size within `max_input_bytes`
/// 2. Rejects XML with `<!DOCTYPE` (prevents entity expansion attacks)
/// 3. Parses the SCXML
/// 4. Validates structural correctness and liveness
/// 5. Enforces state count, transition count, and depth limits
/// 6. Validates that all identifiers contain only safe characters
///
/// Returns the validated `Statechart` or an error.
#[cfg(feature = "xml")]
pub fn parse_untrusted(xml: &str, limits: &InputLimits) -> Result<Statechart> {
    // 1. Size check.
    if xml.len() > limits.max_input_bytes {
        return Err(ScxmlError::Xml(format!(
            "input too large: {} bytes (limit: {})",
            xml.len(),
            limits.max_input_bytes
        )));
    }

    // 2. Reject DOCTYPE declarations (prevents billion laughs, entity bombs).
    if xml.contains("<!DOCTYPE") || xml.contains("<!ENTITY") {
        return Err(ScxmlError::Xml(
            "DOCTYPE and ENTITY declarations are not allowed in untrusted input".into(),
        ));
    }

    // 3. Parse.
    let chart = crate::parse::xml::parse_xml(xml)?;

    // 4. Validate.
    crate::validate::validate(&chart)?;

    // 5. Enforce limits.
    let stats = crate::stats::stats(&chart);

    if stats.total_states > limits.max_states {
        return Err(ScxmlError::Xml(format!(
            "too many states: {} (limit: {})",
            stats.total_states, limits.max_states
        )));
    }

    if stats.total_transitions > limits.max_transitions {
        return Err(ScxmlError::Xml(format!(
            "too many transitions: {} (limit: {})",
            stats.total_transitions, limits.max_transitions
        )));
    }

    if stats.max_depth > limits.max_depth {
        return Err(ScxmlError::Xml(format!(
            "nesting too deep: {} (limit: {})",
            stats.max_depth, limits.max_depth
        )));
    }

    if stats.total_actions > limits.max_actions {
        return Err(ScxmlError::Xml(format!(
            "too many actions: {} (limit: {})",
            stats.total_actions, limits.max_actions
        )));
    }

    // 6. Validate all string fields contain only safe characters.
    validate_identifier(&chart.initial, "chart initial")?;
    if let Some(name) = &chart.name {
        validate_identifier(name, "chart name")?;
    }

    // Datamodel items.
    for item in &chart.datamodel.items {
        validate_identifier(&item.id, "data item id")?;
        // expr and src are freeform values, but reject control characters and
        // obvious injection patterns.
        if let Some(expr) = &item.expr {
            validate_freeform(expr, "data expr")?;
        }
        if let Some(src) = &item.src {
            validate_freeform(src, "data src")?;
        }
    }

    for state in chart.iter_all_states() {
        validate_identifier(&state.id, "state id")?;
        if let Some(init) = &state.initial {
            validate_identifier(init, "state initial")?;
        }

        for t in &state.transitions {
            if let Some(event) = &t.event {
                validate_identifier(event, "event name")?;
            }
            if let Some(guard) = &t.guard {
                validate_identifier(guard, "guard name")?;
            }
            for target in &t.targets {
                validate_identifier(target, "transition target")?;
            }
            if let Some(delay) = &t.delay {
                validate_delay(delay)?;
            }

            // Action fields.
            for action in &t.actions {
                validate_action(action)?;
            }
        }

        // Entry/exit actions.
        for action in &state.on_entry {
            validate_action(action)?;
        }
        for action in &state.on_exit {
            validate_action(action)?;
        }
    }

    Ok(chart)
}

/// Check that an identifier contains only safe characters.
///
/// Allows: alphanumeric, underscore, hyphen, dot, colon (for namespaced IDs).
/// Rejects: quotes, angle brackets, semicolons, backticks, control characters,
/// and anything else that could be used for injection.
fn validate_identifier(id: &str, context: &str) -> Result<()> {
    if id.is_empty() {
        return Err(ScxmlError::Xml(format!("empty {context}")));
    }

    if id.len() > 256 {
        return Err(ScxmlError::Xml(format!(
            "{context} '{}...' too long ({} chars, max 256)",
            &id[..32],
            id.len()
        )));
    }

    for ch in id.chars() {
        if !matches!(ch, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '-' | '.' | ':') {
            return Err(ScxmlError::Xml(format!(
                "{context} '{id}' contains unsafe character '{ch}'"
            )));
        }
    }

    Ok(())
}

/// Validate a delay string looks like an ISO 8601 duration.
/// Accepts: strings starting with P (e.g. PT30M, P1D, PT48H).
fn validate_delay(delay: &str) -> Result<()> {
    if delay.is_empty() {
        return Err(ScxmlError::Xml("empty delay value".into()));
    }
    if !delay.starts_with('P') {
        return Err(ScxmlError::Xml(format!(
            "delay '{delay}' is not a valid ISO 8601 duration (must start with 'P')"
        )));
    }
    // Check for safe characters only (digits, letters used in durations, dot for decimals).
    for ch in delay.chars() {
        if !matches!(
            ch,
            'P' | 'T' | 'Y' | 'M' | 'W' | 'D' | 'H' | 'S' | '0'..='9' | '.'
        ) {
            return Err(ScxmlError::Xml(format!(
                "delay '{delay}' contains invalid character '{ch}'"
            )));
        }
    }
    Ok(())
}

/// Validate an action's string fields.
fn validate_action(action: &crate::model::Action) -> Result<()> {
    use crate::model::ActionKind;
    match &action.kind {
        ActionKind::Raise { event } => {
            validate_identifier(event, "raise event")?;
        }
        ActionKind::Send {
            event,
            target,
            delay,
        } => {
            validate_identifier(event, "send event")?;
            if let Some(t) = target {
                validate_freeform(t, "send target")?;
            }
            if let Some(d) = delay {
                validate_delay(d)?;
            }
        }
        ActionKind::Assign { location, expr } => {
            validate_identifier(location, "assign location")?;
            validate_freeform(expr, "assign expr")?;
        }
        ActionKind::Log { label, expr } => {
            if let Some(l) = label {
                validate_freeform(l, "log label")?;
            }
            if let Some(e) = expr {
                validate_freeform(e, "log expr")?;
            }
        }
        ActionKind::Cancel { sendid } => {
            validate_identifier(sendid, "cancel sendid")?;
        }
        ActionKind::If { branches, actions } => {
            for branch in branches {
                if let Some(ref guard) = branch.guard {
                    validate_freeform(guard, "if/elseif cond")?;
                }
            }
            for a in actions {
                validate_action(a)?;
            }
        }
        ActionKind::Foreach {
            array,
            item,
            index,
            actions,
        } => {
            validate_freeform(array, "foreach array")?;
            validate_identifier(item, "foreach item")?;
            if let Some(idx) = index {
                validate_identifier(idx, "foreach index")?;
            }
            for a in actions {
                validate_action(a)?;
            }
        }
        ActionKind::Script { content } => {
            validate_freeform(content, "script content")?;
        }
        ActionKind::Invoke {
            invoke_type,
            src,
            id,
        } => {
            if let Some(t) = invoke_type {
                validate_freeform(t, "invoke type")?;
            }
            if let Some(s) = src {
                validate_freeform(s, "invoke src")?;
            }
            if let Some(i) = id {
                validate_identifier(i, "invoke id")?;
            }
        }
        ActionKind::Custom { name, .. } => {
            validate_identifier(name, "custom action name")?;
        }
        #[allow(unreachable_patterns)]
        _ => {} // Forward-compatible: unknown variants pass through.
    }
    Ok(())
}

/// Validate a freeform string value (expressions, URIs, labels).
/// More permissive than identifiers but rejects control characters
/// and obvious injection patterns.
fn validate_freeform(value: &str, context: &str) -> Result<()> {
    if value.len() > 4096 {
        return Err(ScxmlError::Xml(format!(
            "{context} too long ({} chars, max 4096)",
            value.len()
        )));
    }
    for ch in value.chars() {
        if ch.is_control() && ch != '\n' && ch != '\r' && ch != '\t' {
            return Err(ScxmlError::Xml(format!(
                "{context} contains control character U+{:04X}",
                ch as u32
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    const VALID_SCXML: &str = r#"
        <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
            <state id="a"><transition event="go" target="b"/></state>
            <final id="b"/>
        </scxml>
    "#;

    #[test]
    fn valid_input_passes() {
        let chart = parse_untrusted(VALID_SCXML, &InputLimits::default());
        assert!(chart.is_ok());
    }

    #[test]
    fn rejects_oversized_input() {
        let limits = InputLimits {
            max_input_bytes: 10,
            ..Default::default()
        };
        let err = parse_untrusted(VALID_SCXML, &limits).unwrap_err();
        assert!(err.to_string().contains("too large"));
    }

    #[test]
    fn rejects_doctype() {
        let xml = r#"
            <!DOCTYPE foo [<!ENTITY xxe "boom">]>
            <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
                <state id="a"/>
            </scxml>
        "#;
        let err = parse_untrusted(xml, &InputLimits::default()).unwrap_err();
        assert!(err.to_string().contains("DOCTYPE"));
    }

    #[test]
    fn rejects_too_many_states() {
        let limits = InputLimits {
            max_states: 1,
            ..Default::default()
        };
        let err = parse_untrusted(VALID_SCXML, &limits).unwrap_err();
        assert!(err.to_string().contains("too many states"));
    }

    #[test]
    fn rejects_unsafe_characters_in_id() {
        let xml = r#"
            <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a&lt;b">
                <state id="a&lt;b"><transition event="go" target="c"/></state>
                <final id="c"/>
            </scxml>
        "#;
        // quick-xml will unescape &lt; to < which our validator should catch.
        let result = parse_untrusted(xml, &InputLimits::default());
        assert!(result.is_err());
    }

    #[test]
    fn rejects_script_injection_in_guard() {
        let xml = r#"
            <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="a">
                <state id="a">
                    <transition event="go" target="b" cond="x'; DROP TABLE users;--"/>
                </state>
                <final id="b"/>
            </scxml>
        "#;
        let err = parse_untrusted(xml, &InputLimits::default()).unwrap_err();
        assert!(err.to_string().contains("unsafe character"));
    }

    #[test]
    fn allows_namespaced_ids() {
        let xml = r#"
            <scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="approval.quant.review">
                <state id="approval.quant.review">
                    <transition event="approve" target="done" cond="approval.quant.signed_off"/>
                </state>
                <final id="done"/>
            </scxml>
        "#;
        assert!(parse_untrusted(xml, &InputLimits::default()).is_ok());
    }
}