xtrom-engine 0.3.1__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.
- xtrom/__init__.py +12 -0
- xtrom/allowances.py +63 -0
- xtrom/brokers/__init__.py +217 -0
- xtrom/brokers/_http.py +266 -0
- xtrom/cli_fuzz.py +169 -0
- xtrom/cli_fuzz_cross.py +306 -0
- xtrom/core.py +1519 -0
- xtrom/interfaces/__init__.py +42 -0
- xtrom/interfaces/corpus_sink.py +147 -0
- xtrom/interfaces/idp_broker.py +118 -0
- xtrom/interfaces/policy_engine.py +120 -0
- xtrom/memory.py +178 -0
- xtrom/reason_text.json +30 -0
- xtrom/sinks/__init__.py +325 -0
- xtrom/telemetry/__init__.py +169 -0
- xtrom_engine-0.3.1.dist-info/METADATA +142 -0
- xtrom_engine-0.3.1.dist-info/RECORD +19 -0
- xtrom_engine-0.3.1.dist-info/WHEEL +4 -0
- xtrom_engine-0.3.1.dist-info/licenses/LICENSE +190 -0
xtrom/cli_fuzz.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI adapter for the differential-fuzz harness (engine-fuzz).
|
|
3
|
+
|
|
4
|
+
Reads one JSON case per line from stdin, adjudicates it with the Python
|
|
5
|
+
reference `xtrom.core.Engine`, and writes `VERDICT REASON_CODE` (space-separated)
|
|
6
|
+
followed by a newline to stdout. Emitting the reason_code is what lets the
|
|
7
|
+
harness catch a same-verdict / different-reason divergence (the bug class the
|
|
8
|
+
old verdict-only compare was structurally blind to).
|
|
9
|
+
|
|
10
|
+
Wire format (in):
|
|
11
|
+
{"action":"wire_transfer","fail_closed":true,
|
|
12
|
+
"args":[{"k":"amount","v":"1000","trust":"TRUSTED","secret":false}, ...]}
|
|
13
|
+
|
|
14
|
+
`fail_closed` is OPTIONAL and defaults to True (the Python reference
|
|
15
|
+
default). When present it selects the policy's unknown-action semantics so
|
|
16
|
+
the harness can exercise BOTH the fail-closed (unknown→HIGH→sink) and the
|
|
17
|
+
permissive (unknown→LOW) default paths and keep the Rust/Python policies in
|
|
18
|
+
lockstep per case.
|
|
19
|
+
|
|
20
|
+
`tuning` is OPTIONAL: {"untrusted_content_stepup": bool, "known_destinations": [str]} turns on
|
|
21
|
+
balanced mode and known destinations for that case (design/CUSTOMER-TUNING.md), and
|
|
22
|
+
{"transfer_stepup_threshold": number, "destructive_actions": [str]} sets the tighten-only holds
|
|
23
|
+
(design/POLICY-THRESHOLDS.md). Absent → strict and the built-in holds.
|
|
24
|
+
|
|
25
|
+
Wire format (out):
|
|
26
|
+
ALLOW policy.allow\\n
|
|
27
|
+
|
|
28
|
+
The adapter uses the same policy the Rust harness uses in
|
|
29
|
+
`crates/engine-fuzz/src/main.rs::fixed_policy` so verdicts are directly
|
|
30
|
+
comparable. Keep the two policies in lockstep.
|
|
31
|
+
|
|
32
|
+
This file is on the enforcement-path allowlist for the invariants scan and
|
|
33
|
+
must not import network / clock / filesystem modules beyond stdin/stdout.
|
|
34
|
+
"""
|
|
35
|
+
from __future__ import annotations
|
|
36
|
+
|
|
37
|
+
import json
|
|
38
|
+
import sys
|
|
39
|
+
|
|
40
|
+
from xtrom.core import (
|
|
41
|
+
Engine,
|
|
42
|
+
Label,
|
|
43
|
+
Policy,
|
|
44
|
+
Sensitivity,
|
|
45
|
+
TRANSFER_STEPUP_THRESHOLD,
|
|
46
|
+
Trust,
|
|
47
|
+
Value,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _fixed_policy(fail_closed: bool = True, tuning: dict | None = None) -> Policy:
|
|
52
|
+
"""Must mirror crates/engine-fuzz/src/main.rs::fixed_policy exactly.
|
|
53
|
+
|
|
54
|
+
`ghost_action` is deliberately granted as a capability but given NO
|
|
55
|
+
sensitivity entry and is absent from every explicit set — so it exercises
|
|
56
|
+
the UNKNOWN-ACTION default path (sens.get(action, HIGH if fail_closed else
|
|
57
|
+
LOW)). `fail_closed` is threaded in so the harness can randomize it and test
|
|
58
|
+
both the fail-closed and permissive unknown-action branches.
|
|
59
|
+
"""
|
|
60
|
+
return Policy(
|
|
61
|
+
capabilities={
|
|
62
|
+
"read_file", "wire_transfer", "http_post", "send_email",
|
|
63
|
+
"list_dir", "rds_delete",
|
|
64
|
+
"custom_write", # Custom MEDIUM action, NOT in SINK_ACTIONS
|
|
65
|
+
"ghost_action", # UNKNOWN action: in caps, NO sensitivity entry, not a sink
|
|
66
|
+
"remember", # Memory-write tool, LOW: a secret written to memory still needs approval
|
|
67
|
+
},
|
|
68
|
+
sensitivity={
|
|
69
|
+
"read_file": Sensitivity.LOW,
|
|
70
|
+
"list_dir": Sensitivity.LOW,
|
|
71
|
+
"http_post": Sensitivity.MEDIUM,
|
|
72
|
+
"custom_write": Sensitivity.MEDIUM, # Exercises the sens>=MEDIUM sink gate
|
|
73
|
+
"remember": Sensitivity.LOW,
|
|
74
|
+
"send_email": Sensitivity.HIGH,
|
|
75
|
+
"wire_transfer": Sensitivity.HIGH,
|
|
76
|
+
"rds_delete": Sensitivity.HIGH,
|
|
77
|
+
# NOTE: ghost_action intentionally absent → default (unknown) path.
|
|
78
|
+
},
|
|
79
|
+
allowlist_hosts={"api.trusted.example"},
|
|
80
|
+
env="prod",
|
|
81
|
+
version="fuzz",
|
|
82
|
+
fail_closed=fail_closed,
|
|
83
|
+
untrusted_content_stepup=bool((tuning or {}).get("untrusted_content_stepup", False)),
|
|
84
|
+
known_destinations={str(d) for d in (tuning or {}).get("known_destinations") or []},
|
|
85
|
+
transfer_stepup_threshold=(tuning or {}).get("transfer_stepup_threshold", TRANSFER_STEPUP_THRESHOLD),
|
|
86
|
+
destructive_actions=frozenset(str(a) for a in (tuning or {}).get("destructive_actions") or []),
|
|
87
|
+
allowlisted_reads=bool((tuning or {}).get("allowlisted_reads", False)),
|
|
88
|
+
fetch_actions=frozenset(str(a) for a in (tuning or {}).get("fetch_actions") or []),
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _tuning_key(case: dict) -> tuple:
|
|
93
|
+
t = case.get("tuning") or {}
|
|
94
|
+
return (bool(t.get("untrusted_content_stepup", False)), tuple(sorted(str(d) for d in t.get("known_destinations") or [])),
|
|
95
|
+
t.get("transfer_stepup_threshold", TRANSFER_STEPUP_THRESHOLD),
|
|
96
|
+
tuple(sorted(str(a) for a in t.get("destructive_actions") or [])),
|
|
97
|
+
bool(t.get("allowlisted_reads", False)), tuple(sorted(str(a) for a in t.get("fetch_actions") or [])))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _case_to_args(case: dict):
|
|
101
|
+
"""Build the args map. Trust handling exercises fail-closed labeling:
|
|
102
|
+
|
|
103
|
+
* "TRUSTED" → a Value labeled TRUSTED
|
|
104
|
+
* "UNTRUSTED" → a Value labeled UNTRUSTED
|
|
105
|
+
* "" (empty) → an UNLABELED plain value (not a Value). This is the genuine
|
|
106
|
+
Path: _authorize() sees a non-Value arg, cannot tell
|
|
107
|
+
"trusted" from "never labeled", and MUST treat it as
|
|
108
|
+
UNTRUSTED (fail-closed). We pass the raw string so the
|
|
109
|
+
engine's own fail-closed labeling runs, rather than pre-labeling it.
|
|
110
|
+
"""
|
|
111
|
+
out: dict = {}
|
|
112
|
+
for i, a in enumerate(case.get("args", [])):
|
|
113
|
+
raw_trust = a.get("trust", "")
|
|
114
|
+
is_secret = bool(a.get("secret", False))
|
|
115
|
+
v = a.get("v", "")
|
|
116
|
+
if raw_trust == "":
|
|
117
|
+
# Unlabeled → let the engine apply fail-closed labeling itself.
|
|
118
|
+
out[a["k"]] = v
|
|
119
|
+
continue
|
|
120
|
+
# KNOWN MASKED GAP (R4 — documentation only, no logic change here):
|
|
121
|
+
# the wire `secret` flag sets Label.is_secret DIRECTLY, bypassing
|
|
122
|
+
# xtrom.core.looks_like_secret() / the broker-minted secret fingerprint.
|
|
123
|
+
# The engine's Rule 2 (secret-at-sink) therefore trusts the caller's claim.
|
|
124
|
+
# This is SAFE TODAY only because xtrom.core._authorize evaluates Rule 1
|
|
125
|
+
# (untrusted → sink → BLOCK) BEFORE the secret rule: any untrusted arg at a
|
|
126
|
+
# sink is already blocked regardless of its secret flag, so a forged/omitted
|
|
127
|
+
# secret flag on an untrusted arg cannot FAIL-OPEN. A FUTURE REORDERING that
|
|
128
|
+
# moved the secret rule ahead of Rule 1 (or evaluated secret handling on an
|
|
129
|
+
# untrusted-but-unblocked path) would expose this: an attacker-controlled arg
|
|
130
|
+
# could then set secret=false to dodge the egress BLOCK. If the rule order is
|
|
131
|
+
# ever changed, the wire secret flag MUST be re-validated against
|
|
132
|
+
# looks_like_secret rather than trusted verbatim.
|
|
133
|
+
trust = Trust.UNTRUSTED if raw_trust == "UNTRUSTED" else Trust.TRUSTED
|
|
134
|
+
lbl = Label(trust=trust, is_secret=is_secret, origin=f"fuzz:{i}")
|
|
135
|
+
out[a["k"]] = Value(data=v, label=lbl)
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def main() -> int:
|
|
140
|
+
# Engines keyed by the per-case fail_closed flag and tuning so we don't rebuild a Policy every
|
|
141
|
+
# line. Default is the fail-closed, strict engine (Python reference default).
|
|
142
|
+
engines: dict = {}
|
|
143
|
+
for raw in sys.stdin:
|
|
144
|
+
raw = raw.strip()
|
|
145
|
+
if not raw:
|
|
146
|
+
continue
|
|
147
|
+
try:
|
|
148
|
+
case = json.loads(raw)
|
|
149
|
+
risk = float(case.get("risk", 0.0))
|
|
150
|
+
fail_closed = bool(case.get("fail_closed", True))
|
|
151
|
+
key = (fail_closed, _tuning_key(case))
|
|
152
|
+
if key not in engines:
|
|
153
|
+
engines[key] = Engine(policy=_fixed_policy(fail_closed, case.get("tuning")), identity="fuzz")
|
|
154
|
+
decision = engines[key].authorize(
|
|
155
|
+
case["action"], _case_to_args(case), risk=risk
|
|
156
|
+
)
|
|
157
|
+
# Emit "VERDICT REASON_CODE" so the harness can compare BOTH. The
|
|
158
|
+
# reason_code is the stable machine key (see xtrom.core.ReasonCode).
|
|
159
|
+
sys.stdout.write(f"{decision.verdict.value} {decision.reason_code}\n")
|
|
160
|
+
except Exception as ex: # noqa: BLE001 — fail-closed on adapter errors
|
|
161
|
+
# Fail-closed: BLOCK with the fail_closed reason code.
|
|
162
|
+
sys.stdout.write("BLOCK fail_closed\n")
|
|
163
|
+
sys.stderr.write(f"adapter-error: {type(ex).__name__}: {ex}\n")
|
|
164
|
+
sys.stdout.flush()
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
if __name__ == "__main__":
|
|
169
|
+
raise SystemExit(main())
|
xtrom/cli_fuzz_cross.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Go ↔ Python differential driver for the hardened enforcement engine.
|
|
3
|
+
|
|
4
|
+
Runs locally (no cargo required): it ports the SAME deterministic LCG + widened
|
|
5
|
+
corpus the Rust harness (crates/engine-fuzz/src/main.rs) uses, computes the Python
|
|
6
|
+
verdict via xtrom.core directly under the fixed policy, pipes each case to the Go
|
|
7
|
+
fuzz-adapter subprocess, and asserts Go == Python over N (default 10000) cases.
|
|
8
|
+
|
|
9
|
+
The widened corpus exercises the hardening fixes:
|
|
10
|
+
* Some generated args carry trust="" (empty / unlabeled) → must be treated
|
|
11
|
+
as UNTRUSTED at a sink (fail-closed).
|
|
12
|
+
* A custom MEDIUM action "custom_write" (NOT in the sink set) → gated by the
|
|
13
|
+
sens>=MEDIUM structural sink default.
|
|
14
|
+
* Secret flags so a secret into wire_transfer/rds_delete (durable sinks) →
|
|
15
|
+
STEP_UP, and a secret into http_post/send_email egress → BLOCK/ALLOW by host.
|
|
16
|
+
|
|
17
|
+
Determinism: seeded LCG, two-decimal risk grid, no wall-clock / random / network.
|
|
18
|
+
|
|
19
|
+
Usage:
|
|
20
|
+
python3 xtrom/cli_fuzz_cross.py [--runs N] [--seed S] [--adapter PATH]
|
|
21
|
+
|
|
22
|
+
Exit 0 and "N runs, 0 divergences" on success; exit 1 and the first 5 divergences
|
|
23
|
+
(with the exact case JSON) on failure.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import argparse
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import subprocess
|
|
31
|
+
import sys
|
|
32
|
+
|
|
33
|
+
from xtrom.cli_fuzz import _case_to_args, _fixed_policy
|
|
34
|
+
from xtrom.core import Engine, looks_like_secret
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# ── LCG — identical constants to crates/engine-fuzz/src/main.rs::Lcg ─────────
|
|
38
|
+
class Lcg:
|
|
39
|
+
def __init__(self, seed: int) -> None:
|
|
40
|
+
self.state = seed & 0xFFFF_FFFF_FFFF_FFFF
|
|
41
|
+
|
|
42
|
+
def next_u32(self) -> int:
|
|
43
|
+
self.state = (self.state * 1_664_525 + 1_013_904_223) & 0xFFFF_FFFF_FFFF_FFFF
|
|
44
|
+
return (self.state >> 16) & 0xFFFF_FFFF
|
|
45
|
+
|
|
46
|
+
def choose(self, xs: list):
|
|
47
|
+
return xs[self.next_u32() % len(xs)]
|
|
48
|
+
|
|
49
|
+
def boolean(self) -> bool:
|
|
50
|
+
return self.next_u32() & 1 == 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _trailing_zeros_u32(n: int) -> int:
|
|
54
|
+
"""Mirror Rust u32::trailing_zeros (0 → 32)."""
|
|
55
|
+
if n & 0xFFFF_FFFF == 0:
|
|
56
|
+
return 32
|
|
57
|
+
count = 0
|
|
58
|
+
n &= 0xFFFF_FFFF
|
|
59
|
+
while n & 1 == 0:
|
|
60
|
+
count += 1
|
|
61
|
+
n >>= 1
|
|
62
|
+
return count
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ── Widened corpus — kept in lockstep with engine-fuzz ACTIONS/ARG_* ────────
|
|
66
|
+
ACTIONS = [
|
|
67
|
+
"read_file",
|
|
68
|
+
"wire_transfer",
|
|
69
|
+
"http_post",
|
|
70
|
+
"send_email",
|
|
71
|
+
"rds_delete",
|
|
72
|
+
"delete_prod_db", # not in caps → Rule 0 scope BLOCK
|
|
73
|
+
"list_dir",
|
|
74
|
+
"custom_write", # Custom MEDIUM action, NOT in SINK_ACTIONS
|
|
75
|
+
"ghost_action", # UNKNOWN action: in caps, NO sensitivity entry, not a sink →
|
|
76
|
+
# exercises the fail-closed unknown-action default (sens==HIGH).
|
|
77
|
+
# The Go gateway/adapter are permanently fail-closed, so this
|
|
78
|
+
# path is driven against Python's fail_closed=True default — the
|
|
79
|
+
# security-relevant direction (unknown + untrusted → BLOCK).
|
|
80
|
+
"remember", # memory-write tool, LOW: a secret written to memory still needs approval
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
ARG_KEYS = ["path", "amount", "url", "memo", "host", "body", "to", "payload"]
|
|
84
|
+
|
|
85
|
+
ARG_VALS = [
|
|
86
|
+
"./README.md",
|
|
87
|
+
"http://api.trusted.example/x",
|
|
88
|
+
"http://evil.example/",
|
|
89
|
+
"hello",
|
|
90
|
+
"1000",
|
|
91
|
+
"50000",
|
|
92
|
+
"10000",
|
|
93
|
+
"AKIA0123456789ABCDEF",
|
|
94
|
+
"root@evil.example",
|
|
95
|
+
# Host edge cases exercising the CANONICAL host_of fix (must stay in EXACT
|
|
96
|
+
# lockstep with engine-fuzz::ARG_VALS — same list, same order):
|
|
97
|
+
"ftp://api.trusted.example/x", # non-http scheme → raw → NOT allowlisted → secret egress BLOCK (was FAIL-OPEN)
|
|
98
|
+
"a@b@api.trusted.example", # multi-@: last-@ host resolves to allowlisted (http:// prefix absent → raw, see note)
|
|
99
|
+
"user@api.trusted.example", # userinfo host (no scheme → raw)
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
# Trust corpus: explicit TRUSTED/UNTRUSTED plus "" (unlabeled) to exercise fail-closed labeling.
|
|
103
|
+
TRUSTS = ["TRUSTED", "UNTRUSTED", ""]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def generate(rng: Lcg) -> dict:
|
|
107
|
+
action = rng.choose(ACTIONS)
|
|
108
|
+
n = rng.next_u32() % 4
|
|
109
|
+
args: list[dict] = []
|
|
110
|
+
used: list[str] = []
|
|
111
|
+
tries = 0
|
|
112
|
+
while len(args) < n and tries < 32:
|
|
113
|
+
tries += 1
|
|
114
|
+
k = rng.choose(ARG_KEYS)
|
|
115
|
+
if k in used:
|
|
116
|
+
continue
|
|
117
|
+
used.append(k)
|
|
118
|
+
v = rng.choose(ARG_VALS)
|
|
119
|
+
trust = rng.choose(TRUSTS)
|
|
120
|
+
# ~25% of labeled args carry the secret label (independent of trust) — same shape as Rust. An
|
|
121
|
+
# unlabeled arg is passed raw, so the reference labels it secret only by its shape.
|
|
122
|
+
drawn = _trailing_zeros_u32(rng.next_u32()) >= 2
|
|
123
|
+
is_secret = looks_like_secret(v) if trust == "" else drawn
|
|
124
|
+
args.append({"k": k, "v": v, "trust": trust, "secret": is_secret})
|
|
125
|
+
pct = rng.next_u32() % 101
|
|
126
|
+
risk = pct / 100.0
|
|
127
|
+
return {"action": action, "risk": risk, "args": args}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def case_to_json(case: dict) -> str:
|
|
131
|
+
"""Serialise to the EXACT wire format the Go adapter reads. Two-decimal risk grid
|
|
132
|
+
so float formatting can't skew. Field order fixed for readability only."""
|
|
133
|
+
parts = []
|
|
134
|
+
for a in case["args"]:
|
|
135
|
+
parts.append(
|
|
136
|
+
'{"k":"%s","v":"%s","trust":"%s","secret":%s}'
|
|
137
|
+
% (a["k"], a["v"], a["trust"], "true" if a["secret"] else "false")
|
|
138
|
+
)
|
|
139
|
+
tuning = ""
|
|
140
|
+
if case.get("tuning"):
|
|
141
|
+
t = case["tuning"]
|
|
142
|
+
wire = {"untrusted_content_stepup": bool(t.get("untrusted_content_stepup")),
|
|
143
|
+
"known_destinations": list(t.get("known_destinations") or [])}
|
|
144
|
+
for k in ("transfer_stepup_threshold", "destructive_actions", # design/POLICY-THRESHOLDS.md
|
|
145
|
+
"allowlisted_reads", "fetch_actions"): # known-site reads (GATEWAY-PLANS.md)
|
|
146
|
+
if k in t:
|
|
147
|
+
wire[k] = t[k]
|
|
148
|
+
tuning = ',"tuning":' + json.dumps(wire, separators=(",", ":"))
|
|
149
|
+
return '{"action":"%s","risk":%.2f,"args":[%s]%s}' % (
|
|
150
|
+
case["action"],
|
|
151
|
+
case["risk"],
|
|
152
|
+
",".join(parts),
|
|
153
|
+
tuning,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def python_verdict(engine: Engine, case: dict) -> str:
|
|
158
|
+
args = _case_to_args(case)
|
|
159
|
+
risk = float(case.get("risk", 0.0))
|
|
160
|
+
return engine.authorize(case["action"], args, risk=risk).verdict.value
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _default_golden_path() -> str:
|
|
164
|
+
return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "fuzz_golden.json"))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def run_golden(adapter: str, golden_path: str) -> int:
|
|
168
|
+
"""--golden mode: run every hand-crafted golden vector through BOTH the Python
|
|
169
|
+
reference engine AND the Go fuzz-adapter, and assert each reproduces the baked
|
|
170
|
+
expected_verdict (the single shared oracle). Fails on the FIRST mismatch on
|
|
171
|
+
either side. The Rust engine-fuzz harness loads the SAME file in CI so all three
|
|
172
|
+
adapters are gated against identical expected verdicts, not only against Python."""
|
|
173
|
+
with open(golden_path) as f:
|
|
174
|
+
doc = json.load(f)
|
|
175
|
+
vectors = doc["vectors"]
|
|
176
|
+
|
|
177
|
+
proc = subprocess.Popen(
|
|
178
|
+
[adapter], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
|
179
|
+
stderr=sys.stderr, text=True, bufsize=1,
|
|
180
|
+
)
|
|
181
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
182
|
+
|
|
183
|
+
failures: list[str] = []
|
|
184
|
+
for i, vec in enumerate(vectors):
|
|
185
|
+
case = {"action": vec["action"], "risk": vec["risk"], "args": vec["args"]}
|
|
186
|
+
if vec.get("tuning"):
|
|
187
|
+
case["tuning"] = vec["tuning"]
|
|
188
|
+
expected = vec["expected_verdict"]
|
|
189
|
+
py_v = python_verdict(Engine(policy=_fixed_policy(tuning=vec.get("tuning")), identity="golden"), case)
|
|
190
|
+
line = case_to_json(case)
|
|
191
|
+
proc.stdin.write(line + "\n")
|
|
192
|
+
proc.stdin.flush()
|
|
193
|
+
go_v = proc.stdout.readline().strip()
|
|
194
|
+
if py_v != expected:
|
|
195
|
+
failures.append(
|
|
196
|
+
"vector %d (%s): PYTHON=%s expected=%s | %s"
|
|
197
|
+
% (i, vec["action"], py_v, expected, vec.get("note", ""))
|
|
198
|
+
)
|
|
199
|
+
if go_v != expected:
|
|
200
|
+
failures.append(
|
|
201
|
+
"vector %d (%s): GO=%s expected=%s | %s"
|
|
202
|
+
% (i, vec["action"], go_v, expected, vec.get("note", ""))
|
|
203
|
+
)
|
|
204
|
+
proc.stdin.close()
|
|
205
|
+
proc.wait()
|
|
206
|
+
|
|
207
|
+
if not failures:
|
|
208
|
+
print("cli_fuzz_cross --golden: %d vectors, Python ✓ Go ✓ (all match oracle)" % len(vectors))
|
|
209
|
+
return 0
|
|
210
|
+
sys.stderr.write("cli_fuzz_cross --golden: %d mismatch(es) — fail\n" % len(failures))
|
|
211
|
+
for f in failures:
|
|
212
|
+
sys.stderr.write(" GOLDEN MISMATCH " + f + "\n")
|
|
213
|
+
return 1
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def main() -> int:
|
|
217
|
+
ap = argparse.ArgumentParser()
|
|
218
|
+
ap.add_argument("--runs", type=int, default=10000)
|
|
219
|
+
ap.add_argument("--seed", type=lambda s: int(s, 0), default=0xDEADBEEF)
|
|
220
|
+
ap.add_argument(
|
|
221
|
+
"--golden",
|
|
222
|
+
nargs="?",
|
|
223
|
+
const=_default_golden_path(),
|
|
224
|
+
default=None,
|
|
225
|
+
help="run the shared golden vectors (JSON path; default ../fuzz_golden.json) "
|
|
226
|
+
"through BOTH Python and Go and assert both match the baked verdict",
|
|
227
|
+
)
|
|
228
|
+
ap.add_argument(
|
|
229
|
+
"--adapter",
|
|
230
|
+
default=os.environ.get(
|
|
231
|
+
"XTROM_GO_FUZZ_ADAPTER",
|
|
232
|
+
os.path.join(
|
|
233
|
+
os.path.dirname(__file__),
|
|
234
|
+
"..", "..", "xtrom-gateway", "cmd", "fuzz-adapter", "fuzz-adapter",
|
|
235
|
+
),
|
|
236
|
+
),
|
|
237
|
+
)
|
|
238
|
+
a = ap.parse_args()
|
|
239
|
+
|
|
240
|
+
adapter = os.path.abspath(a.adapter)
|
|
241
|
+
if not os.path.exists(adapter):
|
|
242
|
+
sys.stderr.write(
|
|
243
|
+
"cli_fuzz_cross: Go adapter binary not found at %s\n"
|
|
244
|
+
"Build it first:\n"
|
|
245
|
+
" (cd product/xtrom-gateway && GOTOOLCHAIN=auto go build "
|
|
246
|
+
"-o cmd/fuzz-adapter/fuzz-adapter ./cmd/fuzz-adapter/)\n" % adapter
|
|
247
|
+
)
|
|
248
|
+
return 2
|
|
249
|
+
|
|
250
|
+
if a.golden is not None:
|
|
251
|
+
golden_path = os.path.abspath(a.golden)
|
|
252
|
+
if not os.path.exists(golden_path):
|
|
253
|
+
sys.stderr.write(
|
|
254
|
+
"cli_fuzz_cross: golden file not found at %s\n"
|
|
255
|
+
"Generate it: PYTHONPATH=. python3 scripts/gen_golden.py\n" % golden_path
|
|
256
|
+
)
|
|
257
|
+
return 2
|
|
258
|
+
return run_golden(adapter, golden_path)
|
|
259
|
+
|
|
260
|
+
engine = Engine(policy=_fixed_policy(), identity="fuzz-cross")
|
|
261
|
+
rng = Lcg(a.seed)
|
|
262
|
+
|
|
263
|
+
proc = subprocess.Popen(
|
|
264
|
+
[adapter],
|
|
265
|
+
stdin=subprocess.PIPE,
|
|
266
|
+
stdout=subprocess.PIPE,
|
|
267
|
+
stderr=sys.stderr,
|
|
268
|
+
text=True,
|
|
269
|
+
bufsize=1,
|
|
270
|
+
)
|
|
271
|
+
assert proc.stdin is not None and proc.stdout is not None
|
|
272
|
+
|
|
273
|
+
divergences: list[tuple[int, str, str, str]] = []
|
|
274
|
+
for i in range(a.runs):
|
|
275
|
+
case = generate(rng)
|
|
276
|
+
py_v = python_verdict(engine, case)
|
|
277
|
+
line = case_to_json(case)
|
|
278
|
+
proc.stdin.write(line + "\n")
|
|
279
|
+
proc.stdin.flush()
|
|
280
|
+
go_v = proc.stdout.readline().strip()
|
|
281
|
+
if go_v == "":
|
|
282
|
+
sys.stderr.write("cli_fuzz_cross: Go adapter closed early at run %d\n" % i)
|
|
283
|
+
proc.kill()
|
|
284
|
+
return 2
|
|
285
|
+
if go_v != py_v:
|
|
286
|
+
divergences.append((i, line, py_v, go_v))
|
|
287
|
+
if len(divergences) >= 5:
|
|
288
|
+
break
|
|
289
|
+
|
|
290
|
+
proc.stdin.close()
|
|
291
|
+
proc.wait()
|
|
292
|
+
|
|
293
|
+
if not divergences:
|
|
294
|
+
print("cli_fuzz_cross: %d runs, 0 divergences" % a.runs)
|
|
295
|
+
return 0
|
|
296
|
+
|
|
297
|
+
sys.stderr.write("cli_fuzz_cross: %d divergence(s) — fail\n" % len(divergences))
|
|
298
|
+
for (i, line, py_v, go_v) in divergences:
|
|
299
|
+
sys.stderr.write(
|
|
300
|
+
"DIVERGENCE run %d: case=%s py=%s go=%s\n" % (i, line, py_v, go_v)
|
|
301
|
+
)
|
|
302
|
+
return 1
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
if __name__ == "__main__":
|
|
306
|
+
raise SystemExit(main())
|