Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
fix(apigateway): validate request bodies against the full draft 4 schema (#1930)
iot-rocket97d43408ecfb
diff --git a/ministack/services/apigateway_v1.py b/ministack/services/apigateway_v1.pyindex d59fff58..7ef71f07 100644--- a/ministack/services/apigateway_v1.py+++ b/ministack/services/apigateway_v1.py@@ -93,6 +93,9 @@ Custom domains:import base64import copyimport datetime+import decimal+import functools+import ipaddressimport jsonimport loggingimport re@@ -222,6 +225,9 @@ _GATEWAY_RESPONSE_ERROR_TYPES = {"AUTHORIZER_FAILURE": "AuthorizerConfigurationException","AUTHORIZER_CONFIGURATION_ERROR": "AuthorizerConfigurationException","API_CONFIGURATION_ERROR": "InternalServerErrorException",+ "BAD_REQUEST_PARAMETERS": "BadRequestException",+ "BAD_REQUEST_BODY": "BadRequestException",+ "DEFAULT_5XX": "InternalServerErrorException","THROTTLED": "TooManyRequestsException",}@@ -1494,12 +1500,14 @@ def _gateway_error_response(error, request):message = error.messagemessage_string = "null" if message is None else json.dumps(message)rendered_type = response_type- if response_type in ("API_CONFIGURATION_ERROR", "AUTHORIZER_CONFIGURATION_ERROR"):- # AWS renders the messageString of both types with a leading space, and- # $context.error.responseType of an authorizer configuration error as- # API_CONFIGURATION_ERROR, while the response entry, its status and- # x-amzn-ErrorType stay those of AUTHORIZER_CONFIGURATION_ERROR (measured).+ if response_type in ("API_CONFIGURATION_ERROR", "AUTHORIZER_CONFIGURATION_ERROR",+ "BAD_REQUEST_BODY", "BAD_REQUEST_PARAMETERS", "DEFAULT_5XX"):+ # AWS renders the messageString of these types with a leading space (measured).message_string = " " + message_string+ if response_type == "AUTHORIZER_CONFIGURATION_ERROR":+ # $context.error.responseType renders as API_CONFIGURATION_ERROR, while the+ # response entry, its status and x-amzn-ErrorType stay those of+ # AUTHORIZER_CONFIGURATION_ERROR (measured).rendered_type = "API_CONFIGURATION_ERROR"variables = {"context.error.message": "" if message is None else message,@@ -1514,7 +1522,7 @@ def _gateway_error_response(error, request):body = _GATEWAY_TEMPLATE_VARIABLE.sub(lambda m: variables.get(m.group(1) or m.group(2), m.group(0)), template)- return int(response["statusCode"]), headers, body.encode("utf-8")+ return int(response.get("statusCode") or 500), headers, body.encode("utf-8")def _arn_matches(pattern, arn):@@ -2027,6 +2035,7 @@ _GATEWAY_ERROR_MESSAGES = {"QUOTA_EXCEEDED": "Limit Exceeded", # not captured"UNSUPPORTED_MEDIA_TYPE": "Unsupported Media Type","BAD_REQUEST_BODY": "Invalid request body",+ "DEFAULT_5XX": "Internal server error",}# In-process only; a restart forgets them.@@ -2177,29 +2186,221 @@ def _missing_request_parameters(method_obj, request, headers, query_params):return missing-def _json_schema_violation(schema, document):- """The first violation, or None. Subset: type, required, property type."""- if not isinstance(schema, dict):+_JSON_TYPES = {+ "object": lambda v: isinstance(v, dict),+ "array": lambda v: isinstance(v, list),+ "string": lambda v: isinstance(v, str),+ "boolean": lambda v: isinstance(v, bool),+ "null": lambda v: v is None,+ "integer": lambda v: isinstance(v, int) and not isinstance(v, bool),+ "number": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),+}+++def _parse_date_time(value):+ """Parse an RFC 3339 date-time, raising ValueError otherwise."""+ match = re.fullmatch(r"(\d{4}-\d\d-\d\d)[Tt](\d\d:\d\d:\d\d)(\.\d+)?([Zz]|[+-]\d\d:\d\d)", value)+ if not match:+ raise ValueError(value)+ datetime.datetime.strptime(match[1] + match[2], "%Y-%m-%d%H:%M:%S")+++def _parses(parse):+ """A format check that holds when parse accepts the value."""+ def check(value):+ try:+ parse(value)+ except ValueError:+ return False+ return True+ return check+++_HOST_LABEL = r"[A-Za-z0-9_](?:[A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?"+_JSON_FORMATS = {+ "date-time": _parses(_parse_date_time),+ "email": lambda v: re.fullmatch(r"[^@\s]+@[^@\s]+", v) is not None,+ "hostname": lambda v: re.fullmatch(rf"{_HOST_LABEL}(?:\.{_HOST_LABEL})*", v) is not None,+ "ipv4": _parses(ipaddress.IPv4Address),+ "ipv6": _parses(ipaddress.IPv6Address),+ "uri": lambda v: re.search(r"[\s<>\"{}|\\^`]", v) is None,+}+++def _regex_search(pattern, text):+ """Whether pattern matches somewhere in text; None when Python cannot compile it."""+ try:+ return re.search(pattern, text) is not None+ except re.error:return None- expected = schema.get("type")- if expected == "object" and not isinstance(document, dict):- return "expected an object"- if expected == "array" and not isinstance(document, list):- return "expected an array"- if expected == "string" and not isinstance(document, str):- return "expected a string"- if expected in ("number", "integer") and not isinstance(document, (int, float)):- return "expected a number"- if isinstance(document, dict):- for name in schema.get("required") or []:- if name not in document:- return f"missing required property {name}"- for name, sub in (schema.get("properties") or {}).items():- if name in document:- violation = _json_schema_violation(sub, document[name])- if violation:- return violation- return None+++def _multiple_of(value, divisor):+ """Exact multipleOf on the decimal representations."""+ try:+ return decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0+ except (decimal.DecimalException, ValueError):+ return True+++def _json_equal(a, b):+ """JSON equality: booleans are not numbers."""+ if isinstance(a, bool) != isinstance(b, bool):+ return False+ if isinstance(a, dict) and isinstance(b, dict):+ return a.keys() == b.keys() and all(_json_equal(a[k], b[k]) for k in a)+ if isinstance(a, list) and isinstance(b, list):+ return len(a) == len(b) and all(map(_json_equal, a, b))+ return a == b+++def _json_key(value):+ """A hashable key, equal for two values exactly when _json_equal says so."""+ if isinstance(value, bool):+ return ("b", value)+ if isinstance(value, (int, float)):+ return ("n", decimal.Decimal(str(value)).normalize())+ if isinstance(value, list):+ return ("l", tuple(map(_json_key, value)))+ if isinstance(value, dict):+ return ("d", frozenset((k, _json_key(v)) for k, v in value.items()))+ return ("v", value)++[email protected]_cache(maxsize=256)+def _parse_schema(text):+ """A parsed schema, shared per text so it keeps its identity across $refs; None if not JSON."""+ try:+ return json.loads(text or "{}")+ except json.JSONDecodeError:+ return None+++def _model_schema(api_id, model_name):+ """The parsed schema of a model of the API, or None."""+ schema = (_models.get(api_id, {}).get(model_name) or {}).get("schema")+ return _parse_schema(schema) if isinstance(schema, str) else schema+++def _resolve_schema_ref(ref, root):+ """The schema a $ref names, and the document its own refs resolve in."""+ base, _, pointer = ref.partition("#")+ if base:+ match = re.search(r"/restapis/([^/]+)/models/([^/]+)$", base)+ root = _model_schema(match[1], urllib.parse.unquote(match[2])) if match else None+ target = root+ for part in filter(None, pointer.split("/")):+ part = urllib.parse.unquote(part).replace("~1", "/").replace("~0", "~")+ if isinstance(target, list) and part.isdigit() and int(part) < len(target):+ target = target[int(part)]+ else:+ target = target.get(part) if isinstance(target, dict) else None+ return target, root+++# Bodies nested deeper than this are refused before the schema applies.+_MAX_BODY_DEPTH = 1000+++def _json_depth(value):+ """How deeply arrays and objects nest in a parsed JSON value."""+ depth, level = 0, [value]+ while level := [c for c in level if isinstance(c, (dict, list))]:+ depth += 1+ level = [v for c in level for v in (c.values() if isinstance(c, dict) else c)]+ return depth+++class _SchemaLoop(Exception):+ """A schema that applies itself to the same value again."""+++def _json_schema_valid(schema, value, root, seen=()):+ """Whether value satisfies the JSON Schema draft 4 schema; _SchemaLoop on a validation loop."""+ chain = set()+ while isinstance(schema, dict) and isinstance(schema.get("$ref"), str):+ if id(schema) in chain:+ return True+ chain.add(id(schema))+ schema, root = _resolve_schema_ref(schema["$ref"], root)+ if not isinstance(schema, dict):+ return True+ if id(schema) in seen:+ raise _SchemaLoop+ seen += (id(schema),)++ def valid(sub):+ return _json_schema_valid(sub, value, root, seen)++ # Every subschema that applies to the same value runs, so any loop among them is found.+ all_of = [valid(sub) for sub in schema.get("allOf") or []]+ any_of = [valid(sub) for sub in schema.get("anyOf") or []]+ one_of = [valid(sub) for sub in schema.get("oneOf") or []]+ negated = "not" in schema and valid(schema["not"])+ depends = [all(n in value for n in needs) if isinstance(needs, list) else valid(needs)+ for name, needs in (schema.get("dependencies") or {}).items()+ if isinstance(value, dict) and name in value]+ if (not all(all_of + depends) or "anyOf" in schema and not any(any_of)+ or "oneOf" in schema and sum(one_of) != 1 or negated):+ return False+ types = schema.get("type")+ if types is not None and not any(+ _JSON_TYPES.get(t, lambda v: True)(value)+ for t in (types if isinstance(types, list) else [types])):+ return False+ if "enum" in schema and not any(_json_equal(value, e) for e in schema["enum"]):+ return False+ if _JSON_TYPES["number"](value):+ if "minimum" in schema and (value <= schema["minimum"] if schema.get(+ "exclusiveMinimum") else value < schema["minimum"]):+ return False+ if "maximum" in schema and (value >= schema["maximum"] if schema.get(+ "exclusiveMaximum") else value > schema["maximum"]):+ return False+ if "multipleOf" in schema and not _multiple_of(value, schema["multipleOf"]):+ return False+ if isinstance(value, str):+ if len(value) < schema.get("minLength", 0) or len(value) > schema.get("maxLength", len(value)):+ return False+ if "pattern" in schema and _regex_search(schema["pattern"], value) is False:+ return False+ if not _JSON_FORMATS.get(schema.get("format"), lambda v: True)(value):+ return False+ children = []+ if isinstance(value, list):+ if not schema.get("minItems", 0) <= len(value) <= schema.get("maxItems", len(value)):+ return False+ if schema.get("uniqueItems") and len({_json_key(v) for v in value}) != len(value):+ return False+ items = schema.get("items", {})+ if isinstance(items, list):+ extra = schema.get("additionalItems", True)+ if extra is False and len(value) > len(items):+ return False+ subs = items + [extra if isinstance(extra, dict) else {}] * (len(value) - len(items))+ else:+ subs = [items] * len(value)+ children = zip(subs, value)+ if isinstance(value, dict):+ if not schema.get("minProperties", 0) <= len(value) <= schema.get("maxProperties", len(value)):+ return False+ if any(name not in value for name in schema.get("required") or []):+ return False+ properties = schema.get("properties") or {}+ patterns = schema.get("patternProperties") or {}+ extra = schema.get("additionalProperties", True)+ for name, item in value.items():+ matched = [sub for pattern, sub in patterns.items() if _regex_search(pattern, name)]+ if name in properties:+ matched.append(properties[name])+ elif not matched:+ if extra is False:+ return False+ matched.append(extra)+ children += [(sub, item) for sub in matched]+ # Once the value passes, every child runs, so a loop below a refused sibling is still found.+ results = [_json_schema_valid(sub, item, root) for sub, item in children if sub]+ return all(results)def _check_request_validation(method_obj, api_id, request, headers, body, query_params):@@ -2224,21 +2425,22 @@ def _check_request_validation(method_obj, api_id, request, headers, body, query_method_obj.get("requestModels") or {}).get("application/json")if not model_name:return None- model = _models.get(api_id, {}).get(model_name)- if not model:+ schema = _model_schema(api_id, model_name)+ if schema is None:return None- schema = model.get("schema")- if isinstance(schema, str):- try:- schema = json.loads(schema or "{}")- except json.JSONDecodeError:- return Nonetry:- document = json.loads(body or b"{}")- except (json.JSONDecodeError, TypeError, ValueError):+ document = json.loads(body)+ except (json.JSONDecodeError, TypeError, ValueError, RecursionError):return _gw_error("BAD_REQUEST_BODY",_GATEWAY_ERROR_MESSAGES["BAD_REQUEST_BODY"])- if _json_schema_violation(schema, document):+ try:+ valid = _json_depth(document) <= _MAX_BODY_DEPTH and _json_schema_valid(+ schema, document, schema)+ except _SchemaLoop:+ return _gw_error("DEFAULT_5XX", _GATEWAY_ERROR_MESSAGES["DEFAULT_5XX"])+ except (RecursionError, TypeError, AttributeError):+ return None+ if not valid:return _gw_error("BAD_REQUEST_BODY",_GATEWAY_ERROR_MESSAGES["BAD_REQUEST_BODY"])return Nonediff --git a/tests/test_apigatewayv1.py b/tests/test_apigatewayv1.pyindex 0d5cde25..8cd1a76e 100644--- a/tests/test_apigatewayv1.py+++ b/tests/test_apigatewayv1.py@@ -5094,15 +5094,181 @@ def test_apigwv1_request_validator_checks_parameters_and_body(apigw_v1):json_header = [("Content-Type", "application/json")]assert _stage_call(api_id, "/val", "POST", '{"name":"x"}', json_header) == (- 400, '{"message":"Missing required request parameters: [q]"}')+ 400, '{"message": "Missing required request parameters: [q]"}')assert _stage_call(api_id, "/val?q=1", "POST", "{}", json_header) == (- 400, '{"message":"Invalid request body"}')+ 400, '{"message": "Invalid request body"}')assert _stage_call(api_id, "/val?q=1", "POST", "not json", json_header) == (- 400, '{"message":"Invalid request body"}')+ 400, '{"message": "Invalid request body"}')assert _stage_call(api_id, "/val?q=1", "POST", '{"name":123}', json_header) == (- 400, '{"message":"Invalid request body"}')+ 400, '{"message": "Invalid request body"}')assert _stage_call(api_id, "/val?q=1", "POST", '{"name":"x"}',json_header) == (200, '{"ok":true}')+ import urllib.error as _urlerr+ import urllib.request as _urlreq++ for path in ("/val", "/val?q=1"):+ with pytest.raises(_urlerr.HTTPError) as exc:+ _urlreq.urlopen(_urlreq.Request(+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/p{path}",+ method="POST", data=b"{}", headers=dict(json_header)))+ assert exc.value.headers["x-amzn-ErrorType"] == "BadRequestException"+ apigw_v1.put_gateway_response(+ restApiId=api_id, responseType="BAD_REQUEST_BODY", responseTemplates={+ "application/json":+ '{"m":$context.error.messageString,"e":"$context.error.message"}'})+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")+ assert _stage_call(api_id, "/val?q=1", "POST", "{}", json_header) == (+ 400, '{"m": "Invalid request body","e":"Invalid request body"}')+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)+++def test_apigwv1_request_validator_applies_json_schema_draft4(apigw_v1):+ """The body is checked against the draft 4 keywords of the model."""+ api_id, root = _gw_api(apigw_v1, f"gwjs-{_uuid_mod.uuid4().hex[:8]}")++ def prop(schema, ok, bad):+ return ({"type": "object", "properties": {"v": schema}},+ [f'{{"v":{b}}}' for b in ok], [f'{{"v":{b}}}' for b in bad])++ cases = {+ "Enum": prop({"enum": ["red", "blue"]}, ['"red"'], ['"green"']),+ "Pattern": prop({"type": "string", "pattern": "[0-9]"}, ['"a1b"'], ['"abc"']),+ "Length": prop({"type": "string", "minLength": 2, "maxLength": 2},+ ['"ab"', '"\U0001F600\U0001F600"'], ['"a"', '"abc"']),+ "Range": prop({"minimum": 1, "maximum": 10, "exclusiveMaximum": True},+ ["1", "9.5", '"x"'], ["0", "10"]),+ "Multiple": prop({"multipleOf": 0.5}, ["1.5"], ["1.2"]),+ "Int": prop({"type": "integer"}, ["3", "-0"], ["3.0", "3.5", "1e2", "true", '"3"']),+ "Num": prop({"type": "number"}, ["1e2"], ["true", '"1"']),+ "Bool": prop({"type": "boolean"}, ["false"], ['"true"', "0"]),+ "Nullable": prop({"type": ["string", "null"]}, ["null", '"x"'], ["1"]),+ "List": prop({"type": "array", "items": {"type": "string"}, "minItems": 1,+ "maxItems": 2, "uniqueItems": True},+ ['["a"]'], ["[]", '["a","b","c"]', "[1]", '["a","a"]']),+ "Tuple": prop({"type": "array", "items": [{"type": "string"}, {"type": "integer"}],+ "additionalItems": False}, ['["a",1]', '["a"]'], ["[1,1]", '["a",1,2]']),+ "Combined": prop({"anyOf": [{"type": "string"}, {"allOf": [{"minimum": 1}, {"maximum": 2}]}],+ "not": {"enum": ["no"]}}, ['"x"', "1.5"], ["3", '"no"']),+ "OneOf": prop({"oneOf": [{"type": "integer"}, {"minimum": 2}]}, ["1"], ["3", "1.5"]),+ "Formats": ({"type": "object", "properties": {+ "email": {"format": "email"}, "time": {"format": "date-time"},+ "ip": {"format": "ipv4"}, "ip6": {"format": "ipv6"},+ "host": {"format": "hostname"}, "uri": {"format": "uri"}}},+ ['{"email":"[email protected]","time":"2026-09-30T12:00:00Z","ip":"10.0.0.1","ip6":"::1",'+ '"host":"a_b.example","uri":"rel/path"}'],+ ['{"email":"nope"}', '{"time":"2026-09-30"}', '{"ip":"999.0.0.1"}',+ '{"ip6":"zz::"}', '{"host":"-bad-"}', '{"uri":"not a uri"}']),+ "Closed": ({"type": "object", "properties": {"a": {}}, "additionalProperties": False},+ ['{"a":1}'], ['{"a":1,"b":2}']),+ "Extra": ({"type": "object", "patternProperties": {"^n_": {"type": "number"}},+ "additionalProperties": {"type": "string"}},+ ['{"n_a":1,"b":"x"}'], ['{"n_a":"x"}', '{"b":1}']),+ "Count": ({"type": "object", "minProperties": 1, "maxProperties": 2,+ "dependencies": {"a": ["b"]}},+ ['{"a":1,"b":1}', '{"b":1}'], ["{}", '{"a":1}', '{"a":1,"b":2,"c":3}']),+ "Local": ({"definitions": {"s": {"type": "string"}}, "type": "object",+ "properties": {"v": {"$ref": "#/definitions/s"}}}, ['{"v":"x"}'], ['{"v":1}']),+ "Ref": prop({"$ref": f"https://apigateway.amazonaws.com/restapis/{api_id}/models/Other"},+ ['{"id":"x"}'], ["{}", '{"id":1}']),+ "Any": ({}, ["1", '"x"', "[" * 1000 + "]" * 1000],+ ["", "not json", "[" * 1001 + "]" * 1001, "[" * 100000 + "]" * 100000]),+ "Deep": ({"definitions": {"a": {"type": "array", "items": {"$ref": "#/definitions/a"}}},+ "$ref": "#/definitions/a"}, ["[[]]", "[" * 1000 + "]" * 1000], ["[1]", "[" * 1001 + "]" * 1001]),+ }+ try:+ validator = apigw_v1.create_request_validator(+ restApiId=api_id, name="v", validateRequestBody=True)["id"]+ apigw_v1.create_model(+ restApiId=api_id, name="Other", contentType="application/json",+ schema=json.dumps({"type": "object", "required": ["id"],+ "properties": {"id": {"type": "string"}}}))+ for name, (schema, _ok, _bad) in cases.items():+ apigw_v1.create_model(restApiId=api_id, name=name,+ contentType="application/json", schema=json.dumps(schema))+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,+ pathPart=name)["id"]+ _mock_method(apigw_v1, api_id, resource, "POST", requestValidatorId=validator,+ requestModels={"application/json": name})+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")+ json_header = [("Content-Type", "application/json")]+ for name, (_schema, ok, bad) in cases.items():+ for body in ok:+ assert _stage_call(api_id, f"/{name}", "POST", body, json_header) == (+ 200, '{"ok":true}'), (name, body)+ for body in bad:+ assert _stage_call(api_id, f"/{name}", "POST", body, json_header) == (+ 400, '{"message": "Invalid request body"}'), (name, body)+ finally:+ apigw_v1.delete_rest_api(restApiId=api_id)+++def test_apigwv1_request_validator_schema_loop_answers_500(apigw_v1):+ """A schema that applies itself to the same value answers 500; a pure $ref cycle passes."""+ api_id, root = _gw_api(apigw_v1, f"gwloop-{_uuid_mod.uuid4().hex[:8]}")+ models = f"https://apigateway.amazonaws.com/restapis/{api_id}/models"++ def defs(a, b=None):+ return {"definitions": {"a": a, "b": b or {}}, "$ref": "#/definitions/a"}++ loop = {"allOf": [{"$ref": "#/definitions/a"}]}+ cases = {+ "PureRef": (defs({"$ref": "#/definitions/b"}, {"$ref": "#/definitions/a"}), ["{}"], [], []),+ "AllOf": (defs(loop), [], [], ["{}", "1"]),+ "AnyOf": (defs({"anyOf": [{"type": "object"}, {"$ref": "#/definitions/a"}]}), [], [], ["{}"]),+ "Not": (defs({"not": {"$ref": "#/definitions/a"}}), [], [], ["{}"]),+ "TypeFirst": (defs({"type": "string", "allOf": [{"$ref": "#/definitions/a"}]}), [], [], ["{}"]),+ "Depends": (defs({"dependencies": {"x": {"$ref": "#/definitions/a"}}}), ["{}"], [], ['{"x":1}']),+ "Nested": ({"definitions": {"a": loop}, "type": "object", "required": ["n"],+ "properties": {"c": {"$ref": "#/definitions/a"}}}, ['{"n":1}'], ['{"c":1}'],+ ['{"n":1,"c":1}']),+ "Twice": (defs({"allOf": [{"$ref": "#/definitions/b"}] * 2}, {"type": "object"}),+ ["{}"], ["1"], []),+ "Siblings": ({"definitions": {"a": loop}, "properties": {+ "a": {"type": "string"}, "c": {"$ref": "#/definitions/a"}}},+ ['{"a":"x"}'], ['{"a":1}'], ['{"a":1,"c":1}', '{"c":1,"a":1}']),+ "Closed": ({"definitions": {"a": loop}, "properties": {"c": {"$ref": "#/definitions/a"}},+ "additionalProperties": False}, [], ['{"c":1,"z":1}', '{"z":1,"c":1}'], ['{"c":1}']),+ "Items": ({"definitions": {"a": loop}, "items": [{"type": "string"}, {"$ref": "#/definitions/a"}]},+ [], ["[1]"], ["[1,1]"]),+ "Yy": ({"type": "object"}, [], [], ["{}"]),+ "Xx": ({"allOf": [{"$ref": f"{models}/Yy"}]}, [], [], ["{}"]),+ "Py": ({"type": "object"}, ["{}"], [], []),+ "Px": ({"$ref": f"{models}/Py"}, ["{}", "1"], [], []),+ "Self": ({"type": "object"}, ["{}"], [], []),+ }+ updates = {"Yy": {"allOf": [{"$ref": f"{models}/Xx"}]}, "Py": {"$ref": f"{models}/Px"},+ "Self": defs({"$ref": f"{models}/Self"})}+ try:+ validator = apigw_v1.create_request_validator(+ restApiId=api_id, name="v", validateRequestBody=True)["id"]+ for name, (schema, *_bodies) in cases.items():+ apigw_v1.create_model(restApiId=api_id, name=name,+ contentType="application/json", schema=json.dumps(schema))+ resource = apigw_v1.create_resource(restApiId=api_id, parentId=root,+ pathPart=name)["id"]+ _mock_method(apigw_v1, api_id, resource, "POST", requestValidatorId=validator,+ requestModels={"application/json": name})+ for name, schema in updates.items():+ apigw_v1.update_model(restApiId=api_id, modelName=name, patchOperations=[{+ "op": "replace", "path": "/schema", "value": json.dumps(schema)}])+ apigw_v1.create_deployment(restApiId=api_id, stageName="p")+ json_header = [("Content-Type", "application/json")]+ expected = ((200, '{"ok":true}'), (400, '{"message": "Invalid request body"}'),+ (500, '{"message": "Internal server error"}'))+ for name, (_schema, *bodies) in cases.items():+ for answer, sent in zip(expected, bodies):+ for body in sent:+ assert _stage_call(api_id, f"/{name}", "POST", body, json_header) == answer, (+ name, body)+ import urllib.error as _urlerr+ import urllib.request as _urlreq++ with pytest.raises(_urlerr.HTTPError) as exc:+ _urlreq.urlopen(_urlreq.Request(+ f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/p/AllOf",+ method="POST", data=b"{}", headers=dict(json_header)))+ assert exc.value.headers["x-amzn-ErrorType"] == "InternalServerErrorException"finally:apigw_v1.delete_rest_api(restApiId=api_id)