forgeproof-cli 0.2.0__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.
Files changed (89) hide show
  1. forge_gate/__init__.py +44 -0
  2. forge_gate/_deprecated_cli.py +16 -0
  3. forgeproof/__init__.py +3 -0
  4. forgeproof/catalog.py +110 -0
  5. forgeproof/cli.py +560 -0
  6. forgeproof/config.py +339 -0
  7. forgeproof/data/gate_catalog.json +66 -0
  8. forgeproof/data/host_sets.json +7 -0
  9. forgeproof/debug_caller.py +271 -0
  10. forgeproof/debug_core.py +368 -0
  11. forgeproof/fixture_engine.py +81 -0
  12. forgeproof/fixtures/__init__.py +19 -0
  13. forgeproof/fixtures/decision_tree_id3.py +90 -0
  14. forgeproof/fixtures/gradient_descent_momentum.py +73 -0
  15. forgeproof/fixtures/kmeans_clustering.py +98 -0
  16. forgeproof/fixtures/knn_classifier.py +79 -0
  17. forgeproof/fixtures/linear_regression_gd.py +77 -0
  18. forgeproof/fixtures/logistic_regression.py +85 -0
  19. forgeproof/fixtures/naive_bayes_text.py +114 -0
  20. forgeproof/fixtures/perceptron.py +84 -0
  21. forgeproof/fixtures/polynomial_regression.py +67 -0
  22. forgeproof/fixtures/ridge_regression_normal_eq.py +75 -0
  23. forgeproof/ledger.py +633 -0
  24. forgeproof/lens_tools/__init__.py +11 -0
  25. forgeproof/lens_tools/guard_lens.py +1250 -0
  26. forgeproof/lens_tools/invariant_contracts/linear_regression_gd.json +74 -0
  27. forgeproof/lens_tools/invariant_contracts/polynomial_regression.json +86 -0
  28. forgeproof/lens_tools/invariant_contracts/ridge_regression_normal_eq.json +86 -0
  29. forgeproof/lens_tools/invariant_gate.py +199 -0
  30. forgeproof/lens_tools/metamorphic/__init__.py +9 -0
  31. forgeproof/lens_tools/metamorphic/relations.py +962 -0
  32. forgeproof/lens_tools/metamorphic/runner.py +112 -0
  33. forgeproof/lens_tools/twin_consensus.py +395 -0
  34. forgeproof/lenses.py +923 -0
  35. forgeproof/paths.py +56 -0
  36. forgeproof/reference/ORIGIN.md +29 -0
  37. forgeproof/reference/decision_tree_id3.py +197 -0
  38. forgeproof/reference/gradient_descent_momentum.py +141 -0
  39. forgeproof/reference/kmeans_clustering.py +139 -0
  40. forgeproof/reference/knn_classifier.py +118 -0
  41. forgeproof/reference/linear_regression_gd.py +106 -0
  42. forgeproof/reference/logistic_regression.py +141 -0
  43. forgeproof/reference/naive_bayes_text.py +152 -0
  44. forgeproof/reference/perceptron.py +123 -0
  45. forgeproof/reference/polynomial_regression.py +125 -0
  46. forgeproof/reference/ridge_regression_normal_eq.py +165 -0
  47. forgeproof/runner.py +147 -0
  48. forgeproof/scout/__init__.py +7 -0
  49. forgeproof/scout/behaviour.py +365 -0
  50. forgeproof/scout/box.py +581 -0
  51. forgeproof/scout/cards.py +180 -0
  52. forgeproof/scout/contract.py +37 -0
  53. forgeproof/scout/corpus.py +104 -0
  54. forgeproof/scout/embed.py +217 -0
  55. forgeproof/scout/engines/__init__.py +1 -0
  56. forgeproof/scout/engines/chaos.py +454 -0
  57. forgeproof/scout/engines/chaos_port.py +1331 -0
  58. forgeproof/scout/engines/chaos_runner.py +178 -0
  59. forgeproof/scout/engines/executor_port.py +239 -0
  60. forgeproof/scout/envfit.py +54 -0
  61. forgeproof/scout/experience.py +161 -0
  62. forgeproof/scout/fetchproxy.py +368 -0
  63. forgeproof/scout/ghcache.py +395 -0
  64. forgeproof/scout/ghpool.py +253 -0
  65. forgeproof/scout/ghsearch.py +248 -0
  66. forgeproof/scout/ids.py +82 -0
  67. forgeproof/scout/intent_lens.py +170 -0
  68. forgeproof/scout/learn.py +583 -0
  69. forgeproof/scout/meaning_lens.py +231 -0
  70. forgeproof/scout/outcomes.py +42 -0
  71. forgeproof/scout/plant.py +327 -0
  72. forgeproof/scout/ratify.py +214 -0
  73. forgeproof/scout/report.py +448 -0
  74. forgeproof/scout/rule2.py +177 -0
  75. forgeproof/scout/shape.py +107 -0
  76. forgeproof/scout/shape_lens.py +71 -0
  77. forgeproof/scout/signature.py +52 -0
  78. forgeproof/scout/slots.py +39 -0
  79. forgeproof/scout/upstream_facts.py +536 -0
  80. forgeproof/unsupported.py +83 -0
  81. forgeproof/verifier.py +208 -0
  82. forgeproof/view_coverage.py +166 -0
  83. forgeproof_cli-0.2.0.dist-info/METADATA +285 -0
  84. forgeproof_cli-0.2.0.dist-info/RECORD +89 -0
  85. forgeproof_cli-0.2.0.dist-info/WHEEL +5 -0
  86. forgeproof_cli-0.2.0.dist-info/entry_points.txt +3 -0
  87. forgeproof_cli-0.2.0.dist-info/licenses/LICENSE +201 -0
  88. forgeproof_cli-0.2.0.dist-info/licenses/NOTICE +23 -0
  89. forgeproof_cli-0.2.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,368 @@
1
+ """Fetch mode's network gate (design v1.4.5 §4a.6, V42-1 / V43-1; build step 7 slice 1).
2
+
3
+ The box in fetch mode keeps bubblewrap's fresh network namespace (only its own loopback, no
4
+ route out, no resolver). Its ONLY way out is a unix socket bound into the box, served by
5
+ :class:`Proxy` running OUTSIDE the box as the calling user. The proxy speaks HTTP ``CONNECT``
6
+ only and opens an upstream connection only when ``host:port`` is a member of the run's named
7
+ host set. It resolves names itself, so the box never needs DNS, and it logs every request,
8
+ allowed or denied: that log is the fetch record's witness, kept outside the box.
9
+
10
+ No root and no firewall rules are needed (this replaces KD-8 (a)'s assumption).
11
+
12
+ Named host sets live in ``forgeproof/data/host_sets.json``: tracked, so widening a set is a
13
+ diff in git (V43-1), and its sha256 goes into each fetch record. Members are lower-case DNS
14
+ names with an explicit port. IP literals and wildcards are refused when the file is loaded.
15
+
16
+ What the gate binds (step-7 crew review, 6E F8): it checks the NAME. The proxy resolves it and
17
+ logs the address it reached (``peer``) but does not check that address; what ties the name to
18
+ GitHub is the TLS certificate check made by git inside the box.
19
+
20
+ Idle tunnels (6E F7, accepted, not fixed): each direction of a tunnel has its own 300 s idle limit
21
+ and either one ending closes both, so 16 idle tunnels hold every slot and later CONNECTs get 503
22
+ until one ends. The socket is mode 0660: the box's git is the intended client, but the owner and
23
+ the box group can connect too. The effect is a stalled fetch, not a way out. The same limit also
24
+ cuts a real fetch whose client sends nothing upstream for 300 s (a long pack download); whether a
25
+ GitHub fetch on this link ever does is not measured. Any change to the limit waits for a measured
26
+ fetch.
27
+
28
+ Decided by the maintainer 2026-11-14 (DECISIONS-7-github G1): ``github-git`` = {github.com:443}; ``pypi``
29
+ is configured but no step-7 fetch uses it.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import hashlib
34
+ import json
35
+ import os
36
+ import re
37
+ import socket
38
+ import threading
39
+ import time
40
+ from pathlib import Path
41
+
42
+ HOST_SETS_FILE = Path(__file__).resolve().parent.parent / "data" / "host_sets.json"
43
+ MAX_BYTES = 300 * 1024 * 1024 # per proxy lifetime, both directions; a runaway fetch is cut
44
+ HEADER_MAX = 8192
45
+ HEADER_DEADLINE_S = 10 # the whole request header must arrive within this (review F6)
46
+ MAX_CONNECTIONS = 16 # concurrent tunnels; more get a 503 (review F6: threads run as us)
47
+ REFUSE_READ_S = 0.5 # over the cap: read the request (at most this long) before the 503
48
+ MAX_LOG = 10000 # log entries kept; the rest are counted, not stored
49
+ _NAME = re.compile(r"^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$")
50
+ _IPV4 = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$")
51
+
52
+ # Runs INSIDE the box (python3 from the host's /usr, read-only). It listens on the box's own
53
+ # loopback and joins each connection to the proxy's unix socket, then runs the command with
54
+ # the proxy variables set. It decides nothing: every decision is the outside proxy's.
55
+ FORWARDER = r'''
56
+ import os, socket, subprocess, sys, threading
57
+ sock_path, port = sys.argv[1], int(sys.argv[2])
58
+ assert sys.argv[3] == "--", sys.argv
59
+ cmd = sys.argv[4:]
60
+ ls = socket.socket()
61
+ ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
62
+ ls.bind(("127.0.0.1", port))
63
+ ls.listen(32)
64
+ def pump(a, b):
65
+ try:
66
+ while True:
67
+ d = a.recv(65536)
68
+ if not d:
69
+ break
70
+ b.sendall(d)
71
+ except OSError:
72
+ pass
73
+ finally:
74
+ for s in (a, b):
75
+ try:
76
+ s.shutdown(socket.SHUT_RDWR)
77
+ except OSError:
78
+ pass
79
+ def serve():
80
+ while True:
81
+ c, _ = ls.accept()
82
+ u = socket.socket(socket.AF_UNIX)
83
+ try:
84
+ u.connect(sock_path)
85
+ except OSError:
86
+ c.close(); u.close(); continue
87
+ threading.Thread(target=pump, args=(c, u), daemon=True).start()
88
+ threading.Thread(target=pump, args=(u, c), daemon=True).start()
89
+ threading.Thread(target=serve, daemon=True).start()
90
+ url = "http://127.0.0.1:%d" % port
91
+ env = dict(os.environ, https_proxy=url, http_proxy=url, HTTPS_PROXY=url, HTTP_PROXY=url,
92
+ ALL_PROXY=url, all_proxy=url, no_proxy="", NO_PROXY="")
93
+ sys.exit(subprocess.call(cmd, env=env))
94
+ '''
95
+ FORWARD_PORT = 3128 # inside the box's own network namespace: nothing else listens there
96
+
97
+
98
+ SOCK_PATH_MAX = 100 # AF_UNIX sun_path: 104 bytes on macOS, 108 on Linux, minus the terminator
99
+
100
+
101
+ class SocketPathTooLong(OSError):
102
+ """The proxy's socket path does not fit AF_UNIX; the box root is too deep."""
103
+
104
+
105
+ class BadHostSet(ValueError):
106
+ """host_sets.json is malformed or names something that is not a plain host:port."""
107
+
108
+
109
+ def _member(text: str) -> str:
110
+ if not isinstance(text, str) or text != text.strip().lower():
111
+ raise BadHostSet(f"member must be lower-case without spaces: {text!r}")
112
+ host, sep, port = text.rpartition(":")
113
+ if not sep or not port.isdigit() or not 1 <= int(port) <= 65535 or str(int(port)) != port:
114
+ raise BadHostSet(f"member needs an explicit port: {text!r}")
115
+ if _IPV4.match(host) or ":" in host or "*" in host or not _NAME.match(host):
116
+ raise BadHostSet(f"member must be a DNS name, not an IP or a wildcard: {text!r}")
117
+ return text
118
+
119
+
120
+ def load_host_sets(path: Path = HOST_SETS_FILE) -> tuple[dict[str, frozenset[str]], str]:
121
+ """({set name: frozenset of "host:port"}, sha256 of the file's bytes)."""
122
+ raw = Path(path).read_bytes()
123
+ data = json.loads(raw)
124
+ if not isinstance(data, dict) or not isinstance(data.get("sets"), dict) or not data["sets"]:
125
+ raise BadHostSet(f"{path}: expected {{\"sets\": {{name: [host:port, ...]}}}}")
126
+ sets = {}
127
+ for name, members in data["sets"].items():
128
+ if not re.match(r"^[a-z0-9][a-z0-9-]*$", name) or not isinstance(members, list) or not members:
129
+ raise BadHostSet(f"{path}: bad set {name!r}")
130
+ sets[name] = frozenset(_member(m) for m in members)
131
+ if len(sets[name]) != len(members):
132
+ raise BadHostSet(f"{path}: duplicate member in {name!r}")
133
+ return sets, hashlib.sha256(raw).hexdigest()
134
+
135
+
136
+ def normalise_target(text: str) -> str | None:
137
+ """'Host.Example.:443' -> 'host.example:443'; None when it is not a host:port at all."""
138
+ host, sep, port = text.strip().rpartition(":")
139
+ if not sep or not (port.isascii() and port.isdigit()): # review F8: '²' is a digit to isdigit()
140
+ return None
141
+ host = host.lower().rstrip(".")
142
+ if host.startswith("[") or not host:
143
+ return f"{host}:{port}" # an IPv6 literal: never a member (members are DNS names)
144
+ return f"{host}:{int(port)}"
145
+
146
+
147
+ class Proxy:
148
+ """An allowlisting CONNECT proxy on a unix socket. ``resolve`` maps an ALLOWED "host:port" to
149
+ the (address, port) actually dialled; tests point it at a local fake upstream. It is never
150
+ consulted for a denied target, so a denied target is never dialled."""
151
+
152
+ def __init__(self, sock_path: Path, allowed: frozenset[str], *, resolve=None,
153
+ max_bytes: int = MAX_BYTES, connect_timeout: float = 20):
154
+ self.sock_path = Path(sock_path)
155
+ self.allowed = frozenset(allowed)
156
+ self.resolve = resolve or (lambda target: (target.rpartition(":")[0], int(target.rpartition(":")[2])))
157
+ self.max_bytes = max_bytes
158
+ self.connect_timeout = connect_timeout
159
+ self.log: list[dict] = []
160
+ self.dropped = 0
161
+ self.phase = "run"
162
+ self._slots = threading.BoundedSemaphore(MAX_CONNECTIONS)
163
+ self._bytes = 0
164
+ self._lock = threading.Lock()
165
+ self._srv: socket.socket | None = None
166
+ self._threads: list[threading.Thread] = []
167
+ self._stop = threading.Event()
168
+
169
+ # -- lifecycle -------------------------------------------------------------------------
170
+ def start(self, mode: int = 0o660) -> "Proxy":
171
+ if len(os.fsencode(str(self.sock_path))) > SOCK_PATH_MAX:
172
+ raise SocketPathTooLong(f"{self.sock_path}: longer than {SOCK_PATH_MAX} bytes (AF_UNIX)")
173
+ srv = socket.socket(socket.AF_UNIX)
174
+ srv.bind(str(self.sock_path))
175
+ os.chmod(self.sock_path, mode) # the box user's group may connect; nobody else
176
+ srv.listen(32)
177
+ srv.settimeout(0.2)
178
+ self._srv = srv
179
+ t = threading.Thread(target=self._accept_loop, daemon=True)
180
+ t.start()
181
+ self._threads.append(t)
182
+ return self
183
+
184
+ def stop(self) -> list[dict]:
185
+ self._stop.set()
186
+ for t in list(self._threads):
187
+ t.join(timeout=5)
188
+ if self._srv is not None:
189
+ self._srv.close()
190
+ try:
191
+ self.sock_path.unlink()
192
+ except FileNotFoundError:
193
+ pass
194
+ return self.log
195
+
196
+ def __enter__(self):
197
+ return self.start()
198
+
199
+ def __exit__(self, *exc):
200
+ self.stop()
201
+
202
+ # -- serving ---------------------------------------------------------------------------
203
+ def _record(self, **entry) -> dict:
204
+ entry = {"t": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "phase": self.phase, **entry}
205
+ with self._lock:
206
+ if len(self.log) < MAX_LOG:
207
+ self.log.append(entry)
208
+ else:
209
+ self.dropped += 1
210
+ return entry
211
+
212
+ def _accept_loop(self):
213
+ while not self._stop.is_set():
214
+ try:
215
+ c, _ = self._srv.accept()
216
+ except socket.timeout:
217
+ continue
218
+ except OSError:
219
+ return
220
+ if not self._slots.acquire(blocking=False):
221
+ self._record(target=None, decision="denied:too-many-connections", upstream=None)
222
+ self._refuse(c, b"HTTP/1.1 503 Service Unavailable\r\n\r\n")
223
+ continue
224
+ try:
225
+ t = threading.Thread(target=self._guarded, args=(c,), daemon=True)
226
+ t.start()
227
+ except RuntimeError: # cannot start a thread: refuse, logged, keep accepting
228
+ self._slots.release()
229
+ self._record(target=None, decision="denied:no-thread", upstream=None)
230
+ c.close()
231
+ continue
232
+ self._threads = [x for x in self._threads if x.is_alive()] + [t]
233
+
234
+ def _refuse(self, c: socket.socket, reply: bytes):
235
+ """Reply to a client the proxy will not serve, AFTER reading its request. Replying and
236
+ closing first let the client's own CONNECT hit a closed socket (EPIPE), so it never read
237
+ the reply (seen 2026-11-15: 11/200 on macOS). The read is bounded by REFUSE_READ_S in
238
+ total, so a silent or trickling client stalls the accept loop for at most that long."""
239
+ deadline = time.monotonic() + REFUSE_READ_S
240
+ buf = b""
241
+ try:
242
+ while b"\r\n\r\n" not in buf and len(buf) <= HEADER_MAX:
243
+ left = deadline - time.monotonic()
244
+ if left <= 0:
245
+ break
246
+ c.settimeout(left)
247
+ d = c.recv(4096)
248
+ if not d:
249
+ break
250
+ buf += d
251
+ except OSError:
252
+ pass
253
+ try:
254
+ c.sendall(reply)
255
+ except OSError:
256
+ pass
257
+ c.close()
258
+
259
+ def _guarded(self, c: socket.socket):
260
+ try:
261
+ self._handle(c)
262
+ finally:
263
+ self._slots.release()
264
+
265
+ def _handle(self, c: socket.socket):
266
+ deadline = time.monotonic() + HEADER_DEADLINE_S
267
+ try:
268
+ buf = b""
269
+ while b"\r\n\r\n" not in buf:
270
+ left = deadline - time.monotonic()
271
+ if left <= 0:
272
+ self._record(target=None, decision="denied:header-deadline", upstream=None)
273
+ return
274
+ c.settimeout(left)
275
+ d = c.recv(4096)
276
+ if not d:
277
+ self._record(target=None, decision="denied:malformed", upstream=None)
278
+ return
279
+ buf += d
280
+ if len(buf) > HEADER_MAX:
281
+ self._record(target=None, decision="denied:header-too-long", upstream=None)
282
+ c.sendall(b"HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n")
283
+ return
284
+ head, rest = buf.split(b"\r\n\r\n", 1)
285
+ line = head.split(b"\r\n", 1)[0].decode("latin-1")
286
+ parts = line.split(" ")
287
+ if len(parts) != 3 or not parts[2].startswith("HTTP/1."):
288
+ self._record(target=None, decision="denied:malformed", upstream=None, line=line[:200])
289
+ c.sendall(b"HTTP/1.1 400 Bad Request\r\n\r\n")
290
+ return
291
+ method, raw_target = parts[0], parts[1]
292
+ if method != "CONNECT":
293
+ self._record(target=raw_target[:200], decision="denied:not-connect", upstream=None)
294
+ c.sendall(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n")
295
+ return
296
+ target = normalise_target(raw_target)
297
+ if target is None or target not in self.allowed:
298
+ self._record(target=target or raw_target[:200], decision="denied:not-in-set", upstream=None)
299
+ c.sendall(b"HTTP/1.1 403 Forbidden\r\n\r\n")
300
+ return
301
+ try:
302
+ up = socket.create_connection(self.resolve(target), timeout=self.connect_timeout)
303
+ except OSError as e:
304
+ self._record(target=target, decision="allowed", upstream=f"error:{type(e).__name__}")
305
+ c.sendall(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
306
+ return
307
+ try:
308
+ peer = "%s:%s" % up.getpeername()[:2] # review F9: which address was reached
309
+ except OSError:
310
+ peer = "?"
311
+ entry = self._record(target=target, decision="allowed", upstream="ok", peer=peer, up=0, down=0)
312
+ c.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
313
+ if rest:
314
+ up.sendall(rest)
315
+ entry["up"] += len(rest)
316
+ self._splice(c, up, entry)
317
+ except socket.timeout:
318
+ self._record(target=None, decision="denied:header-deadline", upstream=None)
319
+ except Exception as e: # review F8: every request is logged, whatever breaks
320
+ self._record(target=None, decision=f"denied:malformed:{type(e).__name__}", upstream=None)
321
+ finally:
322
+ c.close()
323
+
324
+ def _splice(self, c: socket.socket, up: socket.socket, entry: dict):
325
+ def pump(a, b, key):
326
+ try:
327
+ a.settimeout(300)
328
+ while not self._stop.is_set():
329
+ d = a.recv(65536)
330
+ if not d:
331
+ break
332
+ with self._lock:
333
+ self._bytes += len(d)
334
+ over = self._bytes > self.max_bytes
335
+ if over:
336
+ entry["cut"] = f"max-bytes {self.max_bytes}"
337
+ break
338
+ b.sendall(d)
339
+ entry[key] += len(d)
340
+ except OSError:
341
+ pass
342
+ finally:
343
+ for s in (a, b):
344
+ try:
345
+ s.shutdown(socket.SHUT_RDWR)
346
+ except OSError:
347
+ pass
348
+ t = threading.Thread(target=pump, args=(up, c, "down"), daemon=True)
349
+ t.start()
350
+ pump(c, up, "up")
351
+ t.join(timeout=310)
352
+ up.close()
353
+
354
+
355
+ def connect_via(sock_path: Path, target: str, timeout: float = 10) -> int | None:
356
+ """Send one CONNECT through the proxy's unix socket; the status code, or None. Test helper and
357
+ the shape of what the in-box probe does through its forwarder."""
358
+ s = socket.socket(socket.AF_UNIX)
359
+ s.settimeout(timeout)
360
+ try:
361
+ s.connect(str(sock_path))
362
+ s.sendall(f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n".encode())
363
+ line = s.recv(256).split(b"\r\n", 1)[0].decode("latin-1")
364
+ return int(line.split(" ")[1]) if line.startswith("HTTP/1.") else None
365
+ except (OSError, ValueError, IndexError):
366
+ return None
367
+ finally:
368
+ s.close()