rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Stub script validation for Admin API.
//!
//! Validates scripts in stub responses before they are added to imposters,
//! ensuring syntax errors and missing functions are caught at configuration time
//! rather than at request time.

use super::validator::ScriptValidator;
use crate::imposter::{RiftScriptConfig, Stub, StubResponse};
use std::fmt;

/// Error type for stub script validation
#[derive(Debug, Clone)]
pub struct StubValidationError {
    /// Stub identifier (id or index)
    pub stub_id: String,
    /// Response index within the stub
    pub response_index: usize,
    /// Script engine type
    pub engine: String,
    /// Detailed error message
    pub message: String,
}

impl fmt::Display for StubValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Invalid {} script in stub '{}' response {}: {}",
            self.engine, self.stub_id, self.response_index, self.message
        )
    }
}

impl std::error::Error for StubValidationError {}

/// Result of validating stubs
#[derive(Debug)]
pub struct StubValidationResult {
    pub errors: Vec<StubValidationError>,
}

impl StubValidationResult {
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn into_error_message(self) -> Option<String> {
        if self.errors.is_empty() {
            None
        } else {
            Some(
                self.errors
                    .iter()
                    .map(|e| e.to_string())
                    .collect::<Vec<_>>()
                    .join("; "),
            )
        }
    }
}

/// Validates all scripts in a list of stubs
pub fn validate_stubs(stubs: &[Stub]) -> StubValidationResult {
    let mut errors = Vec::new();

    for (stub_idx, stub) in stubs.iter().enumerate() {
        let stub_id = stub
            .id
            .clone()
            .unwrap_or_else(|| format!("stub[{stub_idx}]"));

        for (resp_idx, response) in stub.responses.iter().enumerate() {
            if let Some(err) = validate_response(response, &stub_id, resp_idx) {
                errors.push(err);
            }
        }
    }

    StubValidationResult { errors }
}

/// Validates scripts in a single stub
pub fn validate_stub(stub: &Stub, stub_index: usize) -> StubValidationResult {
    let mut errors = Vec::new();

    let stub_id = stub
        .id
        .clone()
        .unwrap_or_else(|| format!("stub[{stub_index}]"));

    for (resp_idx, response) in stub.responses.iter().enumerate() {
        if let Some(err) = validate_response(response, &stub_id, resp_idx) {
            errors.push(err);
        }
    }

    StubValidationResult { errors }
}

/// Validates a single stub response for script errors
fn validate_response(
    response: &StubResponse,
    stub_id: &str,
    response_index: usize,
) -> Option<StubValidationError> {
    match response {
        // Rift script responses (_rift.script)
        StubResponse::RiftScript { rift, .. } => rift.script.as_ref().and_then(|script_config| {
            validate_rift_script_config(script_config, stub_id, response_index)
        }),
        // Is responses with optional _rift extension
        StubResponse::Is { rift, .. } => rift.as_ref().and_then(|rift_ext| {
            rift_ext.script.as_ref().and_then(|script_config| {
                validate_rift_script_config(script_config, stub_id, response_index)
            })
        }),
        // JavaScript inject responses
        StubResponse::Inject { inject, .. } => {
            validate_inject_script(inject, stub_id, response_index)
        }
        // Proxy and Fault responses don't have inline scripts to validate
        StubResponse::Proxy { .. } | StubResponse::Fault { .. } => None,
    }
}

/// Validates a single `_rift.script` config. `code`/`file`/`ref` exactly-one is checked
/// unconditionally; the syntax check only runs against `code` — a `file`/`ref` source is
/// unresolved here (that happens in the config-time resolve-scripts pass, issue #356) so an
/// unresolved script is structurally checked but not syntax-checked by this call site.
fn validate_rift_script_config(
    script_config: &RiftScriptConfig,
    stub_id: &str,
    response_index: usize,
) -> Option<StubValidationError> {
    if !script_config.has_valid_source() {
        return Some(StubValidationError {
            stub_id: stub_id.to_string(),
            response_index,
            engine: script_config.engine.clone().unwrap_or_default(),
            message: format!(
                "script must specify exactly one of `code`, `file`, `ref`, or `component` (found {})",
                script_config.source_count()
            ),
        });
    }
    // `instance` (issue #1793): a name this engine knows, on a wasm script only. Checked when
    // admitted, never decoded, so a stored config carrying a bad value still loads.
    if let Some(instance) = script_config.instance.as_deref() {
        let is_wasm = script_config.component.is_some()
            || script_config
                .engine
                .as_deref()
                .is_some_and(super::ScriptEngineKind::is_wasm);
        let message = if !matches!(instance, "request" | "imposter") {
            Some(format!(
                "wasm instance \"{instance}\" is not supported; use \"request\" or \"imposter\""
            ))
        } else if !is_wasm {
            Some("`instance` applies only to engine \"wasm\"".to_string())
        } else {
            None
        };
        if let Some(message) = message {
            return Some(StubValidationError {
                stub_id: stub_id.to_string(),
                response_index,
                engine: script_config.engine.clone().unwrap_or_default(),
                message,
            });
        }
    }
    if let Some(component) = script_config.component.as_deref() {
        let refused = |message: String| {
            Some(StubValidationError {
                stub_id: stub_id.to_string(),
                response_index,
                engine: "wasm".to_string(),
                message,
            })
        };
        if let Err(e) = component.parse::<crate::imposter::components::ComponentId>() {
            return refused(e.to_string());
        }
        // The bytes are resolved when served, so only the name is checked here: an export the
        // component lacks is a script error on the request (issue #1758).
        if let Some(export) = script_config.export.as_deref()
            && !matches!(export, "rift" | "http")
        {
            return refused(format!(
                "wasm export \"{export}\" is not supported; use \"rift\" or \"http\""
            ));
        }
        return match script_config.engine.as_deref() {
            None => None,
            Some(engine) if super::ScriptEngineKind::is_wasm(engine) => None,
            Some(other) => refused(format!(
                "`component` is a wasm component; engine must be \"wasm\", not \"{other}\""
            )),
        };
    }
    let code = script_config.code.as_deref()?;
    let engine = script_config.engine.as_deref().unwrap_or("rhai");
    validate_rift_script(
        engine,
        code,
        script_config.export.as_deref(),
        stub_id,
        response_index,
    )
}

/// Validates a Rift script (_rift.script) using the appropriate validator
fn validate_rift_script(
    engine: &str,
    code: &str,
    export: Option<&str>,
    stub_id: &str,
    response_index: usize,
) -> Option<StubValidationError> {
    use super::{EngineNameError, ScriptEngineKind};
    let refused = |engine: &str, message: String| {
        Some(StubValidationError {
            stub_id: stub_id.to_string(),
            response_index,
            engine: engine.to_string(),
            message,
        })
    };
    match ScriptEngineKind::parse(engine) {
        Ok(ScriptEngineKind::Rhai) => validate_with_validator(
            &super::RhaiValidator::new(),
            code,
            "rhai",
            stub_id,
            response_index,
        ),
        #[cfg(feature = "javascript")]
        Ok(ScriptEngineKind::JavaScript) => validate_with_validator(
            &super::JsValidator::new(),
            code,
            "javascript",
            stub_id,
            response_index,
        ),
        #[cfg(not(feature = "javascript"))]
        Ok(ScriptEngineKind::JavaScript) => refused(
            "javascript",
            "JavaScript engine is not enabled (requires 'javascript' feature)".to_string(),
        ),
        #[cfg(not(feature = "wasm"))]
        Ok(ScriptEngineKind::Wasm) => {
            let _ = export;
            refused("wasm", super::WASM_UNAVAILABLE.to_string())
        }
        // Compiles and links the component (issue #1751): a core module, an import Rift does not
        // provide and a missing `rift:mock/handler` are refused here, and the cache is warm.
        #[cfg(feature = "wasm")]
        Ok(ScriptEngineKind::Wasm) => match super::wasm::admit(code, export) {
            Ok(()) => None,
            Err(e) => refused("wasm", e.to_string()),
        },
        Err(removed @ EngineNameError::Removed) => refused("lua", removed.to_string()),
        Err(EngineNameError::Unknown(other)) => {
            let message = format!("Unknown script engine type: '{other}'");
            refused(&other, message)
        }
    }
}

/// Generic validation using the ScriptValidator trait
fn validate_with_validator<V: ScriptValidator>(
    validator: &V,
    code: &str,
    engine: &str,
    stub_id: &str,
    response_index: usize,
) -> Option<StubValidationError> {
    match validator.validate(code) {
        Ok(()) => None,
        Err(e) => Some(StubValidationError {
            stub_id: stub_id.to_string(),
            response_index,
            engine: engine.to_string(),
            message: e.to_string(),
        }),
    }
}

/// Validates a Mountebank inject script
fn validate_inject_script(
    code: &str,
    stub_id: &str,
    response_index: usize,
) -> Option<StubValidationError> {
    #[cfg(feature = "javascript")]
    {
        use boa_engine::{Script, Source};

        // Parse only, never evaluate (issue #1183): this runs inline on the admin request task, and
        // evaluating ran user code there with no loop or time budget. The wrapper is the one
        // `execute_mountebank_inject` runs, so what parses here is what the engine will compile.
        let wrapper = format!("var __injectFn = {code};");
        let mut context = crate::scripting::js_engine::sealed_js_context();
        match Script::parse(Source::from_bytes(wrapper.as_bytes()), None, &mut context) {
            Ok(_) => None,
            Err(e) => Some(StubValidationError {
                stub_id: stub_id.to_string(),
                response_index,
                engine: "javascript (inject)".to_string(),
                message: format!("Syntax error: {e}"),
            }),
        }
    }

    #[cfg(not(feature = "javascript"))]
    {
        let _ = (code, stub_id, response_index);
        // If JavaScript feature is not enabled, inject responses won't work at runtime anyway
        // but we can't validate them. We'll let them pass here and fail at runtime.
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::{RiftResponseExtension, RiftScriptConfig};

    fn make_rift_script_stub(engine: &str, code: &str) -> Stub {
        Stub {
            name: None,
            id: Some("test-stub".to_string()),
            route_pattern: None,
            predicates: vec![],
            responses: vec![StubResponse::RiftScript {
                rift: Box::new(RiftResponseExtension {
                    dataset: None,
                    conditional: None,
                    fault: None,
                    script: Some(RiftScriptConfig {
                        engine: Some(engine.to_string()),
                        code: Some(code.to_string()),
                        file: None,
                        ref_name: None,
                        ..Default::default()
                    }),
                    templated: false,
                    state_ops: Vec::new(),
                }),
                ignored_behaviors: None,
            }],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        }
    }

    // Issue #1758: a `component` reference's bytes are resolved when served, but an `export` name
    // that is neither "rift" nor "http" is refused when the stub is admitted.
    #[test]
    fn a_component_reference_with_an_unknown_export_is_refused() {
        let with_export = |export: &str| {
            let mut stub = make_rift_script_stub("wasm", "");
            if let StubResponse::RiftScript { rift, .. } = &mut stub.responses[0]
                && let Some(script) = rift.script.as_mut()
            {
                script.code = None;
                script.component = Some(format!("sha256:{}", "ab".repeat(32)));
                script.export = Some(export.to_string());
            }
            stub
        };
        for ok in ["rift", "http"] {
            assert!(validate_stub(&with_export(ok), 0).is_valid(), "{ok}");
        }
        let refused = validate_stub(&with_export("grpc"), 0);
        assert!(
            refused.errors[0]
                .message
                .contains("wasm export \"grpc\" is not supported"),
            "{:?}",
            refused.errors
        );
    }

    // Issue #1793: `instance` is "request" or "imposter", on a wasm script only.
    #[test]
    fn instance_is_refused_unknown_or_off_wasm() {
        let with = |engine: &str, instance: &str| {
            let mut stub = make_rift_script_stub(engine, "fn respond(ctx) { pass() }");
            if let StubResponse::RiftScript { rift, .. } = &mut stub.responses[0]
                && let Some(script) = rift.script.as_mut()
            {
                script.instance = Some(instance.to_string());
                if engine == "wasm" {
                    script.code = None;
                    script.component = Some(format!("sha256:{}", "ab".repeat(32)));
                }
            }
            stub
        };
        for ok in ["request", "imposter"] {
            assert!(validate_stub(&with("wasm", ok), 0).is_valid(), "{ok}");
        }
        let unknown = validate_stub(&with("wasm", "forever"), 0);
        assert!(
            unknown.errors[0]
                .message
                .contains("wasm instance \"forever\" is not supported"),
            "{:?}",
            unknown.errors
        );
        let off_wasm = validate_stub(&with("rhai", "imposter"), 0);
        assert!(
            off_wasm.errors[0]
                .message
                .contains("applies only to engine \"wasm\""),
            "{:?}",
            off_wasm.errors
        );
    }

    /// Its callers are all `javascript`-gated, so this helper is too — it is otherwise dead in a
    /// `--no-default-features` test build (issue #1000).
    #[cfg(feature = "javascript")]
    fn make_inject_stub(code: &str) -> Stub {
        Stub {
            name: None,
            id: Some("inject-stub".to_string()),
            route_pattern: None,
            predicates: vec![],
            responses: vec![StubResponse::new_inject(code.to_string(), None, None)],
            scenario_name: None,
            required_scenario_state: None,
            new_scenario_state: None,
            space: None,
            recorded_from: None,
            recorded_at: None,
            verify: None,
        }
    }

    #[test]
    fn test_valid_rhai_script() {
        let stub = make_rift_script_stub("rhai", r#"fn respond(ctx) { pass() }"#);
        let result = validate_stub(&stub, 0);
        assert!(
            result.is_valid(),
            "Valid Rhai script should pass: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_invalid_rhai_syntax() {
        let stub = make_rift_script_stub(
            "rhai",
            r#"fn respond(ctx) { http(200, "#, // Missing closing
        );
        let result = validate_stub(&stub, 0);
        assert!(!result.is_valid(), "Invalid syntax should fail");
        assert!(result.errors[0].message.contains("Syntax error"));
    }

    #[test]
    fn test_v2_script_without_should_inject_is_valid() {
        // Issue #453: validation is syntax-only now — a script that never defines
        // `should_inject` (the removed v1 wrapper) validates fine. Entrypoint-matching
        // happens at request time / via `rift script check`, not here.
        let stub = make_rift_script_stub("rhai", r#"fn other_function(x) { x + 1 }"#);
        let result = validate_stub(&stub, 0);
        assert!(
            result.is_valid(),
            "Script without should_inject should validate: {:?}",
            result.errors
        );
    }

    #[test]
    fn test_unknown_engine() {
        let stub = make_rift_script_stub("unknown_engine", "some code");
        let result = validate_stub(&stub, 0);
        assert!(!result.is_valid(), "Unknown engine should fail");
        assert!(result.errors[0].message.contains("Unknown script engine"));
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn test_valid_inject_script() {
        let stub = make_inject_stub(r#"function(config, state) { return { statusCode: 200 }; }"#);
        let result = validate_stub(&stub, 0);
        assert!(
            result.is_valid(),
            "Valid inject script should pass: {:?}",
            result.errors
        );
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn test_invalid_inject_syntax() {
        let stub = make_inject_stub(
            r#"function(config, state) { return { statusCode: "#, // Missing closing
        );
        let result = validate_stub(&stub, 0);
        assert!(!result.is_valid(), "Invalid inject syntax should fail");
    }

    // Issue #1183: validation parses, it does not run. A throw is the non-hanging stand-in for
    // `while(true){}`: before the fix this ran at the admin door and was refused with "ran".
    #[cfg(feature = "javascript")]
    #[test]
    fn an_inject_is_not_executed_by_validation() {
        let stub = make_inject_stub("(function(){ throw new Error('ran'); })()");
        let result = validate_stub(&stub, 0);
        assert!(result.is_valid(), "{:?}", result.errors);
    }

    // Issue #1183: a top-level loop used to run on the admin request task (17 s for this shape at
    // 5M iterations); parse-only is effectively instant. Kept modest so a regression fails, not hangs.
    #[cfg(feature = "javascript")]
    #[test]
    fn a_top_level_loop_in_an_inject_does_not_run_at_validation() {
        let stub = make_inject_stub(
            "(function(){ for (var i = 0; i < 2000000; i++) { Math.sqrt(i); } \
             return function (c) { return {}; }; })()",
        );
        let started = std::time::Instant::now();
        let result = validate_stub(&stub, 0);
        assert!(result.is_valid(), "{:?}", result.errors);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "took {:?}",
            started.elapsed()
        );
    }

    // Issue #1183: what only evaluation would catch is admitted, and fails per request instead —
    // as `42` always did.
    #[cfg(feature = "javascript")]
    #[test]
    fn a_syntactically_valid_non_function_inject_is_admitted() {
        for code in ["undefinedIdentifier", "42"] {
            let result = validate_stub(&make_inject_stub(code), 0);
            assert!(result.is_valid(), "{code}: {:?}", result.errors);
        }
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn a_syntax_error_in_an_inject_is_reported_as_one() {
        let result = validate_stub(&make_inject_stub("function (config) { return 1 ]; }"), 0);
        let message = &result.errors.first().expect("refused").message;
        assert!(message.starts_with("Syntax error: "), "{message}");
    }

    #[test]
    fn test_multiple_stubs_validation() {
        // Create stubs without ids so they get indexed names
        let stubs = vec![
            Stub {
                name: None,
                id: None, // No id, will use stub[0]
                route_pattern: None,
                predicates: vec![],
                responses: vec![StubResponse::RiftScript {
                    rift: Box::new(RiftResponseExtension {
                        dataset: None,
                        conditional: None,
                        fault: None,
                        script: Some(RiftScriptConfig {
                            engine: Some("rhai".to_string()),
                            code: Some(r#"fn respond(ctx) { pass() }"#.to_string()),
                            file: None,
                            ref_name: None,
                            ..Default::default()
                        }),
                        templated: false,
                        state_ops: Vec::new(),
                    }),
                    ignored_behaviors: None,
                }],
                scenario_name: None,
                required_scenario_state: None,
                new_scenario_state: None,
                space: None,
                recorded_from: None,
                recorded_at: None,
                verify: None,
            },
            Stub {
                name: None,
                id: None, // No id, will use stub[1]
                route_pattern: None,
                predicates: vec![],
                responses: vec![StubResponse::RiftScript {
                    rift: Box::new(RiftResponseExtension {
                        dataset: None,
                        conditional: None,
                        fault: None,
                        script: Some(RiftScriptConfig {
                            engine: Some("rhai".to_string()),
                            code: Some(
                                r#"fn respond(ctx) { http(200, "#.to_string(), // Invalid
                            ),
                            file: None,
                            ref_name: None,
                            ..Default::default()
                        }),
                        templated: false,
                        state_ops: Vec::new(),
                    }),
                    ignored_behaviors: None,
                }],
                scenario_name: None,
                required_scenario_state: None,
                new_scenario_state: None,
                space: None,
                recorded_from: None,
                recorded_at: None,
                verify: None,
            },
        ];
        let result = validate_stubs(&stubs);
        assert!(!result.is_valid());
        assert_eq!(result.errors.len(), 1);
        assert!(
            result.errors[0].stub_id.contains("stub[1]"),
            "Expected stub[1], got: {}",
            result.errors[0].stub_id
        );
    }

    // Issue #450: Lua was removed; a `_rift.script` engine of "lua" always fails validation
    // with an actionable message pointing at the two remaining engines.
    #[test]
    fn test_lua_engine_removed() {
        let stub = make_rift_script_stub(
            "lua",
            r#"function should_inject(request, flow_store) return { inject = false } end"#,
        );
        let result = validate_stub(&stub, 0);
        assert!(!result.is_valid(), "lua engine must fail validation");
        assert!(result.errors[0].message.contains("removed"));
        assert!(result.errors[0].message.contains("rhai"));
        assert!(result.errors[0].message.contains("javascript"));
    }
}