Coverage for fuzz/targets.py: 100%
215 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Fuzz targets (V6.6.7, #363): each takes raw bytes, builds an input from them and checks an invariant.
3`fuzz/run_fuzz.py` hands these to Atheris in CI (`.github/workflows/fuzz.yml`); `tests/test_fuzz_targets.py` drives the
4same functions with hypothesis on any machine (Atheris has no Windows wheel). A target raises AssertionError when an
5invariant breaks and lets through only the errors its function documents; anything else is a finding.
6"""
8from __future__ import annotations
10import json
11import math
12import struct
13import sys
14import tempfile
15from collections.abc import Callable, Sequence
16from pathlib import Path
17from typing import Any
19ROOT = Path(__file__).resolve().parents[1]
20sys.path.insert(0, str(ROOT)) # run_fuzz.py starts in fuzz/, so the repo root is not on the path
22from audit.hash_chain import GENESIS_HASH, compute_entry_hash, verify_chain # noqa: E402
23from evaluation.research_cells import record_holdout_read # noqa: E402
24from execution.accounts import OVERRIDE_KEYS, Account, apply_risk_overrides # noqa: E402
25from execution.secrets import SecretValue, parse_ref, redact, redact_url # noqa: E402
26from json_safety import dumps_json_safe, sanitize_json_finite # noqa: E402
27from monitoring.auth import Role, authorize, parse_users # noqa: E402
28from portfolio.target_weights import TargetWeightsConfig, rebalance_deltas # noqa: E402
29from risk.kill_switch import evaluate_kill_switch # noqa: E402
31_SPECIAL_FLOATS = (math.nan, math.inf, -math.inf, -0.0, 0.0, 1e308, -1e308, 5e-324, 1.0, -1.0)
34class Bytes:
35 """A deterministic reader over fuzz input: every call consumes bytes and never fails (an exhausted input reads zeros)."""
37 def __init__(self, data: bytes) -> None:
38 self.data = bytes(data)
39 self.pos = 0
41 def _take(self, count: int) -> bytes:
42 chunk = self.data[self.pos:self.pos + count]
43 self.pos += count
44 return chunk + bytes(count - len(chunk))
46 def int(self, lo: int, hi: int) -> int:
47 span = hi - lo + 1
48 return lo + int.from_bytes(self._take(2), "little") % span
50 def bool(self) -> bool:
51 return self._take(1)[0] & 1 == 1
53 def float(self) -> float:
54 tag = self._take(1)[0]
55 if tag < 64:
56 return _SPECIAL_FLOATS[tag % len(_SPECIAL_FLOATS)]
57 if tag < 160:
58 return struct.unpack("<d", self._take(8))[0]
59 return (int.from_bytes(self._take(2), "little") - 32768) / 256.0
61 def text(self, max_len: int = 24) -> str:
62 length = self.int(0, max_len)
63 alphabet = "abcXYZ019:/@._-* " + chr(0) + chr(233) + chr(0x1F600)
64 return "".join(alphabet[self._take(1)[0] % len(alphabet)] for _ in range(length))
66 def choice(self, items: Sequence[Any]) -> Any:
67 return items[self.int(0, len(items) - 1)]
69 def value(self, depth: int = 0) -> Any:
70 """A JSON-like value: numbers (non-finite included), strings, booleans, None, lists and dicts."""
71 kind = self.int(0, 7 if depth < 3 else 4)
72 if kind == 0:
73 return None
74 if kind == 1:
75 return self.bool()
76 if kind == 2:
77 return self.int(-1000, 1000)
78 if kind == 3:
79 return self.float()
80 if kind == 4:
81 return self.text()
82 if kind in (5, 6):
83 return [self.value(depth + 1) for _ in range(self.int(0, 4))]
84 return {self.text(8): self.value(depth + 1) for _ in range(self.int(0, 4))}
87def fuzz_json_safety(data: bytes) -> None:
88 """Sanitized output is strict JSON, sanitizing is idempotent and keeps every key."""
89 value = Bytes(data).value()
90 clean = sanitize_json_finite(value)
91 json.dumps(clean, allow_nan=False)
92 assert sanitize_json_finite(clean) == clean
93 if isinstance(value, dict):
94 assert set(clean) == set(value)
95 assert json.loads(dumps_json_safe(value)) == json.loads(json.dumps(clean))
98def _plain_password(user: str, password: str, host: str) -> bool:
99 """A password the masked URL cannot spell out by accident: no mask or separator characters, and not part of the text that stays.
100 Atheris found the need for it: the mask's last `*` plus the text after a secret `*XXXXX` spells `*XXXXX` again, which is no leak."""
101 return len(password) >= 4 and not set(password) & set("*:@") and password not in f"{user}:" and password not in host and password not in "redis"
104def fuzz_secret_refs(data: bytes) -> None:
105 """parse_ref raises only ValueError; redaction masks every occurrence of a secret and nothing else, and a masked URL keeps its user and host."""
106 reader = Bytes(data)
107 text = reader.choice(["env:", "file:", "keyring:", "", "envx:"]) + reader.text(40)
108 try:
109 ref = parse_ref(text)
110 except ValueError:
111 pass
112 else:
113 assert ref.scheme in ("env", "file", "keyring") and ref.target
114 secret = reader.text(16)
115 message = reader.text(12) + secret + reader.text(12)
116 redacted = redact(message, [SecretValue(secret)])
117 if len(secret) >= 4:
118 assert redacted == message.replace(secret, "***")
119 if "*" not in secret:
120 assert secret not in redacted
121 else:
122 assert redacted == message, "a value under 4 characters is left alone"
123 user, password, host = reader.text(8).replace("/", ""), reader.text(16).replace("/", ""), reader.text(12).replace("/", "").replace("@", "")
124 url = f"redis://{user}:{password}@{host}/0"
125 masked = redact_url(url)
126 assert masked.startswith("redis://") and masked.endswith(f"@{host}/0") and ":***@" in masked, (url, masked)
127 if _plain_password(user, password, host):
128 assert password not in masked, (url, masked)
131def fuzz_hash_chain(data: bytes) -> None:
132 """A chain built from the input verifies; changing one payload or dropping a middle row is caught at that row."""
133 reader = Bytes(data)
134 rows: list[dict[str, Any]] = []
135 previous = GENESIS_HASH
136 for index in range(reader.int(1, 6)):
137 payload = sanitize_json_finite({"i": index, "v": reader.value(1)})
138 created = f"2026-11-{reader.int(1, 28):02d}T00:00:00+00:00"
139 row = {"prev_hash": previous, "event_type": reader.text(6) or "event", "created_at": created, "payload": payload}
140 row["hash"] = compute_entry_hash(previous, row["event_type"], created, payload)
141 rows.append(row)
142 previous = row["hash"]
143 assert verify_chain(rows) == (True, None)
144 assert verify_chain(rows, expected_tail_hash=previous) == (True, None)
145 target = reader.int(0, len(rows) - 1)
146 tampered = [dict(row) for row in rows]
147 tampered[target]["payload"] = {**tampered[target]["payload"], "tampered": True}
148 assert verify_chain(tampered) == (False, target)
149 if len(rows) >= 3:
150 cut = reader.int(1, len(rows) - 2)
151 assert verify_chain(rows[:cut] + rows[cut + 1:]) == (False, cut)
154_BASE_PHASE_V2: dict[str, Any] = {
155 "live": {"max_allowed_daily_drawdown_pct": 3.0, "max_allowed_total_drawdown_pct": 10.0},
156 "dynamic_risk": {"max_leverage": 1.0},
157 "reconciliation": {"max_tolerated_drift": 0.02},
158 "risk": {"kill_switch": {"min_rolling_sharpe": -1.0, "max_drawdown_velocity_pct_per_bar": 2.0, "max_consecutive_losses": 8,
159 "max_slippage_divergence_bps": 50.0, "max_model_age_days": 30}},
160 "runtime": {"mode": "paper", "allow_live_orders": False},
161}
164def _get(tree: dict[str, Any], dotted: str) -> Any:
165 node: Any = tree
166 for part in dotted.split("."):
167 node = node.get(part) if isinstance(node, dict) else None
168 return node
171def fuzz_account_overrides(data: bytes) -> None:
172 """An account override never loosens a base limit, whatever its type; a refusal is a ValueError."""
173 reader = Bytes(data)
174 overrides = {reader.choice(sorted(OVERRIDE_KEYS)): reader.choice([reader.float(), reader.int(-50, 50), reader.bool(), reader.text(4), None])
175 for _ in range(reader.int(1, 4))}
176 account = Account("acct1", risk_overrides=overrides, mode=reader.choice([None, "observation", "paper", "live"]))
177 try:
178 out = apply_risk_overrides(_BASE_PHASE_V2, account)
179 except ValueError:
180 return
181 for key, direction in OVERRIDE_KEYS.items():
182 before, after = _get(_BASE_PHASE_V2, key), _get(out, key)
183 if direction == "false":
184 assert after is before or after is False, key
185 elif isinstance(before, (int, float)) and not isinstance(before, bool):
186 assert isinstance(after, (int, float)) and not isinstance(after, bool) and after == after, (key, after)
187 assert after <= before if direction == "lower" else after >= before, (key, before, after)
188 assert {"observation": 1, "paper": 2, "live": 3}[_get(out, "runtime.mode")] <= 2
191def fuzz_users_doc(data: bytes) -> None:
192 """A users file of any shape parses or raises ValueError; parsed users never act above their role or scope."""
193 reader = Bytes(data)
194 rows = [reader.value(1) for _ in range(reader.int(0, 3))]
195 if reader.bool():
196 rows.append({"name": reader.text(8), "role": reader.choice(["viewer", "operator", "admin", reader.text(5)]),
197 "salt": "0" * 32, "token_hash": "a" * 64, "accounts": reader.value(1)})
198 try:
199 users = parse_users({"users": rows})
200 except ValueError:
201 return
202 account = reader.text(5) or None
203 for user in users:
204 for required in Role:
205 allowed = authorize(user, required, account, auth_required=True)
206 assert not allowed or (int(user.role) >= int(required) and user.may_access(account))
207 assert not authorize(None, Role.OPERATOR, account, auth_required=reader.bool())
210_KILL_SWITCH_CONFIG = {"enabled": True, "evaluation_bars": 20, "min_bars_for_sharpe": 10, "min_rolling_sharpe": -1.0,
211 "max_drawdown_velocity_pct_per_bar": 2.0, "max_consecutive_losses": 6, "max_slippage_divergence_bps": 40.0,
212 "max_model_age_days": 30, "min_live_rank_ic": -0.2}
215def fuzz_kill_switch(data: bytes) -> None:
216 """Any metrics, finite or not, give a decision (never an exception) whose report is strict JSON once sanitized; a
217 finite velocity above the ceiling always trips."""
218 reader = Bytes(data)
219 metrics = {
220 "recent_bar_returns": [reader.float() for _ in range(reader.int(0, 30))],
221 "drawdown_velocity_pct_per_bar": reader.choice([None, reader.float()]),
222 "live_rank_ic": reader.choice([None, reader.float()]),
223 "consecutive_losses": reader.choice([None, reader.float(), reader.int(0, 20)]),
224 "slippage_divergence_bps": reader.choice([None, reader.float()]),
225 "model_age_days": reader.choice([None, reader.float()]),
226 "rolling_sharpe_tripped_last_bar": reader.bool(),
227 "rolling_sharpe_below_run_last_bar": reader.int(0, 5),
228 }
229 decision = evaluate_kill_switch(metrics, dict(_KILL_SWITCH_CONFIG))
230 json.dumps(sanitize_json_finite(decision.to_dict()), allow_nan=False)
231 velocity = metrics["drawdown_velocity_pct_per_bar"]
232 if isinstance(velocity, float) and math.isfinite(velocity) and velocity > _KILL_SWITCH_CONFIG["max_drawdown_velocity_pct_per_bar"]:
233 assert decision.tripped, metrics
236def fuzz_rebalance(data: bytes) -> None:
237 """Orders are finite, never overshoot the target weight, and a `reduces` order only shrinks a position."""
238 reader = Bytes(data)
239 tickers = ["AAA", "BBB", "CCC", "DDD"][: reader.int(1, 4)]
240 held = {ticker: reader.choice([0.0, reader.float(), float(reader.int(-50, 50))]) for ticker in tickers if reader.bool()}
241 prices = {ticker: reader.choice([reader.float(), float(reader.int(1, 500))]) for ticker in tickers}
242 target = {ticker: reader.choice([reader.float(), reader.int(-100, 100) / 100.0]) for ticker in tickers if reader.bool()}
243 nav = reader.choice([reader.float(), float(reader.int(1, 10**6))])
244 lots = {ticker: reader.choice([1.0, 0.0, reader.float(), 0.001]) for ticker in tickers if reader.bool()}
245 config = TargetWeightsConfig()
246 orders = rebalance_deltas(held, prices, nav, target, config, lot_size=lots)
247 finite = lambda value, default=0.0: value if isinstance(value, (int, float)) and math.isfinite(value) else default # noqa: E731
248 seen_growth = False
249 for ticker, delta in orders:
250 assert math.isfinite(delta) and delta != 0.0, (ticker, delta)
251 units, price, wanted = finite(held.get(ticker, 0.0)), finite(prices[ticker]), finite(target.get(ticker, 0.0))
252 after = units + delta
253 shrinks = units != 0.0 and abs(after) <= abs(units) and after * units >= 0.0
254 if not shrinks:
255 seen_growth = True
256 else:
257 assert not seen_growth, ("a reduction sorted after an order that adds exposure", orders)
258 nav_value = finite(nav)
259 if wanted != 0.0 and nav_value > 0.0 and price > 0.0:
260 current, post = units * price / nav_value, after * price / nav_value
261 low, high = min(current, wanted), max(current, wanted)
262 slack = 1e-9 * max(1.0, abs(low), abs(high))
263 assert low - slack <= post <= high + slack, (ticker, current, wanted, post)
266def fuzz_holdout_ledger(data: bytes) -> None:
267 """A ledger line that names a cell, in any shape, never lets that cell be read again: the record either refuses with
268 PermissionError or ValueError (a corrupt ledger fails closed) or the cell was never named."""
269 reader = Bytes(data)
270 cells = ("V1", "V2", "P", "CV")
271 lines: list[str] = []
272 named: set[str] = set()
273 for _ in range(reader.int(0, 4)):
274 shape = reader.int(0, 4)
275 cell = reader.choice(cells)
276 if shape == 0:
277 entry: Any = {"candidate": "c", "cells": [cell]}
278 elif shape == 1:
279 entry = {"candidate": "c", "cells": cell}
280 elif shape == 2:
281 entry = [cell]
282 elif shape == 3:
283 entry = {"candidate": "c", "cells": [cell, reader.value(1)]}
284 else:
285 entry = reader.value(1)
286 named |= {cell} if shape < 4 else set()
287 text = json.dumps(entry)
288 lines.append(text[: reader.int(1, len(text))] if reader.int(0, 9) == 0 else text)
289 wanted = (reader.choice(cells),)
290 with tempfile.TemporaryDirectory() as tmp:
291 ledger = Path(tmp) / "holdout_ledger.jsonl"
292 ledger.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8")
293 try:
294 record_holdout_read(ledger, candidate="fuzz", cells=wanted, digest="d", created_at="2026-11-14T00:00:00Z")
295 except (PermissionError, ValueError):
296 return
297 assert wanted[0] not in named, (lines, wanted)
300TARGETS: dict[str, Callable[[bytes], None]] = {
301 "json_safety": fuzz_json_safety,
302 "secret_refs": fuzz_secret_refs,
303 "hash_chain": fuzz_hash_chain,
304 "account_overrides": fuzz_account_overrides,
305 "users_doc": fuzz_users_doc,
306 "kill_switch": fuzz_kill_switch,
307 "rebalance": fuzz_rebalance,
308 "holdout_ledger": fuzz_holdout_ledger,
309}