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
//! The imposter document's grammar as a JSON Schema (issue #1342).
//!
//! Generated from the config types in this crate — the raw door types where there is one, since
//! those are what `POST /imposters` and a config file accept — so it cannot say something the
//! engine does not read. The checked-in copy at `sdk-conformance/schema/imposter.schema.json` is
//! what ships in the conformance tarball; `rift-lint schema` regenerates it, and a drift test in
//! `rift-lint` fails when the two differ.
//!
//! The schema is strict where the engine is lenient: every object closes with
//! `additionalProperties: false`, except the two `#[serde(flatten)]` maps an embedder's provider
//! reads (`_rift.flowState`, `_rift.sequencing`). The engine itself refuses no unknown key —
//! rift-cluster replays stored config bytes, so a refusal at decode would make admitted configs
//! undecodable — which is exactly why a schema that does refuse them is needed: a DSL emitting a
//! key the engine drops gets told so here, not by a mock that silently behaves differently.
//!
//! Beyond standard JSON Schema, a few `x-rift-*` extensions carry the lists `rift-lint` keeps by
//! hand, so each can be tested against the schema:
//! - `x-rift-known-keys` on `predicateGenerators` items: the keys the recorder reads;
//! - `x-rift-canonical-order` on `ResponseBehaviors`: the order one object's behaviors run in;
//! - `x-rift-response-variants` on `StubResponse`: the response-type keys, in the precedence a
//!   replayed decode reads them (a config door refuses two, issue #1551);
//! - `x-rift-carrier: true` on a field the engine keeps and returns but never reads;
//! - `x-rift-rewrites-body: true` on a behavior that rewrites the response body.

use crate::behaviors::CANONICAL_ORDER;
use crate::imposter::{ImposterConfig, RESPONSE_VARIANT_KEYS};
use crate::recording::ProxyMode;
use rift_types::PREDICATE_GENERATOR_KEYS;
use schemars::generate::SchemaSettings;
use schemars::{Schema, SchemaGenerator, json_schema};
use serde_json::{Map, Value, json};

/// The schema's `$id`: stable across releases, so a consumer can pin by it. The engine version it
/// was generated from is in `manifest.json`, next to it in the tarball.
pub const SCHEMA_ID: &str =
    "https://github.com/achird-labs/rift/sdk-conformance/schema/imposter.schema.json";

/// The alias spellings the imposter accepts, as `(property, alias)`: each alias reads exactly as
/// the property does. Pinned to the `#[serde(alias)]` attributes by `aliases_decode_as_their_field`.
pub(crate) const IMPOSTER_ALIASES: [(&str, &str); 3] = [
    ("allowCORS", "allowCors"),
    ("serviceName", "service_name"),
    ("serviceInfo", "service_info"),
];

/// The imposter document's JSON Schema (draft 2020-12), as a JSON value. Deterministic: the same
/// engine build always produces the same value, which is what lets the checked-in copy be tested
/// for drift.
#[must_use]
pub fn imposter_schema() -> Value {
    let mut generator = SchemaSettings::draft2020_12().into_generator();
    let mut schema = generator.root_schema_for::<ImposterConfig>();
    let root = schema.ensure_object();
    root.insert("$id".to_owned(), json!(SCHEMA_ID));
    root.insert("title".to_owned(), json!("Rift imposter"));
    // Both definitions are generated from types in this crate, so their absence is a defect in
    // this module, never a runtime condition — and a generator that quietly dropped a marker would
    // ship a schema the linter's grammar tests then fail against.
    let defs = root
        .get_mut("$defs")
        .and_then(Value::as_object_mut)
        .expect("the imposter schema has $defs");
    defs.get_mut("ResponseBehaviors")
        .expect("$defs/ResponseBehaviors is generated from this crate's type")["x-rift-canonical-order"] =
        json!(CANONICAL_ORDER);
    defs.get_mut("StubResponse")
        .expect("$defs/StubResponse is generated from this crate's type")["x-rift-response-variants"] =
        json!(RESPONSE_VARIANT_KEYS);
    let mut value = schema.to_value();
    close_objects(&mut value);
    value
}

/// Whether a schema object's `key` holds a literal (`default`, an `enum` …) or an `x-rift-*`
/// extension rather than a subschema — the children a walk over schemas must not descend into.
fn is_literal_or_extension(key: &str) -> bool {
    matches!(key, "default" | "enum" | "const" | "examples") || key.starts_with("x-")
}

/// Close every object schema that lists `properties` and says nothing about other keys. A schema
/// that already decides — the flattened provider maps say `true`, the hand-written ones say
/// `false` — is left as it is.
fn close_objects(value: &mut Value) {
    match value {
        Value::Object(map) => {
            if map.contains_key("properties") && !map.contains_key("additionalProperties") {
                map.insert("additionalProperties".to_owned(), json!(false));
            }
            for (key, child) in map.iter_mut() {
                match key.as_str() {
                    // The values of `properties` are schemas; the map itself is not one.
                    "properties" => {
                        if let Some(properties) = child.as_object_mut() {
                            properties.values_mut().for_each(close_objects);
                        }
                    }
                    key if is_literal_or_extension(key) => {}
                    _ => close_objects(child),
                }
            }
        }
        Value::Array(items) => items.iter_mut().for_each(close_objects),
        _ => {}
    }
}

/// `schemars` transform for [`ImposterConfig`]: each alias in [`IMPOSTER_ALIASES`] becomes a
/// property of its own, so a document spelled the old way validates. A property the table names
/// that the struct no longer has is a defect in the table, said loudly rather than skipped.
pub(crate) fn alias_properties(schema: &mut Schema) {
    let properties = schema
        .get_mut("properties")
        .and_then(Value::as_object_mut)
        .expect("ImposterConfig is an object schema with properties");
    for (property, alias) in IMPOSTER_ALIASES {
        let mut aliased = properties.get(property).cloned().unwrap_or_else(|| {
            panic!("IMPOSTER_ALIASES names `{property}`, not an imposter property")
        });
        aliased["description"] = json!(alias_description(property));
        properties.insert(alias.to_owned(), aliased);
    }
}

/// `schemars` transform for `StubRaw`: `responses` is required and non-empty (issue #1372). The
/// field keeps `#[serde(default)]`, because the refusal is an admission check rather than a decode
/// one (a replayed stub without responses still decodes), so `schemars` would otherwise call it
/// optional with a `[]` default — exactly what every config door refuses.
pub(crate) fn stub_requires_responses(schema: &mut Schema) {
    let object = schema.ensure_object();
    let responses = object
        .get_mut("properties")
        .and_then(|properties| properties.get_mut("responses"))
        .and_then(Value::as_object_mut)
        .expect("StubRaw is an object schema with a `responses` property");
    responses.remove("default");
    responses.insert("minItems".to_owned(), json!(1));
    let required = object
        .entry("required")
        .or_insert_with(|| json!([]))
        .as_array_mut()
        .expect("`required` is an array");
    required.push(json!("responses"));
}

fn alias_description(property: &str) -> String {
    format!("Alias of `{property}`, read the same way.")
}

/// `proxy.mode`: the canonical spellings, or `""` for the default — the form an omitted mode is
/// written back in. The engine also reads each spelling in any case and with surrounding
/// whitespace; a document is expected to write the canonical one.
pub(crate) fn proxy_mode(_: &mut SchemaGenerator) -> Schema {
    let spellings: Vec<&str> = ProxyMode::SPELLINGS.iter().copied().chain([""]).collect();
    json_schema!({
        "description": "The recording mode: `proxyOnce` (the default, also spelled `\"\"`), \
                        `proxyAlways` or `proxyTransparent`.",
        "type": "string",
        "enum": spellings
    })
}

/// `protocol`: the two the engine serves. Anything else is refused at creation.
pub(crate) fn protocol(_: &mut SchemaGenerator) -> Schema {
    json_schema!({
        "description": "The protocol the imposter serves.",
        "type": "string",
        "enum": ["http", "https"],
        "default": "http"
    })
}

/// `proxy.predicateGenerators`: each entry is read by key, so its known keys are listed both as
/// properties and as `x-rift-known-keys`, from the one constant the recorder reads.
pub(crate) fn predicate_generators(_: &mut SchemaGenerator) -> Schema {
    let mut properties = Map::new();
    // Every key is matched explicitly; a key added to the list without a shape here gets `true`,
    // which `generator_keys_have_a_deliberate_shape` refuses.
    for key in PREDICATE_GENERATOR_KEYS {
        let schema = match key {
            "inject" | "except" => json!({ "type": "string" }),
            // The engine refuses any other operator (issue #1353).
            "predicateOperator" => {
                json!({ "type": "string", "enum": rift_types::GENERATOR_OPERATORS })
            }
            "caseSensitive" => json!({ "type": "boolean" }),
            "matches" | "ignore" => json!({ "type": "object" }),
            "jsonpath" => rift_types::schema::jsonpath_selector(),
            "xpath" => rift_types::schema::xpath_selector(),
            _ => Value::Bool(true),
        };
        properties.insert(key.to_owned(), schema);
    }
    json_schema!({
        "description": "How a recorded response's predicates are generated from the request \
                        that was proxied (Mountebank's `predicateGenerators`).",
        "type": "array",
        "items": {
            "type": "object",
            "properties": properties,
            "additionalProperties": false,
            "x-rift-known-keys": PREDICATE_GENERATOR_KEYS
        }
    })
}

/// `behaviors` (no underscore): one behaviors object, or an array of [`BehaviorElement`]s. An
/// array element may be `null`, which configures nothing.
pub(crate) fn behaviors_block(generator: &mut SchemaGenerator) -> Schema {
    let block = generator.subschema_for::<crate::behaviors::ResponseBehaviors>();
    let element = generator.subschema_for::<BehaviorElement>();
    json_schema!({
        "description": "The behaviors block in array form: each element's behavior is a step, \
                        run in array order. The object form is the same as `_behaviors`.",
        "anyOf": [
            block,
            { "type": "array", "items": { "anyOf": [element, { "type": "null" }] } },
            { "type": "null" }
        ]
    })
}

/// One element of the `behaviors` array (issue #1724), as every config door reads it: at most one
/// behavior, as Mountebank's `behaviorsValidator.js` requires; `copy`, `lookup` and
/// `shellTransform` as one item, never a list (#1639); and no `repeat`, which an element never
/// cycles (#1672). Closed like every object, so a key the engine does not read is refused.
pub(crate) struct BehaviorElement;

impl schemars::JsonSchema for BehaviorElement {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "BehaviorElement".into()
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        let nullable = |schema: Schema| json!({ "anyOf": [schema, { "type": "null" }] });
        let mut properties = Map::new();
        // Every key is matched explicitly; a key added to the canonical order without a shape here
        // gets `true`, which `behavior_element_keys_are_the_canonical_order` refuses.
        for key in crate::behaviors::CANONICAL_ORDER {
            let schema = match key {
                "wait" => nullable(generator.subschema_for::<crate::behaviors::WaitBehavior>()),
                "lookup" => nullable(generator.subschema_for::<crate::behaviors::LookupBehavior>()),
                "copy" => nullable(generator.subschema_for::<crate::behaviors::CopyBehavior>()),
                "shellTransform" | "decorate" => json!({ "type": ["string", "null"] }),
                _ => Value::Bool(true),
            };
            properties.insert(key.to_owned(), schema);
        }
        json_schema!({
            "description": "One element of the `behaviors` array: at most one behavior, as every \
                            config door and Mountebank's behaviorsValidator.js require. `copy`, \
                            `lookup` and `shellTransform` take one item here, never a list: write \
                            several as several elements, or use the `_behaviors` object form. \
                            `repeat` belongs on the response; inside an element it is never read. \
                            A `null` value removes the earlier steps of that behavior.",
            "type": "object",
            "properties": properties,
            "additionalProperties": false,
            "maxProperties": 1
        })
    }
}

/// A response's `statusCode` as the imposter grammar reads it (issue #1558): a number within `u16`,
/// or any string. It replaces the shared `rift_types::schema::StatusCode` here because the intercept
/// rules still take only a numeric string; the definition keeps that name, so every `$ref` stays.
pub(crate) struct ResponseStatusCode;

impl schemars::JsonSchema for ResponseStatusCode {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "StatusCode".into()
    }

    fn json_schema(_: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "description": "An HTTP status code, as a number or a string. A numeric string is that \
                            status; any other string is kept as written, `copy` and `lookup` \
                            substitute into it, and it is read when the response is written, as \
                            Mountebank reads it: one that is not 100-999 answers 500.",
            "anyOf": [
                { "type": "integer", "minimum": 0, "maximum": 65535 },
                { "type": "string" }
            ]
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::imposter::StubResponse;
    use serde_json::json;

    fn defs(schema: &Value) -> &Map<String, Value> {
        schema["$defs"].as_object().expect("$defs")
    }

    #[test]
    fn the_schema_is_a_valid_draft_2020_12_document() {
        let schema = imposter_schema();
        assert_eq!(
            schema["$schema"],
            json!("https://json-schema.org/draft/2020-12/schema")
        );
        assert_eq!(schema["$id"], json!(SCHEMA_ID));
        // A broken `$ref` or keyword is a compile error, not a validation failure.
        let validator = jsonschema::validator_for(&schema).expect("compiles");
        assert!(validator.is_valid(&json!({ "port": 4545, "protocol": "http", "stubs": [] })));
    }

    #[test]
    fn generation_is_deterministic() {
        assert_eq!(imposter_schema(), imposter_schema());
    }

    #[test]
    fn every_object_is_closed_except_the_provider_maps() {
        let schema = imposter_schema();
        let mut open = Vec::new();
        fn walk(value: &Value, path: &str, open: &mut Vec<String>) {
            let Some(map) = value.as_object() else {
                if let Some(items) = value.as_array() {
                    for (i, item) in items.iter().enumerate() {
                        walk(item, &format!("{path}/{i}"), open);
                    }
                }
                return;
            };
            if map.contains_key("properties")
                && map.get("additionalProperties") != Some(&json!(false))
            {
                open.push(path.to_owned());
            }
            for (key, child) in map {
                if key == "properties" {
                    for (name, property) in child.as_object().into_iter().flatten() {
                        walk(property, &format!("{path}/properties/{name}"), open);
                    }
                } else if !is_literal_or_extension(key) {
                    walk(child, &format!("{path}/{key}"), open);
                }
            }
        }
        walk(&schema, "", &mut open);
        open.sort();
        assert_eq!(
            open,
            ["/$defs/RiftFlowStateConfig", "/$defs/RiftSequencingConfig"],
            "only the two provider maps stay open"
        );
        for provider in ["RiftFlowStateConfig", "RiftSequencingConfig"] {
            assert_eq!(defs(&schema)[provider]["additionalProperties"], json!(true));
        }
    }

    #[test]
    fn the_root_is_the_imposter_and_the_doors_are_the_raw_shapes() {
        let schema = imposter_schema();
        let imposter = schema["properties"].as_object().expect("properties");
        for key in [
            "port",
            "protocol",
            "stubs",
            "_rift",
            "defaultResponse",
            "allowCORS",
        ] {
            assert!(imposter.contains_key(key), "{key}");
        }
        let stub = &defs(&schema)["Stub"]["properties"];
        for key in [
            "name",
            "predicates",
            "rules",
            "responses",
            "delayRange",
            "_verify",
            "routePattern",
        ] {
            assert!(stub.get(key).is_some(), "Stub.{key}");
        }
        let response = &defs(&schema)["StubResponse"];
        for key in [
            "is",
            "proxy",
            "inject",
            "fault",
            "_behaviors",
            "behaviors",
            "_rift",
            "statusCode",
            "headers",
            "body",
            "_mode",
            "repeat",
        ] {
            assert!(
                response["properties"].get(key).is_some(),
                "StubResponse.{key}"
            );
        }
        assert_eq!(
            response["x-rift-response-variants"],
            json!(RESPONSE_VARIANT_KEYS)
        );
        assert_eq!(
            defs(&schema)["ResponseBehaviors"]["x-rift-canonical-order"],
            json!(CANONICAL_ORDER)
        );
        let generator =
            &schema["$defs"]["ProxyResponse"]["properties"]["predicateGenerators"]["items"];
        assert_eq!(
            generator["x-rift-known-keys"],
            json!(PREDICATE_GENERATOR_KEYS)
        );
        let mut known: Vec<&str> = generator["properties"]
            .as_object()
            .expect("generator properties")
            .keys()
            .map(String::as_str)
            .collect();
        known.sort_unstable();
        let mut expected = PREDICATE_GENERATOR_KEYS.to_vec();
        expected.sort_unstable();
        assert_eq!(known, expected);
    }

    #[test]
    fn aliases_are_alternate_properties() {
        let schema = imposter_schema();
        let properties = schema["properties"].as_object().expect("properties");
        for (property, alias) in IMPOSTER_ALIASES {
            let mut expected = properties[property].clone();
            expected["description"] = json!(alias_description(property));
            assert_eq!(properties[alias], expected, "{alias}");
        }
    }

    /// Every generator key has a shape of its own — none fell through to the `true` a key without
    /// a shape gets.
    #[test]
    fn generator_keys_have_a_deliberate_shape() {
        let schema = imposter_schema();
        let items = &schema["$defs"]["ProxyResponse"]["properties"]["predicateGenerators"]["items"];
        for (key, property) in items["properties"].as_object().expect("properties") {
            assert!(property.is_object(), "{key} has no shape: {property}");
        }
    }

    /// Each alias in `IMPOSTER_ALIASES` decodes into the field its property names — the constant
    /// is pinned to the `#[serde(alias)]` attributes, not to memory.
    #[test]
    fn aliases_decode_as_their_field() {
        // A sample per property; an alias added to the table without one fails here.
        let samples = |property: &str| match property {
            "allowCORS" => json!(true),
            "serviceName" => json!("svc"),
            "serviceInfo" => json!({ "team": "a" }),
            other => panic!("no sample for `{other}`"),
        };
        for (property, alias) in IMPOSTER_ALIASES {
            let decode = |key: &str| -> Value {
                let config: ImposterConfig =
                    serde_json::from_value(json!({ "protocol": "http", key: samples(property) }))
                        .unwrap_or_else(|e| panic!("{key}: {e}"));
                serde_json::to_value(config).expect("serializes")
            };
            let written = decode(property);
            assert_eq!(decode(alias), written, "{alias} reads as {property}");
            assert_ne!(
                written,
                serde_json::to_value(ImposterConfig::default()).expect("serializes"),
                "the sample for {property} must change something"
            );
        }
    }

    #[test]
    fn hand_written_shapes_accept_what_the_engine_accepts() {
        let schema = imposter_schema();
        let validator = jsonschema::validator_for(&schema).expect("compiles");
        let imposter = |response: Value| json!({ "port": 4545, "protocol": "http", "stubs": [{ "responses": [response] }] });
        let predicate = |predicate: Value| json!({ "port": 4545, "protocol": "http", "stubs": [{ "predicates": [predicate], "responses": [{ "is": {} }] }] });
        let errors = |document: &Value| -> Vec<String> {
            validator
                .iter_errors(document)
                .map(|e| format!("{}: {e}", e.instance_path()))
                .collect()
        };
        let valid = |document: Value| assert_eq!(errors(&document), Vec::<String>::new());
        let refused = |document: Value| assert!(!errors(&document).is_empty(), "{document}");

        // Every tcp fault spelling, bare and probabilistic; an unknown kind or a probability-less
        // object form is refused.
        for kind in crate::imposter::fault_io::TcpFaultKind::SPELLINGS {
            valid(imposter(
                json!({ "is": {}, "_rift": { "fault": { "tcp": kind } } }),
            ));
            valid(imposter(json!({
                "is": {}, "_rift": { "fault": { "tcp": { "probability": 0.5, "type": kind } } }
            })));
        }
        refused(imposter(
            json!({ "is": {}, "_rift": { "fault": { "tcp": "nope" } } }),
        ));
        refused(imposter(
            json!({ "is": {}, "_rift": { "fault": { "tcp": { "type": "reset" } } } }),
        ));
        // Status code as a numeric string, multi-value headers with scalars, the flat form.
        valid(imposter(json!({
            "statusCode": "201", "headers": { "X-N": 1, "X-B": true, "Set-Cookie": ["a", "b"] }
        })));
        // `mode: ""` is what an omitted proxy mode is written back as.
        valid(imposter(
            json!({ "proxy": { "to": "http://x", "mode": "" } }),
        ));
        refused(imposter(
            json!({ "proxy": { "to": "http://x", "mode": "once" } }),
        ));
        // Behaviors: object form, array form with a null element and a null key; `repeat` on the
        // response. One behavior per element (#1724).
        valid(imposter(json!({
            "is": {},
            "behaviors": [null, { "wait": 10 }, { "copy": null }, { "decorate": "x" }],
            "repeat": 2
        })));
        valid(imposter(json!({
            "is": {},
            "_behaviors": {
                "wait": { "min": 1, "max": 2 },
                "shellTransform": ["a", "b"],
                "lookup": { "key": { "from": "path", "using": { "method": "regex", "selector": "x" } },
                            "fromDataSource": { "csv": { "path": "p", "keyColumn": "k" } },
                            "into": "${R}" }
            }
        })));
        refused(imposter(json!({ "is": {}, "_behaviors": { "waitt": 10 } })));
        // `repeat` is at least 1 and never `null`, wherever it sits (#1582, #1724).
        for response in [
            json!({ "is": {}, "repeat": 0 }),
            json!({ "is": {}, "repeat": null }),
            json!({ "is": {}, "_behaviors": { "repeat": 0 } }),
            json!({ "is": {}, "_behaviors": { "repeat": null } }),
        ] {
            refused(imposter(response));
        }
        // A `copy` or `lookup` `from` object names exactly one container (#1582, #1724).
        for from in [json!({}), json!({ "query": "a", "headers": "b" })] {
            refused(imposter(json!({ "is": {}, "_behaviors": { "copy": {
                "from": from, "into": "${X}", "using": { "method": "regex", "selector": ".*" }
            } } })));
        }
        // Predicates: one operator, nested, with a selector; two operators or both selectors are
        // refused.
        valid(predicate(json!({ "and": [
            { "equals": { "path": "/x" }, "caseSensitive": false },
            { "not": { "exists": { "query": { "q": true } } } },
            { "matches": { "body": "a" }, "jsonpath": { "selector": "$.a" }, "except": "z" },
            { "inject": "function (c) { return true; }" }
        ] })));
        refused(predicate(
            json!({ "equals": { "path": "/x" }, "contains": { "path": "x" } }),
        ));
        refused(predicate(json!({
            "equals": { "body": "x" }, "jsonpath": { "selector": "$" }, "xpath": { "selector": "/" }
        })));
        // Aliases, `ca` as one string, `delayRange` with numeric strings, `rules`, any `_verify`.
        valid(json!({
            "port": 4545, "protocol": "https", "allowCors": true, "service_name": "x",
            "service_info": { "team": "a" }, "cert": "c", "key": "k", "ca": "pem",
            "stubs": [{
                "delayRange": [{ "min": "5", "max": 10 }],
                "rules": [{ "equals": { "path": "/" } }],
                "_verify": { "anything": [1, "the rift-verify grammar is not this schema's"] },
                "responses": [{ "is": {} }]
            }]
        }));
        // `defaultResponse` reads `statusCode` like an `is` response does (#1377): a number or a
        // string, which since #1558 is any string; a boolean is refused.
        valid(json!({ "protocol": "http", "defaultResponse": { "statusCode": 404 } }));
        let default_string =
            json!({ "protocol": "http", "defaultResponse": { "statusCode": "404" } });
        valid(default_string.clone());
        assert!(
            serde_json::from_value::<ImposterConfig>(default_string).is_ok(),
            "the engine accepts it too"
        );
        let default_word =
            json!({ "protocol": "http", "defaultResponse": { "statusCode": "${code}" } });
        valid(default_word.clone());
        assert!(
            serde_json::from_value::<ImposterConfig>(default_word).is_ok(),
            "the engine keeps a non-numeric string too"
        );
        valid(imposter(json!({ "is": { "statusCode": "${code}" } })));
        let default_bool = json!({ "protocol": "http", "defaultResponse": { "statusCode": true } });
        refused(default_bool.clone());
        assert!(
            serde_json::from_value::<ImposterConfig>(default_bool).is_err(),
            "the engine refuses a boolean too"
        );
        // `repeat` is a u32 wherever it is read.
        valid(imposter(json!({ "is": {}, "repeat": 3 })));
        refused(imposter(json!({ "is": {}, "repeat": 5_000_000_000u64 })));
        refused(imposter(
            json!({ "is": {}, "_behaviors": { "repeat": 5_000_000_000u64 } }),
        ));
        // A stub must have a response (#1372), like every config door says; no stubs at all is fine.
        for stub in [json!({ "predicates": [] }), json!({ "responses": [] })] {
            let document = json!({ "port": 4545, "protocol": "http", "stubs": [stub] });
            refused(document.clone());
            assert!(
                serde_json::from_value::<ImposterConfig>(document).is_err(),
                "the engine refuses it too"
            );
        }
        valid(json!({ "port": 4545, "protocol": "http", "stubs": [] }));
        // An unread key anywhere is refused.
        refused(json!({ "port": 1, "protocol": "http", "stubs": [], "name2": "x" }));
        refused(imposter(
            json!({ "is": { "statusCode": 200, "bodyy": "x" } }),
        ));
    }

    /// Issue #1724: a `behaviors` array element is valid exactly when every config door admits it.
    /// The schema is closed, so a key the engine never reads is the one documented exception:
    /// refused here, admitted and ignored by the door.
    #[test]
    fn behaviors_elements_match_the_door() {
        let schema = imposter_schema();
        let validator = jsonschema::validator_for(&schema).expect("compiles");
        let copy = json!({ "from": "path", "into": "${X}", "using": { "method": "regex", "selector": ".*" } });
        let lookup = json!({ "key": { "from": "path", "using": { "method": "regex", "selector": "x" } },
                             "fromDataSource": { "csv": { "path": "p", "keyColumn": "k" } },
                             "into": "${R}" });
        let admitted_by_both = [
            json!(null),
            json!({}),
            json!({ "copy": null }),
            json!({ "wait": 10 }),
            json!({ "copy": copy.clone() }),
            json!({ "lookup": lookup.clone() }),
            json!({ "shellTransform": "x" }),
            json!({ "decorate": "x" }),
        ];
        let refused_by_both = [
            json!({ "repeat": 2 }),
            json!({ "foo": 1 }),
            json!({ "wait": 10, "copy": null }),
            json!({ "wait": 1, "decorate": "x" }),
            json!({ "copy": [] }),
            json!({ "lookup": [] }),
            json!({ "shellTransform": ["a"] }),
            json!({ "copy": [copy] }),
        ];
        // Unread keys: the closed schema refuses them; the door admits and ignores them (#1672).
        let unread_keys = [
            json!({ "wait": 1, "repeat": 3 }),
            json!({ "wait": 1, "repeat": "x" }),
            json!({ "wait": 1, "foo": 1 }),
        ];
        let response = |element: &Value| json!({ "is": {}, "behaviors": [element] });
        let schema_valid = |element: &Value| {
            let document =
                json!({ "protocol": "http", "stubs": [{ "responses": [response(element)] }] });
            validator.is_valid(&document)
        };
        let door_admits =
            |element: &Value| serde_json::from_value::<StubResponse>(response(element)).is_ok();
        for element in &admitted_by_both {
            assert!(schema_valid(element), "schema refuses {element}");
            assert!(door_admits(element), "door refuses {element}");
        }
        for element in &refused_by_both {
            assert!(!schema_valid(element), "schema admits {element}");
            assert!(!door_admits(element), "door admits {element}");
        }
        for element in &unread_keys {
            assert!(!schema_valid(element), "schema admits {element}");
            assert!(door_admits(element), "door refuses {element}");
        }
    }

    /// `RESPONSE_VARIANT_KEYS` lists the response-type keys in the order `TryFrom<StubResponseRaw>`
    /// prefers them: with every key present, the first one is the response.
    #[test]
    fn response_variant_keys_follow_the_decode_precedence() {
        let full = |from: usize| {
            let mut response = Map::new();
            let values = [
                json!({}),
                json!({ "to": "http://x" }),
                json!("function () {}"),
                json!("CONNECTION_RESET_BY_PEER"),
            ];
            for (key, value) in RESPONSE_VARIANT_KEYS.iter().zip(values).skip(from) {
                response.insert((*key).to_owned(), value);
            }
            // Replayed: a config door refuses two types (#1551), so the precedence is what a
            // stored config an older engine admitted decodes to.
            crate::imposter::deserialize_replayed::<StubResponse, _>(Value::Object(response))
                .expect("decodes")
        };
        assert!(matches!(full(0), StubResponse::Is { .. }));
        assert!(matches!(full(1), StubResponse::Proxy { .. }));
        assert!(matches!(full(2), StubResponse::Inject { .. }));
        assert!(matches!(full(3), StubResponse::Fault { .. }));
    }
}