stacklatch 0.1.0a1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stacklatch/__init__.py +2 -0
- stacklatch/cli.py +76 -0
- stacklatch/core.py +386 -0
- stacklatch/v21.py +273 -0
- stacklatch/v22.py +483 -0
- stacklatch/v23.py +159 -0
- stacklatch/v24.py +199 -0
- stacklatch/v24_contract.py +188 -0
- stacklatch/v24_graph.py +338 -0
- stacklatch/v25.py +156 -0
- stacklatch/v31.py +380 -0
- stacklatch/v31_checkout.py +146 -0
- stacklatch/v31_graph.py +600 -0
- stacklatch/v31_graph_legacy.py +506 -0
- stacklatch-0.1.0a1.dist-info/METADATA +70 -0
- stacklatch-0.1.0a1.dist-info/RECORD +21 -0
- stacklatch-0.1.0a1.dist-info/WHEEL +5 -0
- stacklatch-0.1.0a1.dist-info/entry_points.txt +2 -0
- stacklatch-0.1.0a1.dist-info/licenses/LICENSE +21 -0
- stacklatch-0.1.0a1.dist-info/licenses/LICENSE_INVENTORY.md +12 -0
- stacklatch-0.1.0a1.dist-info/top_level.txt +1 -0
stacklatch/v24.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""V2.4 bounded JSON adapters. Pinned source runs only in restricted Docker."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import selectors
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .core import DOCKER_IMAGE, InspectionError, _sandbox_command, _write_deterministic_zip
|
|
17
|
+
from .v21 import _checked_cases
|
|
18
|
+
from .v22 import _mapping, _provenance, _stage, propose
|
|
19
|
+
from .v24_contract import MAX_BYTES, ContractError, check_schema, strict_dumps, strict_loads, validate
|
|
20
|
+
from .v24_graph import propose_graph, stage_graph
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _remove_container(container: str) -> None:
|
|
24
|
+
"""Require daemon-confirmed removal, allowing its bounded async teardown."""
|
|
25
|
+
removed = subprocess.run(["docker", "rm", "-f", container], capture_output=True, timeout=10)
|
|
26
|
+
missing = (b"No such object", b"No such container")
|
|
27
|
+
if removed.returncode and not any(x in removed.stderr + removed.stdout
|
|
28
|
+
for x in (*missing, b"already in progress")):
|
|
29
|
+
raise InspectionError(f"Sandbox container removal failed: {removed.stderr[:160]!r}")
|
|
30
|
+
deadline = time.monotonic() + 5
|
|
31
|
+
while True:
|
|
32
|
+
gone = subprocess.run(["docker", "container", "inspect", container],
|
|
33
|
+
capture_output=True, timeout=5)
|
|
34
|
+
if gone.returncode and any(x in gone.stderr + gone.stdout for x in missing):
|
|
35
|
+
return
|
|
36
|
+
if time.monotonic() >= deadline:
|
|
37
|
+
raise InspectionError(f"Sandbox container cleanup could not be verified: "
|
|
38
|
+
f"inspect={gone.returncode} {gone.stderr[:160]!r}, "
|
|
39
|
+
f"rm={removed.returncode} {removed.stderr[:160]!r}")
|
|
40
|
+
time.sleep(0.2)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _run_docker(artifact: Path, value: Any, *, wall_timeout: float = 45) -> dict[str, Any]:
|
|
44
|
+
"""Bound input/output pipes; never import repository code on the host."""
|
|
45
|
+
command, backend = _sandbox_command(artifact)
|
|
46
|
+
if backend != "docker":
|
|
47
|
+
raise InspectionError("V2.4 verification requires Docker")
|
|
48
|
+
command = command[:-3]
|
|
49
|
+
command.insert(2, "-i")
|
|
50
|
+
command += ["-B", "run.py"]
|
|
51
|
+
container = command[command.index("--name") + 1]
|
|
52
|
+
if not 0 < wall_timeout <= 60:
|
|
53
|
+
raise InspectionError("Docker wall timeout out of bounds")
|
|
54
|
+
payload = strict_dumps(value) + b"\n"
|
|
55
|
+
proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
56
|
+
stderr=subprocess.PIPE)
|
|
57
|
+
output = {"stdout": bytearray(), "stderr": bytearray()}
|
|
58
|
+
try:
|
|
59
|
+
assert proc.stdin and proc.stdout and proc.stderr
|
|
60
|
+
os.set_blocking(proc.stdin.fileno(), False)
|
|
61
|
+
with selectors.DefaultSelector() as selector:
|
|
62
|
+
selector.register(proc.stdin, selectors.EVENT_WRITE, "stdin")
|
|
63
|
+
for name, pipe in (("stdout", proc.stdout), ("stderr", proc.stderr)):
|
|
64
|
+
selector.register(pipe, selectors.EVENT_READ, name)
|
|
65
|
+
deadline = time.monotonic() + wall_timeout
|
|
66
|
+
sent = 0
|
|
67
|
+
while selector.get_map():
|
|
68
|
+
if time.monotonic() >= deadline:
|
|
69
|
+
raise InspectionError("Docker execution timed out")
|
|
70
|
+
for key, _ in selector.select(timeout=min(1, max(0, deadline - time.monotonic()))):
|
|
71
|
+
if key.data == "stdin":
|
|
72
|
+
sent += os.write(proc.stdin.fileno(), payload[sent:sent + 8192])
|
|
73
|
+
if sent == len(payload):
|
|
74
|
+
selector.unregister(proc.stdin)
|
|
75
|
+
proc.stdin.close()
|
|
76
|
+
continue
|
|
77
|
+
chunk = key.fileobj.read1(8192)
|
|
78
|
+
if not chunk:
|
|
79
|
+
selector.unregister(key.fileobj)
|
|
80
|
+
continue
|
|
81
|
+
output[key.data].extend(chunk)
|
|
82
|
+
if len(output[key.data]) > MAX_BYTES:
|
|
83
|
+
raise InspectionError("Sandbox output byte limit exceeded")
|
|
84
|
+
if proc.wait(timeout=max(0.1, deadline - time.monotonic())):
|
|
85
|
+
raise InspectionError(f"Docker exited {proc.returncode}; stderr={bytes(output['stderr'])[:200]!r}")
|
|
86
|
+
return strict_loads(bytes(output["stdout"]))
|
|
87
|
+
except (subprocess.TimeoutExpired, BrokenPipeError) as exc:
|
|
88
|
+
raise InspectionError("Docker execution failed or timed out") from exc
|
|
89
|
+
finally:
|
|
90
|
+
if proc.poll() is None:
|
|
91
|
+
proc.kill()
|
|
92
|
+
try:
|
|
93
|
+
proc.wait(timeout=5)
|
|
94
|
+
except subprocess.TimeoutExpired:
|
|
95
|
+
proc.kill()
|
|
96
|
+
# Killing the Docker CLI does not guarantee that the daemon stopped
|
|
97
|
+
# its container. Explicitly force removal and verify it disappeared.
|
|
98
|
+
_remove_container(container)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _generate(roots, analyses, artifact: Path, candidate, mapping,
|
|
102
|
+
input_schema, intermediate_schema, output_schema):
|
|
103
|
+
artifact.mkdir()
|
|
104
|
+
stage = stage_graph if "closure" in candidate["source"] else _stage
|
|
105
|
+
modules = [stage(root, analysis, candidate[side], artifact / f"source_{i}")
|
|
106
|
+
for i, (root, analysis, side) in enumerate(
|
|
107
|
+
zip(roots, analyses, ("source", "target"), strict=True))]
|
|
108
|
+
# Trusted validator is included byte-for-byte in the generated prototype.
|
|
109
|
+
trusted = Path(__file__).with_name("v24_contract.py").read_bytes()
|
|
110
|
+
(artifact / "contract.py").write_bytes(trusted)
|
|
111
|
+
args = ", ".join(f"{key}=intermediate" if value == "$output"
|
|
112
|
+
else f"{key}=intermediate[{value!r}]" for key, value in mapping.items())
|
|
113
|
+
code = ("import importlib, json, sys\n"
|
|
114
|
+
"from contract import strict_loads, strict_dumps, validate\n"
|
|
115
|
+
"sys.path.insert(0, '/app/source_0')\n"
|
|
116
|
+
"sys.path.insert(0, '/app/source_1')\n"
|
|
117
|
+
f"first = getattr(importlib.import_module({modules[0]!r}), {candidate['source']['name']!r})\n"
|
|
118
|
+
f"second = getattr(importlib.import_module({modules[1]!r}), {candidate['target']['name']!r})\n"
|
|
119
|
+
f"INPUT = {input_schema!r}\nINTERMEDIATE = {intermediate_schema!r}\nOUTPUT = {output_schema!r}\n"
|
|
120
|
+
"def integrate(value):\n"
|
|
121
|
+
" validate(value, INPUT)\n"
|
|
122
|
+
" intermediate = first(value)\n"
|
|
123
|
+
" validate(intermediate, INTERMEDIATE)\n"
|
|
124
|
+
f" result = second({args})\n"
|
|
125
|
+
" validate(result, OUTPUT)\n"
|
|
126
|
+
" return result\n"
|
|
127
|
+
"if __name__ == '__main__':\n"
|
|
128
|
+
" try:\n"
|
|
129
|
+
" raw = sys.stdin.buffer.read(65537)\n"
|
|
130
|
+
" value = integrate(strict_loads(raw))\n"
|
|
131
|
+
" sys.stdout.buffer.write(strict_dumps({'ok': True, 'value': value}))\n"
|
|
132
|
+
" except Exception as exc:\n"
|
|
133
|
+
" sys.stdout.buffer.write(strict_dumps({'ok': False, 'error': type(exc).__name__}))\n")
|
|
134
|
+
(artifact / "run.py").write_text(code, encoding="utf-8")
|
|
135
|
+
return hashlib.sha256(trusted).hexdigest()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def verify(roots, originals, proposal: dict[str, Any], candidate_id: int,
|
|
139
|
+
mapping: dict[str, str], cases: list[dict[str, Any]],
|
|
140
|
+
input_schema: dict, intermediate_schema: dict, output_schema: dict,
|
|
141
|
+
out: Path, *, confirmed: bool) -> dict[str, Any]:
|
|
142
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
143
|
+
archive = out / "prototype.zip"
|
|
144
|
+
archive.unlink(missing_ok=True)
|
|
145
|
+
report = {"status": "failed", "verified": False, "tests": [], "runtime_image": DOCKER_IMAGE}
|
|
146
|
+
try:
|
|
147
|
+
if not confirmed:
|
|
148
|
+
raise InspectionError("Explicit semantic confirmation required")
|
|
149
|
+
for schema in (input_schema, intermediate_schema, output_schema):
|
|
150
|
+
check_schema(schema)
|
|
151
|
+
_checked_cases(cases)
|
|
152
|
+
if sum(len(strict_dumps(c)) for c in cases) > 1024 * 1024:
|
|
153
|
+
raise ContractError("Acceptance case byte limit exceeded")
|
|
154
|
+
for case in cases:
|
|
155
|
+
validate(case["input"], input_schema)
|
|
156
|
+
if "expected" in case:
|
|
157
|
+
validate(case["expected"], output_schema)
|
|
158
|
+
analyses = tuple(_provenance(root, original)
|
|
159
|
+
for root, original in zip(roots, originals, strict=True))
|
|
160
|
+
canonical = (propose_graph if proposal.get("schema_version") == 24 else propose)(
|
|
161
|
+
*analyses, *roots, proposal["goal"])
|
|
162
|
+
if proposal != canonical or type(candidate_id) is not int or not 0 <= candidate_id < len(canonical["candidates"]):
|
|
163
|
+
raise InspectionError("Plan differs from pinned reindexed source")
|
|
164
|
+
candidate = canonical["candidates"][candidate_id]
|
|
165
|
+
_mapping(candidate, mapping)
|
|
166
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
167
|
+
artifact = Path(tmp) / "prototype"
|
|
168
|
+
contract_sha = _generate(roots, analyses, artifact, candidate, mapping,
|
|
169
|
+
input_schema, intermediate_schema, output_schema)
|
|
170
|
+
for index, case in enumerate(cases):
|
|
171
|
+
actual = _run_docker(artifact, case["input"])
|
|
172
|
+
passed = (actual == {"ok": False, "error": case["error"]} if "error" in case
|
|
173
|
+
else actual.get("ok") is True and
|
|
174
|
+
(math.isclose(actual.get("value"), case["expected"], rel_tol=0,
|
|
175
|
+
abs_tol=case["abs_tol"])
|
|
176
|
+
if "abs_tol" in case and type(actual.get("value")) in (int, float)
|
|
177
|
+
and type(case["expected"]) in (int, float)
|
|
178
|
+
else actual.get("value") == case["expected"]))
|
|
179
|
+
report["tests"].append({"index": index, "input": case["input"], "actual": actual,
|
|
180
|
+
"expected": {k: v for k, v in case.items() if k != "input"},
|
|
181
|
+
"passed": passed, "backend": "docker"})
|
|
182
|
+
if not passed:
|
|
183
|
+
raise InspectionError(f"Independent acceptance case {index} failed")
|
|
184
|
+
report["files_sha256"] = _write_deterministic_zip(artifact, archive)
|
|
185
|
+
report["archive_sha256"] = hashlib.sha256(archive.read_bytes()).hexdigest()
|
|
186
|
+
report["sources_provenance"] = canonical["sources"]
|
|
187
|
+
report["contract_sha256"] = contract_sha
|
|
188
|
+
report["schemas_sha256"] = hashlib.sha256(strict_dumps(
|
|
189
|
+
[input_schema, intermediate_schema, output_schema])).hexdigest()
|
|
190
|
+
report["status"], report["verified"] = "passed", True
|
|
191
|
+
except Exception as exc:
|
|
192
|
+
archive.unlink(missing_ok=True)
|
|
193
|
+
report["error"] = f"{type(exc).__name__}: {exc}"
|
|
194
|
+
report.pop("archive_sha256", None)
|
|
195
|
+
report.pop("files_sha256", None)
|
|
196
|
+
(out / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True), encoding="utf-8")
|
|
197
|
+
(out / "report.md").write_text("# StackLatch V2.4 validation\n\n" +
|
|
198
|
+
json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
|
199
|
+
return report
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Bounded, deliberately small JSON contract shared by host and sandbox.
|
|
2
|
+
|
|
3
|
+
No source repository is imported by this module. The contract is data, never
|
|
4
|
+
Python syntax or a general JSON-Schema interpreter.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
MAX_BYTES = 65536
|
|
12
|
+
MAX_SCHEMA_BYTES = 16384
|
|
13
|
+
MAX_DEPTH = 8
|
|
14
|
+
MAX_NODES = 2048
|
|
15
|
+
MAX_ARRAY = 256
|
|
16
|
+
MAX_OBJECT = 64
|
|
17
|
+
MAX_STRING = 8192
|
|
18
|
+
MAX_KEY = 128
|
|
19
|
+
MAX_INTEGER = 2**53 - 1
|
|
20
|
+
MAX_NUMBER = 10**12
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ContractError(ValueError):
|
|
24
|
+
"""A bounded JSON or schema contract was violated."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _pairs(items):
|
|
28
|
+
result = {}
|
|
29
|
+
for key, value in items:
|
|
30
|
+
if key in result:
|
|
31
|
+
raise ContractError("Duplicate JSON key")
|
|
32
|
+
result[key] = value
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def strict_loads(raw: bytes | str):
|
|
37
|
+
if isinstance(raw, bytes):
|
|
38
|
+
if len(raw) > MAX_BYTES:
|
|
39
|
+
raise ContractError("JSON byte limit exceeded")
|
|
40
|
+
try:
|
|
41
|
+
raw = raw.decode("utf-8", errors="strict")
|
|
42
|
+
except UnicodeError as exc:
|
|
43
|
+
raise ContractError("Invalid UTF-8") from exc
|
|
44
|
+
if not isinstance(raw, str) or len(raw.encode("utf-8", errors="surrogatepass")) > MAX_BYTES:
|
|
45
|
+
raise ContractError("JSON byte limit exceeded")
|
|
46
|
+
try:
|
|
47
|
+
value = json.loads(raw, object_pairs_hook=_pairs,
|
|
48
|
+
parse_constant=lambda _: (_ for _ in ()).throw(ContractError("Nonfinite JSON number")),
|
|
49
|
+
parse_float=lambda n: _finite_float(n))
|
|
50
|
+
strict_dumps(value) # Reject lone surrogates and non-JSON results before use.
|
|
51
|
+
return value
|
|
52
|
+
except (json.JSONDecodeError, UnicodeError, RecursionError) as exc:
|
|
53
|
+
raise ContractError("Malformed JSON") from exc
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _finite_float(raw):
|
|
57
|
+
value = float(raw)
|
|
58
|
+
if not math.isfinite(value):
|
|
59
|
+
raise ContractError("Nonfinite JSON number")
|
|
60
|
+
return value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def strict_dumps(value):
|
|
64
|
+
try:
|
|
65
|
+
data = json.dumps(value, allow_nan=False, ensure_ascii=False, sort_keys=True,
|
|
66
|
+
separators=(",", ":")).encode("utf-8", errors="strict")
|
|
67
|
+
except (ValueError, TypeError, UnicodeError, RecursionError) as exc:
|
|
68
|
+
raise ContractError("Value is not bounded JSON") from exc
|
|
69
|
+
if len(data) > MAX_BYTES:
|
|
70
|
+
raise ContractError("JSON byte limit exceeded")
|
|
71
|
+
return data
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_schema(schema):
|
|
75
|
+
"""Validate a closed, recursion-bounded schema before using it."""
|
|
76
|
+
if len(strict_dumps(schema)) > MAX_SCHEMA_BYTES:
|
|
77
|
+
raise ContractError("Schema byte limit exceeded")
|
|
78
|
+
count = 0
|
|
79
|
+
|
|
80
|
+
def visit(node, depth):
|
|
81
|
+
nonlocal count
|
|
82
|
+
count += 1
|
|
83
|
+
if count > MAX_NODES or depth > MAX_DEPTH or not isinstance(node, dict):
|
|
84
|
+
raise ContractError("Invalid schema size or depth")
|
|
85
|
+
kind = node.get("type")
|
|
86
|
+
if type(kind) is not str:
|
|
87
|
+
raise ContractError("Schema type must be a string")
|
|
88
|
+
if kind in {"string", "integer", "number", "boolean", "null"}:
|
|
89
|
+
allowed = {"type"}
|
|
90
|
+
if kind == "string":
|
|
91
|
+
allowed |= {"maxLength"}
|
|
92
|
+
bound = node.get("maxLength", MAX_STRING)
|
|
93
|
+
if type(bound) is not int or not 0 <= bound <= MAX_STRING:
|
|
94
|
+
raise ContractError("Invalid string bound")
|
|
95
|
+
if kind in {"integer", "number"}:
|
|
96
|
+
allowed |= {"minimum", "maximum"}
|
|
97
|
+
for name in ("minimum", "maximum"):
|
|
98
|
+
if name in node and (type(node[name]) not in (int, float)
|
|
99
|
+
or not math.isfinite(node[name]) or abs(node[name]) > MAX_NUMBER):
|
|
100
|
+
raise ContractError("Invalid numeric bound")
|
|
101
|
+
if node.get("minimum", -MAX_NUMBER) > node.get("maximum", MAX_NUMBER):
|
|
102
|
+
raise ContractError("Inverted numeric bounds")
|
|
103
|
+
elif kind == "array":
|
|
104
|
+
allowed = {"type", "items", "minItems", "maxItems"}
|
|
105
|
+
if "items" not in node:
|
|
106
|
+
raise ContractError("Array item schema required")
|
|
107
|
+
lo, hi = node.get("minItems", 0), node.get("maxItems", MAX_ARRAY)
|
|
108
|
+
if type(lo) is not int or type(hi) is not int or not 0 <= lo <= hi <= MAX_ARRAY:
|
|
109
|
+
raise ContractError("Invalid array bounds")
|
|
110
|
+
visit(node["items"], depth + 1)
|
|
111
|
+
elif kind == "object":
|
|
112
|
+
allowed = {"type", "properties", "required", "additionalProperties"}
|
|
113
|
+
props, required = node.get("properties"), node.get("required")
|
|
114
|
+
if (not isinstance(props, dict) or len(props) > MAX_OBJECT
|
|
115
|
+
or not isinstance(required, list) or len(required) != len(set(map(str, required)))
|
|
116
|
+
or node.get("additionalProperties") is not False):
|
|
117
|
+
raise ContractError("Closed object properties and required list needed")
|
|
118
|
+
if any(type(k) is not str or len(k) > MAX_KEY for k in props):
|
|
119
|
+
raise ContractError("Invalid property name")
|
|
120
|
+
if any(type(k) is not str or k not in props for k in required):
|
|
121
|
+
raise ContractError("Invalid required property")
|
|
122
|
+
for child in props.values():
|
|
123
|
+
visit(child, depth + 1)
|
|
124
|
+
else:
|
|
125
|
+
raise ContractError("Unsupported schema type")
|
|
126
|
+
if set(node) - allowed:
|
|
127
|
+
raise ContractError("Unsupported schema keyword")
|
|
128
|
+
visit(schema, 1)
|
|
129
|
+
return schema
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def validate(value, schema):
|
|
133
|
+
check_schema(schema)
|
|
134
|
+
seen = set()
|
|
135
|
+
count = 0
|
|
136
|
+
|
|
137
|
+
def visit(item, spec, depth):
|
|
138
|
+
nonlocal count
|
|
139
|
+
count += 1
|
|
140
|
+
if count > MAX_NODES or depth > MAX_DEPTH:
|
|
141
|
+
raise ContractError("JSON node or depth limit exceeded")
|
|
142
|
+
kind = spec["type"]
|
|
143
|
+
if kind == "string":
|
|
144
|
+
if type(item) is not str or len(item) > spec.get("maxLength", MAX_STRING):
|
|
145
|
+
raise ContractError("String contract mismatch")
|
|
146
|
+
try:
|
|
147
|
+
item.encode("utf-8", errors="strict")
|
|
148
|
+
except UnicodeError as exc:
|
|
149
|
+
raise ContractError("Invalid Unicode string") from exc
|
|
150
|
+
elif kind == "integer":
|
|
151
|
+
if type(item) is not int or abs(item) > MAX_INTEGER:
|
|
152
|
+
raise ContractError("Integer contract mismatch")
|
|
153
|
+
elif kind == "number":
|
|
154
|
+
if type(item) not in (int, float) or not math.isfinite(item) or abs(item) > MAX_NUMBER:
|
|
155
|
+
raise ContractError("Number contract mismatch")
|
|
156
|
+
elif kind == "boolean":
|
|
157
|
+
if type(item) is not bool:
|
|
158
|
+
raise ContractError("Boolean contract mismatch")
|
|
159
|
+
elif kind == "null":
|
|
160
|
+
if item is not None:
|
|
161
|
+
raise ContractError("Null contract mismatch")
|
|
162
|
+
elif kind == "array":
|
|
163
|
+
if type(item) is not list or not spec.get("minItems", 0) <= len(item) <= spec.get("maxItems", MAX_ARRAY):
|
|
164
|
+
raise ContractError("Array contract mismatch")
|
|
165
|
+
if id(item) in seen:
|
|
166
|
+
raise ContractError("Cyclic JSON input")
|
|
167
|
+
seen.add(id(item))
|
|
168
|
+
for child in item:
|
|
169
|
+
visit(child, spec["items"], depth + 1)
|
|
170
|
+
seen.remove(id(item))
|
|
171
|
+
elif kind == "object":
|
|
172
|
+
if type(item) is not dict or len(item) > MAX_OBJECT:
|
|
173
|
+
raise ContractError("Object contract mismatch")
|
|
174
|
+
if id(item) in seen:
|
|
175
|
+
raise ContractError("Cyclic JSON input")
|
|
176
|
+
seen.add(id(item))
|
|
177
|
+
for key, child in item.items():
|
|
178
|
+
if type(key) is not str or len(key) > MAX_KEY or key not in spec["properties"]:
|
|
179
|
+
raise ContractError("Unknown object property")
|
|
180
|
+
visit(child, spec["properties"][key], depth + 1)
|
|
181
|
+
if not set(spec["required"]) <= item.keys():
|
|
182
|
+
raise ContractError("Missing object property")
|
|
183
|
+
seen.remove(id(item))
|
|
184
|
+
if kind in {"integer", "number"} and not (spec.get("minimum", -MAX_NUMBER) <= item <= spec.get("maximum", MAX_NUMBER)):
|
|
185
|
+
raise ContractError("Numeric range mismatch")
|
|
186
|
+
visit(value, schema, 1)
|
|
187
|
+
strict_dumps(value)
|
|
188
|
+
return value
|