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};
pub const SCHEMA_ID: &str =
"https://github.com/achird-labs/rift/sdk-conformance/schema/imposter.schema.json";
pub(crate) const IMPOSTER_ALIASES: [(&str, &str); 3] = [
("allowCORS", "allowCors"),
("serviceName", "service_name"),
("serviceInfo", "service_info"),
];
#[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"));
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
}
fn is_literal_or_extension(key: &str) -> bool {
matches!(key, "default" | "enum" | "const" | "examples") || key.starts_with("x-")
}
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() {
"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),
_ => {}
}
}
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);
}
}
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.")
}
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
})
}
pub(crate) fn protocol(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "The protocol the imposter serves.",
"type": "string",
"enum": ["http", "https"],
"default": "http"
})
}
pub(crate) fn predicate_generators(_: &mut SchemaGenerator) -> Schema {
let mut properties = Map::new();
for key in PREDICATE_GENERATOR_KEYS {
let schema = match key {
"inject" | "except" => json!({ "type": "string" }),
"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
}
})
}
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" }
]
})
}
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();
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
})
}
}
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));
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}");
}
}
#[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}");
}
}
#[test]
fn aliases_decode_as_their_field() {
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}");
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" } } } }),
));
valid(imposter(json!({
"statusCode": "201", "headers": { "X-N": 1, "X-B": true, "Set-Cookie": ["a", "b"] }
})));
valid(imposter(
json!({ "proxy": { "to": "http://x", "mode": "" } }),
));
refused(imposter(
json!({ "proxy": { "to": "http://x", "mode": "once" } }),
));
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 } })));
for response in [
json!({ "is": {}, "repeat": 0 }),
json!({ "is": {}, "repeat": null }),
json!({ "is": {}, "_behaviors": { "repeat": 0 } }),
json!({ "is": {}, "_behaviors": { "repeat": null } }),
] {
refused(imposter(response));
}
for from in [json!({}), json!({ "query": "a", "headers": "b" })] {
refused(imposter(json!({ "is": {}, "_behaviors": { "copy": {
"from": from, "into": "${X}", "using": { "method": "regex", "selector": ".*" }
} } })));
}
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": "/" }
})));
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": {} }]
}]
}));
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"
);
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 } }),
));
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": [] }));
refused(json!({ "port": 1, "protocol": "http", "stubs": [], "name2": "x" }));
refused(imposter(
json!({ "is": { "statusCode": 200, "bodyy": "x" } }),
));
}
#[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] }),
];
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}");
}
}
#[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);
}
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 { .. }));
}
}