tzero-mcp 12.2.1 ā 12.2.2
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.
- package/package.json +1 -1
- package/src/addmcp.py +10 -5
- package/src/app.py +3 -9
- package/src/tzero/__init__.py +1 -1
- package/src/tzero/anti_rea/asar_shield.py +3 -1
- package/src/tzero/anti_rea/auditor.py +42 -12
- package/src/tzero/anti_rea/canary_beacon.py +27 -19
- package/src/tzero/anti_rea/cli.py +7 -1
- package/src/tzero/anti_rea/confusables.py +62 -18
- package/src/tzero/anti_rea/engine.py +79 -10
- package/src/tzero/anti_rea/extractor_shield.py +52 -9
- package/src/tzero/anti_rea/gui.py +1 -4
- package/src/tzero/anti_rea/integrity_guard.py +17 -5
- package/src/tzero/anti_rea/rdtsc_guard.py +21 -8
- package/src/tzero/anti_rea/string_vault.py +10 -7
- package/src/tzero/siber_akademi.ico +0 -0
- package/src/tzero/siber_akademi_icon.py +14 -8
- package/src/tzero/tzero_armor.py +27 -5
- package/src/tzero/tzero_benchmark.py +4 -2
- package/src/tzero/tzero_budget.py +14 -5
- package/src/tzero/tzero_ci.py +1 -1
- package/src/tzero/tzero_contracts.py +7 -5
- package/src/tzero/tzero_dashboard.py +28 -9
- package/src/tzero/tzero_debt.py +19 -4
- package/src/tzero/tzero_explain.py +1 -1
- package/src/tzero/tzero_features.py +43 -29
- package/src/tzero/tzero_federation.py +9 -2
- package/src/tzero/tzero_fixer/mcp_server.py +10 -0
- package/src/tzero/tzero_golden.py +37 -9
- package/src/tzero/tzero_growth.py +166 -8
- package/src/tzero/tzero_guard.py +147 -46
- package/src/tzero/tzero_lsp.py +1 -1
- package/src/tzero/tzero_mcp.py +64 -16
- package/src/tzero/tzero_mutation.py +88 -15
- package/src/tzero/tzero_promo.py +1 -1
- package/src/tzero/tzero_proxy.py +105 -12
- package/src/tzero/tzero_scip.py +12 -6
- package/src/tzero/tzero_security.py +375 -60
- package/src/tzero/tzero_task_benchmark.py +2 -2
- package/src/tzero/tzero_traffic.py +35 -10
- package/src/tzero/tzero_tui.py +17 -8
- package/src/tzero/tzero_v3.py +268 -88
- package/src/tzero/tzero_welcome.py +12 -4
package/src/tzero/tzero_mcp.py
CHANGED
|
@@ -33,7 +33,7 @@ import ast
|
|
|
33
33
|
import inspect
|
|
34
34
|
import logging
|
|
35
35
|
|
|
36
|
-
SERVER_VERSION = "12.2.
|
|
36
|
+
SERVER_VERSION = "12.2.2"
|
|
37
37
|
|
|
38
38
|
# Version checks must not initialize the MCP SDK or dependency bootstrap. Besides
|
|
39
39
|
# being needlessly expensive, that path may wait on package discovery/network
|
|
@@ -1434,22 +1434,47 @@ def create_mcp_server():
|
|
|
1434
1434
|
return "\n".join(out)
|
|
1435
1435
|
return f"š [ZERO-LEAK PASS] File `{target_file}` is 100% clean. Zero hardcoded secrets detected."
|
|
1436
1436
|
|
|
1437
|
-
# Audit entire workspace
|
|
1437
|
+
# Audit entire workspace on FULL unpruned raw files (never AST-pruned skeletons)
|
|
1438
1438
|
scanner = CodebaseScanner()
|
|
1439
|
-
files,
|
|
1439
|
+
files, _, _ = scanner.scan_directory(abs_root)
|
|
1440
1440
|
all_leaks = []
|
|
1441
|
+
fully_scanned = 0
|
|
1442
|
+
partially_scanned = 0
|
|
1443
|
+
skipped = 0
|
|
1444
|
+
unreadable = []
|
|
1441
1445
|
for f in files:
|
|
1442
|
-
|
|
1446
|
+
fp = os.path.join(abs_root, f)
|
|
1447
|
+
try:
|
|
1448
|
+
with open(fp, "r", encoding="utf-8", errors="replace") as fh:
|
|
1449
|
+
content = fh.read()
|
|
1450
|
+
fully_scanned += 1
|
|
1451
|
+
except Exception as exc:
|
|
1452
|
+
unreadable.append(f"{f} ({exc})")
|
|
1453
|
+
continue
|
|
1443
1454
|
leaks = scan_text_for_secrets(content)
|
|
1444
1455
|
for leak in leaks:
|
|
1445
1456
|
all_leaks.append((f, leak))
|
|
1446
|
-
|
|
1457
|
+
|
|
1447
1458
|
if all_leaks:
|
|
1448
|
-
out = [
|
|
1459
|
+
out = [
|
|
1460
|
+
f"šØ **[ZERO-LEAK ALERT] Zero-Leak Security Audit: Found {len(all_leaks)} potential secret leaks in workspace `{abs_root}`!**",
|
|
1461
|
+
f"- Scan Coverage: `{fully_scanned}` fully scanned, `{partially_scanned}` partial, `{skipped}` skipped, `{len(unreadable)}` unreadable\n",
|
|
1462
|
+
]
|
|
1449
1463
|
for fname, leak in all_leaks[:20]:
|
|
1450
1464
|
out.append(f"- `{fname}` (Line {leak['line']}): {leak['desc']}")
|
|
1465
|
+
if unreadable:
|
|
1466
|
+
out.append(f"\nā ļø Unreadable files: {', '.join(unreadable[:10])}")
|
|
1451
1467
|
return "\n".join(out)
|
|
1452
|
-
|
|
1468
|
+
if unreadable or partially_scanned > 0:
|
|
1469
|
+
return (
|
|
1470
|
+
f"ā ļø **[ZERO-LEAK INCOMPLETE]** Scan could not certify `{abs_root}` clean: "
|
|
1471
|
+
f"`{fully_scanned}` full, `{partially_scanned}` partial, `{skipped}` skipped, `{len(unreadable)}` unreadable "
|
|
1472
|
+
f"({', '.join(unreadable[:10])})."
|
|
1473
|
+
)
|
|
1474
|
+
return (
|
|
1475
|
+
f"š [ZERO-LEAK PASS] All {fully_scanned} files in `{abs_root}` (0 partial, 0 skipped, 0 unreadable) "
|
|
1476
|
+
f"passed full raw unpruned Zero-Leak security audit. Zero exposed secrets."
|
|
1477
|
+
)
|
|
1453
1478
|
|
|
1454
1479
|
# -------------------------------------------------------------------------
|
|
1455
1480
|
# TOOL 17: verify_hallucination_guard
|
|
@@ -4738,6 +4763,13 @@ def create_mcp_server():
|
|
|
4738
4763
|
md.append(f"- **Video Prompt:** `{sc.video_prompt}`\n")
|
|
4739
4764
|
return "\n".join(md)
|
|
4740
4765
|
|
|
4766
|
+
elif act in ("telemetry", "savings_telemetry", "sqlite_telemetry"):
|
|
4767
|
+
from tzero.tzero_telemetry import render_report, get_summary
|
|
4768
|
+
target_dir = target if os.path.isdir(target) else "."
|
|
4769
|
+
if opts.get("format") == "json" or query.strip().lower() == "json":
|
|
4770
|
+
return json.dumps(get_summary(workspace_dir=target_dir), indent=2)
|
|
4771
|
+
return render_report(workspace_dir=target_dir)
|
|
4772
|
+
|
|
4741
4773
|
# Fallback to general dispatch
|
|
4742
4774
|
handler = _CANONICAL_DISPATCH.get(act) or _LEGACY_DISPATCH.get(act)
|
|
4743
4775
|
if handler:
|
|
@@ -4759,7 +4791,7 @@ def create_mcp_server():
|
|
|
4759
4791
|
f"ā Unknown action '{act}'.\n"
|
|
4760
4792
|
f"Supported actions: 'auto', 'context', 'audit', 'security', 'blueprint', 'dependencies', "
|
|
4761
4793
|
f"'impact', 'search', 'prune', 'rules', 'enforce', 'cost', 'memory', 'swarm', 'heal', 'design', "
|
|
4762
|
-
f"'patch', 'pagerank', 'dead_code', 'duplicity', 'call_chain', 'sync', 'roi', 'drift', 'ci', 'local_ci', "
|
|
4794
|
+
f"'patch', 'pagerank', 'dead_code', 'duplicity', 'call_chain', 'sync', 'roi', 'drift', 'telemetry', 'ci', 'local_ci', "
|
|
4763
4795
|
f"'armor', 'anti_rea', 'audit_rea'."
|
|
4764
4796
|
)
|
|
4765
4797
|
|
|
@@ -5202,27 +5234,43 @@ def create_mcp_server():
|
|
|
5202
5234
|
)
|
|
5203
5235
|
def resource_file_skeleton(path: str) -> str:
|
|
5204
5236
|
import urllib.parse
|
|
5205
|
-
ws_root = os.path.abspath(".")
|
|
5237
|
+
ws_root = os.path.realpath(os.path.abspath("."))
|
|
5206
5238
|
rel_clean = urllib.parse.unquote(path or "").lstrip("/\\")
|
|
5207
5239
|
if not rel_clean or ".." in rel_clean.replace("\\", "/").split("/"):
|
|
5208
5240
|
return f"[BLOCKED] Unsafe relative path blocked: {rel_clean or path}"
|
|
5209
|
-
|
|
5241
|
+
joined = os.path.abspath(os.path.join(ws_root, rel_clean))
|
|
5242
|
+
if os.path.islink(joined):
|
|
5243
|
+
return f"[BLOCKED] Symlink traversal blocked: {path}"
|
|
5244
|
+
real_target = os.path.realpath(joined)
|
|
5210
5245
|
try:
|
|
5211
|
-
if os.path.commonpath([ws_root,
|
|
5212
|
-
return f"[BLOCKED]
|
|
5246
|
+
if os.path.commonpath([ws_root, real_target]) != ws_root:
|
|
5247
|
+
return f"[BLOCKED] Real path escapes workspace root: {path}"
|
|
5213
5248
|
except ValueError:
|
|
5214
5249
|
return f"[BLOCKED] Invalid workspace path: {path}"
|
|
5215
|
-
if not os.path.isfile(
|
|
5250
|
+
if not os.path.isfile(real_target):
|
|
5216
5251
|
return f"[ERROR] File not found: {rel_clean}"
|
|
5217
5252
|
try:
|
|
5218
|
-
|
|
5219
|
-
|
|
5253
|
+
open_flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
|
|
5254
|
+
fd = os.open(real_target, open_flags)
|
|
5255
|
+
try:
|
|
5256
|
+
st_expected = os.stat(real_target)
|
|
5257
|
+
st_opened = os.fstat(fd)
|
|
5258
|
+
if st_expected.st_ino and st_opened.st_ino and (st_expected.st_ino != st_opened.st_ino or st_expected.st_dev != st_opened.st_dev):
|
|
5259
|
+
return f"[BLOCKED] Target identity changed during open: {path}"
|
|
5260
|
+
with os.fdopen(fd, "r", encoding="utf-8", errors="replace") as fp:
|
|
5261
|
+
fd = -1
|
|
5262
|
+
raw_code = fp.read()
|
|
5263
|
+
finally:
|
|
5264
|
+
if fd >= 0:
|
|
5265
|
+
os.close(fd)
|
|
5220
5266
|
from tzero.tzero_polyglot import PolyglotTokenReducer
|
|
5221
|
-
reduced = PolyglotTokenReducer.reduce_code(raw_code, filename=
|
|
5267
|
+
reduced = PolyglotTokenReducer.reduce_code(raw_code, filename=real_target, mode="ultra")
|
|
5222
5268
|
from tzero.tzero_security import ZeroLeakEngine
|
|
5223
5269
|
if ZeroLeakEngine.scan_text(reduced):
|
|
5224
5270
|
reduced = ZeroLeakEngine.sanitize_text(reduced)
|
|
5225
5271
|
return reduced
|
|
5272
|
+
except OSError as e:
|
|
5273
|
+
return f"[BLOCKED] Unsafe or inaccessible file '{rel_clean}': {e}"
|
|
5226
5274
|
except Exception as e:
|
|
5227
5275
|
return f"[ERROR] Failed to extract skeleton for '{rel_clean}': {e}"
|
|
5228
5276
|
|
|
@@ -212,14 +212,47 @@ class ASTMutationEngine:
|
|
|
212
212
|
|
|
213
213
|
return mutants
|
|
214
214
|
|
|
215
|
+
_ALLOWED_TEST_ARGS = {
|
|
216
|
+
tok: tok
|
|
217
|
+
for tok in ("-m", "unittest", "discover", "pytest", "-v", "-q", "--verbose", "-s", "-p", "-x", "--tb=short", "test_*.py")
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
@classmethod
|
|
221
|
+
def _build_allowed_test_entries(cls, roots: List[str]) -> Dict[str, str]:
|
|
222
|
+
"""Builds an allowlist mapping real filesystem paths to verified on-disk paths."""
|
|
223
|
+
allowed: Dict[str, str] = {}
|
|
224
|
+
for root in roots:
|
|
225
|
+
if not os.path.isdir(root):
|
|
226
|
+
continue
|
|
227
|
+
real_root = os.path.realpath(root)
|
|
228
|
+
for walk_root, dirnames, files in os.walk(real_root):
|
|
229
|
+
dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != "__pycache__"]
|
|
230
|
+
real_dir = os.path.realpath(walk_root)
|
|
231
|
+
rel_dir = os.path.relpath(real_dir, real_root)
|
|
232
|
+
if rel_dir != ".." and not rel_dir.startswith(".." + os.sep) and not os.path.isabs(rel_dir):
|
|
233
|
+
allowed[real_dir] = real_dir
|
|
234
|
+
for fname in files:
|
|
235
|
+
if not fname.endswith(".py"):
|
|
236
|
+
continue
|
|
237
|
+
real_entry = os.path.realpath(os.path.join(walk_root, fname))
|
|
238
|
+
rel_entry = os.path.relpath(real_entry, real_root)
|
|
239
|
+
if rel_entry != ".." and not rel_entry.startswith(".." + os.sep) and not os.path.isabs(rel_entry):
|
|
240
|
+
allowed[real_entry] = real_entry
|
|
241
|
+
return allowed
|
|
242
|
+
|
|
215
243
|
@staticmethod
|
|
216
244
|
def _sanitize_target_path(target_path: str) -> str:
|
|
217
245
|
if not target_path or "\x00" in target_path:
|
|
218
246
|
raise ValueError("Invalid target path.")
|
|
219
247
|
ws_root = os.path.realpath(".")
|
|
220
248
|
tmp_root = os.path.realpath(tempfile.gettempdir())
|
|
221
|
-
|
|
222
|
-
if
|
|
249
|
+
resolved = os.path.realpath(os.path.abspath(target_path))
|
|
250
|
+
base_root = tmp_root if (resolved == tmp_root or resolved.startswith(tmp_root + os.sep)) else ws_root
|
|
251
|
+
rel = os.path.relpath(resolved, base_root)
|
|
252
|
+
if rel == ".." or rel.startswith(".." + os.sep) or os.path.isabs(rel):
|
|
253
|
+
raise ValueError(f"Path outside allowed workspace or temp scope: {target_path}")
|
|
254
|
+
real_target = os.path.normpath(os.path.join(base_root, rel))
|
|
255
|
+
if not real_target.startswith(base_root):
|
|
223
256
|
raise ValueError(f"Path outside allowed workspace or temp scope: {target_path}")
|
|
224
257
|
return real_target
|
|
225
258
|
|
|
@@ -233,7 +266,16 @@ class ASTMutationEngine:
|
|
|
233
266
|
) -> MutationReport:
|
|
234
267
|
"""Executes full mutation testing on target_file against test_command."""
|
|
235
268
|
start_time = time.time()
|
|
236
|
-
|
|
269
|
+
ws_root = os.path.realpath(".")
|
|
270
|
+
tmp_root = os.path.realpath(tempfile.gettempdir())
|
|
271
|
+
resolved_t = os.path.realpath(os.path.abspath(cls._sanitize_target_path(target_file)))
|
|
272
|
+
base_root = tmp_root if (resolved_t == tmp_root or resolved_t.startswith(tmp_root + os.sep)) else ws_root
|
|
273
|
+
rel_t = os.path.relpath(resolved_t, base_root)
|
|
274
|
+
if rel_t == ".." or rel_t.startswith(".." + os.sep) or os.path.isabs(rel_t):
|
|
275
|
+
raise ValueError(f"Target path outside allowed root: {target_file}")
|
|
276
|
+
abs_target = os.path.normpath(os.path.join(base_root, rel_t))
|
|
277
|
+
if not abs_target.startswith(base_root):
|
|
278
|
+
raise ValueError(f"Target path outside allowed root: {target_file}")
|
|
237
279
|
if not os.path.isfile(abs_target):
|
|
238
280
|
raise FileNotFoundError(f"Target file not found: {target_file}")
|
|
239
281
|
|
|
@@ -254,15 +296,29 @@ class ASTMutationEngine:
|
|
|
254
296
|
mutants=[]
|
|
255
297
|
)
|
|
256
298
|
|
|
257
|
-
|
|
299
|
+
target_dir = os.path.dirname(abs_target)
|
|
300
|
+
expected_test_name = f"test_{os.path.splitext(os.path.basename(abs_target))[0]}.py"
|
|
301
|
+
|
|
302
|
+
# Discover untainted test files strictly from workspace root (and tzero_* temp dirs)
|
|
303
|
+
discover_roots = [ws_root]
|
|
304
|
+
try:
|
|
305
|
+
for d_entry in os.scandir(tmp_root):
|
|
306
|
+
if d_entry.is_dir() and d_entry.name.startswith("tzero_"):
|
|
307
|
+
discover_roots.append(os.path.realpath(d_entry.path))
|
|
308
|
+
except OSError:
|
|
309
|
+
pass
|
|
310
|
+
|
|
311
|
+
# Build argv strictly from fixed flags and untainted on-disk entries without shell=True
|
|
258
312
|
if not test_command:
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
313
|
+
ws_tests_map: Dict[str, str] = {}
|
|
314
|
+
ws_tests_root = os.path.join(ws_root, "tests")
|
|
315
|
+
if os.path.isdir(ws_tests_root):
|
|
316
|
+
for fn in os.listdir(ws_tests_root):
|
|
317
|
+
if fn.startswith("test_") and fn.endswith(".py"):
|
|
318
|
+
ws_tests_map[fn] = os.path.join(ws_tests_root, fn)
|
|
319
|
+
matched_test = ws_tests_map.get(expected_test_name)
|
|
320
|
+
if matched_test:
|
|
321
|
+
test_cmd_args = [sys.executable, "-m", "unittest", matched_test]
|
|
266
322
|
else:
|
|
267
323
|
test_cmd_args = [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-p", "test_*.py"]
|
|
268
324
|
else:
|
|
@@ -277,20 +333,35 @@ class ASTMutationEngine:
|
|
|
277
333
|
raise ValueError("Empty test_command.")
|
|
278
334
|
bin_name = os.path.basename(parsed_args[0]).lower()
|
|
279
335
|
if bin_name.startswith("python"):
|
|
280
|
-
|
|
336
|
+
runner_prefix = [sys.executable]
|
|
281
337
|
elif bin_name in ("pytest", "pytest.exe"):
|
|
282
|
-
|
|
338
|
+
runner_prefix = [sys.executable, "-m", "pytest"]
|
|
283
339
|
else:
|
|
284
340
|
raise ValueError(f"Unsupported test runner executable: {parsed_args[0]}")
|
|
285
341
|
|
|
342
|
+
allowed_entries = cls._build_allowed_test_entries(discover_roots)
|
|
343
|
+
safe_tail: List[str] = []
|
|
344
|
+
for tok in parsed_args[1:]:
|
|
345
|
+
if tok in cls._ALLOWED_TEST_ARGS:
|
|
346
|
+
safe_tail.append(cls._ALLOWED_TEST_ARGS[tok])
|
|
347
|
+
else:
|
|
348
|
+
cand_primary = os.path.realpath(os.path.abspath(tok))
|
|
349
|
+
cand_rel = os.path.realpath(os.path.join(target_dir, tok))
|
|
350
|
+
matched_rel = allowed_entries.get(cand_primary) or allowed_entries.get(cand_rel)
|
|
351
|
+
if not matched_rel:
|
|
352
|
+
raise ValueError(f"Unsupported or missing test argument: {tok}")
|
|
353
|
+
safe_tail.append(matched_rel)
|
|
354
|
+
test_cmd_args = runner_prefix + safe_tail
|
|
355
|
+
|
|
286
356
|
killed = 0
|
|
287
357
|
survived = 0
|
|
288
358
|
timeouts = 0
|
|
289
359
|
errors = 0
|
|
290
360
|
|
|
291
|
-
target_dir = os.path.dirname(abs_target)
|
|
292
361
|
safe_bak_name = os.path.basename(abs_target) + ".tzero_mut_bak"
|
|
293
|
-
backup_path = os.path.join(target_dir, safe_bak_name)
|
|
362
|
+
backup_path = os.path.normpath(os.path.join(target_dir, safe_bak_name))
|
|
363
|
+
if not backup_path.startswith(target_dir):
|
|
364
|
+
raise ValueError("Backup path escaped target directory.")
|
|
294
365
|
with open(backup_path, "w", encoding="utf-8") as f:
|
|
295
366
|
f.write(original_code)
|
|
296
367
|
|
|
@@ -301,6 +372,8 @@ class ASTMutationEngine:
|
|
|
301
372
|
try:
|
|
302
373
|
for m in mutants:
|
|
303
374
|
# Write mutant to disk
|
|
375
|
+
if not abs_target.startswith(base_root):
|
|
376
|
+
raise ValueError("Target path escaped allowed root.")
|
|
304
377
|
with open(abs_target, "w", encoding="utf-8") as f:
|
|
305
378
|
f.write(m.mutated_code)
|
|
306
379
|
|
package/src/tzero/tzero_promo.py
CHANGED
package/src/tzero/tzero_proxy.py
CHANGED
|
@@ -15,6 +15,7 @@ import re
|
|
|
15
15
|
import socketserver
|
|
16
16
|
import sys
|
|
17
17
|
import threading
|
|
18
|
+
import time
|
|
18
19
|
from typing import Any, Dict, Optional, Tuple
|
|
19
20
|
|
|
20
21
|
logger = logging.getLogger("tzero.proxy")
|
|
@@ -84,16 +85,93 @@ class LiveContextPruner:
|
|
|
84
85
|
|
|
85
86
|
|
|
86
87
|
class ContextProxyHandler(http.server.BaseHTTPRequestHandler):
|
|
87
|
-
"""HTTP handler that intercepts /v1/chat/completions."""
|
|
88
|
+
"""HTTP handler that intercepts /v1/chat/completions with strict request bounds."""
|
|
89
|
+
|
|
90
|
+
MAX_BODY_BYTES = 2 * 1024 * 1024 # 2 MiB max JSON payload
|
|
91
|
+
MAX_REJECT_DRAIN_BYTES = 8 * 1024 * 1024 # Bound unread TCP drain on 413 to avoid Winsock RST
|
|
92
|
+
REQUEST_TIMEOUT = 10.0
|
|
93
|
+
|
|
94
|
+
def setup(self) -> None:
|
|
95
|
+
super().setup()
|
|
96
|
+
try:
|
|
97
|
+
self.connection.settimeout(self.REQUEST_TIMEOUT)
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
88
100
|
|
|
89
101
|
def log_message(self, format: str, *args: Any) -> None:
|
|
90
102
|
pass # quiet
|
|
91
103
|
|
|
104
|
+
def _drain_rejected_body(self, content_length: int) -> None:
|
|
105
|
+
"""Briefly drain bounded unread bytes so TCP close sends FIN instead of RST."""
|
|
106
|
+
to_drain = min(max(0, content_length), self.MAX_REJECT_DRAIN_BYTES)
|
|
107
|
+
if to_drain <= 0:
|
|
108
|
+
return
|
|
109
|
+
deadline = time.monotonic() + 0.5
|
|
110
|
+
try:
|
|
111
|
+
self.connection.settimeout(0.1)
|
|
112
|
+
remaining = to_drain
|
|
113
|
+
while remaining > 0 and time.monotonic() < deadline:
|
|
114
|
+
chunk = self.rfile.read1(min(remaining, 65536)) if hasattr(self.rfile, "read1") else self.rfile.read(min(remaining, 65536))
|
|
115
|
+
if not chunk:
|
|
116
|
+
break
|
|
117
|
+
remaining -= len(chunk)
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
|
|
121
|
+
def _send_json_error(self, code: int, msg: str, drain_bytes: int = 0) -> None:
|
|
122
|
+
err_msg = json.dumps({"error": msg}).encode("utf-8")
|
|
123
|
+
self.close_connection = True
|
|
124
|
+
self.send_response(code)
|
|
125
|
+
self.send_header("Content-Type", "application/json")
|
|
126
|
+
self.send_header("Content-Length", str(len(err_msg)))
|
|
127
|
+
self.send_header("Connection", "close")
|
|
128
|
+
self.end_headers()
|
|
129
|
+
self.wfile.write(err_msg)
|
|
130
|
+
self.wfile.flush()
|
|
131
|
+
if drain_bytes > 0:
|
|
132
|
+
self._drain_rejected_body(drain_bytes)
|
|
133
|
+
|
|
92
134
|
def do_POST(self) -> None:
|
|
93
|
-
|
|
94
|
-
|
|
135
|
+
sem = getattr(self.server, "concurrency_semaphore", None)
|
|
136
|
+
acquired = False
|
|
137
|
+
if sem is not None:
|
|
138
|
+
acquired = sem.acquire(blocking=False)
|
|
139
|
+
if not acquired:
|
|
140
|
+
self._send_json_error(503, "Too many concurrent requests")
|
|
141
|
+
return
|
|
95
142
|
|
|
96
143
|
try:
|
|
144
|
+
raw_len = self.headers.get("Content-Length")
|
|
145
|
+
if raw_len is None:
|
|
146
|
+
self._send_json_error(411, "Content-Length header required")
|
|
147
|
+
return
|
|
148
|
+
try:
|
|
149
|
+
content_length = int(raw_len)
|
|
150
|
+
except ValueError:
|
|
151
|
+
self._send_json_error(400, "Invalid Content-Length header")
|
|
152
|
+
return
|
|
153
|
+
if content_length < 0:
|
|
154
|
+
self._send_json_error(400, "Negative Content-Length rejected")
|
|
155
|
+
return
|
|
156
|
+
if content_length > self.MAX_BODY_BYTES:
|
|
157
|
+
self._send_json_error(
|
|
158
|
+
413,
|
|
159
|
+
f"Payload exceeds {self.MAX_BODY_BYTES} byte limit",
|
|
160
|
+
drain_bytes=content_length,
|
|
161
|
+
)
|
|
162
|
+
return
|
|
163
|
+
|
|
164
|
+
raw_bytes = bytearray()
|
|
165
|
+
remaining = content_length
|
|
166
|
+
while remaining > 0:
|
|
167
|
+
chunk = self.rfile.read(min(remaining, 65536))
|
|
168
|
+
if not chunk:
|
|
169
|
+
self._send_json_error(400, "Truncated request body")
|
|
170
|
+
return
|
|
171
|
+
raw_bytes.extend(chunk)
|
|
172
|
+
remaining -= len(chunk)
|
|
173
|
+
|
|
174
|
+
body = raw_bytes.decode("utf-8", errors="replace")
|
|
97
175
|
data = json.loads(body)
|
|
98
176
|
pruned_data, saved = LiveContextPruner.prune_payload(data)
|
|
99
177
|
resp = {
|
|
@@ -110,18 +188,33 @@ class ContextProxyHandler(http.server.BaseHTTPRequestHandler):
|
|
|
110
188
|
self.send_header("X-TZero-Saved-Tokens", str(saved))
|
|
111
189
|
self.end_headers()
|
|
112
190
|
self.wfile.write(resp_bytes)
|
|
191
|
+
except TimeoutError:
|
|
192
|
+
try:
|
|
193
|
+
self._send_json_error(408, "Request body read timed out")
|
|
194
|
+
except Exception:
|
|
195
|
+
pass
|
|
113
196
|
except Exception as exc:
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
197
|
+
try:
|
|
198
|
+
self._send_json_error(400, str(exc))
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
finally:
|
|
202
|
+
if sem is not None and acquired:
|
|
203
|
+
sem.release()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class _BoundedThreadingHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
|
|
207
|
+
daemon_threads = True
|
|
208
|
+
allow_reuse_address = True
|
|
209
|
+
|
|
210
|
+
def __init__(self, server_address: Tuple[str, int], handler_cls: Any, max_concurrent: int = 16):
|
|
211
|
+
self.concurrency_semaphore = threading.Semaphore(max(1, int(max_concurrent)))
|
|
212
|
+
super().__init__(server_address, handler_cls)
|
|
120
213
|
|
|
121
214
|
|
|
122
|
-
def start_context_proxy(host: str = "127.0.0.1", port: int = 7350) -> socketserver.TCPServer:
|
|
123
|
-
"""Start local transparent context optimizer proxy."""
|
|
124
|
-
server =
|
|
215
|
+
def start_context_proxy(host: str = "127.0.0.1", port: int = 7350, max_concurrent: int = 16) -> socketserver.TCPServer:
|
|
216
|
+
"""Start local transparent context optimizer proxy with timeout and concurrency limits."""
|
|
217
|
+
server = _BoundedThreadingHTTPServer((host, port), ContextProxyHandler, max_concurrent=max_concurrent)
|
|
125
218
|
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
|
|
126
219
|
server_thread.start()
|
|
127
220
|
return server
|
package/src/tzero/tzero_scip.py
CHANGED
|
@@ -344,12 +344,18 @@ class ScipIndexImporter:
|
|
|
344
344
|
ws_root = os.path.realpath(".")
|
|
345
345
|
tmp_root = os.path.realpath(tempfile.gettempdir())
|
|
346
346
|
home_root = os.path.realpath(os.path.expanduser("~"))
|
|
347
|
-
|
|
348
|
-
if (
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
347
|
+
cand_path = os.path.realpath(os.path.abspath(path))
|
|
348
|
+
if cand_path == tmp_root or cand_path.startswith(tmp_root + os.sep):
|
|
349
|
+
base_root = tmp_root
|
|
350
|
+
elif cand_path == home_root or cand_path.startswith(home_root + os.sep):
|
|
351
|
+
base_root = home_root
|
|
352
|
+
else:
|
|
353
|
+
base_root = ws_root
|
|
354
|
+
rel_path = os.path.relpath(cand_path, base_root)
|
|
355
|
+
if rel_path == ".." or rel_path.startswith(".." + os.sep) or os.path.isabs(rel_path):
|
|
356
|
+
raise ValueError(f"SCIP/LSIF path outside allowed scope: {path}")
|
|
357
|
+
real_path = os.path.normpath(os.path.join(base_root, rel_path))
|
|
358
|
+
if not real_path.startswith(base_root):
|
|
353
359
|
raise ValueError(f"SCIP/LSIF path outside allowed scope: {path}")
|
|
354
360
|
if not os.path.isfile(real_path):
|
|
355
361
|
raise FileNotFoundError(f"SCIP/LSIF index file not found: {path}")
|