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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
//! Issue #500: end-to-end handler coverage for the script-failure response contracts (throwing
//! inject/predicate/decorate — issues #355/#440/#323/#375 — and, issue #499, their timeout
//! counterparts that map to 504 + `x-rift-script-timeout`).
//!
//! The equivalent parity tests already exist as integration binaries under
//! `crates/rift-http-proxy/tests/` (issue_355/440/323/375), but CI's main job runs
//! `cargo test --workspace --all-features --lib`, and `--lib` excludes every `tests/*.rs` binary —
//! so those contracts had no CI-run coverage (tracked as #510). These tests drive the full handler
//! through a real listener (`ImposterManager` + reqwest) and assert status/headers/body shape per
//! contract, and CI runs them via a dedicated `--test handler_error_responses` step.
//!
//! They live in their own integration binary — a SEPARATE PROCESS with its own MB JS script pool —
//! rather than in the rift-mock-core lib test binary, so they don't contend for the shared script pool
//! with the timing-sensitive bounded-matcher unit tests (whose runaway-script cases park pool
//! workers; co-locating server tests there starves the 60s inject-matching deadline under CI load).

#![cfg(feature = "javascript")]

use rift_mock_core::imposter::ImposterManager;
use std::time::Duration;

/// Creates the imposter on an auto-assigned port and returns it (issue #1438): the manager keeps
/// the probe listener bound, so two concurrent runs of this file can never share a port.
async fn create(manager: &ImposterManager, cfg: serde_json::Value) -> u16 {
    let config = serde_json::from_value(cfg).expect("config");
    let port = manager.create_imposter(config).await.expect("create");
    // Give the listener a moment to bind before the request (matches the sibling HTTP tests).
    tokio::time::sleep(Duration::from_millis(150)).await;
    port
}

async fn get(port: u16) -> reqwest::Response {
    reqwest::Client::new()
        .get(format!("http://127.0.0.1:{port}/x"))
        .send()
        .await
        .expect("send")
}

/// Issue #687: a door that serves the canonical JSON envelope must also declare it. The proxy doors
/// (#681) and the admin plane already did, so the same `{"errors":[...]}` envelope reached clients
/// typed on one path and untyped on another. Asserted per door rather than once, so a door added
/// later that forgets the header fails here rather than shipping the inconsistency again.
fn assert_json_content_type(resp: &reqwest::Response, door: &str) {
    assert_eq!(
        resp.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/json"),
        "the {door} door serves the JSON error envelope, so it must declare content-type"
    );
}

// Contract 1: a throwing response `inject` → 500 (issue #1581) Mountebank error body + inject-error header.
#[tokio::test]
async fn throwing_inject_response_returns_500() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "inject": "function (config) { throw new Error('boom-inject'); }" }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        500,
        "a throwing inject is a 500, as in Mountebank"
    );
    assert!(resp.headers().contains_key("x-rift-imposter"));
    assert!(
        resp.headers().contains_key("x-rift-inject-error"),
        "the inject-error marker header must be present"
    );
    assert_json_content_type(&resp, "response inject error");
    let body: serde_json::Value = resp.json().await.expect("json body");
    assert_eq!(body["errors"][0]["code"], "invalid injection");
    assert_eq!(
        body["errors"][0]["data"], "boom-inject",
        "data is the thrown error's message, got: {body}"
    );
    assert!(
        body["errors"][0]["message"]
            .as_str()
            .is_some_and(|m| m.contains("boom-inject")),
        "error message must surface the script failure, got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// Contract 2 (lenient): a throwing `decorate` → the original response is still served (status +
// body unchanged) with an `x-rift-decorate-error` signal header, not a 500.
#[tokio::test]
async fn decorate_error_lenient_serves_undecorated_with_header() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": "function (request, response) { throw new Error('boom-decorate'); }" } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    let status = resp.status();
    let has_header = resp.headers().contains_key("x-rift-decorate-error");
    let body = resp.text().await.expect("body");
    assert_eq!(
        status, 200,
        "lenient decorate failure still serves the original response"
    );
    assert!(
        has_header,
        "the undecorated response must carry x-rift-decorate-error"
    );
    assert_eq!(
        body, "original",
        "the original (undecorated) body is served"
    );

    let _ = manager.delete_imposter(port).await;
}

// Contract 2 (strict): the same failing `decorate` under `strictBehaviors` → 500, the fallback
// body is NOT served, and the signal header is still present.
#[tokio::test]
async fn decorate_error_strict_returns_500() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true, "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": "function (request, response) { throw new Error('boom-decorate'); }" } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    let status = resp.status();
    let has_header = resp.headers().contains_key("x-rift-decorate-error");
    assert_json_content_type(&resp, "strict decorate error");
    let body = resp.text().await.expect("body");
    assert_eq!(status, 500, "strict decorate failure fails loud with 500");
    assert!(has_header, "the 500 must still carry x-rift-decorate-error");
    assert_ne!(
        body, "original",
        "the fallback body must NOT be served in strict mode"
    );
    assert!(
        body.contains("decorate failed"),
        "the 500 body must name the strict decorate failure, got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// Contract 3: a throwing predicate `inject` (matcher error) → 500 with the DISTINCT
// "invalid predicate injection" code (vs "invalid injection" for a response inject), and the
// inject-error header. Any other matcher error keeps the 5xx backend mapping (unit-tested in
// handler.rs `matcher_error_response_tests`, since a listener test can't easily provoke it).
#[tokio::test]
async fn predicate_inject_error_returns_500() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "predicates": [{ "inject": "function (config) { throw new Error('boom-predicate'); }" }],
                  "responses": [{ "is": { "statusCode": 200, "body": "unreached" } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 500, "a throwing predicate inject is a 500");
    assert!(resp.headers().contains_key("x-rift-inject-error"));
    assert_json_content_type(&resp, "predicate inject error");
    let body: serde_json::Value = resp.json().await.expect("json body");
    assert_eq!(
        body["errors"][0]["code"], "invalid predicate injection",
        "matcher inject error uses the DISTINCT predicate-injection code, got: {body}"
    );
    assert!(
        body["errors"][0]["message"]
            .as_str()
            .is_some_and(|m| m.contains("boom-predicate")),
        "error message must surface the predicate script failure, got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// Issue #499: a script hook that exceeds its wall-clock deadline is a transient 504 carrying the
// `x-rift-script-timeout` marker — distinct from the 400/500 a genuinely broken script returns, so
// monitoring can tell a retry-worthy timeout apart from a permanent config error.
//
// Which timeout paths are E2E-tested here vs unit-tested elsewhere, and why: a timeout can only be
// exercised end-to-end with a script that actually outlasts the deadline. For the Boa (JavaScript)
// hooks — response `inject` and predicate `inject` — that means a CPU busy-loop, and because Boa
// has no per-instruction interrupt the loop keeps running (parking a shared MB-script-pool worker)
// well past the point where the client is released with its 504. Under CI's parallel execution
// those busy-loops parked every pool worker for long enough to starve the throwing-inject/predicate
// tests of a worker until the job was cancelled. So the Boa timeout paths are covered by fast,
// deterministic UNIT tests instead — `imposter::handler::matcher_error_response_tests`
// (predicate → 504) and `imposter::handler::inject_timeout_response` (the shared inject/predicate
// 504 body+headers) — while the two paths that CAN self-interrupt or run off the MB pool are tested
// here end-to-end: `_rift.script` (Rhai `loop {}`, abort-interruptible → frees its thread at the
// deadline) and `decorate` (Rhai, which runs on the large `spawn_blocking` pool, not the MB pool,
// so its parked thread cannot starve the shared-pool tests).
const SLOW_RHAI_LOOP: &str = "let i = 0; while i < 500000 { i += 1; }";

// AC3: a `_rift.script` that misses the deadline → 504 + `x-rift-script-error` + timeout marker;
// a broken script still returns 500 (Rhai `loop {}` is abort-interruptible, freeing its thread).
#[tokio::test]
async fn rift_script_timeout_returns_504() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "_rift": { "scriptEngine": { "timeoutMs": 50 } },
            "stubs": [
                { "responses": [{ "_rift": { "script": { "engine": "rhai", "code": "let i = 0; loop { i += 1; }" } } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        504,
        "a _rift.script deadline miss is a 504, not the broken-script 500"
    );
    assert!(resp.headers().contains_key("x-rift-script-error"));
    assert!(resp.headers().contains_key("x-rift-script-timeout"));
    assert_json_content_type(&resp, "script timeout");
    let body = resp.text().await.expect("body");
    assert!(
        body.contains("Script timeout"),
        "the 504 body must name the timeout, got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// AC4 (lenient): a decorate that misses the deadline still serves the original response, now with
// BOTH `x-rift-decorate-error` and the timeout marker.
#[tokio::test]
async fn decorate_timeout_lenient_serves_original_with_markers() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "_rift": { "scriptEngine": { "timeoutMs": 5 } },
            "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": SLOW_RHAI_LOOP } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    let status = resp.status();
    let has_decorate_err = resp.headers().contains_key("x-rift-decorate-error");
    let has_timeout = resp.headers().contains_key("x-rift-script-timeout");
    let body = resp.text().await.expect("body");
    assert_eq!(
        status, 200,
        "lenient decorate timeout still serves the original response"
    );
    assert!(
        has_decorate_err,
        "the response must carry x-rift-decorate-error"
    );
    assert!(
        has_timeout,
        "a decorate timeout adds x-rift-script-timeout on top of the decorate-error marker"
    );
    assert_eq!(
        body, "original",
        "the original (undecorated) body is served"
    );

    let _ = manager.delete_imposter(port).await;
}

// AC4 (strict): the same decorate timeout under `strictBehaviors` → 504 (not the broken-script
// 500), with both markers.
#[tokio::test]
async fn decorate_timeout_strict_returns_504() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true,
            "_rift": { "scriptEngine": { "timeoutMs": 5 } },
            "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": SLOW_RHAI_LOOP } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    let status = resp.status();
    let has_decorate_err = resp.headers().contains_key("x-rift-decorate-error");
    let has_timeout = resp.headers().contains_key("x-rift-script-timeout");
    assert_json_content_type(&resp, "strict decorate timeout");
    let body = resp.text().await.expect("body");
    assert_eq!(
        status, 504,
        "strict decorate timeout is a 504, not the broken-script 500"
    );
    assert!(has_decorate_err, "the 504 must carry x-rift-decorate-error");
    assert!(has_timeout, "the 504 must carry x-rift-script-timeout");
    assert_ne!(
        body, "original",
        "the fallback body must NOT be served in strict mode"
    );

    let _ = manager.delete_imposter(port).await;
}

// ---------------------------------------------------------------------------
// Issue #682: these doors hand-built their JSON by interpolating the error into a string literal,
// so a message holding a `"` produced a body the client could not decode (the #611 class), in a
// legacy `{"error"}` shape that 0.13.6/#681 had unified everywhere else. Assert the envelope AND
// that a quoted message survives — a script's error text is user JavaScript, so quotes are ordinary.
// ---------------------------------------------------------------------------

/// The canonical envelope, parsed. Panics with the raw body when it is not valid JSON — which is
/// exactly the pre-#682 failure for a quoted message.
fn envelope(body: &str) -> serde_json::Value {
    serde_json::from_str(body)
        .unwrap_or_else(|e| panic!("body must be valid JSON ({e}), got: {body}"))
}

// A rhai script whose error message carries quotes, the way real user code reads:
//   throw new Error('expected "ready", got "pending"')
#[tokio::test]
async fn script_error_with_quotes_yields_valid_json_envelope() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "stubs": [
                { "responses": [{ "_rift": { "script": { "engine": "rhai",
                  "code": r#"fn respond(ctx) { throw `expected "ready", got "pending"`; }"# } } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 500, "a broken script is a 500");
    assert!(resp.headers().contains_key("x-rift-script-error"));
    assert_json_content_type(&resp, "script error");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
    let msg = v["errors"][0]["message"]
        .as_str()
        .expect("message is a string");
    assert!(
        msg.contains("Script error:"),
        "message keeps its prefix, got: {msg}"
    );
    assert!(
        msg.contains(r#""ready""#),
        "the quoted text must survive escaping intact, got: {msg}"
    );
    assert!(v.get("error").is_none(), "the legacy shape must be gone");

    let _ = manager.delete_imposter(port).await;
}

#[tokio::test]
async fn script_timeout_body_is_the_canonical_envelope() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "_rift": { "scriptEngine": { "timeoutMs": 50 } },
            "stubs": [
                { "responses": [{ "_rift": { "script": { "engine": "rhai", "code": "let i = 0; loop { i += 1; }" } } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 504, "a deadline miss stays a 504");
    // The markers are the contract #499 established — the envelope change must not disturb them.
    assert!(resp.headers().contains_key("x-rift-script-error"));
    assert!(resp.headers().contains_key("x-rift-script-timeout"));
    assert_json_content_type(&resp, "script timeout");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "504", "envelope code is the status");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("Script timeout"),
        "the 504 must still name the timeout: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

#[tokio::test]
async fn strict_decorate_error_body_is_the_canonical_envelope() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true, "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": "function (request, response) { throw new Error('boom-decorate'); }" } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 500);
    assert!(resp.headers().contains_key("x-rift-decorate-error"));
    assert_json_content_type(&resp, "strict decorate error");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("decorate failed"),
        "the strict failure must still be named: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// A static body (no error interpolated) — always valid JSON before and after, so this covers only
// the shape half of the change. Note this door's marker is `x-rift-imposter-disabled`, NOT the
// usual `x-rift-imposter`; the envelope change must not quietly normalise it.
#[tokio::test]
async fn disabled_imposter_body_is_the_canonical_envelope() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "never served" } }] }
            ]
        }),
    )
    .await;
    manager
        .get_imposter(port)
        .expect("imposter exists")
        .set_enabled(false);

    let resp = get(port).await;
    assert_eq!(resp.status(), 503);
    assert!(resp.headers().contains_key("x-rift-imposter-disabled"));
    assert_json_content_type(&resp, "disabled imposter");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "503");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("disabled"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// The decorate door is the only one whose status is a VARIABLE (500 when the script throws, 504
// when it misses the deadline), and the same variable feeds the envelope's `code`. That coupling is
// what the CHANGELOG claims, so it gets pinned: its two neighbours (shellTransform, binary decode)
// pass a hardcoded 500, and "harmonising" this site to match them would ship a 504 whose body says
// `"code": "500"` — with every other test still green.
#[tokio::test]
async fn strict_decorate_timeout_envelope_code_follows_the_504() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true,
            "_rift": { "scriptEngine": { "timeoutMs": 5 } },
            "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "decorate": SLOW_RHAI_LOOP } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 504, "a strict decorate timeout is a 504");
    assert_json_content_type(&resp, "strict decorate timeout");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(
        v["errors"][0]["code"], "504",
        "the envelope code must track the door's OWN status, not a hardcoded 500: {body}"
    );
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("decorate failed"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// ---------------------------------------------------------------------------
// Issue #687: the remaining envelope doors, which had no end-to-end coverage at all — so the
// content-type they now declare is pinned here rather than assumed. One door is not reachable from
// here: the template door fires only under `RIFT_DEBUG`, a process-global these parallel tests
// cannot toggle without racing each other, so it is pinned by a unit test instead
// (`handler::template_error_tests`).
// ---------------------------------------------------------------------------

// The over-size door is reached before any stub matching, by exceeding the configured body
// ceiling (issue #1439). One byte over, with a known length: the refusal precedes the body, so the
// 413 arrives instead of a reset.
#[tokio::test]
async fn oversize_request_body_door_declares_json() {
    let manager = ImposterManager::new().with_body_limits(
        rift_mock_core::imposter::body_limits::BodyLimits::new(1024 * 1024, None)
            .expect("valid limits"),
    );
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "never served" } }] }
            ]
        }),
    )
    .await;

    let resp = reqwest::Client::new()
        .post(format!("http://127.0.0.1:{port}/x"))
        .body(vec![b'x'; 1024 * 1024 + 1])
        .send()
        .await
        .expect("send");
    assert_eq!(resp.status(), 413, "an over-size body is a 413");
    assert_json_content_type(&resp, "over-size request body");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "413");

    let _ = manager.delete_imposter(port).await;
}

#[tokio::test]
async fn strict_shelltransform_door_declares_json() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true, "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "original" },
                  "_behaviors": { "shellTransform": ["rift-no-such-command-687"] } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        500,
        "a strict shellTransform failure is a 500"
    );
    assert!(resp.headers().contains_key("x-rift-shelltransform-error"));
    assert_json_content_type(&resp, "strict shellTransform error");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("shellTransform failed"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

#[tokio::test]
async fn strict_binary_decode_door_declares_json() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "strictBehaviors": true, "stubs": [
                { "responses": [{ "is": { "statusCode": 200, "body": "not!valid!base64", "_mode": "binary" } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        500,
        "a strict base64 decode failure is a 500"
    );
    assert!(resp.headers().contains_key("x-rift-binary-error"));
    assert_json_content_type(&resp, "strict binary decode error");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("binary base64 decode failed"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// The unresolved-script door. `file:`/`ref:` sources are populated by the config-time resolve pass,
// which lives in rift-http-proxy — `ImposterManager::create_imposter` (what `create()` calls here,
// and what an embedded/FFI host calls) never runs it. So a stub declaring `file:` arrives with
// `code: None` and takes this door, rather than silently serving an empty script.
#[tokio::test]
async fn unresolved_script_door_declares_json() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "_rift": { "script": { "engine": "rhai",
                  "file": "never-resolved-687.rhai" } } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 500, "an unresolved script source is a 500");
    assert!(resp.headers().contains_key("x-rift-script-error"));
    assert_json_content_type(&resp, "unresolved file:/ref: script");
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("script not resolved"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}

// Issue #1556: an unrecognised `fault` is ignored, as in Mountebank (`helpers.js:104-106` logs it
// and writes nothing, then `baseHttpServer.js` writes the post-processed response). So the answer
// is an empty response, `200` with no body when the imposter has no `defaultResponse`. It is not a
// fault, so it carries no `x-rift-fault`, and not an error, so it is no envelope either.
#[tokio::test]
async fn unknown_fault_is_ignored_as_an_empty_200() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "fault": "NOT_A_REAL_FAULT" }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 200, "an unknown fault is ignored, not a 500");
    assert!(
        !resp.headers().contains_key("x-rift-fault"),
        "no fault fired, so no fault header"
    );
    assert!(resp.headers().contains_key("x-rift-imposter"));
    assert_ne!(
        resp.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/json"),
        "nothing was written, so nothing is labelled JSON"
    );
    assert_eq!(resp.text().await.expect("body"), "");

    let _ = manager.delete_imposter(port).await;
}

// Issue #1556: the empty response is completed by `defaultResponse` (Mountebank's `postProcess`),
// and it is a matched stub's answer, so it carries no `x-rift-default-response` marker.
#[tokio::test]
async fn unknown_fault_is_completed_by_default_response() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "defaultResponse": { "statusCode": 418, "headers": { "X-D": "1" }, "body": "dflt" },
            "stubs": [ { "responses": [{ "fault": "NOPE" }] } ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        418,
        "the defaultResponse status completes it"
    );
    assert_eq!(
        resp.headers().get("x-d").and_then(|v| v.to_str().ok()),
        Some("1")
    );
    assert!(!resp.headers().contains_key("x-rift-fault"));
    assert!(
        !resp.headers().contains_key("x-rift-default-response"),
        "a stub matched, so this is not a default-response answer"
    );
    assert_eq!(resp.text().await.expect("body"), "dflt");

    let _ = manager.delete_imposter(port).await;
}

// Issue #1556: `repeat` still counts on an ignored fault, so the cycle advances after two.
#[tokio::test]
async fn unknown_fault_honours_repeat() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "defaultResponse": { "statusCode": 418 },
            "stubs": [ { "responses": [
                { "fault": "NOPE", "repeat": 2 },
                { "is": { "body": "second" } }
            ] } ]
        }),
    )
    .await;

    let mut seen = Vec::new();
    for _ in 0..3 {
        let resp = get(port).await;
        let status = resp.status().as_u16();
        seen.push((status, resp.text().await.expect("body")));
    }
    assert_eq!(
        seen,
        vec![
            (418, String::new()),
            (418, String::new()),
            (418, "second".to_string())
        ]
    );

    let _ = manager.delete_imposter(port).await;
}

// Issue #1556: a binary `defaultResponse` completes the ignored fault decoded, as it does an
// unmatched request.
#[tokio::test]
async fn unknown_fault_decodes_a_binary_default_response() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http",
            "defaultResponse": { "body": "aGk=", "_mode": "binary" },
            "stubs": [ { "responses": [{ "fault": "NOPE" }] } ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(resp.status(), 200);
    assert!(!resp.headers().contains_key("x-rift-binary-error"));
    assert_eq!(resp.bytes().await.expect("body").as_ref(), b"hi");

    let _ = manager.delete_imposter(port).await;
}

// Issue #695: the terminal "Response build error" door — reached when a stub's own header value is
// one hyper rejects (here a newline), so building the response fails — now serves the canonical
// envelope like every other imposter error door, not a bare plain-text string. Drives a live door
// end-to-end, proving the config path actually routes through the shared fallback.
#[tokio::test]
async fn response_build_error_door_declares_json() {
    let manager = ImposterManager::new();
    let port = create(
        &manager,
        serde_json::json!({
            "protocol": "http", "stubs": [
                { "responses": [{ "is": {
                    "statusCode": 200,
                    "headers": { "X-Bad": "line1\nline2" },
                    "body": "unreached"
                } }] }
            ]
        }),
    )
    .await;

    let resp = get(port).await;
    assert_eq!(
        resp.status(),
        500,
        "a response that cannot be built is a 500"
    );
    assert_eq!(
        resp.headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok()),
        Some("application/json"),
        "the build-error door serves the JSON envelope now"
    );
    let body = resp.text().await.expect("body");
    let v = envelope(&body);
    assert_eq!(v["errors"][0]["code"], "500");
    assert!(
        v["errors"][0]["message"]
            .as_str()
            .expect("string")
            .contains("Response build error"),
        "got: {body}"
    );

    let _ = manager.delete_imposter(port).await;
}