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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
//! The response behavior pipeline: a response's behaviors program — every step, in order (issue
//! #1198) — applied to its status, headers and body.
//!
//! One function so every response type that carries behaviors runs the same pipeline with the
//! same failure contract (issue #1184): the `is`, `inject` and `proxy` serve paths call it.
use super::body_limits::BodyGuard;
use super::handler::{
SCRIPT_TIMEOUT_HEADER, lookup_budget_response, xpath_selector_error_response,
};
use super::headers::StubRef;
use super::response::{apply_decorate_bounded, body_text};
use super::types::{IsResponse, ResponseMode, StatusValue};
use crate::behaviors::{
BehaviorProgram, BehaviorStep, CsvCache, Decorated, LoadOutcome, RequestContext,
ResponseStatus, ShellTransformError, Spliced, SplicedHeaders, SplicedName, WaitScriptError,
apply_copy_spliced, apply_lookup_row, apply_shell_transform, lookup_key,
};
use crate::util::build_response_with_headers;
use bytes::Bytes;
use http_body_util::Full;
use hyper::{Response, StatusCode};
use std::cell::OnceCell;
use std::hash::BuildHasher;
use std::time::Duration;
use tracing::warn;
/// The parts of a response the pipeline reads and rewrites.
///
/// Body and header values carry which bytes the engine substituted in (issue #1203), so `copy` and
/// `lookup` never expand a token that arrived inside request text.
#[derive(Debug)]
pub(crate) struct ServedParts {
/// The status, unless `status_text` is set.
pub status: u16,
/// A `statusCode` string that is not a number (issue #1558): `copy` and `lookup` substitute
/// into it, `decorate` and `shellTransform` see it as a string, and it is read when the
/// response is written ([`super::status::resolve`]).
pub status_text: Option<Spliced>,
/// Multi-value (issue #238): one entry per header name, one element per header line.
pub headers: SplicedHeaders,
pub body: Spliced,
/// The body as the JSON value it was written as, when that is not a string (issue #1639): an
/// `is` body written as an object, array, number or boolean. A shellTransform reads it as
/// `MB_RESPONSE.body`, as Mountebank hands a command the response object, until a step rewrites
/// the body. `None` for a string body, which is its own text, for a binary one (base64 text in
/// both engines) and for an upstream's body (text in both).
pub typed_body: Option<serde_json::Value>,
}
impl ServedParts {
/// [`ServedParts::typed_body`] for a body written as `body` in `mode`.
pub(crate) fn typed_body_of(
body: Option<&serde_json::Value>,
mode: &ResponseMode,
) -> Option<serde_json::Value> {
body.filter(|body| !body.is_string() && *mode == ResponseMode::Text)
.cloned()
}
/// A response a script wrote, completed from the imposter's `defaultResponse` (issue #1369)
/// or, without one, from the built-in `200`, no headers and an empty body. What the script
/// wrote is its own text (issue #1203); a string status taken from the default is supplied
/// whole, since Mountebank merges the default after the behaviors (issue #1558).
pub(crate) fn completed(authored: &IsResponse, default: Option<&IsResponse>) -> Self {
let fallback = IsResponse::default();
let completed = authored.completed_by(default.unwrap_or(&fallback));
let status_text = completed.status_text.as_deref().map(|text| {
if authored.omitted.status_code {
Spliced::supplied(text.to_string())
} else {
Spliced::authored(text.to_string())
}
});
ServedParts {
status: completed.status_code,
status_text,
headers: completed
.headers
.iter()
.map(|(k, values)| {
(
k.as_str().into(),
values
.iter()
.map(|v| Spliced::authored(v.clone()))
.collect(),
)
})
.collect(),
body: Spliced::authored(body_text(completed.body.as_ref())),
typed_body: Self::typed_body_of(completed.body.as_ref(), &completed.mode),
}
}
}
/// What running the pipeline produced. A dropped `StrictFailure` would serve the response the
/// strict contract refused, so the outcome must be matched.
#[derive(Debug)]
#[must_use]
pub(crate) enum BehaviorOutcome {
/// The response to serve. `degraded` is true when a behavior failed under the lenient
/// contract (#269/#323): the response is served, but carries a signal header and is not the
/// response the configuration asked for.
Applied { parts: ServedParts, degraded: bool },
/// A behavior failed under `strictBehaviors` (#375), or failed in a way Mountebank always
/// answers with an error, as a `wait` function that throws (#1616): serve this error response
/// instead.
StrictFailure(Response<Full<Bytes>>),
}
/// The response for a request its imposter's delete cut off (issues #1616, #1643): a
/// `TcpFaultKind::Empty` carrier, so the listener closes the connection without writing a byte,
/// the one mechanism that already aborts a connection from a response. Over HTTP/1 the client sees the connection close before a
/// response, as when Mountebank destroys an imposter's sockets; over HTTP/2 the stream resets, on
/// every listener, and the connection ends through the shutdown already under way. An in-process
/// caller sees the
/// carrier, which [`tcp_fault_carrier`](super::fault_io::tcp_fault_carrier) names
/// `EMPTY_RESPONSE`.
pub(crate) fn aborted_response() -> Response<Full<Bytes>> {
let mut response = build_response_with_headers(
StatusCode::SERVICE_UNAVAILABLE,
[("x-rift-imposter", "true")],
Bytes::new(),
);
response
.extensions_mut()
.insert(super::fault_io::TcpFaultKind::Empty);
response
}
/// Mountebank's answer to a `wait` function that throws (issue #1616): `500` with
/// `{"errors":[{"code":"invalid injection","message":"invalid wait injection","data":...}]}`, as
/// its HTTP server writes an `InjectionError`. `data` is the thrown message, left out when the
/// thrown value has none. `type` reuses the frozen `invalid injection` slug (#797); `source`,
/// `name` and `stack` are left out, as on every Rift error envelope.
fn wait_error_response(e: &WaitScriptError) -> Response<Full<Bytes>> {
let kind = crate::response::ErrorKind::InvalidInjection.slug();
let mut error = serde_json::json!({
"code": kind,
"type": kind,
"message": "invalid wait injection",
});
if let Some(data) = &e.data {
error["data"] = data.as_str().into();
}
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-wait-error", "true"),
("content-type", "application/json"),
],
serde_json::json!({ "errors": [error] }).to_string(),
)
}
/// Everything the pipeline reads besides the response itself.
pub(crate) struct BehaviorRun<'a, SH> {
pub behaviors: &'a BehaviorProgram,
pub method: &'a str,
pub uri: &'a hyper::Uri,
pub request_headers: &'a indexmap::IndexMap<String, Vec<String>, SH>,
pub request_body: Option<&'a str>,
/// The body did not decode (issue #1584): `request_body` is `None`, and the behaviors see no
/// body rather than an empty one.
pub request_body_undefined: bool,
/// The client's socket, for `requestFrom` / `ip` in `decorate` and `MB_REQUEST` (issue #1451).
/// `None` only for a caller with no socket.
pub client_addr: Option<std::net::SocketAddr>,
pub script_scope: crate::scripting::ScriptScope,
/// What the imposter's scripts may `require()` (issue #1611).
pub script_files: std::sync::Arc<crate::imposter::ScriptFileAccess>,
pub stub: StubRef<'a>,
/// `'static` so a miss can be loaded and inserted on a blocking thread (issue #1654).
pub csv_cache: &'static CsvCache,
/// The imposter's body limits, under which a `lookup` reads its CSV file (issue #1654).
pub body_guard: &'a std::sync::Arc<BodyGuard>,
pub script_timeout: Duration,
pub strict: bool,
/// The imposter's `defaultResponse`: it completes a response a `decorate` returned (issue
/// #1567), as Mountebank completes every response it serves.
pub default_response: Option<&'a IsResponse>,
}
/// The `500` a `lookup` answers under `strictBehaviors` when loading its CSV file panicked.
fn lookup_panic_response(path: &str) -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::ErrorKind::BehaviorError,
&format!("lookup failed (strictBehaviors): loading CSV data source '{path}' failed"),
),
)
}
/// The response's headers as a script sees them in `MB_RESPONSE` (issue #1589): one string per
/// header, an array for a header with several lines.
fn headers_json(headers: &SplicedHeaders) -> serde_json::Value {
headers
.iter()
.map(|(name, lines)| {
let value = match lines.as_slice() {
[line] => line.as_str().into(),
lines => lines.iter().map(Spliced::as_str).collect(),
};
(name.to_string(), value)
})
.collect::<serde_json::Map<_, _>>()
.into()
}
/// A shellTransform's stdout as the response it replaces this one with (issue #1589): an object
/// is read as an `is` response, and any other value is an empty one, as Mountebank reads no field
/// of it. What the response leaves out is the default's.
fn shell_response(stdout: serde_json::Value) -> Result<IsResponse, ShellTransformError> {
if stdout.is_object() {
serde_json::from_value(stdout)
.map_err(|e| ShellTransformError::InvalidResponse(e.to_string()))
} else {
Ok(IsResponse::empty())
}
}
impl<SH: BuildHasher> BehaviorRun<'_, SH> {
/// Run the program's steps over `parts`, in order (issue #1198). A step that fails under the
/// lenient contract marks the response degraded and the next step still runs; under
/// `strictBehaviors` the first failure is the response.
pub(crate) async fn apply(&self, parts: ServedParts) -> BehaviorOutcome {
let ServedParts {
mut status,
mut status_text,
mut headers,
mut body,
typed_body,
} = parts;
// What `decorate` and `shellTransform` see as `statusCode`, as Mountebank hands it over.
let script_status = |status: u16, text: &Option<Spliced>| match text {
Some(text) => ResponseStatus::Text(text.as_str().to_string()),
None => ResponseStatus::Code(status),
};
let mut degraded = false;
// The body's JSON value: as the response was written (issue #1639), then as the last
// shellTransform or returned decorate object left it (#1589), so a command reads a number
// as a number, as in Mountebank. Used only while the body is still its rendering: any step
// that rewrites the body leaves text.
let mut shell_body = typed_body;
let still_typed = |shell_body: Option<serde_json::Value>, body: &Spliced| {
shell_body.filter(|value| body_text(Some(value)) == body.as_str())
};
// Lazy request context (issue #561): only copy/lookup/decorate/shellTransform read
// it, and `RequestContext::from_request` re-parses the query, clones a key and
// one value per header, and copies the body — so a wait/repeat-only stub must not pay
// for it.
//
// Built on first read rather than behind a hand-maintained "does anything below
// need this?" predicate: such a predicate has to be kept in sync with consumers
// 100+ lines away, and getting it wrong would hand one an empty-but-valid context —
// wrong output, no error. Here a consumer that forgets to ask simply cannot exist.
let request_context: OnceCell<RequestContext> = OnceCell::new();
let build_request_context = || RequestContext {
body_undefined: self.request_body_undefined,
..RequestContext::from_request(
self.method,
self.uri,
self.request_headers,
self.request_body,
self.client_addr,
)
};
// copy/lookup are pure token substitution — apply them across each value of
// multi-value headers so multiplicity survives (e.g. multiple Set-Cookie;
// RFC 7230 §3.2.2 forbids folding Set-Cookie). decorate uses a single-value
// JS/Rhai object model, so only that path collapses — and even there Set-Cookie
// is held aside, never comma-folded.
for step in &self.behaviors.steps {
match step {
BehaviorStep::Wait(wait) => {
// A wait function that throws is the response (issue #1616), with or without
// `strictBehaviors`: Mountebank has no lenient mode for it.
let wait_ms = match wait.get_duration_ms() {
Ok(ms) => ms,
Err(e) => return BehaviorOutcome::StrictFailure(wait_error_response(&e)),
};
if wait_ms > 0 {
// A delete cuts the wait off at the request's funnel (issues #1616, #1643).
tokio::time::sleep(Duration::from_millis(wait_ms)).await;
}
}
BehaviorStep::Copy(copy) => {
// An XPath `using` that fails when it runs is the response (issue #1585), with
// or without `strictBehaviors`: Mountebank's copy throws and fails the request.
if let Err(e) = apply_copy_spliced(
&mut body,
&mut headers,
&mut status_text,
std::slice::from_ref(copy),
request_context.get_or_init(build_request_context),
self.stub,
) {
return BehaviorOutcome::StrictFailure(xpath_selector_error_response(&e));
}
}
BehaviorStep::Lookup(lookup) => {
let key =
lookup_key(lookup, request_context.get_or_init(build_request_context));
if let Some(key) = key {
let csv = &lookup.from_data_source.csv;
// A cache hit, the common case, is served here. A miss reads and parses
// the file off the tokio worker (issue #1654), as shellTransform runs its
// command (#478): a large file would otherwise stall every request
// multiplexed on the worker. Concurrent misses on one file share that one
// load and its outcome (issue #1715).
let data = match self
.csv_cache
.fetch(
&csv.path,
&csv.delimiter,
std::sync::Arc::clone(&self.script_files),
std::sync::Arc::clone(self.body_guard),
)
.await
{
LoadOutcome::Loaded(loaded) => loaded,
// Server load, not a behavior failure: a `503` with or without
// `strictBehaviors`, never the tokens left in place quietly.
LoadOutcome::Exhausted(e) => {
return BehaviorOutcome::StrictFailure(lookup_budget_response(&e));
}
// A defect, not a data source fault: the response under
// `strictBehaviors`, as a failed shellTransform is; otherwise the
// tokens stay and the response is marked degraded.
LoadOutcome::Panicked(e) => {
tracing::error!(
"lookup behavior: loading CSV data source '{}' panicked: {e}; \
the tokens are left in place",
csv.path
);
if self.strict {
return BehaviorOutcome::StrictFailure(lookup_panic_response(
&csv.path,
));
}
degraded = true;
None
}
};
if let Some(data) = data {
apply_lookup_row(
&mut body,
&mut headers,
&mut status_text,
lookup,
&key,
&data,
self.stub,
);
}
}
}
BehaviorStep::Decorate(decorate_script) => {
// decorate uses a single-value JS/Rhai object model. Set-Cookie is held
// aside and never folded (RFC 7230 §3.2.2); other multi-value headers
// degrade to single-value for the script (issue #238 boundary) — warn so
// the collapse is not silent (e.g. WWW-Authenticate is also corrupted by
// comma-folding).
let is_set_cookie = |k: &str| k.eq_ignore_ascii_case("set-cookie");
let folded: Vec<&str> = headers
.iter()
.filter(|(k, v)| v.len() > 1 && !is_set_cookie(k))
.map(|(k, _)| k.as_str())
.collect();
if !folded.is_empty() {
warn!(
"decorate uses a single-value object model; multi-value headers \
{folded:?} are comma-folded (issue #238 boundary). Set-Cookie is \
exempt; other headers that forbid list-folding will be corrupted."
);
}
let set_cookie: Vec<(SplicedName, Vec<Spliced>)> = headers
.iter()
.filter(|(k, _)| is_set_cookie(k))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let single: crate::util::OrderedMap<String, String> = headers
.iter()
.filter(|(k, _)| !is_set_cookie(k))
.map(|(k, v)| {
let lines: Vec<&str> = v.iter().map(Spliced::as_str).collect();
(k.to_string(), lines.join(", "))
})
.collect();
match apply_decorate_bounded(
decorate_script.clone(),
request_context.get_or_init(build_request_context).clone(),
body.as_str().to_string(),
script_status(status, &status_text),
single,
self.script_scope.clone(),
self.stub.id.map(str::to_owned),
std::sync::Arc::clone(&self.script_files),
self.script_timeout,
)
.await
{
// A returned object replaces the response (issue #1567). Mountebank keeps
// nothing of the original, Set-Cookie included, and completes what the
// object leaves out from `defaultResponse`.
Ok(Decorated {
status_code,
headers: single,
body: new_body,
returned: Some(omits),
}) => {
let authored = IsResponse::decoded(
(!omits.status_code).then(|| match status_code {
ResponseStatus::Code(code) => StatusValue::Code(code),
ResponseStatus::Text(text) => StatusValue::Text(text.into()),
}),
(!omits.headers).then(|| {
single.into_iter().map(|(k, v)| (k, vec![v])).collect()
}),
(!omits.body).then_some(serde_json::Value::String(new_body)),
None,
);
let completed =
ServedParts::completed(&authored, self.default_response);
status = completed.status;
status_text = completed.status_text;
headers = completed.headers;
body = completed.body;
shell_body = completed.typed_body;
}
// A script's output is the author's text (issue #1203): ranges cannot
// survive an arbitrary rewrite, and the script is configuration.
Ok(Decorated {
status_code: new_status,
headers: single,
body: new_body,
returned: None,
}) => {
body = Spliced::authored(new_body);
match new_status {
ResponseStatus::Code(code) => {
status = code;
status_text = None;
}
ResponseStatus::Text(text) => {
status_text = Some(Spliced::authored(text));
}
}
// Restore the held-aside Set-Cookie lines unless the script set its
// own (case-insensitively) — a script override wins deterministically.
let script_set_cookie = single.keys().any(|k| is_set_cookie(k));
headers = single
.into_iter()
.map(|(k, v)| (k.into(), vec![Spliced::authored(v)]))
.collect();
if !script_set_cookie {
headers.extend(set_cookie);
}
}
// Behave as if decorate was absent: keep the original multi-value
// `headers` and pre-decorate body/status rather than serving a folded,
// undecorated response. Attach a visible signal so the skipped behavior
// isn't a silent success (issue #323); the body is still served (#269).
Err(e) => {
warn!("Decorate script error: {e}");
// A deadline miss (issue #499) carries `x-rift-script-timeout` and,
// under strict mode, a 504 rather than the broken-script 500 — so a
// retry-worthy timeout is distinguishable from a permanent failure.
let timed_out =
matches!(e, crate::behaviors::DecorateError::Timeout(_));
if self.strict {
let status = if timed_out {
StatusCode::GATEWAY_TIMEOUT
} else {
StatusCode::INTERNAL_SERVER_ERROR
};
let mut hdrs = vec![
("x-rift-imposter", "true"),
("x-rift-decorate-error", "true"),
("content-type", "application/json"),
];
if timed_out {
hdrs.push((SCRIPT_TIMEOUT_HEADER, "true"));
}
return BehaviorOutcome::StrictFailure(
build_response_with_headers(
status,
hdrs,
crate::response::error_body_typed(
status,
crate::response::ErrorKind::BehaviorError,
&format!("decorate failed (strictBehaviors): {e}"),
),
),
);
}
degraded = true;
headers.insert(
"x-rift-decorate-error".into(),
vec![Spliced::authored("true".to_string())],
);
if timed_out {
headers.insert(
SCRIPT_TIMEOUT_HEADER.into(),
vec![Spliced::authored("true".to_string())],
);
}
}
}
}
// shellTransform (issues #269, #1589): Mountebank's contract. The command gets the
// request and the response as `MB_REQUEST` / `MB_RESPONSE` and as two arguments,
// and its stdout is a JSON response that replaces this one, completed from
// `defaultResponse` like a returned decorate object (#1567).
BehaviorStep::ShellTransform(cmd) => {
let response_in = serde_json::json!({
"statusCode": script_status(status, &status_text).to_json(),
"headers": headers_json(&headers),
"body": still_typed(shell_body.clone(), &body)
.unwrap_or_else(|| body.as_str().into()),
});
// Run the fork/exec/wait off the tokio worker (issue #478): a synchronous
// subprocess run inline would stall the worker for its whole lifetime,
// starving unrelated requests multiplexed on it.
let shell_result = {
let cmd = cmd.clone();
let rc = request_context.get_or_init(build_request_context).clone();
// Plain `spawn_blocking`, not `spawn_blocking_annotated` (issue #987):
// `apply_shell_transform` is a fork/exec of an external command and never
// touches a `FlowStore`, so nothing here can annotate.
tokio::task::spawn_blocking(move || {
apply_shell_transform(&cmd, &rc, &response_in)
})
.await
.unwrap_or_else(|e| {
Err(ShellTransformError::Spawn(format!(
"shellTransform task panicked: {e}"
)))
})
.and_then(shell_response)
};
match shell_result {
Ok(authored) => {
let completed =
ServedParts::completed(&authored, self.default_response);
status = completed.status;
status_text = completed.status_text;
headers = completed.headers;
body = completed.body;
shell_body = completed.typed_body;
}
// Not a response (#1589), or the command failed: keep the response
// unchanged (issue #269) but signal the failure so it isn't a silent
// success (issue #323); a 500 under `strictBehaviors`.
Err(e) => {
warn!("shellTransform command {cmd:?} failed: {e}");
if self.strict {
return BehaviorOutcome::StrictFailure(
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-shelltransform-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::ErrorKind::BehaviorError,
&format!(
"shellTransform failed (strictBehaviors): {e}"
),
),
),
);
}
degraded = true;
headers.insert(
"x-rift-shelltransform-error".into(),
vec![Spliced::authored("true".to_string())],
);
}
}
}
}
}
BehaviorOutcome::Applied {
parts: ServedParts {
typed_body: still_typed(shell_body, &body),
status,
status_text,
headers,
body,
},
degraded,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::BodyExt;
use serde_json::json;
const STUB: StubRef<'static> = StubRef {
port: 4545,
index: 0,
id: None,
};
fn behaviors(block: serde_json::Value) -> BehaviorProgram {
BehaviorProgram::from_elements([&block]).expect("fixture block parses")
}
fn original() -> ServedParts {
ServedParts {
status: 201,
status_text: None,
headers: crate::behaviors::authored_headers(crate::imposter::Headers::from([(
"set-cookie".to_string(),
vec!["a=1".to_string(), "b=2".to_string()],
)])),
body: Spliced::authored("orig".to_string()),
typed_body: None,
}
}
async fn run(block: serde_json::Value, strict: bool) -> BehaviorOutcome {
run_with_default(block, strict, None).await
}
async fn run_with_default(
block: serde_json::Value,
strict: bool,
default_response: Option<&IsResponse>,
) -> BehaviorOutcome {
run_program(&behaviors(block), strict, default_response, original()).await
}
/// Run `behaviors` over `parts`.
async fn run_program(
behaviors: &BehaviorProgram,
strict: bool,
default_response: Option<&IsResponse>,
parts: ServedParts,
) -> BehaviorOutcome {
let uri: hyper::Uri = "/users/42?x=1".parse().expect("fixture uri");
let request_headers: crate::imposter::Headers = crate::imposter::Headers::new();
let csv_cache: &'static CsvCache = Box::leak(Box::new(CsvCache::new()));
BehaviorRun {
behaviors,
method: "GET",
uri: &uri,
request_headers: &request_headers,
request_body: None,
request_body_undefined: false,
client_addr: None,
script_scope: crate::scripting::ScriptScope::detached(4545),
script_files: std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
stub: STUB,
csv_cache,
body_guard: &std::sync::Arc::default(),
script_timeout: Duration::from_secs(5),
strict,
default_response,
}
.apply(parts)
.await
}
#[tokio::test]
async fn a_successful_transform_is_applied_and_not_degraded() {
let command = r#"printf '{"statusCode":201,"body":"transformed"}' #"#;
match run(json!({ "shellTransform": [command] }), false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(!degraded);
assert_eq!(parts.body, "transformed");
assert_eq!(parts.status, 201);
// The printed response replaces the original, headers included (#1589).
assert!(parts.headers.is_empty(), "{:?}", parts.headers);
}
BehaviorOutcome::StrictFailure(_) => {
panic!("nothing failed")
}
}
}
#[tokio::test]
async fn a_lenient_failure_serves_the_original_marked_and_degraded() {
match run(json!({ "shellTransform": ["exit 3"] }), false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(degraded, "a failed behavior must be reported as degraded");
assert_eq!(parts.body, "orig");
assert_eq!(parts.status, 201);
assert_eq!(parts.headers["x-rift-shelltransform-error"], vec!["true"]);
assert_eq!(parts.headers["set-cookie"], vec!["a=1", "b=2"]);
}
BehaviorOutcome::StrictFailure(_) => {
panic!("lenient mode must not fail the response")
}
}
}
/// A `lookup` on the CSV at `csv`, run with `guard` and the response `orig`, keyed by `?x=1`.
async fn run_lookup(csv: &str, guard: &std::sync::Arc<BodyGuard>) -> BehaviorOutcome {
run_lookup_strict(csv, guard, false).await
}
async fn run_lookup_strict(
csv: &str,
guard: &std::sync::Arc<BodyGuard>,
strict: bool,
) -> BehaviorOutcome {
let behaviors = behaviors(json!({ "lookup": {
"key": { "from": { "query": "x" }, "using": { "method": "regex", "selector": ".*" } },
"fromDataSource": { "csv": { "path": csv, "keyColumn": "id" } },
"into": "${row}"
} }));
let uri: hyper::Uri = "/users/42?x=1".parse().expect("fixture uri");
let request_headers: crate::imposter::Headers = crate::imposter::Headers::new();
let csv_cache: &'static CsvCache = Box::leak(Box::new(CsvCache::new()));
let parts = ServedParts {
body: Spliced::authored("name=${row}[name]".to_string()),
..original()
};
BehaviorRun {
behaviors: &behaviors,
method: "GET",
uri: &uri,
request_headers: &request_headers,
request_body: None,
request_body_undefined: false,
client_addr: None,
script_scope: crate::scripting::ScriptScope::detached(4545),
script_files: std::sync::Arc::new(crate::imposter::ScriptFileAccess::trusted_cwd()),
stub: STUB,
csv_cache,
body_guard: guard,
script_timeout: Duration::from_secs(5),
strict,
default_response: None,
}
.apply(parts)
.await
}
/// Issue #1654: a CSV file the body memory budget cannot hold now is a `503` with
/// `Retry-After`, even without `strictBehaviors`; once the budget frees, the row is served.
#[tokio::test]
async fn a_lookup_the_budget_cannot_hold_is_a_503() {
let dir = tempfile::tempdir().expect("tempdir");
let csv = dir.path().join("data.csv");
std::fs::write(&csv, format!("id,name\n1,ROW\n{}", "9,pad\n".repeat(400)))
.expect("write csv");
let csv = csv.to_string_lossy().into_owned();
let guard = std::sync::Arc::new(BodyGuard::new(
super::super::body_limits::BodyLimits::new(64 * 1024, Some(64 * 1024))
.expect("valid limits"),
));
let held = guard
.start(Some(64 * 1024))
.await
.expect("fills the budget");
match run_lookup(&csv, &guard).await {
BehaviorOutcome::StrictFailure(response) => {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()["retry-after"], "1");
}
other => panic!("an exhausted budget must answer 503: {other:?}"),
}
drop(held);
match run_lookup(&csv, &guard).await {
BehaviorOutcome::Applied { parts, .. } => assert_eq!(parts.body.as_str(), "name=ROW"),
other => panic!("the budget is free again: {other:?}"),
}
}
/// Review of #1654 (S3): a load that panics is the response under `strictBehaviors`, and
/// otherwise leaves the tokens and marks the response degraded.
#[tokio::test]
async fn a_lookup_load_that_panics_fails_a_strict_response() {
let dir = tempfile::tempdir().expect("t");
let csv = dir.path().join("panic.csv");
std::fs::write(&csv, "id,name\n1,ROW\n").expect("w");
let csv = csv.to_string_lossy().into_owned();
let guard = std::sync::Arc::new(BodyGuard::default());
match run_lookup_strict(&csv, &guard, true).await {
BehaviorOutcome::StrictFailure(response) => {
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
other => panic!("strict mode must fail the response: {other:?}"),
}
match run_lookup_strict(&csv, &guard, false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(degraded);
assert_eq!(parts.body.as_str(), "name=${row}[name]");
}
other => panic!("lenient mode serves the response: {other:?}"),
}
}
#[tokio::test]
async fn a_strict_failure_is_a_500_carrying_the_signal_header() {
match run(json!({ "shellTransform": ["exit 3"] }), true).await {
BehaviorOutcome::StrictFailure(response) => {
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(response.headers()["x-rift-shelltransform-error"], "true");
let body = response
.into_body()
.collect()
.await
.expect("body")
.to_bytes();
let text = String::from_utf8_lossy(&body);
assert!(
text.contains("shellTransform failed (strictBehaviors)"),
"{text}"
);
}
BehaviorOutcome::Applied { .. } => {
panic!("strict mode must fail the response")
}
}
}
#[cfg(feature = "javascript")]
#[tokio::test]
async fn a_failed_decorate_is_degraded_and_keeps_the_multi_value_headers() {
let block =
json!({ "decorate": "function (request, response) { throw new Error('boom'); }" });
match run(block.clone(), false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(degraded, "a failed decorate must be reported as degraded");
assert_eq!(parts.body, "orig");
assert_eq!(parts.status, 201);
assert_eq!(parts.headers["x-rift-decorate-error"], vec!["true"]);
assert_eq!(parts.headers["set-cookie"], vec!["a=1", "b=2"]);
}
BehaviorOutcome::StrictFailure(_) => {
panic!("lenient mode must not fail the response")
}
}
match run(block, true).await {
BehaviorOutcome::StrictFailure(response) => {
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(response.headers()["x-rift-decorate-error"], "true");
}
BehaviorOutcome::Applied { .. } => {
panic!("strict mode must fail the response")
}
}
}
#[tokio::test]
async fn a_failure_stops_the_pipeline_only_in_strict_mode() {
// Two commands: the first fails, the second would rewrite the body. Lenient keeps going.
let block = json!({ "shellTransform": ["exit 3", r#"printf '{"body":"second"}' #"#] });
match run(block.clone(), false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(degraded);
assert_eq!(parts.body, "second");
}
BehaviorOutcome::StrictFailure(_) => {
panic!("lenient mode must not fail")
}
}
assert!(matches!(
run(block, true).await,
BehaviorOutcome::StrictFailure(_)
));
}
fn applied(outcome: BehaviorOutcome) -> (ServedParts, bool) {
match outcome {
BehaviorOutcome::Applied { parts, degraded } => (parts, degraded),
BehaviorOutcome::StrictFailure(_) => {
panic!("nothing should fail")
}
}
}
/// Issue #1589: the command's stdout is a JSON response that replaces the response, Set-Cookie
/// included, and what it leaves out comes from `defaultResponse`, as for a returned decorate.
#[tokio::test]
async fn shell_stdout_replaces_the_response_completed_from_the_default_response() {
let default: IsResponse = serde_json::from_value(json!({
"statusCode": 418, "headers": { "X-Def": "d" }, "body": "dflt"
}))
.expect("default response");
let block = json!({ "shellTransform": r#"printf '{"body":"b"}' #"# });
let (parts, degraded) =
applied(run_with_default(block.clone(), false, Some(&default)).await);
assert!(!degraded);
assert_eq!(parts.status, 418);
assert_eq!(parts.body, "b");
assert_eq!(parts.headers.len(), 1, "{:?}", parts.headers);
assert_eq!(parts.headers["X-Def"], vec!["d"]);
// Without a default: the built-in 200 and no headers.
let (parts, _) = applied(run(block, false).await);
assert_eq!((parts.status, parts.body.as_str()), (200, "b"));
assert!(parts.headers.is_empty(), "{:?}", parts.headers);
// Every field written: status, the whole header map and a non-string body as `is` renders it.
let block = json!({ "shellTransform":
r#"printf '{"statusCode":202,"headers":{"X-S":["1","2"]},"body":{"k":3}}' #"# });
let (parts, _) = applied(run_with_default(block, false, Some(&default)).await);
assert_eq!(parts.status, 202);
assert_eq!(parts.headers.len(), 1, "{:?}", parts.headers);
assert_eq!(parts.headers["X-S"], vec!["1", "2"]);
assert_eq!(parts.body, r#"{"k":3}"#);
}
/// Issue #1589: the command line carries the request and the response JSON as two arguments,
/// as Mountebank appends them, and `MB_RESPONSE` holds the same response, headers included.
#[tokio::test]
async fn the_command_receives_the_request_and_response_as_two_arguments() {
let block = json!({ "shellTransform":
r#"f() { printf '{"body":[%s,%s,%s]}' "$1" "$2" "$MB_RESPONSE"; }; f"# });
let (parts, degraded) = applied(run(block, false).await);
assert!(!degraded, "{:?}", parts.headers);
let [request, response, env]: [serde_json::Value; 3] =
serde_json::from_str(parts.body.as_str()).expect("three JSON values");
assert_eq!(request["method"], "GET");
assert_eq!(request["path"], "/users/42");
assert_eq!(request["query"], json!({ "x": "1" }));
assert_eq!(
response,
json!({ "statusCode": 201, "headers": { "set-cookie": ["a=1", "b=2"] }, "body": "orig" })
);
assert_eq!(env, response, "MB_RESPONSE is the second argument");
}
/// Issue #1589: each step reads the response the previous one returned, with its body's JSON
/// type, so `body += 1` on a number adds (Mountebank's "array of shell transforms in order").
#[tokio::test]
async fn a_chained_command_sees_the_previous_commands_response() {
let block = json!({ "shellTransform": [
r#"printf '{"statusCode":203,"body":2}' #"#,
r#"printf '{"body":%s}' "$MB_RESPONSE" #"#,
] });
let (parts, _) = applied(run(block, false).await);
let seen: serde_json::Value = serde_json::from_str(parts.body.as_str()).expect("JSON body");
assert_eq!(seen, json!({ "statusCode": 203, "headers": {}, "body": 2 }));
}
/// The parts of an `is` response written with `body`, as the handler builds them.
fn is_parts(body: &serde_json::Value) -> ServedParts {
ServedParts {
body: Spliced::authored(body_text(Some(body))),
typed_body: ServedParts::typed_body_of(Some(body), &ResponseMode::Text),
..original()
}
}
/// What the one command `printf '{"body":%s}' "$MB_RESPONSE"` saw as `MB_RESPONSE.body`,
/// after `before` ran.
async fn shell_saw_body(before: &[serde_json::Value], parts: ServedParts) -> serde_json::Value {
let shell = json!({ "shellTransform": r#"printf '{"body":%s}' "$MB_RESPONSE" #"# });
let program = BehaviorProgram::from_elements(before.iter().chain([&shell]))
.expect("fixture program parses");
let (parts, degraded) = applied(run_program(&program, false, None, parts).await);
assert!(!degraded, "{:?}", parts.headers);
let seen: serde_json::Value = serde_json::from_str(parts.body.as_str()).expect("JSON body");
seen["body"].clone()
}
/// Issue #1639: the first command reads an `is` body written as a number as that number, as
/// Mountebank hands it the response object, so `body + 1` adds.
#[tokio::test]
async fn the_first_shell_command_sees_a_typed_is_body() {
assert_eq!(shell_saw_body(&[], is_parts(&json!(3))).await, json!(3));
assert_eq!(
shell_saw_body(&[], is_parts(&json!(true))).await,
json!(true)
);
// A string body is its own text.
assert_eq!(shell_saw_body(&[], is_parts(&json!("3"))).await, json!("3"));
}
/// Issue #1639: an object or array body reaches `MB_RESPONSE.body` as that value.
#[tokio::test]
async fn an_object_is_body_reaches_mb_response_as_an_object() {
for body in [json!({ "a": 1, "b": [true, null] }), json!([1, "x"])] {
assert_eq!(shell_saw_body(&[], is_parts(&body)).await, body);
}
}
/// Issue #1639, the documented residual: Rift's `copy` is a text pass, so once it rewrote an
/// object body the command gets text. Mountebank's copy replaces inside the object.
#[tokio::test]
async fn a_copy_before_shell_transform_hands_text() {
let copy = json!({ "copy": { "from": "path", "into": "${P}",
"using": { "method": "regex", "selector": ".+" } } });
let body = json!({ "p": "${P}" });
assert_eq!(
shell_saw_body(std::slice::from_ref(©), is_parts(&body)).await,
json!(r#"{"p":"/users/42"}"#)
);
// A copy that substitutes nothing leaves the body as written, still a value.
let unmatched = json!({ "q": 1 });
assert_eq!(
shell_saw_body(&[copy], is_parts(&unmatched)).await,
unmatched
);
}
/// Issue #1639: a binary body is base64 text in both engines.
#[test]
fn a_binary_or_string_body_has_no_typed_value() {
assert_eq!(
ServedParts::typed_body_of(Some(&json!({ "a": 1 })), &ResponseMode::Binary),
None
);
assert_eq!(
ServedParts::typed_body_of(Some(&json!("AQID")), &ResponseMode::Text),
None
);
assert_eq!(ServedParts::typed_body_of(None, &ResponseMode::Text), None);
}
/// Issue #1589: stdout that is valid JSON but not an object replaces the response with an empty
/// one, as Mountebank reads no field of it.
#[tokio::test]
async fn a_non_object_stdout_is_an_empty_response() {
for output in ["3", r#""text""#, "[1]"] {
let block = json!({ "shellTransform": format!("printf '{output}' #") });
let (parts, degraded) = applied(run(block, false).await);
assert!(!degraded, "{output}");
assert_eq!((parts.status, parts.body.as_str()), (200, ""), "{output}");
assert!(parts.headers.is_empty(), "{output}: {:?}", parts.headers);
}
}
/// Issue #1589: stdout that is not a JSON response — plain text, empty, `null` — is a failed
/// shellTransform, never a body: the original is kept and marked, or a 500 under strict.
#[tokio::test]
async fn stdout_that_is_not_a_json_response_fails_the_transform() {
for (command, message) in [
("echo hello", "Shell command returned invalid JSON"),
("true", "Shell command returned invalid JSON"),
("printf null #", "Shell command returned null"),
] {
let block = json!({ "shellTransform": command });
let (parts, degraded) = applied(run(block.clone(), false).await);
assert!(degraded, "{command}");
assert_eq!(
(parts.status, parts.body.as_str()),
(201, "orig"),
"{command}"
);
assert_eq!(parts.headers["x-rift-shelltransform-error"], vec!["true"]);
assert_eq!(parts.headers["set-cookie"], vec!["a=1", "b=2"], "{command}");
match run(block, true).await {
BehaviorOutcome::StrictFailure(response) => {
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = response
.into_body()
.collect()
.await
.expect("body")
.to_bytes();
let text = String::from_utf8_lossy(&body);
assert!(text.contains(message), "{command}: {text}");
}
BehaviorOutcome::Applied { .. } => {
panic!("strict mode must fail: {command}")
}
}
}
}
// Issue #1567: a decorate's returned object replaces the response, Set-Cookie included, and
// what it leaves out comes from `defaultResponse`, as in Mountebank.
#[cfg(feature = "javascript")]
#[tokio::test]
async fn a_returned_decorate_object_is_completed_from_the_default_response() {
let default: IsResponse = serde_json::from_value(json!({
"statusCode": 418, "headers": { "X-Def": "d" }, "body": "dflt"
}))
.expect("default response");
let block = json!({ "decorate": "config => ({ body: 'ret' })" });
match run_with_default(block.clone(), false, Some(&default)).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(!degraded);
assert_eq!(parts.status, 418);
assert_eq!(parts.body, "ret");
assert_eq!(parts.headers.len(), 1, "{:?}", parts.headers);
assert_eq!(parts.headers["X-Def"], vec!["d"]);
}
BehaviorOutcome::StrictFailure(_) => {
panic!("nothing failed")
}
}
// Without a default: the built-in 200, no headers.
match run(block, false).await {
BehaviorOutcome::Applied { parts, .. } => {
assert_eq!(parts.status, 200);
assert_eq!(parts.body, "ret");
assert!(parts.headers.is_empty(), "{:?}", parts.headers);
}
BehaviorOutcome::StrictFailure(_) => {
panic!("nothing failed")
}
}
}
// A mutated response keeps its held-aside Set-Cookie lines; a deleted header is gone.
// Returning the response it was given (`return response;`, `return config.response;`) is a
// mutation too, not a replacement.
#[cfg(feature = "javascript")]
#[tokio::test]
async fn a_mutating_decorate_keeps_set_cookie_and_drops_deleted_headers() {
for script in [
"(request, response) => { response.headers['X-A'] = '1'; delete response.headers['X-A']; response.body = 'm'; }",
"function (request, response) { response.headers['X-A'] = '1'; delete response.headers['X-A']; response.body = 'm'; return response; }",
"config => { config.response.headers['X-A'] = '1'; delete config.response.headers['X-A']; config.response.body = 'm'; return config.response; }",
] {
match run(json!({ "decorate": script }), false).await {
BehaviorOutcome::Applied { parts, degraded } => {
assert!(!degraded, "{script}");
assert_eq!((parts.status, parts.body.as_str()), (201, "m"), "{script}");
assert!(!parts.headers.contains_key("X-A"), "{script}");
assert_eq!(parts.headers["set-cookie"], vec!["a=1", "b=2"], "{script}");
}
BehaviorOutcome::StrictFailure(_) => {
panic!("nothing failed: {script}")
}
}
}
}
}