From 1cbb0ca3b0ba6a4a759cc078dd6b59a58e05db53 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 19:11:44 +0530 Subject: [PATCH 01/53] feat(setup): report run start and end to the install report [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 115 +++++++++++++++++++--- binary/tests/test_setup_migration.py | 3 + binary/tests/test_setup_reporting.py | 138 +++++++++++++++++++++++++++ 3 files changed, 241 insertions(+), 15 deletions(-) create mode 100644 binary/tests/test_setup_reporting.py diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index ab707664d..e5d2716b1 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -27,8 +27,10 @@ import subprocess import sys import time +from datetime import datetime, timezone from pathlib import Path +from . import __version__ from ._loader import load_mdm_setup_module from ._resources import ( DISCOVERY_BINARY, @@ -98,6 +100,27 @@ def _parse_args(argv): return opts +# Reports about this run (start/end, hook errors) must never hold setup up. +REPORT_TIMEOUT_SECONDS = 5 + + +def _post_json(url, body, headers, timeout=REPORT_TIMEOUT_SECONDS): + """POST a JSON body with curl (the system trust store, as every call here uses). + Returns (http status, response bytes); status 0 when nothing came back. Never raises.""" + cmd = ["curl", "-sS", "-m", str(timeout), "-X", "POST", "-w", "\n%{http_code}", + "-H", "Content-Type: application/json"] + for name, value in headers.items(): + cmd += ["-H", f"{name}: {value}"] + cmd += ["--data-binary", "@-", "--", url] + try: + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=timeout + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + + def _module(tool): m = load_mdm_setup_module(tool) m.DEBUG = True # MDM runs always log diagnostics (parity with python path) @@ -110,6 +133,71 @@ def _normalized_urls(m, opts): return base, gateway +def _write_user_config(m, opts, username, home_dir, api_key) -> bool: + """Every adapter's per-user ~/.unbound/config.json write, tallied per home for the end report: + a home counts as configured only if every tool that reached it wrote there.""" + base, gateway = _normalized_urls(m, opts) + ok = m.write_unbound_config_for_user( + username, home_dir, api_key, + urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) + writes = opts.setdefault("config_writes", {}) + writes[str(home_dir)] = writes.get(str(home_dir), True) and bool(ok) + return ok + + +# --------------------------------------------------------------------------- +# Run reports (WEB-6392): the device's install report hears when this run +# started and how it ended, on the endpoint and admin key onboard.sh's exit +# report uses. Fail-open: a report that can't be sent logs one line. +# --------------------------------------------------------------------------- + +INSTALL_REPORT_PATH = "/api/v1/automations/mdm/install-report/" + + +def _utc_now() -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _send_run_report(opts, serial, phase, fields) -> None: + try: + if not serial: # the endpoint joins on it; without one the report is dropped anyway + print(f"[report] install-report {phase} not sent: no device serial") + return + body = {"serial_number": serial, "phase": phase, + "install_mode": "binary-skip" if opts["skip_managed_settings"] else "binary", **fields} + code, _ = _post_json(opts["backend_url"] + INSTALL_REPORT_PATH, body, {"X-API-KEY": opts["api_key"]}) + if not 200 <= code < 300: + print(f"[report] install-report {phase} not sent: HTTP {code}") + except Exception as e: + print(f"[report] install-report {phase} not sent: {e}") + + +def _start_fields() -> dict: + host = {"hostname": platform.node(), "arch": platform.machine()} + return {"runtime_version": __version__, + "os_version": platform.mac_ver()[0] or platform.release(), + **{k: v for k, v in host.items() if v}, + "timestamps": {"started_at": _utc_now()}} + + +def _preflight_warnings(user_homes) -> list: + """What this run can already tell will keep the device from reporting.""" + warnings = [] + if not HOOK_BINARY.is_file(): # every managed hook command points at it + warnings.append(f"hook binary not found at {HOOK_BINARY}") + if not user_homes: + warnings.append("no user homes found") + return warnings + + +def _end_fields(opts, user_homes, warnings) -> dict: + writes = opts.get("config_writes", {}) + configured = sum(1 for _, home in user_homes if writes.get(str(home)) is True) + return {"timestamps": {"completed_at": _utc_now()}, + "preflight_warnings": warnings, + "user_homes": {"configured": configured, "skipped": len(user_homes) - configured}} + + def _detect_state(settings_path: Path, expected_hooks, relative_ok=False): """'persisted' if every event runs our exact command (or the python-era unbound.py being migrated), 'tampered' otherwise or if unparsable, 'fresh' with no file, None if unreadable. Admin-owned files only.""" @@ -1027,9 +1115,7 @@ def _setup_claude_code(opts): for username, home_dir in m.get_all_user_homes(): m.remove_gateway_artifacts_for_user(username, home_dir) m.remove_user_level_hooks_for_user(username, home_dir) - config_ok = m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) and config_ok + config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok m.remove_legacy_key_env() skip_settings = opts["skip_managed_settings"] @@ -1086,9 +1172,7 @@ def _setup_augment(opts): config_ok = True user_homes = m.get_all_user_homes() for username, home_dir in user_homes: - config_ok = m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) and config_ok + config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok m.remove_legacy_key_env() state = _detect_state(m.get_managed_settings_dir() / "settings.json", _augment_written_hooks(m)) @@ -1136,9 +1220,7 @@ def _setup_codex(opts): config_ok = True for username, home_dir in user_homes: m.remove_gateway_artifacts_for_user(username, home_dir) - config_ok = m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) and config_ok + config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok m.enable_codex_hooks_feature_for_user(username, home_dir) _strip_codex_user_hooks(m, username, home_dir) # After the new hooks are in place: an older codex hook reads only the per-tool var. @@ -1336,9 +1418,7 @@ def _setup_cursor(opts): config_ok = True for username, home_dir in m.get_all_user_homes(): - if m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}): + if _write_user_config(m, opts, username, home_dir, api_key): m.remove_user_level_hooks(username, home_dir) else: config_ok = False @@ -1430,9 +1510,7 @@ def _setup_copilot(opts): for username, home_dir in user_homes: if home_dir is None: continue # no home to hold a config or a registration - config_ok = m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) and config_ok + config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok # Earlier versions configured the exporter here, per user, in VS Code # settings. The managed file written below outranks those, so they are only # taken back out. @@ -1564,6 +1642,12 @@ def run(argv) -> int: if opts["frontend_url"]: opts["frontend_url"] = m0.normalize_url(opts["frontend_url"]) + opts["config_writes"] = {} + serial = m0.get_device_identifier() + user_homes = m0.get_all_user_homes() + warnings = _preflight_warnings(user_homes) + _send_run_report(opts, serial, "start", _start_fields()) + statuses = {} print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") @@ -1597,4 +1681,5 @@ def run(argv) -> int: print(line) if status == "deferred": any_deferred = True + _send_run_report(opts, serial, "end", _end_fields(opts, user_homes, warnings)) return 1 if any_deferred else 0 diff --git a/binary/tests/test_setup_migration.py b/binary/tests/test_setup_migration.py index a5a93e779..56b955fce 100644 --- a/binary/tests/test_setup_migration.py +++ b/binary/tests/test_setup_migration.py @@ -80,6 +80,9 @@ def env(tmp_path, monkeypatch): discovery_bin.write_text("#!/bin/sh\nexit 0\n") discovery_bin.chmod(0o755) monkeypatch.setattr(setup_cmd, "DISCOVERY_BINARY", discovery_bin) + # The run's own reports never leave the machine from a test; test_setup_reporting + # points them at a local server instead. + monkeypatch.setattr(setup_cmd, "_post_json", lambda *a, **k: (0, b"")) return {"tmp": tmp_path, "home": home, "modules": modules, "notified": notified, "backfilled": backfilled, "bounded": bounded, "bootouts": bootouts, "daemon_bootouts": daemon_bootouts} diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py new file mode 100644 index 000000000..0bfbd17a1 --- /dev/null +++ b/binary/tests/test_setup_reporting.py @@ -0,0 +1,138 @@ +"""WEB-6392: what `unbound-hook setup` tells the backend about its own run. + +Driven end to end through setup_cmd.run against a real HTTP server on 127.0.0.1, +so the curl requests are the ones a Mac sends. The vendored modules' root-only +primitives are stubbed by the `env` fixture, as in test_setup_migration. +""" + +import json +import re +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from unbound_hook import __version__, setup_cmd +from test_setup_migration import env # noqa: F401 (the shared sandbox fixture) + +REAL_POST_JSON = setup_cmd._post_json +ISO_Z = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") + + +class _Recorder(BaseHTTPRequestHandler): + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) + try: + body = json.loads(raw.decode("utf-8")) + except ValueError: + body = raw + self.server.requests.append({"path": self.path, "headers": dict(self.headers), "body": body}) + status, answer = self.server.answer(self.path) + data = json.dumps(answer).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *args): + pass + + +@pytest.fixture +def backend(monkeypatch): + """A local stand-in for both the backend and the gateway. The env fixture keeps + setup off the network; these tests let it talk to this server only.""" + server = ThreadingHTTPServer(("127.0.0.1", 0), _Recorder) + server.requests = [] + server.answer = lambda path: (200, {"status": "ok", "success": True, "accepted": 1}) + threading.Thread(target=server.serve_forever, daemon=True).start() + monkeypatch.setattr(setup_cmd, "_post_json", REAL_POST_JSON) + server.url = "http://127.0.0.1:%d" % server.server_address[1] + yield server + server.shutdown() + server.server_close() + + +def _run(backend, *extra): + return setup_cmd.run(["--api-key", "admin-key", "--backend-url", backend.url, + "--gateway-url", backend.url, *extra]) + + +def _run_reports(backend): + return [r for r in backend.requests if r["path"] == "/api/v1/automations/mdm/install-report/"] + + +# --- Step 2: start and end reports ------------------------------------------- + +def test_setup_reports_its_start_first_and_its_end_last(env, backend): + assert _run(backend) == 0 + reports = _run_reports(backend) + assert [r["body"]["phase"] for r in reports] == ["start", "end"] + assert backend.requests[0] is reports[0] and backend.requests[-1] is reports[-1] + + start, end = reports[0]["body"], reports[1]["body"] + assert start["serial_number"] == end["serial_number"] == "TESTSERIAL1" + assert start["install_mode"] == end["install_mode"] == "binary" + assert start["runtime_version"] == __version__ + assert isinstance(start["os_version"], str) and start["os_version"] + assert ISO_Z.match(start["timestamps"]["started_at"]) + assert ISO_Z.match(end["timestamps"]["completed_at"]) + assert end["user_homes"] == {"configured": 1, "skipped": 0} + assert isinstance(end["preflight_warnings"], list) + # A run report never carries a tool list: the backend would read it as a full snapshot. + assert "components" not in start and "components" not in end + # The same credentials onboard.sh's exit report uses: the MDM admin key. + assert all(r["headers"]["X-API-KEY"] == "admin-key" for r in reports) + + +def test_a_run_without_managed_settings_reports_that_mode(env, backend): + assert _run(backend, "--skip-managed-settings") == 0 + assert {r["body"]["install_mode"] for r in _run_reports(backend)} == {"binary-skip"} + + +def test_a_home_whose_config_write_failed_counts_as_skipped(env, backend, monkeypatch): + monkeypatch.setattr(env["modules"]["cursor"], "write_unbound_config_for_user", lambda *a, **k: False) + assert _run(backend) == 1 # cursor defers, as before + end = _run_reports(backend)[-1]["body"] + assert end["user_homes"] == {"configured": 0, "skipped": 1} + + +def test_a_missing_hook_binary_is_a_preflight_warning(env, backend, monkeypatch, tmp_path): + monkeypatch.setattr(setup_cmd, "HOOK_BINARY", tmp_path / "gone" / "unbound-hook") + assert _run(backend) == 0 + warnings = _run_reports(backend)[-1]["body"]["preflight_warnings"] + assert warnings == [f"hook binary not found at {tmp_path / 'gone' / 'unbound-hook'}"] + + +def test_an_installed_hook_binary_leaves_no_preflight_warning(env, backend, monkeypatch, tmp_path): + binary = tmp_path / "unbound-hook" + binary.write_text("#!/bin/sh\n") + monkeypatch.setattr(setup_cmd, "HOOK_BINARY", binary) + assert _run(backend) == 0 + assert _run_reports(backend)[-1]["body"]["preflight_warnings"] == [] + + +def test_a_device_without_a_serial_sends_no_run_report(env, backend, monkeypatch): + for m in env["modules"].values(): + monkeypatch.setattr(m, "get_device_identifier", lambda: None) + _run(backend) + assert _run_reports(backend) == [] + + +def test_an_unreachable_backend_changes_nothing_about_the_run(env, backend, capsys): + rc = setup_cmd.run(["--api-key", "admin-key", "--backend-url", "http://127.0.0.1:9", + "--gateway-url", "http://127.0.0.1:9"]) + assert rc == 0 + assert (env["tmp"] / "managed-claude" / "managed-settings.json").exists() + out = capsys.readouterr().out + assert "[report] install-report start not sent" in out + assert "[report] install-report end not sent" in out + + +def test_a_backend_error_changes_nothing_about_the_run(env, backend, capsys): + backend.answer = lambda path: (500, {"error": "boom"}) + assert _run(backend) == 0 + assert [r["body"]["phase"] for r in _run_reports(backend)] == ["start", "end"] + assert "[report] install-report end not sent: HTTP 500" in capsys.readouterr().out From cb7a480ec97a159ddb8e8f2a7dff06d59a5b07b9 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 19:19:40 +0530 Subject: [PATCH 02/53] feat(setup): report every tool's setup outcome each run [WEB-6392] --- augment/hooks/mdm/setup.py | 10 +- binary/README.md | 7 +- binary/src/unbound_hook/setup_cmd.py | 153 ++++++++++++++++++++------- binary/tests/test_setup_migration.py | 6 +- binary/tests/test_setup_reporting.py | 135 +++++++++++++++++++++++ claude-code/hooks/mdm/setup.py | 10 +- codex/hooks/mdm/setup.py | 10 +- copilot/hooks/mdm/setup.py | 10 +- cursor/mdm/setup.py | 10 +- 9 files changed, 302 insertions(+), 49 deletions(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index d9678c924..5de66c6c1 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1442,8 +1442,11 @@ def hook_script_hash(script_path) -> Optional[str]: def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend how tool setup ended. Never fails the setup. status is configured, skipped or + deferred; left out, the backend reads configured, as from older installers.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -1455,6 +1458,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) # X-API-KEY off-argv via 0600 temp header file; body off-argv via stdin. curl_with_auth( diff --git a/binary/README.md b/binary/README.md index cc6d9cc49..956be3fb1 100644 --- a/binary/README.md +++ b/binary/README.md @@ -79,7 +79,12 @@ the python path, by design: - **Per-component status** (`configured | skipped(reason) | deferred(reason)`) with fail-open orchestration: a component failure is reported in the summary + exit code but never aborts the others. `deferred` means a re-run - should retry; `skipped` is intentional. + should retry; `skipped` is intentional. Every tool that got its device key + sends this status, reason and `written_to` to `/api/v1/setup/complete/` each + run; a tool with no footprint on the Mac (`_TOOL_FOOTPRINTS`) is still + written but reported `skipped` (" is not installed"). A discovery run + that prints `Scan skipped: ` is `skipped`. The run itself posts + `phase: start` first and `phase: end` last to the MDM install report. - **`detect_install_state`** is adapted: the python version checked for the managed `unbound.py`, which no longer exists. Binary semantics: settings file absent → `fresh`; present and referencing the binary → `persisted`; diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index e5d2716b1..2028cceba 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -18,6 +18,7 @@ but never aborts the remaining components. """ +import functools import json import math import os @@ -26,6 +27,7 @@ import stat import subprocess import sys +import threading import time from datetime import datetime, timezone from pathlib import Path @@ -190,6 +192,58 @@ def _preflight_warnings(user_homes) -> list: return warnings +# --------------------------------------------------------------------------- +# Per-tool outcome (WEB-6392): every tool sends setup/complete every run, +# configured | skipped | deferred, with the reason setup prints. +# --------------------------------------------------------------------------- + +_TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", + "copilot": "copilot", "augment": "augment_code"} + +# What an installed tool leaves on disk: (name, its CLI, its app bundles, other files under a home). +# None of these is a file setup writes, so a re-run never takes its own files for the tool. +_TOOL_FOOTPRINTS = { + "claude-code": ("Claude Code", "claude", ("Claude.app",), (".claude/local/claude", ".claude.json")), + "cursor": ("Cursor", "cursor-agent", ("Cursor.app",), ()), + "codex": ("Codex", "codex", ("Codex.app",), (".codex/auth.json", ".codex/sessions")), + "copilot": ("GitHub Copilot", "copilot", + ("Visual Studio Code.app", "Visual Studio Code - Insiders.app"), ()), + "augment": ("Augment", "auggie", (), ()), +} +_MACHINE_ROOT = Path("/") + + +def _present(root: Path, relpath: str) -> bool: + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return False + + +def _tool_installed(tool, user_homes) -> bool: + """Any footprint machine-wide (Homebrew, /usr/local, /Applications) or in a home (a user install, Bun, + npm, nvm, ~/Applications). A check that fails counts as installed, the report setup always sent.""" + try: + _, cli, apps, home_files = _TOOL_FOOTPRINTS[tool] + app_paths = [f"Applications/{app}" for app in apps] + machine = [f"opt/homebrew/bin/{cli}", f"usr/local/bin/{cli}", *app_paths] + per_home = [f".local/bin/{cli}", f".bun/bin/{cli}", f".npm-global/bin/{cli}", + f".nvm/versions/node/*/bin/{cli}", *home_files, *app_paths] + roots = [(_MACHINE_ROOT, machine)] + [(home, per_home) for _, home in user_homes if home is not None] + return any(_present(root, rel) for root, rels in roots for rel in rels) + except Exception: + return True + + +def _report(m, tool, api_key, status, reason=None, **fields): + """This tool's setup/complete call for the run; returns the (status, reason) it sent. Configured on a Mac + without the tool reads skipped: its config is still written, so the hook works once the tool arrives.""" + if status == "configured" and not _tool_installed(tool, m.get_all_user_homes()): + status, reason = "skipped", f"{_TOOL_FOOTPRINTS[tool][0]} is not installed" + m.notify_setup_complete(api_key, _TOOL_TYPES[tool], status=status, reason=reason, **fields) + return status, reason + + def _end_fields(opts, user_homes, warnings) -> dict: writes = opts.get("config_writes", {}) configured = sum(1 for _, home in user_homes if writes.get(str(home)) is True) @@ -1106,6 +1160,9 @@ def _setup_claude_code(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") + skip_settings = opts["skip_managed_settings"] + report = functools.partial(_report, m, "claude-code", api_key, backend_url=base, serial_number=device_id, + install_mode="binary-skip" if skip_settings else "binary") for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "UNBOUND_API_KEY") @@ -1118,13 +1175,12 @@ def _setup_claude_code(opts): config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok m.remove_legacy_key_env() - skip_settings = opts["skip_managed_settings"] # None (unknown) without looking: in skip mode managed-settings.json is the # admin's file, and unknown leaves the backend's tamper state untouched. state = None if skip_settings else _detect_state( m.get_managed_settings_dir() / "managed-settings.json", _claude_detected_hooks()) if not _write_claude_managed_settings(m, skip_settings=skip_settings): - return ("deferred", "managed settings update failed") + return report("deferred", "managed settings update failed") if skip_settings: # A remote policy may name the python script; deleting it here would # strand that policy on a missing file with no local error. @@ -1133,18 +1189,18 @@ def _setup_claude_code(opts): _remove_stale_managed_script(m.get_managed_settings_dir()) if not config_ok: - return ("deferred", "config.json write failed for some users") + return report("deferred", "config.json write failed for some users") - m.notify_setup_complete(api_key, "claude-code", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("claude-code")), - install_mode="binary-skip" if skip_settings else "binary") + # skip mode writes no hook config of its own: the remote policy holds it + outcome = report("configured", install_state=state, + hook_hash=m.hook_script_hash(hook_source_path("claude-code")), + written_to=None if skip_settings else str(m.get_managed_settings_dir() / "managed-settings.json")) if opts["backfill"]: # Bounded like the MDM script: a heavy history must not hold setup open. The # deadline origin is this tool's turn, not module import in the shared process. m._SCRIPT_START = time.time() m._run_backfill_bounded(api_key, base, m.get_all_user_homes()) - return ("configured", None) + return outcome def _setup_augment(opts): @@ -1165,6 +1221,8 @@ def _setup_augment(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") + report = functools.partial(_report, m, "augment", api_key, backend_url=base, serial_number=device_id, + install_mode="binary") # Write the per-user unbound config now (needed by the managed hook). User # hook removal is deferred until the managed write succeeds (parity with @@ -1177,7 +1235,7 @@ def _setup_augment(opts): state = _detect_state(m.get_managed_settings_dir() / "settings.json", _augment_written_hooks(m)) if not _write_augment_managed_settings(m): - return ("deferred", "managed settings write failed") + return report("deferred", "managed settings write failed") _remove_stale_managed_script(m.get_managed_settings_dir()) # Strip leftover user-level Unbound hooks only after the managed write @@ -1186,13 +1244,10 @@ def _setup_augment(opts): m.remove_user_level_hooks_for_user(username, home_dir) if not config_ok: - return ("deferred", "config.json write failed for some users") + return report("deferred", "config.json write failed for some users") - m.notify_setup_complete(api_key, "augment_code", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("augment")), - install_mode="binary") - return ("configured", None) + return report("configured", install_state=state, hook_hash=m.hook_script_hash(hook_source_path("augment")), + written_to=str(m.get_managed_settings_dir() / "settings.json")) def _setup_codex(opts): @@ -1205,6 +1260,8 @@ def _setup_codex(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") + report = functools.partial(_report, m, "codex", api_key, backend_url=base, serial_number=device_id, + install_mode="binary") for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "OPENAI_API_KEY") @@ -1216,7 +1273,7 @@ def _setup_codex(opts): user_homes = m.get_all_user_homes() state = _codex_detect_state(m, user_homes) if not _write_codex_system_hooks(m): - return ("deferred", "codex system hooks.json write failed") + return report("deferred", "codex system hooks.json write failed") config_ok = True for username, home_dir in user_homes: m.remove_gateway_artifacts_for_user(username, home_dir) @@ -1227,16 +1284,14 @@ def _setup_codex(opts): m.remove_legacy_key_env() if not config_ok: - return ("deferred", "config.json write failed for some users") + return report("deferred", "config.json write failed for some users") - m.notify_setup_complete(api_key, "codex", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("codex")), - install_mode="binary") + outcome = report("configured", install_state=state, hook_hash=m.hook_script_hash(hook_source_path("codex")), + written_to=str(m.get_managed_settings_dir() / "hooks.json")) if opts["backfill"]: m._RUN_AS_USER_TIMEOUT = None # a backfill takes as long as it takes m.run_backfill(api_key, base, m.get_all_user_homes()) - return ("configured", None) + return outcome # Characters the shell acts on in an unquoted word. @@ -1415,6 +1470,8 @@ def _setup_cursor(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") + report = functools.partial(_report, m, "cursor", api_key, backend_url=base, serial_number=device_id, + install_mode="binary") config_ok = True for username, home_dir in m.get_all_user_homes(): @@ -1428,19 +1485,17 @@ def _setup_cursor(opts): relative_ok=True) hooks_ok, hooks_changed = _write_cursor_enterprise_hooks(m) if not hooks_ok: - return ("deferred", "enterprise hooks.json write failed") + return report("deferred", "enterprise hooks.json write failed") _remove_stale_managed_script(m.get_enterprise_hooks_dir()) if not config_ok: - return ("deferred", "config.json write failed for some users") + return report("deferred", "config.json write failed for some users") - m.notify_setup_complete(api_key, "cursor", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("cursor")), - install_mode="binary") + outcome = report("configured", install_state=state, hook_hash=m.hook_script_hash(hook_source_path("cursor")), + written_to=str(m.get_enterprise_hooks_dir() / "hooks.json")) if hooks_changed: m.restart_cursor() - return ("configured", None) + return outcome def _copilot_detect_state(m, user_homes): @@ -1502,6 +1557,8 @@ def _setup_copilot(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") + report = functools.partial(_report, m, "copilot", api_key, backend_url=base, serial_number=device_id, + install_mode="binary") user_homes = m.get_all_user_homes() state = _copilot_detect_state(m, user_homes) @@ -1539,20 +1596,19 @@ def _setup_copilot(opts): m.notify_setup_complete(api_key, "copilot", backend_url=base, install_state=state, serial_number=device_id, install_mode="binary") - return ("deferred", "hook install failed for all users") + return report("deferred", "hook install failed for all users") if not config_ok: - return ("deferred", "config.json write failed for some users") + return report("deferred", "config.json write failed for some users") - m.notify_setup_complete(api_key, "copilot", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("copilot")), - install_mode="binary") + # One file per user, so the per-user path rather than any one home's. + outcome = report("configured", install_state=state, hook_hash=m.hook_script_hash(hook_source_path("copilot")), + written_to="~/.copilot/hooks/unbound.json") if opts["backfill"]: hook_source = hook_source_path("copilot").read_text(encoding="utf-8") m._RUN_AS_USER_TIMEOUT = None # a backfill takes as long as it takes m.run_backfill(api_key, base, user_homes, hook_source) - return ("configured", None) + return outcome def _fetch_device_owner_key(opts): @@ -1569,6 +1625,23 @@ def _fetch_device_owner_key(opts): ) +SCAN_SKIPPED_PREFIX = "Scan skipped:" + + +def _echo_scan_output(stream, skipped) -> None: + """Pass the scan's stdout through to the MDM log line by line, keeping the reason + of the first 'Scan skipped: ' line it prints.""" + try: + for raw in iter(stream.readline, b""): + line = raw.decode("utf-8", "replace") + sys.stdout.write(line) + sys.stdout.flush() + if not skipped and line.startswith(SCAN_SKIPPED_PREFIX): + skipped.append(line[len(SCAN_SKIPPED_PREFIX):].strip()) + except Exception: + pass + + def _run_discovery(opts): """Run the locally installed discovery binary (no install.sh download). Mirrors onboard.py's process-group + backstop-kill discipline.""" @@ -1584,9 +1657,13 @@ def _run_discovery(opts): env = {**os.environ, "UNBOUND_API_KEY": scan_key} backstop = DISCOVERY_TIMEOUT_SECONDS + DISCOVERY_KILL_GRACE_SECONDS try: - proc = subprocess.Popen(cmd, start_new_session=True, env=env) + proc = subprocess.Popen(cmd, start_new_session=True, env=env, stdout=subprocess.PIPE) + skipped = [] + echo = threading.Thread(target=_echo_scan_output, args=(proc.stdout, skipped), daemon=True) + echo.start() try: rc = proc.wait(timeout=backstop) + echo.join(timeout=5) # a child still holding the pipe must not hold setup except subprocess.TimeoutExpired: import signal try: @@ -1598,6 +1675,8 @@ def _run_discovery(opts): except Exception: pass return ("deferred", f"discovery exceeded {backstop}s and was terminated") + if skipped: # it ran and chose not to scan: nothing for a re-run to retry + return ("skipped", skipped[0] or "scan skipped") if rc != 0: return ("deferred", f"discovery exited with code {rc}") return ("configured", None) diff --git a/binary/tests/test_setup_migration.py b/binary/tests/test_setup_migration.py index 56b955fce..76343cfdb 100644 --- a/binary/tests/test_setup_migration.py +++ b/binary/tests/test_setup_migration.py @@ -83,6 +83,8 @@ def env(tmp_path, monkeypatch): # The run's own reports never leave the machine from a test; test_setup_reporting # points them at a local server instead. monkeypatch.setattr(setup_cmd, "_post_json", lambda *a, **k: (0, b"")) + # Which tools look installed must not depend on the machine running the tests. + monkeypatch.setattr(setup_cmd, "_MACHINE_ROOT", tmp_path / "machine") return {"tmp": tmp_path, "home": home, "modules": modules, "notified": notified, "backfilled": backfilled, "bounded": bounded, "bootouts": bootouts, "daemon_bootouts": daemon_bootouts} @@ -1824,7 +1826,9 @@ def _as_user(_u, fn, *a, _timeout=None, **k): # the real helper returns None wh setup_cmd.run(["--api-key", "admin-key"]) finally: hooks_dir.chmod(0o755) - assert _states(env, "copilot") == ["tampered"] + # The tamper is still reported, then why setup deferred (WEB-6392). + assert _states(env, "copilot") == ["tampered", None] + assert [k.get("status") for a, k in env["notified"] if a[1] == "copilot"] == [None, "deferred"] @pytest.mark.parametrize("tool", ["claude-code", "augment_code"]) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 0bfbd17a1..799036cb0 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -136,3 +136,138 @@ def test_a_backend_error_changes_nothing_about_the_run(env, backend, capsys): assert _run(backend) == 0 assert [r["body"]["phase"] for r in _run_reports(backend)] == ["start", "end"] assert "[report] install-report end not sent: HTTP 500" in capsys.readouterr().out + + +# --- Step 3: every tool's outcome, every run ----------------------------------- + +# One footprint per tool that proves it is installed, under the patched machine root. +FOOTPRINTS = { + "claude-code": "opt/homebrew/bin/claude", + "cursor": "Applications/Cursor.app", + "codex": "usr/local/bin/codex", + "copilot": "Applications/Visual Studio Code.app", + "augment": "opt/homebrew/bin/auggie", +} +TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", + "copilot": "copilot", "augment": "augment_code"} +NAMES = {"claude-code": "Claude Code", "cursor": "Cursor", "codex": "Codex", + "copilot": "GitHub Copilot", "augment": "Augment"} + + +def _install(root, relpath): + path = root / relpath + path.parent.mkdir(parents=True, exist_ok=True) + path.mkdir() if relpath.endswith(".app") else path.write_text("") + + +@pytest.fixture +def machine(env, tmp_path, monkeypatch): + root = tmp_path / "machine" + root.mkdir() + monkeypatch.setattr(setup_cmd, "_MACHINE_ROOT", root) + return root + + +def _reports(env, tool): + return [k for a, k in env["notified"] if a[1] == TOOL_TYPES[tool]] + + +def test_every_installed_tool_reports_configured_and_where_it_wrote(env, machine): + for relpath in FOOTPRINTS.values(): + _install(machine, relpath) + assert setup_cmd.run(["--api-key", "admin-key"]) == 0 + written = { + "claude-code": str(env["tmp"] / "managed-claude" / "managed-settings.json"), + "cursor": str(env["tmp"] / "enterprise-cursor" / "hooks.json"), + "codex": str(env["tmp"] / "managed-codex" / "hooks.json"), + "copilot": "~/.copilot/hooks/unbound.json", + "augment": str(env["tmp"] / "managed-augment" / "settings.json"), + } + for tool in FOOTPRINTS: + [report] = _reports(env, tool) + assert (report["status"], report["reason"], report["written_to"]) == ("configured", None, written[tool]) + + +@pytest.mark.parametrize("tool", sorted(FOOTPRINTS)) +def test_a_tool_that_is_not_installed_is_reported_skipped_and_still_written(env, machine, tool): + for other, relpath in FOOTPRINTS.items(): + if other != tool: + _install(machine, relpath) + assert setup_cmd.run(["--api-key", "admin-key"]) == 0 + [report] = _reports(env, tool) + assert (report["status"], report["reason"]) == ("skipped", f"{NAMES[tool]} is not installed") + # Reporting only: the config is written all the same, so the hook works once the tool arrives. + assert report["written_to"] + assert all(_reports(env, other)[0]["status"] == "configured" for other in FOOTPRINTS if other != tool) + + +@pytest.mark.parametrize("tool,relpath", [ + ("claude-code", "HOME/.local/bin/claude"), ("claude-code", "HOME/.claude.json"), + ("claude-code", "HOME/.nvm/versions/node/v22.1.0/bin/claude"), ("claude-code", "Applications/Claude.app"), + ("cursor", "HOME/Applications/Cursor.app"), ("cursor", "HOME/.local/bin/cursor-agent"), + ("codex", "opt/homebrew/bin/codex"), ("codex", "HOME/.codex/auth.json"), ("codex", "Applications/Codex.app"), + ("copilot", "usr/local/bin/copilot"), ("copilot", "HOME/.bun/bin/copilot"), + ("copilot", "Applications/Visual Studio Code - Insiders.app"), + ("augment", "usr/local/bin/auggie"), ("augment", "HOME/.local/bin/auggie"), +]) +def test_each_install_location_counts_as_installed(env, machine, tool, relpath): + if relpath.startswith("HOME/"): + _install(env["home"], relpath[len("HOME/"):]) + else: + _install(machine, relpath) + setup_cmd.run(["--api-key", "admin-key"]) + assert _reports(env, tool)[0]["status"] == "configured" + + +def test_our_own_files_do_not_count_as_the_tool_being_installed(env, machine): + # A re-run finds the files the first run wrote; none of them is the tool. + setup_cmd.run(["--api-key", "admin-key"]) + env["notified"].clear() + setup_cmd.run(["--api-key", "admin-key"]) + assert {k["status"] for _, k in env["notified"]} == {"skipped"} + + +def test_a_failed_write_is_reported_deferred_with_the_printed_reason(env, machine, monkeypatch): + _install(machine, FOOTPRINTS["cursor"]) + monkeypatch.setattr(setup_cmd, "_write_cursor_enterprise_hooks", lambda m: (False, False)) + assert setup_cmd.run(["--api-key", "admin-key"]) == 1 + [report] = _reports(env, "cursor") + assert (report["status"], report["reason"]) == ("deferred", "enterprise hooks.json write failed") + + +def test_a_deferred_tool_is_reported_even_when_it_is_not_installed(env, machine, monkeypatch): + monkeypatch.setattr(setup_cmd, "_write_codex_system_hooks", lambda m: False) + assert setup_cmd.run(["--api-key", "admin-key"]) == 1 + [report] = _reports(env, "codex") + assert (report["status"], report["reason"]) == ("deferred", "codex system hooks.json write failed") + + +def test_a_skipped_scan_is_reported_skipped_not_configured(env, machine, capsys): + env["tmp"].joinpath("unbound-discovery").write_text( + "#!/bin/sh\necho 'Scan skipped: another scan is running'\nexit 0\n") + assert setup_cmd.run(["--api-key", "admin-key"]) == 0 + out = capsys.readouterr().out + assert " discovery skipped (another scan is running)" in out + # The scan's own output still reaches the MDM log. + assert "Scan skipped: another scan is running" in out.split("[discovery] coding-tool scan")[1] + + +def test_a_completed_scan_is_still_configured(env, machine, capsys): + env["tmp"].joinpath("unbound-discovery").write_text("#!/bin/sh\necho 'Scan complete'\nexit 0\n") + assert setup_cmd.run(["--api-key", "admin-key"]) == 0 + assert " discovery configured" in capsys.readouterr().out + + +@pytest.mark.parametrize("tool", sorted(TOOL_TYPES)) +def test_the_notifier_sends_status_reason_and_where_it_wrote(tool, monkeypatch): + from unbound_hook._loader import load_mdm_setup_module + m = load_mdm_setup_module(tool) + sent = [] + monkeypatch.setattr(m.subprocess, "run", lambda cmd, **kw: sent.append(json.loads(kw["input"]))) + m.notify_setup_complete("k", TOOL_TYPES[tool], backend_url="https://b", status="skipped", + reason="r" * 600, written_to="/p" * 300) + m.notify_setup_complete("k", TOOL_TYPES[tool], backend_url="https://b") + skipped, plain = sent + assert (skipped["status"], skipped["reason"], skipped["written_to"]) == ("skipped", "r" * 500, ("/p" * 300)[:500]) + # An old-style call sends the body it always did: a missing status means configured. + assert not {"status", "reason", "written_to"} & set(plain) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index efcacf85a..d4c2b1624 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3182,8 +3182,11 @@ def hook_script_hash(script_path) -> Optional[str]: def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend how tool setup ended. Never fails the setup. status is configured, skipped or + deferred; left out, the backend reads configured, as from older installers.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -3195,6 +3198,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) subprocess.run( ["curl", "-fsSL", "-X", "POST", diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 48fd0aa69..dd5da964b 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2450,8 +2450,11 @@ def hook_script_hash(script_path) -> Optional[str]: def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend how tool setup ended. Never fails the setup. status is configured, skipped or + deferred; left out, the backend reads configured, as from older installers.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -2463,6 +2466,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) subprocess.run( ["curl", "-fsSL", "-X", "POST", diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 7758a8c64..5802e91f6 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2088,8 +2088,11 @@ def hook_script_hash(script_path) -> Optional[str]: def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend how tool setup ended. Never fails the setup. status is configured, skipped or + deferred; left out, the backend reads configured, as from older installers.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -2101,6 +2104,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) subprocess.run( ["curl", "-fsSL", "-X", "POST", diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 27e16d024..25acc6c5c 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1208,8 +1208,11 @@ def hook_script_hash(script_path) -> Optional[str]: def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend how tool setup ended. Never fails the setup. status is configured, skipped or + deferred; left out, the backend reads configured, as from older installers.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -1221,6 +1224,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) subprocess.run( ["curl", "-fsSL", "-X", "POST", From 4a7871078dba40b8c8a2e1fe982493ce26268b32 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 19:38:56 +0530 Subject: [PATCH 03/53] feat(backfill): send every run's outcome and carry an unsent one forward [WEB-6392] --- claude-code/hooks/mdm/setup.py | 131 ++++++++++++--- claude-code/hooks/setup.py | 63 ++++++- .../hooks/test_backfill_outcome.py | 158 ++++++++++++++++++ .../hooks/test_backfill_uploader_stats.py | 22 ++- ...st_backfill_uploader_stats_bands_matrix.py | 2 +- .../test_backfill_uploader_stats_matrix.py | 43 +++-- tests/claude_code/hooks/test_setup.py | 17 +- 7 files changed, 381 insertions(+), 55 deletions(-) create mode 100644 tests/claude_code/hooks/test_backfill_outcome.py diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index d4c2b1624..1873d545d 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -44,6 +44,9 @@ BACKFILL_STATE_FILE = '.unbound_last_backfill' # Where each transcript too big to read whole stopped, beside the walk's state, which other writes replace. BACKFILL_RESUME_FILE = '.unbound_backfill_resume' +# How a run that could not send its closing report ended, for the next run to send as previous_outcome. +BACKFILL_OUTCOME_FILE = '.unbound_backfill_outcome' +BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'failed') _SCRIPT_START = time.time() # All measured from script start. No new batch starts unless it can land before the # soft stop (margin: 90s or 1.5x the slowest batch so far); the hard kill backs it up @@ -61,6 +64,8 @@ # from-s3 is sized to end this long before the hard deadline, and never given less than the floor per attempt. BACKFILL_FROM_S3_SLACK_SECONDS = 10 BACKFILL_FROM_S3_MIN_SECONDS = 5 +# Kept free at the end of the soft stop for the run's closing report (outcome and counts): data stops this early. +BACKFILL_STATS_RESERVE_SECONDS = 30 def normalize_url(value: str) -> str: @@ -2676,13 +2681,13 @@ def _backfill_force_config(api_key: str, backend_url: str) -> Tuple[Optional[flo return None, None -def _backfill_put_budget_seconds() -> int: - # What one PUT may take and still leave from-s3 its turn before the soft stop. - return int(BACKFILL_SOFT_STOP_SECONDS - (time.time() - _SCRIPT_START)) - BACKFILL_FROM_S3_RESERVE_SECONDS +def _backfill_put_budget_seconds(reserve: int = BACKFILL_STATS_RESERVE_SECONDS) -> int: + # What one PUT may take and still leave from-s3 its turn, and the closing report its reserve, before the soft stop. + return int(BACKFILL_SOFT_STOP_SECONDS - (time.time() - _SCRIPT_START)) - BACKFILL_FROM_S3_RESERVE_SECONDS - reserve -def _backfill_has_time_for_a_chunk() -> bool: - return _backfill_put_budget_seconds() >= BACKFILL_PUT_MIN_SECONDS +def _backfill_has_time_for_a_chunk(reserve: int = BACKFILL_STATS_RESERVE_SECONDS) -> bool: + return _backfill_put_budget_seconds(reserve) >= BACKFILL_PUT_MIN_SECONDS def _backfill_from_s3_timeout_seconds() -> int: @@ -2694,6 +2699,8 @@ def _backfill_from_s3_timeout_seconds() -> int: def _backfill_upload_chunk(api_key: str, backend_url: str, sessions: List[Dict], force: bool = False) -> Optional[bool]: # None when the chunk ran out of time before its PUT could start: a stop, not a failed upload. + # The closing report (no sessions) is the one upload that may use the reserve. + reserve = BACKFILL_STATS_RESERVE_SECONDS if sessions else 0 payload = {'tool_type': BACKFILL_TOOL_TYPE, 'sessions': sessions} if _backfill_uploader_stats is not None: payload['uploader_stats'] = _backfill_uploader_stats @@ -2709,7 +2716,7 @@ def _backfill_upload_chunk(api_key: str, backend_url: str, sessions: List[Dict], }) for _ in range(BACKFILL_PUT_ATTEMPTS): - if not _backfill_has_time_for_a_chunk(): + if not _backfill_has_time_for_a_chunk(reserve): debug_print("S3 PUT not started: too close to the soft stop") return None code, body = _backfill_http_request( @@ -2735,7 +2742,7 @@ def _backfill_upload_chunk(api_key: str, backend_url: str, sessions: List[Dict], return False # Measured after the link request, whose own retries can use up to two minutes. - put_cap = _backfill_put_budget_seconds() + put_cap = _backfill_put_budget_seconds(reserve) if put_cap < BACKFILL_PUT_MIN_SECONDS: debug_print("S3 PUT not started: the link request used the time left") return None @@ -2952,11 +2959,26 @@ def __init__(self, api_key: str, backend_url: str, device_serial: Optional[str], self.force_epoch, self.force_days = force_config self.completed_watermark = completed_watermark self.slowest_batch = 0.0 + self.uploads_failed = 0 + self.stopped_by_time = False def has_time_for_a_batch(self) -> bool: - # Start a batch only if even the slowest one so far would land before the soft stop. + # Start a batch only if even the slowest one so far would land before the soft stop, less the + # closing report's reserve. margin = max(BACKFILL_MIN_MARGIN_SECONDS, 1.5 * self.slowest_batch) - return BACKFILL_SOFT_STOP_SECONDS - (time.time() - _SCRIPT_START) >= margin + return BACKFILL_SOFT_STOP_SECONDS - BACKFILL_STATS_RESERVE_SECONDS - (time.time() - _SCRIPT_START) >= margin + + def out_of_time(self) -> bool: + """No batch fits any more; remembered, so the run reports it stopped for time.""" + if self.has_time_for_a_batch(): + return False + self.stopped_by_time = True + return True + + def outcome(self, statuses: set) -> str: + if 'failed' in statuses: + return 'failed' + return 'stopped_by_time_limit' if self.stopped_by_time else 'completed' def upload(self, sessions: List[Dict], forced: bool) -> Tuple[int, int, bool]: """(sessions_sent, chunks_failed, out_of_time) for one batch.""" @@ -2964,7 +2986,9 @@ def upload(self, sessions: List[Dict], forced: bool) -> Tuple[int, int, bool]: try: sent, _, failed = _backfill_send_sessions(self.api_key, self.backend_url, sessions, forced) except _BackfillOutOfTime as stop: + self.stopped_by_time = True return stop.args[0], 0, True + self.uploads_failed += failed return sent, failed, False @@ -2984,7 +3008,7 @@ def _backfill_stream_file(run: _BackfillRun, user_home: Tuple[str, Path], sessio _backfill_attach_identity([session], run.device_serial, None) resume = _run_as_user(username, _backfill_read_file_resume, home_dir, session, tag) while True: - if not run.has_time_for_a_batch(): + if run.out_of_time(): return sent, 'more' began = time.time() result = _run_as_user(username, _backfill_read_slice_or_false, session, resume, BACKFILL_CHUNK_BYTES) @@ -3018,7 +3042,7 @@ def _backfill_drain_home(run: _BackfillRun, user_home: Tuple[str, Path]) -> Tupl return 0, 0, 'unreadable' start, home_forced, sent_total, batches = None, None, 0, 0 for _ in range(BACKFILL_MAX_BATCHES_PER_HOME): - if not run.has_time_for_a_batch(): + if run.out_of_time(): return sent_total, batches, 'more' began = time.time() result = _run_as_user(username, _backfill_collect_sessions, home_dir, @@ -3095,6 +3119,77 @@ def _backfill_add_stats(total: Dict, part: Optional[Dict]) -> None: over['by_size'][name]['total_bytes'] += band['total_bytes'] +def _backfill_outcome_path(home: Path) -> Path: + return _backfill_state_path(home).with_name(BACKFILL_OUTCOME_FILE) + + +def _backfill_read_outcome(home: Path) -> Optional[str]: + try: + value = _backfill_outcome_path(home).read_text().strip() + except OSError: + return None + return value if value in BACKFILL_OUTCOMES else None + + +def _backfill_clear_outcome(home: Path) -> None: + path = _backfill_outcome_path(home) + if _backfill_root_is_linked(home / '.claude', path.parent): + return # never delete through a link into another profile + try: + path.unlink() + except OSError: + pass + + +def _backfill_save_outcome(user_homes: List[Tuple[str, Path]], outcome: str) -> None: + # In every profile, each as its own user; the next run takes the first it finds. Never raises: it also + # runs from the error path. + for username, home_dir in user_homes: + try: + _run_as_user(username, _backfill_write_state_text, home_dir, outcome, BACKFILL_OUTCOME_FILE) + except Exception as e: + debug_print(f"backfill outcome not saved for {username}: {e}") + + +def _backfill_take_outcome(user_homes: List[Tuple[str, Path]]) -> Optional[str]: + """The outcome an earlier run could not send. Replaced by stopped_by_time_limit until this run reports: + the hard deadline kills a run with no chance to save anything, and that is how such a run ended.""" + found = (_run_as_user(username, _backfill_read_outcome, home_dir) for username, home_dir in user_homes) + previous = next((outcome for outcome in found if outcome), None) + _backfill_save_outcome(user_homes, 'stopped_by_time_limit') + return previous + + +def _backfill_send_outcome(run: _BackfillRun, user_homes: List[Tuple[str, Path]], outcome: str, + previous: Optional[str]) -> None: + """The run's closing upload: the counts when there is time to walk for them, how the run ended, and an + earlier run's unsent outcome. Left on disk for the next run when it can't go.""" + global _backfill_uploader_stats + stats: Dict = {} + # Walked after the uploads, with the time left, so a large history never holds an upload back. + if run.has_time_for_a_batch(): + stats = _backfill_empty_stats() + for username, home_dir in user_homes: + _backfill_add_stats(stats, _run_as_user(username, _backfill_home_stats, home_dir)) + stats.update(outcome=outcome, uploads_failed=run.uploads_failed) + if previous: + stats['previous_outcome'] = previous + _backfill_uploader_stats = stats + try: + sent = _backfill_upload_chunk(run.api_key, run.backend_url, []) is True + finally: + _backfill_uploader_stats = None # data uploads never carry it + if not sent: + debug_print(f"backfill outcome {outcome} not sent; the next run sends it") + _backfill_save_outcome(user_homes, outcome) + return + for username, home_dir in user_homes: + try: + _run_as_user(username, _backfill_clear_outcome, home_dir) + except Exception as e: # sent already; only the next run's previous_outcome can be off + debug_print(f"backfill outcome not cleared for {username}: {e}") + + def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Path]]) -> None: """Walk every user's ~/.claude/projects and seed historical sessions. @@ -3108,10 +3203,12 @@ def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Pat debug_print("UNBOUND_BACKFILL_DISABLED=1 — skipping backfill") return + reported = False try: if not user_homes: debug_print("no user homes found — skipping backfill") return + previous = _backfill_take_outcome(user_homes) device_serial = get_device_identifier() # Watermark first: a force request filed after this instant must stay pending. completed_watermark = time.time() @@ -3129,17 +3226,13 @@ def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Pat debug_print(f"backfill {user_home[0]}: {status}, {sent} sessions in {home_batches} batches") sessions_sent, batches = sessions_sent + sent, batches + home_batches statuses.add(status) - # Counted after the uploads, with the time left, so a large history never holds an upload back. - if run.has_time_for_a_batch(): - stats = _backfill_empty_stats() - for username, home_dir in user_homes: - _backfill_add_stats(stats, _run_as_user(username, _backfill_home_stats, home_dir)) - if _backfill_skipped_anything(stats): - _backfill_uploader_stats = stats - _backfill_upload_chunk(api_key, backend_url, []) + _backfill_send_outcome(run, user_homes, run.outcome(statuses), previous) + reported = True _backfill_report(sessions_sent, batches, statuses) except Exception as e: print(f"[backfill] Skipped due to error: {e}", file=sys.stderr) + if user_homes and not reported: + _backfill_save_outcome(user_homes, 'failed') def detect_install_state(skip_settings: bool = False) -> Optional[str]: diff --git a/claude-code/hooks/setup.py b/claude-code/hooks/setup.py index 0d5aa2ed5..41848dbd9 100644 --- a/claude-code/hooks/setup.py +++ b/claude-code/hooks/setup.py @@ -40,6 +40,9 @@ BACKFILL_MAX_SESSIONS_PER_RUN = 5000 BACKFILL_MAX_AGE_DAYS = 30 BACKFILL_STATE_FILE = '.unbound_last_backfill' +# How a run that could not send its closing report ended, for the next run to send as previous_outcome. +BACKFILL_OUTCOME_FILE = '.unbound_backfill_outcome' +BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'failed') # An S3 PUT is given up on only after this long below this speed, then re-sent on a fresh link. BACKFILL_PUT_STALL_SECONDS = 60 BACKFILL_PUT_STALL_BYTES_PER_SECOND = 1024 @@ -1529,6 +1532,54 @@ def _backfill_write_cutoff(config_dir: Path, ts: float) -> None: debug_print(f"failed to persist backfill timestamp: {e}") +def _backfill_outcome_path(config_dir: Path) -> Path: + return _backfill_state_path(config_dir).with_name(BACKFILL_OUTCOME_FILE) + + +def _backfill_read_outcome(config_dir: Path) -> Optional[str]: + try: + value = _backfill_outcome_path(config_dir).read_text().strip() + except OSError: + return None + return value if value in BACKFILL_OUTCOMES else None + + +def _backfill_save_outcome(config_dir: Path, outcome: Optional[str]) -> None: + # None clears it. Never raises: it also runs from the error path. + path = _backfill_outcome_path(config_dir) + try: + if outcome is None: + path.unlink() + return + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.parent / f'{path.name}.{os.getpid()}.tmp' + tmp.write_text(outcome) + os.replace(tmp, path) + except FileNotFoundError: + pass + except OSError as e: + debug_print(f"failed to persist backfill outcome: {e}") + + +def _backfill_send_outcome(api_key: str, backend_url: str, config_dir: Path, outcome: str, + uploads_failed: int, previous: Optional[str]) -> None: + """The run's closing upload: the walk's counts, how the run ended, and an earlier run's unsent outcome. + Left on disk for the next run when it can't go.""" + global _backfill_uploader_stats + counts = _backfill_uploader_stats + stats = dict(counts, outcome=outcome, uploads_failed=uploads_failed) + if previous: + stats['previous_outcome'] = previous + _backfill_uploader_stats = stats + try: + sent = _backfill_upload_chunk(api_key, backend_url, []) + finally: + _backfill_uploader_stats = counts # data uploads carry the counts alone + if not sent: + debug_print(f"backfill outcome {outcome} not sent; the next run sends it") + _backfill_save_outcome(config_dir, None if sent else outcome) + + def _backfill_jsonl_files(root: Path, skip_dirs=()): """Every .jsonl under root, never entering or yielding a symlink or Windows junction.""" for dirpath, dirnames, filenames in os.walk(root): @@ -2081,12 +2132,14 @@ def run_backfill(api_key: str, backend_url: str, config_dir: Path = None) -> Non except (OSError, AttributeError) as e: debug_print(f"lowering backfill priority failed: {e}") + reported = False try: # The signed-in email and the desktop session cache are keyed off the home # dir; only the transcripts and the cutoff follow the config dir. home = Path.home() if config_dir is None: config_dir = home / '.claude' + previous = _backfill_read_outcome(config_dir) started_at = time.time() cutoff_mtime = _backfill_read_cutoff(config_dir) force_epoch, force_days = _backfill_force_config(api_key, backend_url) @@ -2159,15 +2212,15 @@ def _flush(): current_size += slice_bytes + 1 _flush() + failed = chunks_total - chunks_sent + # No run clock here, so a run ends completed or failed, never stopped for time. + _backfill_send_outcome(api_key, backend_url, config_dir, 'failed' if failed else 'completed', failed, previous) + reported = True if not found: - if _backfill_skipped_anything(_backfill_uploader_stats): - # Nothing else goes up, so the counts go alone; a device whose every transcript is skipped still reports. - _backfill_upload_chunk(api_key, backend_url, []) _backfill_write_cutoff(config_dir, started_at) print("[backfill] No past sessions found.") return - failed = chunks_total - chunks_sent sessions_sent = len(sessions_sent_ids) if sessions_sent == 0: print(f"[backfill] No sessions queued (all {chunks_total} uploads failed).") @@ -2179,6 +2232,8 @@ def _flush(): print(f"[backfill] Done — queued {sessions_sent} past sessions for processing.") except Exception as e: print(f"[backfill] Skipped due to error: {e}", file=sys.stderr) + if not reported and config_dir is not None: + _backfill_save_outcome(config_dir, 'failed') def _wsl_distros(): diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py new file mode 100644 index 000000000..5e3429a81 --- /dev/null +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -0,0 +1,158 @@ +"""WEB-6392: every backfill run ends with one upload saying how it ended (outcome, failed uploads), and a run +that could not send that leaves it on disk for the next run to send as previous_outcome. Both uploaders: the +MDM one (all profiles, run clock) and the per-user one. The network is faked at the HTTP layer only.""" + +import io +import json +import shutil +import tempfile +import time +import unittest +from contextlib import ExitStack, redirect_stdout +from pathlib import Path +from unittest.mock import patch + +from tests.conftest import tool_module + +mdm = tool_module("claude-code/hooks/mdm", "setup") +setup = tool_module("claude-code/hooks", "setup") + + +class _Backend: + """Records each uploaded body. fail_puts: the PUTs (by index) S3 refuses; down: every request fails.""" + + def __init__(self, fail_puts=(), down=False): + self.bodies, self.fail_puts, self.down, self.puts = [], set(fail_puts), down, 0 + + def __call__(self, url, method, headers, body=None, timeout=30): + if self.down: + return -7, b"" # curl: could not connect + if url.endswith("/upload-url/"): + return 200, json.dumps({"upload_url": "https://s3/put", "object_key": "k"}).encode() + if method == "PUT": + self.puts += 1 + if self.puts - 1 in self.fail_puts: + return 403, b"denied" + self.bodies.append(json.loads(body.decode("utf-8"))) + return 200, b"{}" + + def stats(self): + return [b["uploader_stats"] for b in self.bodies if "outcome" in b.get("uploader_stats", {})] + + +def _run(up, home, backend, more=()): + with ExitStack() as stack: + for ctx in (patch.object(up, "_backfill_http_request", side_effect=backend), + patch.object(up, "_backfill_force_config", return_value=(None, None)), + patch.object(up, "_backfill_account_email", return_value=None), + patch.object(up, "get_device_identifier", return_value="SERIAL"), + patch.object(up.time, "sleep", lambda s: None), + redirect_stdout(io.StringIO()), *more): + stack.enter_context(ctx) + if up is mdm: + stack.enter_context(patch.object(mdm, "_run_as_user", side_effect=lambda u, fn, *a, **k: fn(*a, **k))) + mdm.run_backfill("key", "https://backend", [("alice", home)]) + else: + stack.enter_context(patch.object(setup.Path, "home", return_value=home)) + setup.run_backfill("key", "https://backend", home / ".claude") + return backend + + +class _Homes(unittest.TestCase): + + def _home(self, sessions=("a",)): + home = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, home) + projects = home / ".claude" / "projects" / "p" + projects.mkdir(parents=True) + for sid in sessions: + (projects / f"{sid}.jsonl").write_text(json.dumps({"type": "user", "sessionId": sid}) + "\n") + return home + + +class EveryRunReportsHowItEndedTestCase(_Homes): + + def test_a_clean_run_ends_with_completed(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + backend = _run(up, self._home(("a", "b")), _Backend()) + [stats] = backend.stats() + self.assertEqual((stats["outcome"], stats["uploads_failed"]), ("completed", 0)) + self.assertNotIn("previous_outcome", stats) + self.assertIs(backend.bodies[-1]["uploader_stats"], stats) + self.assertEqual(backend.bodies[-1]["sessions"], []) + # The walk's counts ride along, as before. + self.assertEqual(stats["files_seen"], 2) + + def test_a_run_with_nothing_to_send_still_reports(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + backend = _run(up, self._home(()), _Backend()) + self.assertEqual([s["outcome"] for s in backend.stats()], ["completed"]) + + def test_a_failed_upload_ends_with_failed_and_counts_it(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + backend = _run(up, self._home(("a",)), _Backend(fail_puts={0})) + [stats] = backend.stats() + self.assertEqual((stats["outcome"], stats["uploads_failed"]), ("failed", 1)) + + def test_an_mdm_run_out_of_time_ends_with_stopped_by_time_limit(self): + backend = _run(mdm, self._home(("a",)), _Backend(), + [patch.object(mdm._BackfillRun, "has_time_for_a_batch", return_value=False)]) + self.assertEqual([b["sessions"] for b in backend.bodies], [[]]) + [stats] = backend.stats() + self.assertEqual(stats["outcome"], "stopped_by_time_limit") + # No time to walk every transcript either: the outcome goes up without the counts. + self.assertNotIn("files_seen", stats) + + def test_the_mdm_run_keeps_time_back_for_its_closing_report(self): + # 100s before the soft stop: an old run started one more batch here; now that time is the report's. + start = time.time() - (mdm.BACKFILL_SOFT_STOP_SECONDS - 100) + backend = _run(mdm, self._home(("a",)), _Backend(), [patch.object(mdm, "_SCRIPT_START", start)]) + self.assertEqual([b["sessions"] for b in backend.bodies], [[]]) + self.assertEqual([s["outcome"] for s in backend.stats()], ["stopped_by_time_limit"]) + + def test_data_uploads_carry_no_outcome(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + backend = _run(up, self._home(("a", "b")), _Backend()) + self.assertTrue(all("outcome" not in b.get("uploader_stats", {}) for b in backend.bodies[:-1])) + + +class AnUnsentOutcomeGoesUpNextRunTestCase(_Homes): + + def test_an_outcome_that_could_not_be_sent_is_sent_once_by_the_next_run(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + home = self._home(("a",)) + self.assertEqual(_run(up, home, _Backend(down=True)).bodies, []) + [second] = _run(up, home, _Backend()).stats() + self.assertEqual((second["outcome"], second["previous_outcome"]), ("completed", "failed")) + [third] = _run(up, home, _Backend()).stats() + self.assertNotIn("previous_outcome", third) + + def test_an_mdm_run_killed_before_it_reported_reads_as_stopped_by_time_limit(self): + home = self._home(("a",)) + + class Killed(BaseException): + """The hard deadline's SIGKILL: nothing after it runs.""" + + with self.assertRaises(Killed): + _run(mdm, home, _Backend(), [patch.object(mdm, "_backfill_drain_home", side_effect=Killed)]) + [stats] = _run(mdm, home, _Backend()).stats() + self.assertEqual(stats["previous_outcome"], "stopped_by_time_limit") + + def test_a_garbled_saved_outcome_is_not_sent(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + home = self._home(("a",)) + hooks = home / ".claude" / "hooks" + hooks.mkdir(parents=True, exist_ok=True) + (hooks / up.BACKFILL_OUTCOME_FILE).write_text("exploded\n") + [stats] = _run(up, home, _Backend()).stats() + self.assertNotIn("previous_outcome", stats) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats.py b/tests/claude_code/hooks/test_backfill_uploader_stats.py index 7c22d7a93..1d70af8ee 100644 --- a/tests/claude_code/hooks/test_backfill_uploader_stats.py +++ b/tests/claude_code/hooks/test_backfill_uploader_stats.py @@ -58,6 +58,11 @@ def _run(up, home, more=()): return bodies +def _closing(stats, outcome="completed", failed=0): + """The run's closing report (WEB-6392): the walk's counts plus how the run ended.""" + return {**stats, "outcome": outcome, "uploads_failed": failed} + + # The size bands as the spec states them, by upper bound, written out apart from the code under test. BANDS = (("under_100mb", 100 << 20), ("under_250mb", 250 << 20), ("under_500mb", 500 << 20), ("under_1gb", 1 << 30), ("1gb_or_more", None)) @@ -101,31 +106,33 @@ def _expected(self, seen): "by_size": _by_size(self.big)}} def test_every_standalone_upload_reports_what_was_seen_and_left_behind(self): - bodies = _run(setup, self._populated_home()) + *bodies, closing = _run(setup, self._populated_home()) self.assertEqual(sorted(s["session_id"] for b in bodies for s in b["sessions"]), ["a", "b"]) for body in bodies: self.assertEqual(set(body), {"tool_type", "sessions", "uploader_stats"}) self.assertEqual(body["uploader_stats"], self._expected(6)) + self.assertEqual((closing["sessions"], closing["uploader_stats"]), ([], _closing(self._expected(6)))) def test_mdm_uploads_first_then_sends_the_counts_once(self): bodies = _run(mdm, self._populated_home()) *uploads, counts = bodies self.assertEqual(sorted(s["session_id"] for b in uploads for s in b["sessions"]), ["a", "b"]) self.assertTrue(all("uploader_stats" not in b for b in uploads)) - self.assertEqual((counts["sessions"], counts["uploader_stats"]), ([], self._expected(6))) + self.assertEqual((counts["sessions"], counts["uploader_stats"]), ([], _closing(self._expected(6)))) def test_mdm_skips_the_count_when_the_run_is_out_of_time(self): - # Time for the one batch this home needs, none left for the count. + # Time for the one batch this home needs, none left for the count: the outcome goes up alone. with patch.object(mdm._BackfillRun, "has_time_for_a_batch", side_effect=[True, False]): - bodies = _run(mdm, self._populated_home()) + *bodies, closing = _run(mdm, self._populated_home()) self.assertTrue(bodies) self.assertTrue(all("uploader_stats" not in b for b in bodies)) + self.assertEqual(closing["uploader_stats"], {"outcome": "completed", "uploads_failed": 0}) def test_mdm_counts_every_profile_of_the_run(self): other, projects = self._home() (projects / "c.jsonl").write_text(json.dumps({"type": "user", "sessionId": "c"}) + "\n") bodies = _run(mdm, self._populated_home(), more=[("bob", other)]) - self.assertEqual(bodies[-1]["uploader_stats"], self._expected(7)) + self.assertEqual(bodies[-1]["uploader_stats"], _closing(self._expected(7))) def test_a_run_that_only_skips_still_reports_its_counts(self): for up in (mdm, setup): @@ -136,11 +143,12 @@ def test_a_run_that_only_skips_still_reports_its_counts(self): self.assertEqual([b["sessions"] for b in bodies], [[]]) self.assertEqual(bodies[0]["uploader_stats"]["skipped_over_cap"]["count"], 1) - def test_a_run_with_nothing_skipped_and_nothing_to_send_uploads_nothing(self): + def test_a_run_with_nothing_skipped_and_nothing_to_send_uploads_only_its_closing_report(self): for up in (mdm, setup): with self.subTest(up.__name__): home, _ = self._home() - self.assertEqual(_run(up, home), []) + self.assertEqual(_run(up, home), [{"tool_type": "claude-code", "sessions": [], + "uploader_stats": _closing(up._backfill_empty_stats())}]) def test_unreadable_counts_the_files_the_collector_drops(self): for up in (mdm, setup): diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats_bands_matrix.py b/tests/claude_code/hooks/test_backfill_uploader_stats_bands_matrix.py index c8282193b..d25c5d98b 100644 --- a/tests/claude_code/hooks/test_backfill_uploader_stats_bands_matrix.py +++ b/tests/claude_code/hooks/test_backfill_uploader_stats_bands_matrix.py @@ -154,7 +154,7 @@ def test_a_real_run_over_three_profiles_sends_the_bands_of_all_of_them(self): everything = [s for part in sizes for s in part] self.assertEqual(sorted(s["session_id"] for b in uploads for s in b["sessions"]), ["s0", "s1", "s2"]) self.assertEqual(counts["sessions"], []) - self.assertEqual(counts["uploader_stats"], _sum_profiles(parts)) + self.assertEqual(counts["uploader_stats"], {**_sum_profiles(parts), "outcome": "completed", "uploads_failed": 0}) self.assertEqual(counts["uploader_stats"]["skipped_over_cap"]["by_size"], _spec_bands(everything)) def _run(self, homes): diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py index 2e8d4be06..49d7b4a72 100644 --- a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py +++ b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py @@ -222,6 +222,11 @@ def _stats(seen=0, unreadable=0, count=0, largest=0, total=0): "skipped_over_cap": {"count": count, "largest_bytes": largest, "total_bytes": total, "by_size": by_size}} +def _closing(stats, outcome="completed", failed=0): + """The run's closing report (WEB-6392): the walk's counts plus how the run ended.""" + return {**stats, "outcome": outcome, "uploads_failed": failed} + + def _fake_http(bodies, raw=None): def http(url, method, headers, body=None, timeout=30): if url.endswith("/upload-url/"): @@ -318,22 +323,24 @@ def test_uploads_then_one_counts_body(self): home, expected = self._home(("a", "b", "c"), big=(500, 900), no_id=1) bodies = _run(mdm, [home]) counted = [b for b in bodies if "uploader_stats" in b] - self.assertEqual(counted, [{"tool_type": "claude-code", "sessions": [], "uploader_stats": expected}]) + self.assertEqual(counted, [{"tool_type": "claude-code", "sessions": [], "uploader_stats": _closing(expected)}]) self.assertIs(bodies[-1], counted[0]) self.assertEqual(sorted(s["session_id"] for b in bodies[:-1] for s in b["sessions"]), ["a", "b", "c"]) - def test_no_time_left_sends_no_counts(self): + def test_no_time_left_sends_the_outcome_without_counts(self): home, _ = self._home(("a",), big=(500,)) bodies = _run(mdm, [home], [patch.object(mdm._BackfillRun, "has_time_for_a_batch", side_effect=[True, False])]) - self.assertEqual([[s["session_id"] for s in b["sessions"]] for b in bodies], [["a"]]) + self.assertEqual([[s["session_id"] for s in b["sessions"]] for b in bodies], [["a"], []]) self.assertNotIn("uploader_stats", bodies[0]) + self.assertEqual(bodies[-1]["uploader_stats"], {"outcome": "completed", "uploads_failed": 0}) - def test_nothing_skipped_sends_no_counts(self): + def test_nothing_skipped_still_sends_the_counts_once_at_the_end(self): home, _ = self._home(("a", "b")) - bodies = _run(mdm, [home]) - self.assertTrue(bodies) - self.assertFalse(any("uploader_stats" in b or not b["sessions"] for b in bodies)) + *uploads, closing = _run(mdm, [home]) + self.assertTrue(uploads) + self.assertFalse(any("uploader_stats" in b or not b["sessions"] for b in uploads)) + self.assertEqual((closing["sessions"], closing["uploader_stats"]), ([], _closing(_stats(seen=2)))) def test_every_profile_is_summed(self): alice, first = self._home(("a",), big=(500, 2000), no_id=2) @@ -341,7 +348,7 @@ def test_every_profile_is_summed(self): total = _stats() mdm._backfill_add_stats(total, first) mdm._backfill_add_stats(total, second) - self.assertEqual(_run(mdm, [alice, bob])[-1]["uploader_stats"], total) + self.assertEqual(_run(mdm, [alice, bob])[-1]["uploader_stats"], _closing(total)) def test_a_refused_profile_counts_nothing_and_keeps_no_state(self): alice, counted = self._home(("a",), big=(500,)) @@ -357,7 +364,7 @@ def lstat(path, *args, **kwargs): return result bodies = _run(mdm, [alice, bob], [patch("os.lstat", side_effect=lstat), patch.object(mdm.platform, "system", return_value="Windows")]) - self.assertEqual(bodies[-1]["uploader_stats"], counted) + self.assertEqual(bodies[-1]["uploader_stats"], _closing(counted)) self.assertEqual(sorted(s["session_id"] for b in bodies for s in b["sessions"]), ["a"]) self.assertEqual(list(hooks.iterdir()), []) self.assertTrue((alice / ".claude" / "hooks" / mdm.BACKFILL_STATE_FILE).exists()) @@ -367,8 +374,9 @@ def test_the_counts_do_not_carry_into_the_next_run(self): clean, _ = self._home(("b",)) self.assertIn("uploader_stats", _run(mdm, [skipping])[-1]) bodies = _run(mdm, [clean]) - self.assertEqual([[s["session_id"] for s in b["sessions"]] for b in bodies], [["b"]]) + self.assertEqual([[s["session_id"] for s in b["sessions"]] for b in bodies], [["b"], []]) self.assertNotIn("uploader_stats", bodies[0]) + self.assertEqual(bodies[-1]["uploader_stats"], _closing(_stats(seen=1))) self.assertIsNone(mdm._backfill_uploader_stats) def test_a_disabled_backfill_sends_nothing(self): @@ -384,27 +392,30 @@ class StandaloneRunTestCase(_HomesMixin, unittest.TestCase): def test_every_chunk_carries_the_same_counts(self): home, expected = self._home(("a", "b", "c", "d"), big=(700,), no_id=2) # Room for one session per chunk, so the four go up apart. - bodies = _run(setup, [home], [patch.object(setup, "BACKFILL_CHUNK_BYTES", 150)]) + *bodies, closing = _run(setup, [home], [patch.object(setup, "BACKFILL_CHUNK_BYTES", 150)]) self.assertEqual(len(bodies), 4) self.assertEqual([b["uploader_stats"] for b in bodies], [expected] * 4) + self.assertEqual((closing["sessions"], closing["uploader_stats"]), ([], _closing(expected))) self.assertEqual(sorted(s["session_id"] for b in bodies for s in b["sessions"]), ["a", "b", "c", "d"]) def test_a_run_that_only_skips_sends_the_counts_alone(self): home, expected = self._home(big=(500, 800), no_id=1) self.assertEqual(_run(setup, [home]), - [{"tool_type": "claude-code", "sessions": [], "uploader_stats": expected}]) + [{"tool_type": "claude-code", "sessions": [], "uploader_stats": _closing(expected)}]) - def test_an_empty_home_sends_nothing(self): + def test_an_empty_home_sends_only_its_closing_report(self): home, _ = self._home() - self.assertEqual(_run(setup, [home]), []) + closing = [{"tool_type": "claude-code", "sessions": [], "uploader_stats": _closing(_stats())}] + self.assertEqual(_run(setup, [home]), closing) shutil.rmtree(home / ".claude" / "projects") - self.assertEqual(_run(setup, [home]), []) + self.assertEqual(_run(setup, [home]), closing) def test_with_nothing_skipped_the_counts_still_ride_the_chunks(self): home, expected = self._home(("a", "b")) - bodies = _run(setup, [home]) + *bodies, closing = _run(setup, [home]) self.assertTrue(bodies) self.assertEqual([b["uploader_stats"] for b in bodies], [expected] * len(bodies)) + self.assertEqual(closing["uploader_stats"], _closing(expected)) self.assertEqual(expected, _stats(seen=2)) diff --git a/tests/claude_code/hooks/test_setup.py b/tests/claude_code/hooks/test_setup.py index aae0c8960..58e3f814e 100644 --- a/tests/claude_code/hooks/test_setup.py +++ b/tests/claude_code/hooks/test_setup.py @@ -675,13 +675,13 @@ def test_first_failed_chunk_stops_the_batch_and_keeps_the_previous_cursor(self): """Against a hung backend each chunk burns ~2 min of curl retries, so the rest of a failing batch is never attempted; the batch is retried whole next run.""" calls, cursor, b1_mtime, out = self._drain_with_failing_chunk(failing_call=1) - self.assertEqual(calls, [["b2"]]) + self.assertEqual(calls, [["b2"], []]) # then the run's closing report, sessions-free self.assertEqual(cursor, b1_mtime) self.assertIn("Some uploads failed", out) def test_a_later_failed_chunk_also_stops_the_batch(self): calls, cursor, b1_mtime, out = self._drain_with_failing_chunk(failing_call=2) - self.assertEqual(calls, [["b2"], ["b3"]]) + self.assertEqual(calls, [["b2"], ["b3"], []]) self.assertEqual(cursor, b1_mtime) self.assertIn("Some uploads failed", out) @@ -703,7 +703,7 @@ def slow_chunk(api_key, backend_url, sessions, forced=False): patch.object(mdm, "_backfill_upload_chunk", side_effect=slow_chunk), \ patch.object(mdm, "BACKFILL_CHUNK_BYTES", 10000): out = _drain_real_home(self, home, batch_bytes=30000, real_send=True) - self.assertEqual(calls, [["b2"]]) + self.assertEqual(calls, [["b2"], []]) self.assertEqual(mdm._backfill_read_state(home)["cursor"], b1.stat().st_mtime) self.assertIn("Queued 1 sessions in 1 batches. More history remains", out) self.assertNotIn("Some uploads failed", out) @@ -731,14 +731,15 @@ def upload_at(now, link_took=0.0, put_took=20.0): landed = mdm._backfill_upload_chunk("key", "https://backend", [{"session_id": "s"}]) return landed, requests[1:2], sleep.call_args - # 500s left: the PUT may take all of it but the 40s kept for from-s3, then rests as long as it took. - self.assertEqual(upload_at(100.0), (True, [("PUT", 460)], unittest.mock.call(20))) - # 95s left once the PUT lands: the rest is cut to what still leaves the next chunk its 45s floor. - self.assertEqual(upload_at(485.0), (True, [("PUT", 75)], unittest.mock.call(10))) + # 500s left: the PUT may take all of it but the 40s kept for from-s3 and the 30s kept for the run's + # closing report, then rests as long as it took. + self.assertEqual(upload_at(100.0), (True, [("PUT", 430)], unittest.mock.call(20))) + # 115s left: a PUT at the 45s floor; once it lands nothing is left above the next chunk's floor to rest. + self.assertEqual(upload_at(485.0), (True, [("PUT", 45)], unittest.mock.call(0))) # Under the floor no link is asked for and nothing is sent: None, a stop rather than a failed upload. self.assertEqual(upload_at(520.0), (None, [], None)) # A link request that retried for 60s comes out of the PUT's time, not on top of it. - self.assertEqual(upload_at(100.0, link_took=60.0), (True, [("PUT", 400)], unittest.mock.call(20))) + self.assertEqual(upload_at(100.0, link_took=60.0), (True, [("PUT", 370)], unittest.mock.call(20))) # And when it leaves less than the floor, the link is dropped and nothing is sent. self.assertEqual(upload_at(485.0, link_took=60.0), (None, [], None)) # from-s3 gets 30s an attempt with time in hand, and less when its four attempts must end before the kill. From aef7fb948102fbe407c56da6a038b1d97a336a81 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 19:39:03 +0530 Subject: [PATCH 04/53] feat(setup): forward hook errors stuck in error.log each run [WEB-6392] --- binary/README.md | 4 + binary/src/unbound_hook/setup_cmd.py | 109 +++++++++++++++++++++++++++ binary/tests/test_setup_reporting.py | 93 +++++++++++++++++++++++ 3 files changed, 206 insertions(+) diff --git a/binary/README.md b/binary/README.md index 956be3fb1..c582f69e4 100644 --- a/binary/README.md +++ b/binary/README.md @@ -85,6 +85,10 @@ the python path, by design: written but reported `skipped` (" is not installed"). A discovery run that prints `Scan skipped: ` is `skipped`. The run itself posts `phase: start` first and `phase: end` last to the MDM install report. + Each tool's adapter also forwards its hook's `error.log` entries newer than + the last forwarded one to the gateway's `/v1/hooks/errors` (ten a request), + recording the newest accepted timestamp in `.error_log_forwarded` beside the + log; a failed request saves nothing and ends forwarding for the run. - **`detect_install_state`** is adapted: the python version checked for the managed `unbound.py`, which no longer exists. Binary semantics: settings file absent → `fresh`; present and referencing the binary → `persisted`; diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 2028cceba..0980f2300 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -23,6 +23,7 @@ import math import os import platform +import re import shlex import stat import subprocess @@ -252,6 +253,109 @@ def _end_fields(opts, user_homes, warnings) -> dict: "user_homes": {"configured": configured, "skipped": len(user_homes) - configured}} +# --------------------------------------------------------------------------- +# Stuck hook errors (WEB-6392): a hook reports an error to the gateway at most +# once a minute and never retries, so the rest wait in its error.log. Each run +# sends the entries newer than the last one forwarded, per tool and per home. +# --------------------------------------------------------------------------- + +# Each tool's hook log under a home, and the hook_source its hook reports as. +_HOOK_ERROR_LOGS = { + "claude-code": (".claude/hooks/error.log", "claude-code"), + "cursor": (".cursor/hooks/error.log", "cursor"), + "codex": (".codex/hooks/error.log", "codex"), + "copilot": (".copilot/hooks/error.log", "copilot"), + "augment": (".augment/hooks/error.log", "augment_code"), +} +# Beside each error.log: the timestamp of the newest entry the gateway accepted. +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the profile's user: the log's entries newer than the last one forwarded, oldest first.""" + try: + last = _log_time(_read_user_file(log.with_name(FORWARDED_STATE_NAME), follow=False).decode().strip()) + except (OSError, UnicodeDecodeError): + last = None + entries = [] + for line in _read_user_file(log, follow=False).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + when = _log_time(match.group(1)) if match else None + if when and (last is None or when > last): + entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000]})) + entries.sort(key=lambda entry: entry[0]) + return [entry for _, entry in entries] + + +def _save_forwarded(log: Path, timestamp: str) -> bool: + """Runs as the profile's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), timestamp.encode("utf-8"), 0o600) + return True + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> bool: + """The hook's own request shape and auth. True only when the gateway took them: it answers an + unknown key with 200 and success false.""" + errors = [dict(entry, message=re.sub(r"(?i)\bBearer\s+\S+", "Bearer [REDACTED]", + entry["message"].replace(api_key, "[REDACTED]"))) + for entry in batch] + code, answer = _post_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + try: + return 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + return False + + +def _forward_home_errors(m, username, log, send): + """(entries sent, whether every request went through). The place is saved after each accepted request.""" + entries = _as_user(m, username, _unsent_hook_errors, log) or [] + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + if not send(batch): + return start, False + _as_user(m, username, _save_forwarded, log, batch[-1]["timestamp"]) + return len(entries), True + + +def _forward_hook_errors(m, tool, api_key, opts) -> None: + """Forward every home's unsent error.log entries for this tool. The first failed request ends forwarding + for the whole run, so a gateway that is down costs one short timeout; the next run retries.""" + if opts.get("hook_errors_held"): + return + relpath, hook_source = _HOOK_ERROR_LOGS[tool] + sent = 0 + try: + hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] + send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", + api_key, hook_source, hook_sha) + for username, home_dir in m.get_all_user_homes(): + log = home_dir / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + count, ok = _forward_home_errors(m, username, log, send) + sent += count + if not ok: + opts["hook_errors_held"] = True + print(f"[errors] {tool} hook errors not forwarded; the next run retries") + break + except Exception as e: + print(f"[errors] {tool} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {tool} hook errors") + + def _detect_state(settings_path: Path, expected_hooks, relative_ok=False): """'persisted' if every event runs our exact command (or the python-era unbound.py being migrated), 'tampered' otherwise or if unparsable, 'fresh' with no file, None if unreadable. Admin-owned files only.""" @@ -1163,6 +1267,7 @@ def _setup_claude_code(opts): skip_settings = opts["skip_managed_settings"] report = functools.partial(_report, m, "claude-code", api_key, backend_url=base, serial_number=device_id, install_mode="binary-skip" if skip_settings else "binary") + _forward_hook_errors(m, "claude-code", api_key, opts) for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "UNBOUND_API_KEY") @@ -1223,6 +1328,7 @@ def _setup_augment(opts): return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "augment", api_key, backend_url=base, serial_number=device_id, install_mode="binary") + _forward_hook_errors(m, "augment", api_key, opts) # Write the per-user unbound config now (needed by the managed hook). User # hook removal is deferred until the managed write succeeds (parity with @@ -1262,6 +1368,7 @@ def _setup_codex(opts): return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "codex", api_key, backend_url=base, serial_number=device_id, install_mode="binary") + _forward_hook_errors(m, "codex", api_key, opts) for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "OPENAI_API_KEY") @@ -1472,6 +1579,7 @@ def _setup_cursor(opts): return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "cursor", api_key, backend_url=base, serial_number=device_id, install_mode="binary") + _forward_hook_errors(m, "cursor", api_key, opts) config_ok = True for username, home_dir in m.get_all_user_homes(): @@ -1559,6 +1667,7 @@ def _setup_copilot(opts): return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "copilot", api_key, backend_url=base, serial_number=device_id, install_mode="binary") + _forward_hook_errors(m, "copilot", api_key, opts) user_homes = m.get_all_user_homes() state = _copilot_detect_state(m, user_homes) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 799036cb0..dd6a2915c 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -271,3 +271,96 @@ def test_the_notifier_sends_status_reason_and_where_it_wrote(tool, monkeypatch): assert (skipped["status"], skipped["reason"], skipped["written_to"]) == ("skipped", "r" * 500, ("/p" * 300)[:500]) # An old-style call sends the body it always did: a missing status means configured. assert not {"status", "reason", "written_to"} & set(plain) + + +# --- Step 7: forward hook errors stuck in error.log ------------------------------ + +ERROR_LOGS = {"claude-code": ".claude/hooks/error.log", "cursor": ".cursor/hooks/error.log", + "codex": ".codex/hooks/error.log", "copilot": ".copilot/hooks/error.log", + "augment": ".augment/hooks/error.log"} +STATE = ".error_log_forwarded" + + +def _log(home, tool, lines): + path = home / ERROR_LOGS[tool] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(line + "\n" for line in lines)) + return path + + +def _utc(n): + return "2026-11-21T16:%02d:%02d.000123Z" % (n // 60, n % 60) + + +def _forwarded(backend): + return [r for r in backend.requests if r["path"] == "/v1/hooks/errors"] + + +def test_errors_newer_than_the_last_forwarded_one_go_to_the_gateway(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(n)}: gateway unreachable {n}" for n in range(3)]) + log.with_name(STATE).write_text(_utc(0)) + _run(backend) + [request] = _forwarded(backend) + assert request["headers"]["Authorization"] == "Bearer per-device-key" + body = request["body"] + assert body["hook_source"] == "claude-code" and len(body["hook_sha"]) == 12 + assert [(e["timestamp"], e["message"]) for e in body["errors"]] == [ + (_utc(1), "gateway unreachable 1"), (_utc(2), "gateway unreachable 2")] + assert log.with_name(STATE).read_text() == _utc(2) + + +def test_errors_go_ten_to_a_request_and_none_is_sent_twice(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(n)}: e{n}" for n in range(25)]) + _run(backend) + assert [len(r["body"]["errors"]) for r in _forwarded(backend)] == [10, 10, 5] + assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == [f"e{n}" for n in range(25)] + assert log.with_name(STATE).read_text() == _utc(24) + backend.requests.clear() + _run(backend) + assert _forwarded(backend) == [] + + +def test_an_unreachable_gateway_saves_nothing_and_the_next_run_sends_it_all(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(n)}: e{n}" for n in range(3)]) + rc = setup_cmd.run(["--api-key", "admin-key", "--backend-url", backend.url, + "--gateway-url", "http://127.0.0.1:9"]) + assert rc == 0 + assert not log.with_name(STATE).exists() + _run(backend) + assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["e0", "e1", "e2"] + + +def test_a_refused_request_saves_nothing(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(0)}: e0"]) + # The gateway answers an unknown key with 200 and success false. + backend.answer = lambda path: (200, {"success": False, "reason": "invalid_key"}) + assert _run(backend) == 0 + assert len(_forwarded(backend)) == 1 + assert not log.with_name(STATE).exists() + + +def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, tmp_path): + other = tmp_path / "other-home" + other.mkdir() + for m in env["modules"].values(): + monkeypatch.setattr(m, "get_all_user_homes", lambda: [("alice", env["home"]), ("bob", other)]) + # Cursor's and Copilot's hooks stamp local time with its offset. + _log(env["home"], "cursor", ["2026-11-21T08:40:11.000001-08:00: cursor broke"]) + _log(env["home"], "copilot", ["2026-11-21T08:41:11.000001-08:00: copilot broke"]) + _log(env["home"], "codex", [f"{_utc(1)}: codex broke"]) + _log(other, "claude-code", [f"{_utc(2)}: bob's claude broke"]) + _log(other, "augment", [f"{_utc(3)}: auggie broke"]) + _run(backend) + sent = {r["body"]["hook_source"]: [e["message"] for e in r["body"]["errors"]] for r in _forwarded(backend)} + assert sent == {"cursor": ["cursor broke"], "copilot": ["copilot broke"], "codex": ["codex broke"], + "claude-code": ["bob's claude broke"], "augment_code": ["auggie broke"]} + assert (env["home"] / ".copilot/hooks" / STATE).read_text() == "2026-11-21T08:41:11.000001-08:00" + assert (other / ".claude/hooks" / STATE).exists() and not (env["home"] / ".claude/hooks" / STATE).exists() + # Cursor's setup removes the python-era ~/.cursor/hooks, log and all, after its errors went out. + assert not (env["home"] / ".cursor/hooks").exists() + + +def test_lines_that_are_not_log_entries_are_skipped(env, backend): + _log(env["home"], "claude-code", ["not an entry", f"{_utc(5)}: real one", " continued text"]) + _run(backend) + assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["real one"] From fc2dafd743efaefa99def47d71c138965a0a4356 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 20:40:36 +0530 Subject: [PATCH 05/53] fix(setup): keep run report inputs from stopping the install [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 38 +++++++++++++++-------- binary/tests/test_setup_reporting.py | 45 ++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 0980f2300..531d93dbc 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -161,13 +161,23 @@ def _utc_now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") +def _report_input(fn, fallback, what): + """A value only the run reports use: when it can't be had, the reports lose it, never the install.""" + try: + return fn() + except Exception as e: + print(f"[report] {what} unavailable: {e}") + return fallback + + def _send_run_report(opts, serial, phase, fields) -> None: + """fields is called here, inside the fail-open guard.""" try: if not serial: # the endpoint joins on it; without one the report is dropped anyway print(f"[report] install-report {phase} not sent: no device serial") return body = {"serial_number": serial, "phase": phase, - "install_mode": "binary-skip" if opts["skip_managed_settings"] else "binary", **fields} + "install_mode": "binary-skip" if opts["skip_managed_settings"] else "binary", **fields()} code, _ = _post_json(opts["backend_url"] + INSTALL_REPORT_PATH, body, {"X-API-KEY": opts["api_key"]}) if not 200 <= code < 300: print(f"[report] install-report {phase} not sent: HTTP {code}") @@ -184,11 +194,11 @@ def _start_fields() -> dict: def _preflight_warnings(user_homes) -> list: - """What this run can already tell will keep the device from reporting.""" + """What this run can already tell will keep the device from reporting. user_homes None: unknown.""" warnings = [] if not HOOK_BINARY.is_file(): # every managed hook command points at it warnings.append(f"hook binary not found at {HOOK_BINARY}") - if not user_homes: + if user_homes == []: warnings.append("no user homes found") return warnings @@ -246,11 +256,12 @@ def _report(m, tool, api_key, status, reason=None, **fields): def _end_fields(opts, user_homes, warnings) -> dict: - writes = opts.get("config_writes", {}) - configured = sum(1 for _, home in user_homes if writes.get(str(home)) is True) - return {"timestamps": {"completed_at": _utc_now()}, - "preflight_warnings": warnings, - "user_homes": {"configured": configured, "skipped": len(user_homes) - configured}} + fields = {"timestamps": {"completed_at": _utc_now()}, "preflight_warnings": warnings} + if user_homes is not None: # unknown homes send no counts rather than wrong ones + writes = opts.get("config_writes", {}) + configured = sum(1 for _, home in user_homes if writes.get(str(home)) is True) + fields["user_homes"] = {"configured": configured, "skipped": len(user_homes) - configured} + return fields # --------------------------------------------------------------------------- @@ -1831,10 +1842,11 @@ def run(argv) -> int: opts["frontend_url"] = m0.normalize_url(opts["frontend_url"]) opts["config_writes"] = {} - serial = m0.get_device_identifier() - user_homes = m0.get_all_user_homes() - warnings = _preflight_warnings(user_homes) - _send_run_report(opts, serial, "start", _start_fields()) + # Report-only inputs: none of them may stop the install or change its exit code. + serial = _report_input(m0.get_device_identifier, None, "device serial") + user_homes = _report_input(m0.get_all_user_homes, None, "user homes") + warnings = _report_input(lambda: _preflight_warnings(user_homes), [], "preflight checks") + _send_run_report(opts, serial, "start", _start_fields) statuses = {} @@ -1869,5 +1881,5 @@ def run(argv) -> int: print(line) if status == "deferred": any_deferred = True - _send_run_report(opts, serial, "end", _end_fields(opts, user_homes, warnings)) + _send_run_report(opts, serial, "end", lambda: _end_fields(opts, user_homes, warnings)) return 1 if any_deferred else 0 diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index dd6a2915c..c0e13d384 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -364,3 +364,48 @@ def test_lines_that_are_not_log_entries_are_skipped(env, backend): _log(env["home"], "claude-code", ["not an entry", f"{_utc(5)}: real one", " continued text"]) _run(backend) assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["real one"] + + +# --- F9: the run reports' inputs fail open --------------------------------------- + +def _first_call_raises(module, name, monkeypatch): + """Raises on run()'s own call only: the tools call the same function afterwards.""" + real, calls = getattr(module, name), [] + + def flaky(*a, **k): + calls.append(1) + if len(calls) == 1: + raise RuntimeError(f"{name} broke") + return real(*a, **k) + monkeypatch.setattr(module, name, flaky) + + +def _installs_everything(env): + assert (env["tmp"] / "managed-claude" / "managed-settings.json").exists() + assert (env["tmp"] / "managed-codex" / "hooks.json").exists() + assert (env["tmp"] / "enterprise-cursor" / "hooks.json").exists() + assert (env["home"] / ".copilot" / "hooks" / "unbound.json").exists() + assert len(env["notified"]) == 5 + + +def test_a_serial_lookup_that_raises_costs_only_the_run_reports(env, backend, monkeypatch): + _first_call_raises(env["modules"]["claude-code"], "get_device_identifier", monkeypatch) + assert _run(backend) == 0 + _installs_everything(env) + assert _run_reports(backend) == [] + + +def test_a_home_lookup_that_raises_costs_only_the_home_counts(env, backend, monkeypatch): + _first_call_raises(env["modules"]["claude-code"], "get_all_user_homes", monkeypatch) + assert _run(backend) == 0 + _installs_everything(env) + start, end = (r["body"] for r in _run_reports(backend)) + assert "user_homes" not in end + assert "no user homes found" not in end["preflight_warnings"] + + +def test_preflight_checks_that_raise_cost_only_the_warnings(env, backend, monkeypatch): + monkeypatch.setattr(setup_cmd, "_preflight_warnings", lambda homes: 1 / 0) + assert _run(backend) == 0 + _installs_everything(env) + assert _run_reports(backend)[-1]["body"]["preflight_warnings"] == [] From f895f48bfff605217b747379164b7658a5226cfd Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 20:42:46 +0530 Subject: [PATCH 06/53] fix(setup): cap and age-limit forwarded hook errors [WEB-6392] --- binary/README.md | 4 +- binary/src/unbound_hook/setup_cmd.py | 21 ++++++++--- binary/tests/test_setup_reporting.py | 55 +++++++++++++++++++++++++--- 3 files changed, 69 insertions(+), 11 deletions(-) diff --git a/binary/README.md b/binary/README.md index c582f69e4..2baa7c93a 100644 --- a/binary/README.md +++ b/binary/README.md @@ -86,7 +86,9 @@ the python path, by design: that prints `Scan skipped: ` is `skipped`. The run itself posts `phase: start` first and `phase: end` last to the MDM install report. Each tool's adapter also forwards its hook's `error.log` entries newer than - the last forwarded one to the gateway's `/v1/hooks/errors` (ten a request), + the last forwarded one to the gateway's `/v1/hooks/errors` (ten a request, + at most the newest 25 per tool and home, none older than seven days, with + `category: forwarded_error_log`), recording the newest accepted timestamp in `.error_log_forwarded` beside the log; a failed request saves nothing and ends forwarding for the run. - **`detect_install_state`** is adapted: the python version checked for the diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 531d93dbc..dacc12d27 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -30,7 +30,7 @@ import sys import threading import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from pathlib import Path from . import __version__ @@ -281,6 +281,12 @@ def _end_fields(opts, user_homes, warnings) -> dict: # Beside each error.log: the timestamp of the newest entry the gateway accepted. FORWARDED_STATE_NAME = ".error_log_forwarded" HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per tool and home, a run sends at most the newest 25 (what a hook keeps) +# and nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") @@ -294,19 +300,24 @@ def _log_time(text): def _unsent_hook_errors(log: Path) -> list: - """Runs as the profile's user: the log's entries newer than the last one forwarded, oldest first.""" + """Runs as the profile's user: the newest HOOK_ERRORS_PER_RUN entries newer than both the last one + forwarded and HOOK_ERROR_MAX_AGE, oldest first.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE try: last = _log_time(_read_user_file(log.with_name(FORWARDED_STATE_NAME), follow=False).decode().strip()) except (OSError, UnicodeDecodeError): last = None + if last is not None and last > floor: + floor = last entries = [] for line in _read_user_file(log, follow=False).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) when = _log_time(match.group(1)) if match else None - if when and (last is None or when > last): - entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000]})) + if when and when > floor: + entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY})) entries.sort(key=lambda entry: entry[0]) - return [entry for _, entry in entries] + return [entry for _, entry in entries[-HOOK_ERRORS_PER_RUN:]] def _save_forwarded(log: Path, timestamp: str) -> bool: diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index c0e13d384..918020501 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -8,6 +8,7 @@ import json import re import threading +from datetime import datetime, timedelta, timezone from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pytest @@ -288,8 +289,17 @@ def _log(home, tool, lines): return path -def _utc(n): - return "2026-11-21T16:%02d:%02d.000123Z" % (n // 60, n % 60) +# Entries are stamped an hour before the test run, so the seven-day limit never ages them out. +BASE = datetime.now(timezone.utc).replace(microsecond=123) - timedelta(hours=1) + + +def _utc(n, days_ago=0): + return (BASE + timedelta(seconds=n) - timedelta(days=days_ago)).isoformat().replace("+00:00", "Z") + + +def _pacific(n): + """How Cursor's and Copilot's hooks stamp: local time with its offset.""" + return (BASE + timedelta(seconds=n)).astimezone(timezone(timedelta(hours=-8))).isoformat() def _forwarded(backend): @@ -345,8 +355,8 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, for m in env["modules"].values(): monkeypatch.setattr(m, "get_all_user_homes", lambda: [("alice", env["home"]), ("bob", other)]) # Cursor's and Copilot's hooks stamp local time with its offset. - _log(env["home"], "cursor", ["2026-11-21T08:40:11.000001-08:00: cursor broke"]) - _log(env["home"], "copilot", ["2026-11-21T08:41:11.000001-08:00: copilot broke"]) + _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke"]) + _log(env["home"], "copilot", [f"{_pacific(1)}: copilot broke"]) _log(env["home"], "codex", [f"{_utc(1)}: codex broke"]) _log(other, "claude-code", [f"{_utc(2)}: bob's claude broke"]) _log(other, "augment", [f"{_utc(3)}: auggie broke"]) @@ -354,7 +364,7 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, sent = {r["body"]["hook_source"]: [e["message"] for e in r["body"]["errors"]] for r in _forwarded(backend)} assert sent == {"cursor": ["cursor broke"], "copilot": ["copilot broke"], "codex": ["codex broke"], "claude-code": ["bob's claude broke"], "augment_code": ["auggie broke"]} - assert (env["home"] / ".copilot/hooks" / STATE).read_text() == "2026-11-21T08:41:11.000001-08:00" + assert (env["home"] / ".copilot/hooks" / STATE).read_text() == _pacific(1) assert (other / ".claude/hooks" / STATE).exists() and not (env["home"] / ".claude/hooks" / STATE).exists() # Cursor's setup removes the python-era ~/.cursor/hooks, log and all, after its errors went out. assert not (env["home"] / ".cursor/hooks").exists() @@ -409,3 +419,38 @@ def test_preflight_checks_that_raise_cost_only_the_warnings(env, backend, monkey assert _run(backend) == 0 _installs_everything(env) assert _run_reports(backend)[-1]["body"]["preflight_warnings"] == [] + + +# --- F7: a per-run cap and an age limit on forwarded errors ------------------------ + +def _messages(backend): + return [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] + + +def test_a_huge_log_sends_only_its_25_newest_entries(env, backend): + # About 4 MB in 40,000 lines, just under the read cap: the gateway must not get 4,000 requests. + lines = [f"{_utc(n / 100)}: flood {n} " + "x" * 50 for n in range(40000)] + log = _log(env["home"], "claude-code", lines) + assert 3.5e6 < log.stat().st_size < 4 * 1024 * 1024 + _run(backend) + assert len(_forwarded(backend)) <= 3 + assert [m.split()[1] for m in _messages(backend)] == [str(n) for n in range(39975, 40000)] + assert log.with_name(STATE).read_text() == _utc(39999 / 100) + + +def test_entries_older_than_seven_days_are_never_sent(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(0, days_ago=8)}: stale", f"{_utc(1, days_ago=6)}: recent"]) + _run(backend) + assert _messages(backend) == ["recent"] + # Not even when the last forwarded entry is older still. + log.write_text(f"{_utc(0, days_ago=8)}: stale again\n") + log.with_name(STATE).write_text(_utc(0, days_ago=30)) + backend.requests.clear() + _run(backend) + assert _messages(backend) == [] + + +def test_forwarded_errors_carry_a_category_of_their_own(env, backend): + _log(env["home"], "claude-code", [f"{_utc(0)}: e0"]) + _run(backend) + assert [e["category"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["forwarded_error_log"] From 312269572fec925f97fbb3e9c51ceb872c0c9973 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 20:43:56 +0530 Subject: [PATCH 07/53] fix(setup): count version-manager and editor installs as installed [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 17 ++++++++++++----- binary/tests/test_setup_reporting.py | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index dacc12d27..22bc874be 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -219,8 +219,16 @@ def _preflight_warnings(user_homes) -> list: "codex": ("Codex", "codex", ("Codex.app",), (".codex/auth.json", ".codex/sessions")), "copilot": ("GitHub Copilot", "copilot", ("Visual Studio Code.app", "Visual Studio Code - Insiders.app"), ()), - "augment": ("Augment", "auggie", (), ()), + # The editor extension alone, in VS Code, VS Code Insiders or Cursor, also counts. + "augment": ("Augment", "auggie", (), tuple(f"{editor}/extensions/augment.vscode-augment-*" + for editor in (".vscode", ".vscode-insiders", ".cursor"))), } +# Where a CLI lands under a home: a user install, Bun, npm's user prefix, and the Node version managers +# (nvm, Volta, pnpm's default PNPM_HOME, fnm in both its folders, asdf and mise shims, mise's installs). +_HOME_CLI_DIRS = (".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + "Library/pnpm", ".local/share/fnm/node-versions/*/installation/bin", + ".fnm/node-versions/*/installation/bin", ".asdf/shims", ".local/share/mise/shims", + ".local/share/mise/installs/*/*/bin") _MACHINE_ROOT = Path("/") @@ -232,14 +240,13 @@ def _present(root: Path, relpath: str) -> bool: def _tool_installed(tool, user_homes) -> bool: - """Any footprint machine-wide (Homebrew, /usr/local, /Applications) or in a home (a user install, Bun, - npm, nvm, ~/Applications). A check that fails counts as installed, the report setup always sent.""" + """Any footprint machine-wide (Homebrew, /usr/local, /Applications) or in a home (_HOME_CLI_DIRS, + ~/Applications, the tool's own files). A check that fails counts as installed, the report setup always sent.""" try: _, cli, apps, home_files = _TOOL_FOOTPRINTS[tool] app_paths = [f"Applications/{app}" for app in apps] machine = [f"opt/homebrew/bin/{cli}", f"usr/local/bin/{cli}", *app_paths] - per_home = [f".local/bin/{cli}", f".bun/bin/{cli}", f".npm-global/bin/{cli}", - f".nvm/versions/node/*/bin/{cli}", *home_files, *app_paths] + per_home = [f"{folder}/{cli}" for folder in _HOME_CLI_DIRS] + [*home_files, *app_paths] roots = [(_MACHINE_ROOT, machine)] + [(home, per_home) for _, home in user_homes if home is not None] return any(_present(root, rel) for root, rels in roots for rel in rels) except Exception: diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 918020501..e19c45514 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -454,3 +454,23 @@ def test_forwarded_errors_carry_a_category_of_their_own(env, backend): _log(env["home"], "claude-code", [f"{_utc(0)}: e0"]) _run(backend) assert [e["category"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["forwarded_error_log"] + + +# --- S-U2: version managers and editor extensions count as installed ------------- + +@pytest.mark.parametrize("tool,relpath", [ + ("claude-code", ".volta/bin/claude"), + ("codex", "Library/pnpm/codex"), + ("copilot", ".local/share/fnm/node-versions/v22.11.0/installation/bin/copilot"), + ("claude-code", ".fnm/node-versions/v20.1.0/installation/bin/claude"), + ("augment", ".asdf/shims/auggie"), + ("codex", ".local/share/mise/shims/codex"), + ("claude-code", ".local/share/mise/installs/node/22.1.0/bin/claude"), + ("augment", ".vscode/extensions/augment.vscode-augment-0.512.0"), + ("augment", ".vscode-insiders/extensions/augment.vscode-augment-0.512.0"), + ("augment", ".cursor/extensions/augment.vscode-augment-0.512.0-darwin-arm64"), +]) +def test_installs_through_version_managers_and_editors_count(env, machine, tool, relpath): + _install(env["home"], relpath) + setup_cmd.run(["--api-key", "admin-key"]) + assert _reports(env, tool)[0]["status"] == "configured" From f248f2bab2a337cc6119a0096a85e742f3971b65 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 21:29:42 +0530 Subject: [PATCH 08/53] test(setup): guard linked error logs and redaction in forwarded hook errors [WEB-6392] --- binary/tests/test_setup_reporting.py | 58 ++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index e19c45514..0fb131c93 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -474,3 +474,61 @@ def test_installs_through_version_managers_and_editors_count(env, machine, tool, _install(env["home"], relpath) setup_cmd.run(["--api-key", "admin-key"]) assert _reports(env, tool)[0]["status"] == "configured" + + +# --- S-U4: setup runs as root over paths the user controls ----------------------- + +def _as_user_like_the_real_one(env, monkeypatch): + """The real _run_as_user answers None when fn raises in the user's child; the env stub raises instead.""" + def run_as(username, fn, *args, _timeout=None, **kwargs): + try: + return fn(*args, **kwargs) + except Exception: + return None + for m in env["modules"].values(): + monkeypatch.setattr(m, "_run_as_user", run_as) + + +def test_an_error_log_that_is_a_link_is_never_read_through(env, backend, monkeypatch, tmp_path): + _as_user_like_the_real_one(env, monkeypatch) + other = tmp_path / "other-home" + other.mkdir() + for m in env["modules"].values(): + monkeypatch.setattr(m, "get_all_user_homes", lambda: [("alice", env["home"]), ("bob", other)]) + # alice points her log at a file she must not be able to make setup read and send. + secret = tmp_path / "root-only.txt" + secret.write_text(f"{_utc(0)}: root secret\n") + log = env["home"] / ERROR_LOGS["claude-code"] + log.parent.mkdir(parents=True) + log.symlink_to(secret) + _log(other, "claude-code", [f"{_utc(1)}: bob's error"]) + _run(backend) + assert _messages(backend) == ["bob's error"] + assert not log.with_name(STATE).exists() + + +def test_a_state_file_that_is_a_link_is_replaced_not_followed(env, backend, tmp_path): + log = _log(env["home"], "claude-code", [f"{_utc(0)}: e0", f"{_utc(1)}: e1"]) + # Read through, the link's target would say everything was already sent; written through, it gets overwritten. + victim = tmp_path / "victim.txt" + victim.write_text(_utc(100)) + log.with_name(STATE).symlink_to(victim) + _run(backend) + assert _messages(backend) == ["e0", "e1"] + assert victim.read_text() == _utc(100) + state = log.with_name(STATE) + assert not state.is_symlink() and state.read_text() == _utc(1) + + +# --- S-U5: what reaches the gateway, and Sentry behind it ------------------------ + +def test_the_key_and_bearer_tokens_are_redacted_and_messages_cut(env, backend): + _log(env["home"], "claude-code", [ + f"{_utc(0)}: POST failed for per-device-key with Authorization: Bearer sk-live-abc123", + f"{_utc(1)}: retry said bearer tok_lower and gave up", + f"{_utc(2)}: " + "y" * 5000]) + _run(backend) + assert _messages(backend) == ["POST failed for [REDACTED] with Authorization: Bearer [REDACTED]", + "retry said Bearer [REDACTED] and gave up", "y" * 2000] + [request] = _forwarded(backend) + assert not re.search(r"per-device-key|sk-live-abc123|tok_lower", json.dumps(request["body"])) From e834e9b14800e52f5e6747c08c155cdbedbbeb34 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 21:29:42 +0530 Subject: [PATCH 09/53] test(setup): guard the scan output pipe against big output, held pipes and the backstop [WEB-6392] --- binary/tests/test_setup_discovery_output.py | 89 +++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 binary/tests/test_setup_discovery_output.py diff --git a/binary/tests/test_setup_discovery_output.py b/binary/tests/test_setup_discovery_output.py new file mode 100644 index 000000000..7f0445116 --- /dev/null +++ b/binary/tests/test_setup_discovery_output.py @@ -0,0 +1,89 @@ +"""WEB-6392: setup now reads the discovery scan's stdout (for the 'Scan skipped:' line) instead of +letting the scan inherit it. A pipe can stall a child that a shared stdout never could, so these run +_run_discovery against real child processes: a big and noisy scan, a grandchild that keeps the pipe +open, and a scan that hangs past the backstop. +""" + +import os +import signal +import sys +import time + +import pytest + +from unbound_hook import setup_cmd + +OPTS = {"backend_url": "http://127.0.0.1:9"} +SKIPPED = ("skipped", "another scan is running") + + +def _scan(tmp_path, monkeypatch, body): + """Stand in a discovery binary (a python script) and the owner-key lookup it needs.""" + script = tmp_path / "unbound-discovery" + script.write_text(f"#!{sys.executable}\nimport os, subprocess, sys, time\n" + f"PIDS = {str(tmp_path / 'pids')!r}\n{body}") + script.chmod(0o755) + monkeypatch.setattr(setup_cmd, "DISCOVERY_BINARY", script) + monkeypatch.setattr(setup_cmd, "_fetch_device_owner_key", lambda opts: "owner-key") + return tmp_path / "pids" + + +def _alive(pid): + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +@pytest.fixture +def reap(): + """Kills whatever pids a scan wrote down, so no test leaves a process behind.""" + files = [] + yield files.append + for path in files: + for pid in (int(p) for p in path.read_text().split()) if path.exists() else (): + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + pass + + +# A child that writes a pid down and keeps the scan's stdout open, as a helper the scan starts might. +SPAWN_HOLDER = ("holder = subprocess.Popen(['sleep', '30'])\n" + "open(PIDS, 'a').write(f'{holder.pid}\\n')\n") + + +def test_a_big_scan_whose_grandchild_keeps_the_pipe_is_read_through_and_not_waited_for( + tmp_path, monkeypatch, capsys, reap): + # 20 MB of output, the skipped line (CRLF) at line 500, then a grandchild holding the pipe open. + reap(_scan(tmp_path, monkeypatch, + "out = sys.stdout.buffer\nline = b'x' * 99 + b'\\n'\n" + "for _ in range(499): out.write(line)\n" + "out.write(b'Scan skipped: another scan is running\\r\\n')\n" + "for _ in range(200000): out.write(line)\n" + "out.flush()\n" + SPAWN_HOLDER)) + began = time.monotonic() + assert setup_cmd._run_discovery(OPTS) == SKIPPED + # Nowhere near the grandchild's 30 s: setup gives a held pipe 5 s, then moves on. + assert time.monotonic() - began < 15 + out = capsys.readouterr().out + assert out.count("x" * 99 + "\n") == 200499 # every line reached the MDM log + assert "Scan skipped: another scan is running" in out + + +def test_a_scan_past_the_backstop_is_killed_with_its_whole_group_and_deferred(tmp_path, monkeypatch, reap): + reap(_scan(tmp_path, monkeypatch, + SPAWN_HOLDER + "open(PIDS, 'a').write(f'{os.getpid()}\\n')\n" + "print('detecting', flush=True)\ntime.sleep(60)\n")) + monkeypatch.setattr(setup_cmd, "DISCOVERY_TIMEOUT_SECONDS", 1) + monkeypatch.setattr(setup_cmd, "DISCOVERY_KILL_GRACE_SECONDS", 0) + began = time.monotonic() + assert setup_cmd._run_discovery(OPTS) == ("deferred", "discovery exceeded 1s and was terminated") + assert time.monotonic() - began < 10 + pids = [int(p) for p in (tmp_path / "pids").read_text().split()] + deadline = time.monotonic() + 5 # an orphaned grandchild is reaped by launchd/init, not by us + while any(_alive(pid) for pid in pids) and time.monotonic() < deadline: + time.sleep(0.1) + assert not [pid for pid in pids if _alive(pid)], "a scan process outlived the backstop kill" + From 81ca8630cb8518c0a5764da8b5aa1afc42c8f8c3 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 21:29:42 +0530 Subject: [PATCH 10/53] fix(setup): keep reading the scan's output when the MDM log can't be written [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 12 +++++++--- binary/tests/test_setup_discovery_output.py | 26 ++++++++++++++++++++- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 22bc874be..635e2c043 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -1768,12 +1768,18 @@ def _fetch_device_owner_key(opts): def _echo_scan_output(stream, skipped) -> None: """Pass the scan's stdout through to the MDM log line by line, keeping the reason - of the first 'Scan skipped: ' line it prints.""" + of the first 'Scan skipped: ' line it prints. A log that can't be written stops the + echo, never the reading: a full pipe would stall the scan until the backstop.""" + echo = True try: for raw in iter(stream.readline, b""): line = raw.decode("utf-8", "replace") - sys.stdout.write(line) - sys.stdout.flush() + if echo: + try: + sys.stdout.write(line) + sys.stdout.flush() + except Exception: + echo = False if not skipped and line.startswith(SCAN_SKIPPED_PREFIX): skipped.append(line[len(SCAN_SKIPPED_PREFIX):].strip()) except Exception: diff --git a/binary/tests/test_setup_discovery_output.py b/binary/tests/test_setup_discovery_output.py index 7f0445116..b6798d779 100644 --- a/binary/tests/test_setup_discovery_output.py +++ b/binary/tests/test_setup_discovery_output.py @@ -1,7 +1,7 @@ """WEB-6392: setup now reads the discovery scan's stdout (for the 'Scan skipped:' line) instead of letting the scan inherit it. A pipe can stall a child that a shared stdout never could, so these run _run_discovery against real child processes: a big and noisy scan, a grandchild that keeps the pipe -open, and a scan that hangs past the backstop. +open, a scan that hangs past the backstop, and an MDM log that can no longer be written. """ import os @@ -87,3 +87,27 @@ def test_a_scan_past_the_backstop_is_killed_with_its_whole_group_and_deferred(tm time.sleep(0.1) assert not [pid for pid in pids if _alive(pid)], "a scan process outlived the backstop kill" + +class _UnwritableLog: + """setup's stdout once the MDM agent reading it is gone, or the disk it goes to is full.""" + encoding = "utf-8" + + def write(self, text): + raise BrokenPipeError(32, "Broken pipe") + + def flush(self): + raise BrokenPipeError(32, "Broken pipe") + + +def test_a_log_that_cannot_be_written_never_stalls_the_scan(tmp_path, monkeypatch, reap): + # Before setup piped it, the scan wrote to that log itself and carried on (its logging drops + # failed writes). Now setup must keep draining the pipe, or the scan blocks on a full one. + _scan(tmp_path, monkeypatch, "for n in range(40000): print('detecting', n)\nprint('Scan complete')\n") + monkeypatch.setattr(setup_cmd, "DISCOVERY_TIMEOUT_SECONDS", 20) + monkeypatch.setattr(setup_cmd, "DISCOVERY_KILL_GRACE_SECONDS", 0) + monkeypatch.setattr(sys, "stdout", _UnwritableLog()) + began = time.monotonic() + result = setup_cmd._run_discovery(OPTS) + elapsed = time.monotonic() - began + assert result == ("configured", None) + assert elapsed < 10 From 29cfcca7b35159fc0e6fb487d696de56b6557f94 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Tue, 24 Nov 2026 21:29:42 +0530 Subject: [PATCH 11/53] test(backfill): an unwritable hooks folder never breaks either uploader's run [WEB-6392] --- .../hooks/test_backfill_outcome.py | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index 5e3429a81..957ada3f6 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -8,7 +8,7 @@ import tempfile import time import unittest -from contextlib import ExitStack, redirect_stdout +from contextlib import ExitStack, redirect_stderr, redirect_stdout from pathlib import Path from unittest.mock import patch @@ -22,9 +22,10 @@ class _Backend: """Records each uploaded body. fail_puts: the PUTs (by index) S3 refuses; down: every request fails.""" def __init__(self, fail_puts=(), down=False): - self.bodies, self.fail_puts, self.down, self.puts = [], set(fail_puts), down, 0 + self.bodies, self.fail_puts, self.down, self.puts, self.calls = [], set(fail_puts), down, 0, 0 def __call__(self, url, method, headers, body=None, timeout=30): + self.calls += 1 if self.down: return -7, b"" # curl: could not connect if url.endswith("/upload-url/"): @@ -154,5 +155,37 @@ def test_a_garbled_saved_outcome_is_not_sent(self): self.assertNotIn("previous_outcome", stats) +class AHooksFolderSetupCannotWriteTestCase(_Homes): + """MDM runs can leave a root-owned ~/.claude/hooks behind, which neither uploader can write as the user. + Saving the outcome there fails; the run must end as it always did, and still try to report.""" + + def _hooks_not_writable(self, home): + hooks = home / ".claude" / "hooks" + hooks.mkdir(parents=True, exist_ok=True) + hooks.chmod(0o555) + self.addCleanup(hooks.chmod, 0o755) # runs before the home's rmtree + return hooks + + def test_an_outcome_that_cannot_be_saved_never_breaks_the_run(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + home = self._home(("a",)) + hooks = self._hooks_not_writable(home) + errors = io.StringIO() + with redirect_stderr(errors): + backend = _run(up, home, _Backend(down=True)) + self.assertGreater(backend.calls, 0, "the closing upload was never tried") + self.assertNotIn("Skipped due to error", errors.getvalue()) + self.assertEqual(list(hooks.iterdir()), []) + + def test_the_closing_report_still_goes_up(self): + for up in (mdm, setup): + with self.subTest(up.__name__): + home = self._home(("a",)) + self._hooks_not_writable(home) + [stats] = _run(up, home, _Backend()).stats() + self.assertEqual(stats["outcome"], "completed") + + if __name__ == "__main__": unittest.main() From 223d720776e6f73d24e2e174cba0bae3685e762e Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:00:01 +0530 Subject: [PATCH 12/53] fix(setup): keep report and hook-error keys off curl's command line [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 23 +++++++++++++++++------ binary/tests/test_setup_reporting.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 635e2c043..c603b2750 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -28,6 +28,7 @@ import stat import subprocess import sys +import tempfile import threading import time from datetime import datetime, timedelta, timezone @@ -109,19 +110,29 @@ def _parse_args(argv): def _post_json(url, body, headers, timeout=REPORT_TIMEOUT_SECONDS): """POST a JSON body with curl (the system trust store, as every call here uses). - Returns (http status, response bytes); status 0 when nothing came back. Never raises.""" - cmd = ["curl", "-sS", "-m", str(timeout), "-X", "POST", "-w", "\n%{http_code}", - "-H", "Content-Type: application/json"] - for name, value in headers.items(): - cmd += ["-H", f"{name}: {value}"] - cmd += ["--data-binary", "@-", "--", url] + Returns (http status, response bytes); status 0 when nothing came back. Never raises. + The headers carry keys, and any local user can read a process's argv, so they go to + curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(timeout), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), capture_output=True, timeout=timeout + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass def _module(tool): diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 0fb131c93..97f333f86 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -6,6 +6,8 @@ """ import json +import os +import stat import re import threading from datetime import datetime, timedelta, timezone @@ -532,3 +534,29 @@ def test_the_key_and_bearer_tokens_are_redacted_and_messages_cut(env, backend): "retry said Bearer [REDACTED] and gave up", "y" * 2000] [request] = _forwarded(backend) assert not re.search(r"per-device-key|sk-live-abc123|tok_lower", json.dumps(request["body"])) + + +# --- Review #5: keys never ride on curl's argv ---------------------------------- + +def test_no_key_reaches_a_curl_command_line(env, backend, monkeypatch): + """Any local user can read a process's argv with ps; the headers go in a 0600 file instead.""" + import subprocess as sp + real_run, argvs, modes = sp.run, [], [] + + def recording_run(cmd, *a, **k): + if cmd and cmd[0] == "curl": + argvs.append(list(cmd)) + for arg in cmd: + if arg.startswith("@") and os.path.exists(arg[1:]): + modes.append(stat.S_IMODE(os.stat(arg[1:]).st_mode)) + return real_run(cmd, *a, **k) + + monkeypatch.setattr(setup_cmd.subprocess, "run", recording_run) + _log(env["home"], "claude-code", [f"{_utc(0)}: e0"]) + assert _run(backend) == 0 + assert argvs, "the run made no curl calls" + assert not [a for argv in argvs for a in argv if "admin-key" in a or "per-device-key" in a] + assert modes and set(modes) == {0o600} + # The headers still arrive. + assert {r["headers"].get("X-API-KEY") for r in _run_reports(backend)} == {"admin-key"} + assert _forwarded(backend)[0]["headers"]["Authorization"] == "Bearer per-device-key" From 11f4f623b18579fb6bc3455f9ad126e552e300e6 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:17:00 +0530 Subject: [PATCH 13/53] fix(backfill): reserve enough time for the closing report to clear its floor [WEB-6392] --- claude-code/hooks/mdm/setup.py | 5 +++- .../hooks/test_backfill_outcome.py | 21 ++++++++++++++++ tests/claude_code/hooks/test_setup.py | 25 ++++++++++--------- 3 files changed, 38 insertions(+), 13 deletions(-) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 1873d545d..da2ff6d86 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -65,7 +65,10 @@ BACKFILL_FROM_S3_SLACK_SECONDS = 10 BACKFILL_FROM_S3_MIN_SECONDS = 5 # Kept free at the end of the soft stop for the run's closing report (outcome and counts): data stops this early. -BACKFILL_STATS_RESERVE_SECONDS = 30 +# A last data PUT can run to its cap, so this must hold the closing upload's PUT floor and its link request +# (30s an attempt); from-s3 has a reserve of its own. +BACKFILL_LINK_REQUEST_SECONDS = 30 +BACKFILL_STATS_RESERVE_SECONDS = BACKFILL_PUT_MIN_SECONDS + BACKFILL_LINK_REQUEST_SECONDS def normalize_url(value: str) -> str: diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index 957ada3f6..5bfa6e08a 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -189,3 +189,24 @@ def test_the_closing_report_still_goes_up(self): if __name__ == "__main__": unittest.main() + + +class TheReserveCoversTheClosingReportTestCase(_Homes): + + def test_a_last_data_put_that_runs_to_its_cap_still_leaves_the_closing_report_its_time(self): + """The worst case the reserve exists for: the last batch starts at the edge, its link request takes + a second and its PUT the whole cap. The closing report must still clear the PUT floor.""" + home = self._home(("a",)) + clock = [time.time()] # after the transcript: one stamped later than the clock reads as from the future + start = mdm.BACKFILL_SOFT_STOP_SECONDS - mdm.BACKFILL_STATS_RESERVE_SECONDS - mdm.BACKFILL_MIN_MARGIN_SECONDS + + class Timed(_Backend): + def __call__(self, url, method, headers, body=None, timeout=30): + clock[0] += timeout if method == "PUT" and json.loads(body)["sessions"] else 1 + return super().__call__(url, method, headers, body, timeout) + + backend = _run(mdm, home, Timed(), + [patch.object(mdm.time, "time", lambda: clock[0]), + patch.object(mdm, "_SCRIPT_START", clock[0] - start)]) + self.assertEqual([b["sessions"] != [] for b in backend.bodies], [True, False]) + self.assertEqual(len(backend.stats()), 1) diff --git a/tests/claude_code/hooks/test_setup.py b/tests/claude_code/hooks/test_setup.py index 58e3f814e..51a95deaa 100644 --- a/tests/claude_code/hooks/test_setup.py +++ b/tests/claude_code/hooks/test_setup.py @@ -569,7 +569,8 @@ def config_fetch(api_key, backend_url): def test_slowest_batch_sets_the_margin_before_the_soft_stop(self): """Each batch takes 100s on a fake clock: a new batch needs 1.5x that (150s) - left, not just the 90s floor, so the batch that would end at 600s never starts.""" + left, not just the 90s floor, before the soft stop less the closing report's + 75s reserve (525s), so the batch that would start at 400s never does.""" mdm = self.mdm clock = {"now": 0.0} fake_time = type("T", (), {"time": staticmethod(lambda: clock["now"])}) @@ -581,8 +582,8 @@ def slow_send(sessions): batches = [self._batch([f"a-{i}"], float(i + 1)) for i in range(10)] with patch.object(mdm, "time", fake_time), patch.object(mdm, "_SCRIPT_START", 0.0): events, starts, out = self._run({"a": batches}, send=slow_send) - self.assertEqual(len(starts), 5) # batches start at 0, 100, 200, 300, 400s - self.assertEqual(events[-1], ("write", "a", 5.0)) + self.assertEqual(len(starts), 4) # batches start at 0, 100, 200, 300s + self.assertEqual(events[-1], ("write", "a", 4.0)) self.assertIn("More history remains", out) def test_batch_cap_bounds_one_run(self): @@ -731,21 +732,21 @@ def upload_at(now, link_took=0.0, put_took=20.0): landed = mdm._backfill_upload_chunk("key", "https://backend", [{"session_id": "s"}]) return landed, requests[1:2], sleep.call_args - # 500s left: the PUT may take all of it but the 40s kept for from-s3 and the 30s kept for the run's - # closing report, then rests as long as it took. - self.assertEqual(upload_at(100.0), (True, [("PUT", 430)], unittest.mock.call(20))) - # 115s left: a PUT at the 45s floor; once it lands nothing is left above the next chunk's floor to rest. - self.assertEqual(upload_at(485.0), (True, [("PUT", 45)], unittest.mock.call(0))) + # 500s left: the PUT may take all of it but the 40s kept for from-s3 and the 75s kept for the run's + # closing report (its 45s PUT floor and a 30s link request), then rests as long as it took. + self.assertEqual(upload_at(100.0), (True, [("PUT", 385)], unittest.mock.call(20))) + # 160s left: a PUT at the 45s floor; once it lands nothing is left above the next chunk's floor to rest. + self.assertEqual(upload_at(440.0), (True, [("PUT", 45)], unittest.mock.call(0))) # Under the floor no link is asked for and nothing is sent: None, a stop rather than a failed upload. - self.assertEqual(upload_at(520.0), (None, [], None)) + self.assertEqual(upload_at(485.0), (None, [], None)) # A link request that retried for 60s comes out of the PUT's time, not on top of it. - self.assertEqual(upload_at(100.0, link_took=60.0), (True, [("PUT", 370)], unittest.mock.call(20))) + self.assertEqual(upload_at(100.0, link_took=60.0), (True, [("PUT", 325)], unittest.mock.call(20))) # And when it leaves less than the floor, the link is dropped and nothing is sent. - self.assertEqual(upload_at(485.0, link_took=60.0), (None, [], None)) + self.assertEqual(upload_at(440.0, link_took=60.0), (None, [], None)) # from-s3 gets 30s an attempt with time in hand, and less when its four attempts must end before the kill. upload_at(100.0) self.assertEqual(requests[2], ("POST", 30)) - upload_at(485.0, put_took=74.0) + upload_at(440.0, put_took=119.0) # 91s to the kill less the slack: 17s an attempt puts the call's 4 x 17 + 20 subprocess budget inside it. self.assertEqual(requests[2], ("POST", 17)) From 18d225da0a4d9b786259fbdf2017b84bee22db6a Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:18:18 +0530 Subject: [PATCH 14/53] fix(setup): forward no hook errors where their place cannot be saved [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 10 ++++++++-- binary/tests/test_setup_reporting.py | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index c603b2750..74985a000 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -359,13 +359,19 @@ def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> bool: def _forward_home_errors(m, username, log, send): - """(entries sent, whether every request went through). The place is saved after each accepted request.""" + """(entries sent, whether every request went through). The place is saved after each accepted request; + where it can't be saved nothing more is sent, or every run would send the same entries again.""" + if _as_user(m, username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, True entries = _as_user(m, username, _unsent_hook_errors, log) or [] for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] if not send(batch): return start, False - _as_user(m, username, _save_forwarded, log, batch[-1]["timestamp"]) + if _as_user(m, username, _save_forwarded, log, batch[-1]["timestamp"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), True return len(entries), True diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 97f333f86..16fa5ec08 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -560,3 +560,26 @@ def recording_run(cmd, *a, **k): # The headers still arrive. assert {r["headers"].get("X-API-KEY") for r in _run_reports(backend)} == {"admin-key"} assert _forwarded(backend)[0]["headers"]["Authorization"] == "Bearer per-device-key" + + +# --- Review #3: no forwarding where the place can't be saved -------------------- + +def test_a_log_whose_place_cannot_be_saved_is_not_forwarded_run_after_run(env, backend): + log = _log(env["home"], "claude-code", [f"{_utc(n)}: e{n}" for n in range(3)]) + log.parent.chmod(0o555) # the user can't write .error_log_forwarded beside it + try: + _run(backend) + _run(backend) + finally: + log.parent.chmod(0o755) + assert _forwarded(backend) == [] + assert not log.with_name(STATE).exists() + + +def test_a_save_that_fails_after_a_send_stops_that_home(env, backend, monkeypatch): + _log(env["home"], "claude-code", [f"{_utc(n)}: e{n}" for n in range(15)]) + # What the real privilege drop hands back when the write inside it fails. + monkeypatch.setattr(setup_cmd, "_save_forwarded", lambda log, state: None) + _run(backend) + # The first ten went out; with their place unsaved the rest wait rather than pile up repeats. + assert [len(r["body"]["errors"]) for r in _forwarded(backend)] == [10] From d66f5ceda56dfaccef4a0626e856c436dd3795ce Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:20:06 +0530 Subject: [PATCH 15/53] fix(setup): let a refused key stop only its own tool's hook errors [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 42 ++++++++++++++++------------ binary/tests/test_setup_reporting.py | 19 +++++++++++++ 2 files changed, 43 insertions(+), 18 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 74985a000..5c9dc148f 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -344,40 +344,46 @@ def _save_forwarded(log: Path, timestamp: str) -> bool: return True -def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> bool: - """The hook's own request shape and auth. True only when the gateway took them: it answers an - unknown key with 200 and success false.""" +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this tool's key and not about what the log holds.""" errors = [dict(entry, message=re.sub(r"(?i)\bBearer\s+\S+", "Bearer [REDACTED]", entry["message"].replace(api_key, "[REDACTED]"))) for entry in batch] code, answer = _post_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" try: - return 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True except (ValueError, AttributeError): - return False + taken = False + return "sent" if taken else "refused" def _forward_home_errors(m, username, log, send): - """(entries sent, whether every request went through). The place is saved after each accepted request; - where it can't be saved nothing more is sent, or every run would send the same entries again.""" + """(entries sent, 'sent' or the verdict that stopped it). The place is saved after each accepted + request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" if _as_user(m, username, _writable_dir, log.parent) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") - return 0, True + return 0, "sent" entries = _as_user(m, username, _unsent_hook_errors, log) or [] for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] - if not send(batch): - return start, False + verdict = send(batch) + if verdict != "sent": + return start, verdict if _as_user(m, username, _save_forwarded, log, batch[-1]["timestamp"]) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") - return start + len(batch), True - return len(entries), True + return start + len(batch), "sent" + return len(entries), "sent" def _forward_hook_errors(m, tool, api_key, opts) -> None: - """Forward every home's unsent error.log entries for this tool. The first failed request ends forwarding - for the whole run, so a gateway that is down costs one short timeout; the next run retries.""" + """Forward every home's unsent error.log entries for this tool. A gateway that is down ends forwarding + for the whole run, so it costs one short timeout; a refused key ends it for this tool only. Either way + nothing is marked sent, and the next run retries.""" if opts.get("hook_errors_held"): return relpath, hook_source = _HOOK_ERROR_LOGS[tool] @@ -390,11 +396,11 @@ def _forward_hook_errors(m, tool, api_key, opts) -> None: log = home_dir / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - count, ok = _forward_home_errors(m, username, log, send) + count, verdict = _forward_home_errors(m, username, log, send) sent += count - if not ok: - opts["hook_errors_held"] = True - print(f"[errors] {tool} hook errors not forwarded; the next run retries") + if verdict != "sent": + opts["hook_errors_held"] = opts.get("hook_errors_held") or verdict == "down" + print(f"[errors] {tool} hook errors not forwarded (gateway {verdict}); the next run retries") break except Exception as e: print(f"[errors] {tool} hook errors not forwarded: {e}") diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 16fa5ec08..6d5abed19 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -583,3 +583,22 @@ def test_a_save_that_fails_after_a_send_stops_that_home(env, backend, monkeypatc _run(backend) # The first ten went out; with their place unsaved the rest wait rather than pile up repeats. assert [len(r["body"]["errors"]) for r in _forwarded(backend)] == [10] + + +# --- Review #4: one tool's refused key doesn't hold back the others -------------- + +def test_a_key_the_gateway_refuses_stops_only_that_tool(env, backend): + ok = {"status": "ok", "success": True, "accepted": 1} + + def answer(path): + refused = path == "/v1/hooks/errors" and backend.requests[-1]["body"].get("hook_source") == "codex" + return (200, {"success": False, "reason": "invalid_key"}) if refused else (200, ok) + + backend.answer = answer + _log(env["home"], "codex", [f"{_utc(0)}: codex broke"]) + _log(env["home"], "copilot", [f"{_pacific(1)}: copilot broke"]) + _run(backend) + # Codex runs before Copilot; its refusal must not cost Copilot its turn. + assert {r["body"]["hook_source"] for r in _forwarded(backend)} == {"codex", "copilot"} + assert (env["home"] / ".copilot/hooks" / STATE).exists() + assert not (env["home"] / ".codex/hooks" / STATE).exists() # refused: retried next run From e0520bab12afb4cbae64007e0a353f1f81214a19 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:23:12 +0530 Subject: [PATCH 16/53] fix(setup): keep hook errors that share the last sent timestamp [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 62 ++++++++++++++++++---------- binary/tests/test_setup_reporting.py | 30 +++++++++++--- 2 files changed, 65 insertions(+), 27 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 5c9dc148f..1fbe317c5 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -296,7 +296,8 @@ def _end_fields(opts, user_homes, warnings) -> dict: "copilot": (".copilot/hooks/error.log", "copilot"), "augment": (".augment/hooks/error.log", "augment_code"), } -# Beside each error.log: the timestamp of the newest entry the gateway accepted. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). FORWARDED_STATE_NAME = ".error_log_forwarded" HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten # error.log is the user's to write: per tool and home, a run sends at most the newest 25 (what a hook keeps) @@ -317,30 +318,46 @@ def _log_time(text): return when if when.tzinfo else None -def _unsent_hook_errors(log: Path) -> list: - """Runs as the profile's user: the newest HOOK_ERRORS_PER_RUN entries newer than both the last one - forwarded and HOOK_ERROR_MAX_AGE, oldest first.""" - floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" try: - last = _log_time(_read_user_file(log.with_name(FORWARDED_STATE_NAME), follow=False).decode().strip()) + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME), follow=False).decode().split() except (OSError, UnicodeDecodeError): - last = None - if last is not None and last > floor: - floor = last - entries = [] + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the profile's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then = [], 0 for line in _read_user_file(log, follow=False).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) when = _log_time(match.group(1)) if match else None - if when and when > floor: - entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY})) - entries.sort(key=lambda entry: entry[0]) - return [entry for _, entry in entries[-HOOK_ERRORS_PER_RUN:]] - - -def _save_forwarded(log: Path, timestamp: str) -> bool: + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY})) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: """Runs as the profile's user.""" - _replace_user_file(log.with_name(FORWARDED_STATE_NAME), timestamp.encode("utf-8"), 0o600) + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8"), 0o600) return True @@ -348,8 +365,9 @@ def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> str: """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a 4xx), never an entry, so a refusal is about this tool's key and not about what the log holds.""" - errors = [dict(entry, message=re.sub(r"(?i)\bBearer\s+\S+", "Bearer [REDACTED]", - entry["message"].replace(api_key, "[REDACTED]"))) + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": re.sub(r"(?i)\bBearer\s+\S+", "Bearer [REDACTED]", + entry["message"].replace(api_key, "[REDACTED]"))} for entry in batch] code, answer = _post_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, {"Authorization": f"Bearer {api_key}"}) @@ -374,7 +392,7 @@ def _forward_home_errors(m, username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict - if _as_user(m, username, _save_forwarded, log, batch[-1]["timestamp"]) is not True: + if _as_user(m, username, _save_forwarded, log, batch[-1]["state"]) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent" return len(entries), "sent" diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 6d5abed19..73b9f034c 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -318,7 +318,7 @@ def test_errors_newer_than_the_last_forwarded_one_go_to_the_gateway(env, backend assert body["hook_source"] == "claude-code" and len(body["hook_sha"]) == 12 assert [(e["timestamp"], e["message"]) for e in body["errors"]] == [ (_utc(1), "gateway unreachable 1"), (_utc(2), "gateway unreachable 2")] - assert log.with_name(STATE).read_text() == _utc(2) + assert log.with_name(STATE).read_text() == f"{_utc(2)} 1" def test_errors_go_ten_to_a_request_and_none_is_sent_twice(env, backend): @@ -326,7 +326,7 @@ def test_errors_go_ten_to_a_request_and_none_is_sent_twice(env, backend): _run(backend) assert [len(r["body"]["errors"]) for r in _forwarded(backend)] == [10, 10, 5] assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == [f"e{n}" for n in range(25)] - assert log.with_name(STATE).read_text() == _utc(24) + assert log.with_name(STATE).read_text() == f"{_utc(24)} 1" backend.requests.clear() _run(backend) assert _forwarded(backend) == [] @@ -366,7 +366,7 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, sent = {r["body"]["hook_source"]: [e["message"] for e in r["body"]["errors"]] for r in _forwarded(backend)} assert sent == {"cursor": ["cursor broke"], "copilot": ["copilot broke"], "codex": ["codex broke"], "claude-code": ["bob's claude broke"], "augment_code": ["auggie broke"]} - assert (env["home"] / ".copilot/hooks" / STATE).read_text() == _pacific(1) + assert (env["home"] / ".copilot/hooks" / STATE).read_text() == f"{_pacific(1)} 1" assert (other / ".claude/hooks" / STATE).exists() and not (env["home"] / ".claude/hooks" / STATE).exists() # Cursor's setup removes the python-era ~/.cursor/hooks, log and all, after its errors went out. assert not (env["home"] / ".cursor/hooks").exists() @@ -437,7 +437,7 @@ def test_a_huge_log_sends_only_its_25_newest_entries(env, backend): _run(backend) assert len(_forwarded(backend)) <= 3 assert [m.split()[1] for m in _messages(backend)] == [str(n) for n in range(39975, 40000)] - assert log.with_name(STATE).read_text() == _utc(39999 / 100) + assert log.with_name(STATE).read_text() == f"{_utc(39999 / 100)} 1" def test_entries_older_than_seven_days_are_never_sent(env, backend): @@ -519,7 +519,7 @@ def test_a_state_file_that_is_a_link_is_replaced_not_followed(env, backend, tmp_ assert _messages(backend) == ["e0", "e1"] assert victim.read_text() == _utc(100) state = log.with_name(STATE) - assert not state.is_symlink() and state.read_text() == _utc(1) + assert not state.is_symlink() and state.read_text() == f"{_utc(1)} 1" # --- S-U5: what reaches the gateway, and Sentry behind it ------------------------ @@ -602,3 +602,23 @@ def answer(path): assert {r["body"]["hook_source"] for r in _forwarded(backend)} == {"codex", "copilot"} assert (env["home"] / ".copilot/hooks" / STATE).exists() assert not (env["home"] / ".codex/hooks" / STATE).exists() # refused: retried next run + + +# --- Review #9: entries sharing the saved timestamp aren't lost ------------------ + +def test_an_entry_sharing_the_last_sent_timestamp_is_still_sent(env, backend): + same = _utc(9) + lines = [f"{_utc(n)}: e{n}" for n in range(9)] + [f"{same}: e9", f"{same}: e10"] + _log(env["home"], "claude-code", lines) + ok = {"status": "ok", "success": True, "accepted": 1} + # The batch boundary (ten a request) falls between e9 and e10; the second request fails. + backend.answer = lambda path: (503, {}) if len(_forwarded(backend)) == 2 else (200, ok) + _run(backend) + assert _messages(backend) == [f"e{n}" for n in range(11)] # e10 was tried, not taken + backend.requests.clear() + backend.answer = lambda path: (200, ok) + _run(backend) + assert _messages(backend) == ["e10"] + backend.requests.clear() + _run(backend) + assert _messages(backend) == [] From 7e704fda547175db0b170a30401730e96b1a4bb0 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:24:26 +0530 Subject: [PATCH 17/53] fix(setup): forward a multi-line hook error with its later lines [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 13 +++++++++---- binary/tests/test_setup_reporting.py | 20 ++++++++++++++++++-- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 1fbe317c5..bffdd368a 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -335,18 +335,23 @@ def _unsent_hook_errors(log: Path) -> list: newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE last, sent_then = _forwarded_place(log) - entries, seen_then = [], 0 + entries, seen_then, current = [], 0, None for line in _read_user_file(log, follow=False).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) - when = _log_time(match.group(1)) if match else None + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None if when is None or when <= floor: continue if last is not None and when <= last: seen_then += when == last if when < last or seen_then <= sent_then: continue # sent already - entries.append((when, {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY})) + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 73b9f034c..0f2698f81 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -372,10 +372,26 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, assert not (env["home"] / ".cursor/hooks").exists() -def test_lines_that_are_not_log_entries_are_skipped(env, backend): +def test_lines_before_the_first_entry_are_skipped_and_later_ones_continue_it(env, backend): _log(env["home"], "claude-code", ["not an entry", f"{_utc(5)}: real one", " continued text"]) _run(backend) - assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["real one"] + assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == ["real one\n continued text"] + + +def test_a_multi_line_entry_goes_up_whole_cut_and_redacted(env, backend): + _log(env["home"], "claude-code", [ + f"{_utc(0)}: Traceback (most recent call last):", + ' File "unbound.py", line 9, in post', + " Authorization: Bearer sk-live-123", + "ValueError: boom " + "x" * 3000, + f"{_utc(1)}: next entry", + ]) + _run(backend) + first, second = _messages(backend) + assert first.startswith('Traceback (most recent call last):\n File "unbound.py", line 9, in post\n') + assert "Bearer [REDACTED]" in first and "sk-live-123" not in first + assert len(first) <= 2000 + assert second == "next entry" # --- F9: the run reports' inputs fail open --------------------------------------- From f6852ab47df4bdf143bce8531dc163b17b6b8ce5 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:27:24 +0530 Subject: [PATCH 18/53] fix(backfill): report a run a cap cut short as stopped_by_cap [WEB-6392] --- claude-code/hooks/mdm/setup.py | 7 ++-- claude-code/hooks/setup.py | 7 ++-- .../hooks/test_backfill_outcome.py | 33 +++++++++++++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index da2ff6d86..850cb8de0 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -46,7 +46,7 @@ BACKFILL_RESUME_FILE = '.unbound_backfill_resume' # How a run that could not send its closing report ended, for the next run to send as previous_outcome. BACKFILL_OUTCOME_FILE = '.unbound_backfill_outcome' -BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'failed') +BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'stopped_by_cap', 'failed') _SCRIPT_START = time.time() # All measured from script start. No new batch starts unless it can land before the # soft stop (margin: 90s or 1.5x the slowest batch so far); the hard kill backs it up @@ -2981,7 +2981,10 @@ def out_of_time(self) -> bool: def outcome(self, statuses: set) -> str: if 'failed' in statuses: return 'failed' - return 'stopped_by_time_limit' if self.stopped_by_time else 'completed' + if self.stopped_by_time: + return 'stopped_by_time_limit' + # History left with time to spare: a batch cap (or a cursor that stopped moving) ended it. + return 'stopped_by_cap' if 'more' in statuses else 'completed' def upload(self, sessions: List[Dict], forced: bool) -> Tuple[int, int, bool]: """(sessions_sent, chunks_failed, out_of_time) for one batch.""" diff --git a/claude-code/hooks/setup.py b/claude-code/hooks/setup.py index 41848dbd9..22f629c79 100644 --- a/claude-code/hooks/setup.py +++ b/claude-code/hooks/setup.py @@ -42,7 +42,7 @@ BACKFILL_STATE_FILE = '.unbound_last_backfill' # How a run that could not send its closing report ended, for the next run to send as previous_outcome. BACKFILL_OUTCOME_FILE = '.unbound_backfill_outcome' -BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'failed') +BACKFILL_OUTCOMES = ('completed', 'stopped_by_time_limit', 'stopped_by_cap', 'failed') # An S3 PUT is given up on only after this long below this speed, then re-sent on a fresh link. BACKFILL_PUT_STALL_SECONDS = 60 BACKFILL_PUT_STALL_BYTES_PER_SECOND = 1024 @@ -2213,8 +2213,9 @@ def _flush(): _flush() failed = chunks_total - chunks_sent - # No run clock here, so a run ends completed or failed, never stopped for time. - _backfill_send_outcome(api_key, backend_url, config_dir, 'failed' if failed else 'completed', failed, previous) + # No run clock here, so a run is never stopped for time; the per-run session cap can stop it. + outcome = 'failed' if failed else 'stopped_by_cap' if capped else 'completed' + _backfill_send_outcome(api_key, backend_url, config_dir, outcome, failed, previous) reported = True if not found: _backfill_write_cutoff(config_dir, started_at) diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index 5bfa6e08a..989b47c8e 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -210,3 +210,36 @@ def __call__(self, url, method, headers, body=None, timeout=30): patch.object(mdm, "_SCRIPT_START", clock[0] - start)]) self.assertEqual([b["sessions"] != [] for b in backend.bodies], [True, False]) self.assertEqual(len(backend.stats()), 1) + + +class ACapIsNotCompletionTestCase(_Homes): + """History a cap left behind must not read as a finished run.""" + + def test_the_mdm_batch_cap_ends_the_run_stopped_by_cap(self): + backend = _run(mdm, self._home(("a", "b", "c")), _Backend(), + [patch.object(mdm, "BACKFILL_BATCH_BYTES", 1), + patch.object(mdm, "BACKFILL_MAX_BATCHES_PER_HOME", 1)]) + self.assertTrue(any(b["sessions"] for b in backend.bodies)) + self.assertEqual([s["outcome"] for s in backend.stats()], ["stopped_by_cap"]) + + def test_the_per_user_session_cap_ends_the_run_stopped_by_cap(self): + backend = _run(setup, self._home(("a", "b", "c")), _Backend(), + [patch.object(setup, "BACKFILL_MAX_SESSIONS_PER_RUN", 1)]) + self.assertEqual([s["outcome"] for s in backend.stats()], ["stopped_by_cap"]) + + def test_an_unsent_cap_outcome_is_the_next_runs_previous_outcome(self): + for up, cap in ((mdm, [patch.object(mdm, "BACKFILL_BATCH_BYTES", 1), + patch.object(mdm, "BACKFILL_MAX_BATCHES_PER_HOME", 1)]), + (setup, [patch.object(setup, "BACKFILL_MAX_SESSIONS_PER_RUN", 1)])): + with self.subTest(up.__name__): + home = self._home(("a", "b", "c")) + + class StatsDown(_Backend): + def __call__(self, url, method, headers, body=None, timeout=30): + if method == "PUT" and not json.loads(body)["sessions"]: + return 503, b"" # only the closing report fails + return super().__call__(url, method, headers, body, timeout) + + _run(up, home, StatsDown(), cap) + [stats] = _run(up, home, _Backend()).stats() + self.assertEqual(stats["previous_outcome"], "stopped_by_cap") From c10a63de0f94df6d7369b7c6a7d0f3959a66c1cc Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:28:49 +0530 Subject: [PATCH 19/53] fix(setup): count nodenv, yarn, MacPorts and npmrc-prefix installs [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 38 +++++++++++++++++++++++----- binary/tests/test_setup_reporting.py | 30 ++++++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index bffdd368a..ef7f0557e 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -234,12 +234,35 @@ def _preflight_warnings(user_homes) -> list: "augment": ("Augment", "auggie", (), tuple(f"{editor}/extensions/augment.vscode-augment-*" for editor in (".vscode", ".vscode-insiders", ".cursor"))), } -# Where a CLI lands under a home: a user install, Bun, npm's user prefix, and the Node version managers -# (nvm, Volta, pnpm's default PNPM_HOME, fnm in both its folders, asdf and mise shims, mise's installs). +# Where a CLI lands under a home: a user install, Bun, npm's user prefix, yarn global, and the Node version +# managers (nvm, Volta, pnpm's default PNPM_HOME, fnm in both its folders, asdf and mise shims, mise's +# installs, nodenv). A prefix set in ~/.npmrc is read as well (_npmrc_bin). _HOME_CLI_DIRS = (".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", "Library/pnpm", ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", ".asdf/shims", ".local/share/mise/shims", - ".local/share/mise/installs/*/*/bin") + ".local/share/mise/installs/*/*/bin", ".nodenv/shims", ".nodenv/versions/*/bin", + ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Homebrew (Apple silicon, Intel) and MacPorts. +_MACHINE_CLI_DIRS = ("opt/homebrew/bin", "usr/local/bin", "opt/local/bin") + + +def _npmrc_bin(home: Path): + """The bin folder of a prefix the user set in ~/.npmrc, or None. Read without following a link and + used only to look for a file, so a root run learns nothing else from it.""" + try: + text = _read_user_file(home / ".npmrc", follow=False).decode("utf-8", "replace") + except OSError: + return None + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip('"\'') + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + return Path(value) / "bin" if value.startswith("/") else None + return None _MACHINE_ROOT = Path("/") @@ -256,10 +279,13 @@ def _tool_installed(tool, user_homes) -> bool: try: _, cli, apps, home_files = _TOOL_FOOTPRINTS[tool] app_paths = [f"Applications/{app}" for app in apps] - machine = [f"opt/homebrew/bin/{cli}", f"usr/local/bin/{cli}", *app_paths] + machine = [f"{folder}/{cli}" for folder in _MACHINE_CLI_DIRS] + app_paths per_home = [f"{folder}/{cli}" for folder in _HOME_CLI_DIRS] + [*home_files, *app_paths] - roots = [(_MACHINE_ROOT, machine)] + [(home, per_home) for _, home in user_homes if home is not None] - return any(_present(root, rel) for root, rels in roots for rel in rels) + homes = [home for _, home in user_homes if home is not None] + roots = [(_MACHINE_ROOT, machine)] + [(home, per_home) for home in homes] + npm_bins = [b for b in map(_npmrc_bin, homes) if b is not None] + return (any(_present(root, rel) for root, rels in roots for rel in rels) + or any((b / cli).exists() for b in npm_bins)) except Exception: return True diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 0f2698f81..dab978114 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -638,3 +638,33 @@ def test_an_entry_sharing_the_last_sent_timestamp_is_still_sent(env, backend): backend.requests.clear() _run(backend) assert _messages(backend) == [] + + +# --- Review #7: nodenv, yarn, MacPorts and a custom npm prefix -------------------- + +@pytest.mark.parametrize("tool,relpath", [ + ("claude-code", "HOME/.nodenv/shims/claude"), + ("codex", "HOME/.nodenv/versions/22.1.0/bin/codex"), + ("copilot", "HOME/.yarn/bin/copilot"), + ("augment", "HOME/.config/yarn/global/node_modules/.bin/auggie"), + ("claude-code", "opt/local/bin/claude"), +]) +def test_more_install_locations_count(env, machine, tool, relpath): + if relpath.startswith("HOME/"): + _install(env["home"], relpath[len("HOME/"):]) + else: + _install(machine, relpath) + setup_cmd.run(["--api-key", "admin-key"]) + assert _reports(env, tool)[0]["status"] == "configured" + + +@pytest.mark.parametrize("prefix", ["~/.npm-packages", "${HOME}/.npm-packages", "$HOME/.npm-packages", "HOME"]) +def test_an_npm_prefix_from_npmrc_counts(env, machine, prefix): + prefix = prefix.replace("HOME", str(env["home"])) if prefix == "HOME" else prefix + if prefix == str(env["home"]): + prefix = str(env["home"] / ".npm-packages") + (env["home"] / ".npmrc").write_text(f"; comment\ninit-author-name=me\nprefix = {prefix}\n") + _install(env["home"], ".npm-packages/bin/codex") + setup_cmd.run(["--api-key", "admin-key"]) + assert _reports(env, "codex")[0]["status"] == "configured" + assert _reports(env, "cursor")[0]["status"] == "skipped" From d8e010131878b5f6fd7ee30c5e3a47b4a4b2c508 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 00:32:24 +0530 Subject: [PATCH 20/53] refactor(setup): find installed tools once a run and drop a dead backfill helper [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 16 +++++++++++++--- binary/tests/test_setup_reporting.py | 17 +++++++++++++++++ claude-code/hooks/mdm/setup.py | 4 ---- claude-code/hooks/setup.py | 4 ---- .../test_backfill_uploader_stats_matrix.py | 7 ------- 5 files changed, 30 insertions(+), 18 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index ef7f0557e..89782a114 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -290,10 +290,11 @@ def _tool_installed(tool, user_homes) -> bool: return True -def _report(m, tool, api_key, status, reason=None, **fields): +def _report(m, tool, api_key, status, reason=None, installed=True, **fields): """This tool's setup/complete call for the run; returns the (status, reason) it sent. Configured on a Mac - without the tool reads skipped: its config is still written, so the hook works once the tool arrives.""" - if status == "configured" and not _tool_installed(tool, m.get_all_user_homes()): + without the tool (installed False, from the run's one check) reads skipped: its config is still written, + so the hook works once the tool arrives.""" + if status == "configured" and not installed: status, reason = "skipped", f"{_TOOL_FOOTPRINTS[tool][0]} is not installed" m.notify_setup_complete(api_key, _TOOL_TYPES[tool], status=status, reason=reason, **fields) return status, reason @@ -1367,6 +1368,7 @@ def _setup_claude_code(opts): return ("deferred", "MDM api key fetch failed") skip_settings = opts["skip_managed_settings"] report = functools.partial(_report, m, "claude-code", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("claude-code", True), install_mode="binary-skip" if skip_settings else "binary") _forward_hook_errors(m, "claude-code", api_key, opts) @@ -1428,6 +1430,7 @@ def _setup_augment(opts): if not api_key: return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "augment", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("augment", True), install_mode="binary") _forward_hook_errors(m, "augment", api_key, opts) @@ -1468,6 +1471,7 @@ def _setup_codex(opts): if not api_key: return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "codex", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("codex", True), install_mode="binary") _forward_hook_errors(m, "codex", api_key, opts) @@ -1679,6 +1683,7 @@ def _setup_cursor(opts): if not api_key: return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "cursor", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("cursor", True), install_mode="binary") _forward_hook_errors(m, "cursor", api_key, opts) @@ -1767,6 +1772,7 @@ def _setup_copilot(opts): if not api_key: return ("deferred", "MDM api key fetch failed") report = functools.partial(_report, m, "copilot", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("copilot", True), install_mode="binary") _forward_hook_errors(m, "copilot", api_key, opts) @@ -1942,6 +1948,10 @@ def run(argv) -> int: serial = _report_input(m0.get_device_identifier, None, "device serial") user_homes = _report_input(m0.get_all_user_homes, None, "user homes") warnings = _report_input(lambda: _preflight_warnings(user_homes), [], "preflight checks") + # Once, before any tool writes: unknown homes (or a failed check) leave every tool reported as installed. + opts["installed"] = _report_input(lambda: {} if user_homes is None else { + tool: _tool_installed(tool, user_homes) for tool in opts["tools"] if tool in _TOOL_FOOTPRINTS}, + {}, "installed tools") _send_run_report(opts, serial, "start", _start_fields) statuses = {} diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index dab978114..ff81a91a8 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -668,3 +668,20 @@ def test_an_npm_prefix_from_npmrc_counts(env, machine, prefix): setup_cmd.run(["--api-key", "admin-key"]) assert _reports(env, "codex")[0]["status"] == "configured" assert _reports(env, "cursor")[0]["status"] == "skipped" + + +# --- Review #10: which tools are installed is worked out once per run ------------- + +def test_installed_tools_are_found_once_before_the_first_report(env, machine, monkeypatch): + events, real = [], setup_cmd._tool_installed + monkeypatch.setattr(setup_cmd, "_tool_installed", + lambda tool, homes: events.append(("check", tool)) or real(tool, homes)) + for m in env["modules"].values(): + monkeypatch.setattr(m, "notify_setup_complete", lambda *a, **k: events.append(("report", a[1]))) + _install(machine, FOOTPRINTS["codex"]) + assert setup_cmd.run(["--api-key", "admin-key"]) == 0 + checks = [tool for kind, tool in events if kind == "check"] + assert sorted(checks) == sorted(FOOTPRINTS) # once each + first_report = next(i for i, (kind, _) in enumerate(events) if kind == "report") + assert all(kind == "check" for kind, _ in events[:first_report]) + assert len(events[:first_report]) == len(FOOTPRINTS) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 850cb8de0..7ffcd3f8c 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -2065,10 +2065,6 @@ def _backfill_first_session_id(transcript_path: Path): return None -def _backfill_skipped_anything(stats: Dict) -> bool: - return bool(stats['skipped_over_cap']['count'] or stats['unreadable']) - - def _backfill_walk_stats(root: Path) -> Dict: """uploader_stats for every transcript under root, whatever its age: how many, which are over the cap, and which can't be read.""" diff --git a/claude-code/hooks/setup.py b/claude-code/hooks/setup.py index 22f629c79..d789f0723 100644 --- a/claude-code/hooks/setup.py +++ b/claude-code/hooks/setup.py @@ -1660,10 +1660,6 @@ def _backfill_first_session_id(transcript_path: Path): return None -def _backfill_skipped_anything(stats: Dict) -> bool: - return bool(stats['skipped_over_cap']['count'] or stats['unreadable']) - - def _backfill_walk_stats(root: Path) -> Dict: """uploader_stats for every transcript under root, whatever its age: how many, which are over the cap, and which can't be read.""" diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py index 49d7b4a72..1189020be 100644 --- a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py +++ b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py @@ -254,13 +254,6 @@ def test_adding_counts_sums_and_keeps_the_largest(self): up._backfill_add_stats(total, _stats(0, 0, 1, 900, 900)) self.assertEqual(total, _stats(5, 5, 4, 900, 1950)) - def test_only_a_skip_counts_as_skipping(self): - for up in uploaders: - for over, unreadable in ((0, 0), (1, 0), (0, 1), (2, 3)): - with self.subTest(up.__name__, over=over, unreadable=unreadable): - stats = _stats(seen=7, unreadable=unreadable, count=over) - self.assertIs(up._backfill_skipped_anything(stats), bool(over or unreadable)) - def _payload(self, up): bodies = [] with patch.object(up, "_backfill_http_request", side_effect=_fake_http(bodies)): From 8559b6ef3bab4011e04d8d9ff35a4eb95d7705b6 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 14:39:04 +0530 Subject: [PATCH 21/53] fix(setup): forward hook errors before the migration sweep removes Cursor's log [WEB-6392] --- binary/README.md | 7 +++-- binary/src/unbound_hook/setup_cmd.py | 36 ++++++++++++++++-------- binary/tests/test_setup_reporting.py | 41 +++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 14 deletions(-) diff --git a/binary/README.md b/binary/README.md index 2baa7c93a..93d4df9a6 100644 --- a/binary/README.md +++ b/binary/README.md @@ -85,12 +85,15 @@ the python path, by design: written but reported `skipped` (" is not installed"). A discovery run that prints `Scan skipped: ` is `skipped`. The run itself posts `phase: start` first and `phase: end` last to the MDM install report. - Each tool's adapter also forwards its hook's `error.log` entries newer than + Before the migration sweep (which removes `~/.cursor/hooks`), setup + forwards each tool's hook `error.log` entries, with the device key in the + home's `~/.unbound/config.json` (the key the hooks use), newer than the last forwarded one to the gateway's `/v1/hooks/errors` (ten a request, at most the newest 25 per tool and home, none older than seven days, with `category: forwarded_error_log`), recording the newest accepted timestamp in `.error_log_forwarded` beside the - log; a failed request saves nothing and ends forwarding for the run. + log; a gateway that is down ends forwarding for the run, a refused key ends + it for that tool, and neither saves anything. - **`detect_install_state`** is adapted: the python version checked for the managed `unbound.py`, which no longer exists. Binary semantics: settings file absent → `fresh`; present and referencing the binary → `persisted`; diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 89782a114..67d75b43c 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -430,22 +430,37 @@ def _forward_home_errors(m, username, log, send): return len(entries), "sent" -def _forward_hook_errors(m, tool, api_key, opts) -> None: - """Forward every home's unsent error.log entries for this tool. A gateway that is down ends forwarding - for the whole run, so it costs one short timeout; a refused key ends it for this tool only. Either way - nothing is marked sent, and the next run retries.""" +def _home_device_key(home: Path): + """Runs as the profile's user: the device key in ~/.unbound/config.json, the one its hooks report + errors with, or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json", follow=False).decode("utf-8")) + except (OSError, ValueError): + return None + key = (config.get("device_token") or config.get("api_key")) if isinstance(config, dict) else None + return key if isinstance(key, str) and key else None + + +def _forward_hook_errors(m, tool, opts) -> None: + """Forward every home's unsent error.log entries for this tool, with that home's own device key. Runs + before the migration sweep, which removes ~/.cursor/hooks and its log. A gateway that is down ends + forwarding for the whole run, so it costs one short timeout; a refused key ends it for this tool only. + Either way nothing is marked sent, and the next run retries.""" if opts.get("hook_errors_held"): return relpath, hook_source = _HOOK_ERROR_LOGS[tool] sent = 0 try: hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] - send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", - api_key, hook_source, hook_sha) for username, home_dir in m.get_all_user_homes(): log = home_dir / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue + api_key = _as_user(m, username, _home_device_key, home_dir) + if not api_key: + continue # no hook here has a key to report with yet + send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", + api_key, hook_source, hook_sha) count, verdict = _forward_home_errors(m, username, log, send) sent += count if verdict != "sent": @@ -1370,7 +1385,6 @@ def _setup_claude_code(opts): report = functools.partial(_report, m, "claude-code", api_key, backend_url=base, serial_number=device_id, installed=opts.get("installed", {}).get("claude-code", True), install_mode="binary-skip" if skip_settings else "binary") - _forward_hook_errors(m, "claude-code", api_key, opts) for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "UNBOUND_API_KEY") @@ -1432,7 +1446,6 @@ def _setup_augment(opts): report = functools.partial(_report, m, "augment", api_key, backend_url=base, serial_number=device_id, installed=opts.get("installed", {}).get("augment", True), install_mode="binary") - _forward_hook_errors(m, "augment", api_key, opts) # Write the per-user unbound config now (needed by the managed hook). User # hook removal is deferred until the managed write succeeds (parity with @@ -1473,7 +1486,6 @@ def _setup_codex(opts): report = functools.partial(_report, m, "codex", api_key, backend_url=base, serial_number=device_id, installed=opts.get("installed", {}).get("codex", True), install_mode="binary") - _forward_hook_errors(m, "codex", api_key, opts) for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "OPENAI_API_KEY") @@ -1685,7 +1697,6 @@ def _setup_cursor(opts): report = functools.partial(_report, m, "cursor", api_key, backend_url=base, serial_number=device_id, installed=opts.get("installed", {}).get("cursor", True), install_mode="binary") - _forward_hook_errors(m, "cursor", api_key, opts) config_ok = True for username, home_dir in m.get_all_user_homes(): @@ -1774,7 +1785,6 @@ def _setup_copilot(opts): report = functools.partial(_report, m, "copilot", api_key, backend_url=base, serial_number=device_id, installed=opts.get("installed", {}).get("copilot", True), install_mode="binary") - _forward_hook_errors(m, "copilot", api_key, opts) user_homes = m.get_all_user_homes() state = _copilot_detect_state(m, user_homes) @@ -1953,6 +1963,10 @@ def run(argv) -> int: tool: _tool_installed(tool, user_homes) for tool in opts["tools"] if tool in _TOOL_FOOTPRINTS}, {}, "installed tools") _send_run_report(opts, serial, "start", _start_fields) + # Before the sweep: it removes ~/.cursor/hooks, and with it Cursor's error.log. + for tool in opts["tools"]: + if tool in _HOOK_ERROR_LOGS: + _forward_hook_errors(m0, tool, opts) statuses = {} diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index ff81a91a8..d0b68cddf 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -284,10 +284,16 @@ def test_the_notifier_sends_status_reason_and_where_it_wrote(tool, monkeypatch): STATE = ".error_log_forwarded" -def _log(home, tool, lines): +def _log(home, tool, lines, key="per-device-key"): + """An error.log for the tool, and (unless key is None) the device key a previous run left in the + home's config, which is what the hooks, and so forwarding, report with.""" path = home / ERROR_LOGS[tool] path.parent.mkdir(parents=True, exist_ok=True) path.write_text("".join(line + "\n" for line in lines)) + config = home / ".unbound" / "config.json" + if key is not None and not config.exists(): + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(json.dumps({"api_key": key, "device_token": key})) return path @@ -685,3 +691,36 @@ def test_installed_tools_are_found_once_before_the_first_report(env, machine, mo first_report = next(i for i, (kind, _) in enumerate(events) if kind == "report") assert all(kind == "check" for kind, _ in events[:first_report]) assert len(events[:first_report]) == len(FOOTPRINTS) + + +# --- Cursor: errors go out before the migration sweep deletes ~/.cursor/hooks ----- + +def test_cursor_errors_go_out_before_the_sweep_removes_their_log(env, backend): + """env's one home belongs to the real user running the tests, so the migration sweep runs on it and + removes ~/.cursor/hooks, error.log and all, before Cursor's own setup step.""" + _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + _run(backend) + assert not (env["home"] / ".cursor/hooks").exists() # the sweep did run + sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] + assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] + assert sent[0]["headers"]["Authorization"] == "Bearer per-device-key" + # Gone with its log, so nothing can be sent twice. + backend.requests.clear() + _run(backend) + assert [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] == [] + + +def test_errors_go_out_with_the_key_the_hooks_use(env, backend): + """Forwarding runs before any tool fetches its key, so it uses the one the home's hooks report with.""" + (env["home"] / ".unbound").mkdir(exist_ok=True) + (env["home"] / ".unbound" / "config.json").write_text(json.dumps({"device_token": "home-key"})) + _log(env["home"], "codex", [f"{_utc(0)}: codex broke"], key=None) + _run(backend) + [request] = _forwarded(backend) + assert request["headers"]["Authorization"] == "Bearer home-key" + + +def test_a_home_with_no_key_yet_forwards_nothing(env, backend): + _log(env["home"], "codex", [f"{_utc(0)}: codex broke"], key=None) + _run(backend) + assert _forwarded(backend) == [] From 8dbb6f257a9f378365b82cbfbf4834b330ff6a40 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 15:15:42 +0530 Subject: [PATCH 22/53] fix(setup): send one deferred report with the tamper state when every copilot install fails [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 9 +++------ binary/tests/test_setup_migration.py | 7 ++++--- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 67d75b43c..b56bf3b69 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -1817,12 +1817,9 @@ def _setup_copilot(opts): m.configure_managed_telemetry(api_key, gateway_url=gateway) if user_homes and installed == 0: - # A user can make every install fail, so a detected tamper is still reported. - if state == "tampered": - m.notify_setup_complete(api_key, "copilot", backend_url=base, - install_state=state, serial_number=device_id, - install_mode="binary") - return report("deferred", "hook install failed for all users") + # A user can make every install fail, so the report carries the state found: the backend counts a + # tamper on a deferred report without marking the tool connected or deployed. + return report("deferred", "hook install failed for all users", install_state=state) if not config_ok: return report("deferred", "config.json write failed for some users") diff --git a/binary/tests/test_setup_migration.py b/binary/tests/test_setup_migration.py index 76343cfdb..b53147f23 100644 --- a/binary/tests/test_setup_migration.py +++ b/binary/tests/test_setup_migration.py @@ -1826,9 +1826,10 @@ def _as_user(_u, fn, *a, _timeout=None, **k): # the real helper returns None wh setup_cmd.run(["--api-key", "admin-key"]) finally: hooks_dir.chmod(0o755) - # The tamper is still reported, then why setup deferred (WEB-6392). - assert _states(env, "copilot") == ["tampered", None] - assert [k.get("status") for a, k in env["notified"] if a[1] == "copilot"] == [None, "deferred"] + # One report: why setup deferred, carrying the tamper it found (WEB-6392). + assert _states(env, "copilot") == ["tampered"] + [report] = [k for a, k in env["notified"] if a[1] == "copilot"] + assert (report["status"], report["reason"]) == ("deferred", "hook install failed for all users") @pytest.mark.parametrize("tool", ["claude-code", "augment_code"]) From d6050f94b34b7097e43e3afe1525c091ac7650a5 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 15:34:01 +0530 Subject: [PATCH 23/53] feat(setup): give each tool's MDM script the installed check the binary uses [WEB-6392] --- augment/hooks/mdm/setup.py | 94 ++++++++++++++++ binary/README.md | 2 +- binary/src/unbound_hook/setup_cmd.py | 67 +----------- claude-code/hooks/mdm/setup.py | 95 ++++++++++++++++ codex/hooks/mdm/setup.py | 96 ++++++++++++++++ copilot/hooks/mdm/setup.py | 102 +++++++++++++++++ cursor/mdm/setup.py | 96 ++++++++++++++++ tests/test_tool_installed.py | 158 +++++++++++++++++++++++++++ 8 files changed, 648 insertions(+), 62 deletions(-) create mode 100644 tests/test_tool_installed.py diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 5de66c6c1..896e435e8 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1441,6 +1441,100 @@ def hook_script_hash(script_path) -> Optional[str]: return None +TOOL_NAME, TOOL_CLI = "Augment", "auggie" +# The Auggie CLI, or the Augment extension alone in VS Code, VS Code Insiders or Cursor. +_AUGMENT_EXTENSIONS = tuple(f"{editor}/extensions/augment.vscode-augment-*" + for editor in (".vscode", ".vscode-insiders", ".cursor")) +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = {system: ((), _AUGMENT_EXTENSIONS) for system in ("darwin", "linux", "windows")} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, diff --git a/binary/README.md b/binary/README.md index 93d4df9a6..e2eeb216c 100644 --- a/binary/README.md +++ b/binary/README.md @@ -81,7 +81,7 @@ the python path, by design: summary + exit code but never aborts the others. `deferred` means a re-run should retry; `skipped` is intentional. Every tool that got its device key sends this status, reason and `written_to` to `/api/v1/setup/complete/` each - run; a tool with no footprint on the Mac (`_TOOL_FOOTPRINTS`) is still + run; a tool with no footprint on the Mac (`tool_installed()` in its MDM module) is still written but reported `skipped` (" is not installed"). A discovery run that prints `Scan skipped: ` is `skipped`. The run itself posts `phase: start` first and `phase: end` last to the MDM install report. diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index b56bf3b69..0802d80ce 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -222,70 +222,15 @@ def _preflight_warnings(user_homes) -> list: _TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", "augment": "augment_code"} -# What an installed tool leaves on disk: (name, its CLI, its app bundles, other files under a home). -# None of these is a file setup writes, so a re-run never takes its own files for the tool. -_TOOL_FOOTPRINTS = { - "claude-code": ("Claude Code", "claude", ("Claude.app",), (".claude/local/claude", ".claude.json")), - "cursor": ("Cursor", "cursor-agent", ("Cursor.app",), ()), - "codex": ("Codex", "codex", ("Codex.app",), (".codex/auth.json", ".codex/sessions")), - "copilot": ("GitHub Copilot", "copilot", - ("Visual Studio Code.app", "Visual Studio Code - Insiders.app"), ()), - # The editor extension alone, in VS Code, VS Code Insiders or Cursor, also counts. - "augment": ("Augment", "auggie", (), tuple(f"{editor}/extensions/augment.vscode-augment-*" - for editor in (".vscode", ".vscode-insiders", ".cursor"))), -} -# Where a CLI lands under a home: a user install, Bun, npm's user prefix, yarn global, and the Node version -# managers (nvm, Volta, pnpm's default PNPM_HOME, fnm in both its folders, asdf and mise shims, mise's -# installs, nodenv). A prefix set in ~/.npmrc is read as well (_npmrc_bin). -_HOME_CLI_DIRS = (".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", - "Library/pnpm", ".local/share/fnm/node-versions/*/installation/bin", - ".fnm/node-versions/*/installation/bin", ".asdf/shims", ".local/share/mise/shims", - ".local/share/mise/installs/*/*/bin", ".nodenv/shims", ".nodenv/versions/*/bin", - ".yarn/bin", ".config/yarn/global/node_modules/.bin") -# Homebrew (Apple silicon, Intel) and MacPorts. -_MACHINE_CLI_DIRS = ("opt/homebrew/bin", "usr/local/bin", "opt/local/bin") - - -def _npmrc_bin(home: Path): - """The bin folder of a prefix the user set in ~/.npmrc, or None. Read without following a link and - used only to look for a file, so a root run learns nothing else from it.""" - try: - text = _read_user_file(home / ".npmrc", follow=False).decode("utf-8", "replace") - except OSError: - return None - for line in text.splitlines(): - key, sep, value = line.partition("=") - if sep and key.strip() == "prefix": - value = value.strip().strip('"\'') - for token in ("${HOME}", "$HOME"): - value = value.replace(token, str(home)) - if value.startswith("~/"): - value = str(home) + value[1:] - return Path(value) / "bin" if value.startswith("/") else None - return None +# The machine root the installed check looks under; tests point it at a sandbox. _MACHINE_ROOT = Path("/") -def _present(root: Path, relpath: str) -> bool: - try: - return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() - except OSError: - return False - - def _tool_installed(tool, user_homes) -> bool: - """Any footprint machine-wide (Homebrew, /usr/local, /Applications) or in a home (_HOME_CLI_DIRS, - ~/Applications, the tool's own files). A check that fails counts as installed, the report setup always sent.""" + """The tool's own MDM module answers (one check per tool, shared with the python setup), with the + macOS rules: this binary runs on macOS only. A check that fails counts as installed.""" try: - _, cli, apps, home_files = _TOOL_FOOTPRINTS[tool] - app_paths = [f"Applications/{app}" for app in apps] - machine = [f"{folder}/{cli}" for folder in _MACHINE_CLI_DIRS] + app_paths - per_home = [f"{folder}/{cli}" for folder in _HOME_CLI_DIRS] + [*home_files, *app_paths] - homes = [home for _, home in user_homes if home is not None] - roots = [(_MACHINE_ROOT, machine)] + [(home, per_home) for home in homes] - npm_bins = [b for b in map(_npmrc_bin, homes) if b is not None] - return (any(_present(root, rel) for root, rels in roots for rel in rels) - or any((b / cli).exists() for b in npm_bins)) + return load_mdm_setup_module(tool).tool_installed(user_homes, system="darwin", machine_root=_MACHINE_ROOT) except Exception: return True @@ -295,7 +240,7 @@ def _report(m, tool, api_key, status, reason=None, installed=True, **fields): without the tool (installed False, from the run's one check) reads skipped: its config is still written, so the hook works once the tool arrives.""" if status == "configured" and not installed: - status, reason = "skipped", f"{_TOOL_FOOTPRINTS[tool][0]} is not installed" + status, reason = "skipped", f"{m.TOOL_NAME} is not installed" m.notify_setup_complete(api_key, _TOOL_TYPES[tool], status=status, reason=reason, **fields) return status, reason @@ -1957,7 +1902,7 @@ def run(argv) -> int: warnings = _report_input(lambda: _preflight_warnings(user_homes), [], "preflight checks") # Once, before any tool writes: unknown homes (or a failed check) leave every tool reported as installed. opts["installed"] = _report_input(lambda: {} if user_homes is None else { - tool: _tool_installed(tool, user_homes) for tool in opts["tools"] if tool in _TOOL_FOOTPRINTS}, + tool: _tool_installed(tool, user_homes) for tool in opts["tools"] if tool in _TOOL_TYPES}, {}, "installed tools") _send_run_report(opts, serial, "start", _start_fields) # Before the sweep: it removes ~/.cursor/hooks, and with it Cursor's error.log. diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 7ffcd3f8c..3b23a3348 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3276,6 +3276,101 @@ def hook_script_hash(script_path) -> Optional[str]: return None +TOOL_NAME, TOOL_CLI = "Claude Code", "claude" +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = { + "darwin": (("Applications/Claude.app",), (".claude/local/claude", ".claude.json", "Applications/Claude.app")), + "linux": ((), (".claude/local/claude", ".claude.json")), + "windows": ((), (".claude.json", ".claude/local/claude.exe", "AppData/Local/AnthropicClaude")), +} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index dd5da964b..8a0cc6655 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2449,6 +2449,102 @@ def hook_script_hash(script_path) -> Optional[str]: os.close(fd) +TOOL_NAME, TOOL_CLI = "Codex", "codex" +_CODEX_HOME_FILES = (".codex/auth.json", ".codex/sessions") # codex's own, never setup's +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = { + "darwin": (("Applications/Codex.app",), _CODEX_HOME_FILES + ("Applications/Codex.app",)), + "linux": ((), _CODEX_HOME_FILES), + "windows": ((), _CODEX_HOME_FILES), +} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 5802e91f6..af1e2cb0a 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2087,6 +2087,108 @@ def hook_script_hash(script_path) -> Optional[str]: return None +TOOL_NAME, TOOL_CLI = "GitHub Copilot", "copilot" +# The Copilot CLI, or VS Code (Copilot ships in it) or its Copilot extensions. +_VSCODE_MAC = ("Applications/Visual Studio Code.app", "Applications/Visual Studio Code - Insiders.app") +_COPILOT_EXTENSIONS = (".vscode/extensions/github.copilot-*", ".vscode-insiders/extensions/github.copilot-*") +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = { + "darwin": (_VSCODE_MAC, _VSCODE_MAC + _COPILOT_EXTENSIONS), + "linux": (("usr/share/code", "usr/share/code-insiders", "usr/bin/code", "snap/bin/code", + "var/lib/flatpak/app/com.visualstudio.code"), + (".local/share/flatpak/app/com.visualstudio.code",) + _COPILOT_EXTENSIONS), + "windows": (("Program Files/Microsoft VS Code",), + ("AppData/Local/Programs/Microsoft VS Code", "AppData/Local/Programs/Microsoft VS Code Insiders") + + _COPILOT_EXTENSIONS), +} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 25acc6c5c..c2cae3b5e 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1207,6 +1207,102 @@ def hook_script_hash(script_path) -> Optional[str]: return None +TOOL_NAME, TOOL_CLI = "Cursor", "cursor-agent" +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = { + "darwin": (("Applications/Cursor.app",), ("Applications/Cursor.app",)), + "linux": (("opt/Cursor", "opt/cursor", "usr/share/cursor", "usr/bin/cursor", "usr/local/bin/cursor"), + ("Applications/Cursor*.AppImage", "Applications/cursor*.AppImage", ".local/bin/cursor")), + "windows": (("Program Files/Cursor",), ("AppData/Local/Programs/cursor",)), +} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, diff --git a/tests/test_tool_installed.py b/tests/test_tool_installed.py new file mode 100644 index 000000000..aa656de57 --- /dev/null +++ b/tests/test_tool_installed.py @@ -0,0 +1,158 @@ +"""WEB-6392: whether a tool is installed, for the setup/complete status (skipped " is not installed"). + +Every tool's MDM script is fetched and run on its own, so each carries the same check with its own +footprints; the unbound-hook binary calls the same function. These tests pin the footprints per OS, the +shared CLI folders, and that the five copies stay identical.""" + +import inspect +from pathlib import Path + +import pytest + +from tests.conftest import load_module + +MODULES = { + "claude-code": "claude-code/hooks/mdm/setup.py", + "cursor": "cursor/mdm/setup.py", + "codex": "codex/hooks/mdm/setup.py", + "copilot": "copilot/hooks/mdm/setup.py", + "augment": "augment/hooks/mdm/setup.py", +} +NAMES = {"claude-code": "Claude Code", "cursor": "Cursor", "codex": "Codex", "copilot": "GitHub Copilot", + "augment": "Augment"} + + +def _mod(tool): + return load_module(MODULES[tool]) + + +@pytest.fixture +def box(tmp_path): + """A machine root and one user home, both empty.""" + root, home = tmp_path / "root", tmp_path / "home" + root.mkdir() + home.mkdir() + return root, home + + +def _plant(base: Path, relpath: str): + """A file at relpath: the check only asks whether something is there.""" + path = base / relpath + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("") + + +def _installed(tool, system, box): + root, home = box + return _mod(tool).tool_installed([("u", home)], system=system, machine_root=root) + + +FOOTPRINTS = [ + # (tool, system, "machine" or "home", path) + ("claude-code", "darwin", "machine", "Applications/Claude.app"), + ("claude-code", "darwin", "home", ".claude.json"), + ("claude-code", "linux", "home", ".claude/local/claude"), + ("claude-code", "windows", "home", ".local/bin/claude.exe"), + ("claude-code", "windows", "home", "AppData/Local/AnthropicClaude"), + ("cursor", "darwin", "machine", "Applications/Cursor.app"), + ("cursor", "darwin", "home", ".local/bin/cursor-agent"), + ("cursor", "linux", "machine", "usr/share/cursor"), + ("cursor", "linux", "machine", "usr/bin/cursor"), + ("cursor", "linux", "home", "Applications/Cursor-1.2.3-x86_64.AppImage"), + ("cursor", "windows", "home", "AppData/Local/Programs/cursor"), + ("cursor", "windows", "machine", "Program Files/Cursor"), + ("codex", "darwin", "machine", "usr/local/bin/codex"), + ("codex", "linux", "home", ".codex/auth.json"), + ("codex", "windows", "home", "AppData/Roaming/npm/codex.cmd"), + ("codex", "windows", "home", ".codex/sessions"), + ("copilot", "darwin", "machine", "Applications/Visual Studio Code.app"), + ("copilot", "darwin", "home", ".vscode/extensions/github.copilot-chat-0.30.0"), + ("copilot", "linux", "machine", "usr/share/code"), + ("copilot", "linux", "machine", "snap/bin/code"), + ("copilot", "linux", "home", ".local/share/flatpak/app/com.visualstudio.code"), + ("copilot", "windows", "home", "AppData/Local/Programs/Microsoft VS Code"), + ("copilot", "windows", "machine", "Program Files/Microsoft VS Code"), + ("augment", "darwin", "home", ".vscode/extensions/augment.vscode-augment-0.512.0"), + ("augment", "linux", "home", ".local/bin/auggie"), + ("augment", "linux", "machine", "usr/bin/auggie"), + ("augment", "windows", "home", ".cursor/extensions/augment.vscode-augment-0.512.0"), + ("augment", "windows", "home", "AppData/Roaming/npm/auggie.ps1"), +] + + +@pytest.mark.parametrize("tool,system,where,relpath", FOOTPRINTS) +def test_each_footprint_counts_as_installed(box, tool, system, where, relpath): + _plant(box[0] if where == "machine" else box[1], relpath) + assert _installed(tool, system, box) is True + + +@pytest.mark.parametrize("system", ["darwin", "linux", "windows"]) +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_nothing_on_disk_is_not_installed(box, tool, system): + assert _installed(tool, system, box) is False + + +@pytest.mark.parametrize("system,where,folder", [ + ("darwin", "machine", "opt/homebrew/bin"), ("darwin", "machine", "opt/local/bin"), + ("darwin", "home", "Library/pnpm"), ("darwin", "home", ".volta/bin"), + ("linux", "machine", "usr/local/bin"), ("linux", "machine", "var/lib/flatpak/exports/bin"), + ("linux", "home", ".local/share/pnpm"), ("linux", "home", ".nvm/versions/node/v22.1.0/bin"), + ("linux", "home", ".local/share/mise/installs/node/22.1.0/bin"), ("linux", "home", ".asdf/shims"), + ("windows", "machine", "ProgramData/chocolatey/bin"), ("windows", "home", "scoop/shims"), + ("windows", "home", "AppData/Local/Volta/bin"), ("windows", "home", "AppData/Roaming/nvm/v22.1.0"), +]) +def test_every_tool_finds_its_cli_in_the_shared_folders(box, system, where, folder): + for tool, module in MODULES.items(): + cli = _mod(tool).TOOL_CLI + (".cmd" if system == "windows" else "") + _plant(box[0] if where == "machine" else box[1], f"{folder}/{cli}") + assert _installed(tool, system, box) is True, tool + + +def test_a_tool_is_not_found_by_another_tools_footprint(box): + _plant(box[0], "Applications/Cursor.app") + assert _installed("copilot", "darwin", box) is False + + +@pytest.mark.parametrize("prefix", ["~/.npm-packages", "$HOME/.npm-packages", "${HOME}/.npm-packages"]) +def test_an_npm_prefix_from_npmrc_counts_on_unix(box, prefix): + _, home = box + (home / ".npmrc").write_text(f"; comment\nprefix = {prefix}\n") + _plant(home, ".npm-packages/bin/codex") + assert _installed("codex", "linux", box) is True + + +def test_a_linked_npmrc_is_not_followed(box, tmp_path): + _, home = box + elsewhere = tmp_path / "elsewhere.npmrc" + elsewhere.write_text(f"prefix={home}/.npm-packages\n") + (home / ".npmrc").symlink_to(elsewhere) + _plant(home, ".npm-packages/bin/codex") + assert _installed("codex", "linux", box) is False + + +def test_a_check_that_fails_counts_as_installed(box, monkeypatch): + def broken(): + raise RuntimeError("no account database") + yield # noqa: unreachable, makes this a generator + root, _ = box + assert _mod("cursor").tool_installed(broken(), system="linux", machine_root=root) is True + # A place that can't be looked at says nothing about the tool, so it counts too. + monkeypatch.setattr(Path, "exists", lambda self, *a, **k: (_ for _ in ()).throw(PermissionError(13, "denied"))) + assert _installed("cursor", "linux", box) is True + + +def test_each_module_names_its_tool(): + assert {tool: _mod(tool).TOOL_NAME for tool in MODULES} == NAMES + + +SHARED_FUNCTIONS = ("_install_root", "_found", "_npmrc_cli_dir", "tool_installed") +SHARED_DATA = ("_UNIX_HOME_CLI_DIRS", "_CLI_DIRS", "_CLI_SUFFIXES") + + +@pytest.mark.parametrize("name", SHARED_FUNCTIONS + SHARED_DATA) +def test_the_five_copies_are_identical(name): + def value(tool): + obj = getattr(_mod(tool), name) + return inspect.getsource(obj) if callable(obj) else obj + first = value("claude-code") + assert all(value(tool) == first for tool in MODULES), name From 77ea00a5050fb35db30962daf468bc56c55a9898 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 16:19:20 +0530 Subject: [PATCH 24/53] feat(setup): report every tool's outcome from the python MDM scripts each run [WEB-6392] --- augment/hooks/mdm/setup.py | 17 ++- claude-code/hooks/mdm/setup.py | 20 +++- codex/hooks/mdm/setup.py | 29 ++++- copilot/hooks/mdm/setup.py | 36 ++++-- cursor/mdm/setup.py | 17 ++- tests/test_mdm_setup_status.py | 212 +++++++++++++++++++++++++++++++++ 6 files changed, 311 insertions(+), 20 deletions(-) create mode 100644 tests/test_mdm_setup_status.py diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 896e435e8..6f88a9152 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1658,11 +1658,22 @@ def main(): return False print("API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(api_key, "augment_code", backend_url=base_url, serial_number=device_id, + install_mode="mdm", status=status, reason=reason, **fields) + print("\nSetting environment variables system-wide...") url_ok, _ = set_env_var_system_wide("UNBOUND_BACKEND_URL", base_url) if not url_ok: print("Failed to set UNBOUND_BACKEND_URL") + report("deferred", "Failed to set UNBOUND_BACKEND_URL") return False # Write the per-user unbound config now (needed by the managed hook; harmless @@ -1679,6 +1690,7 @@ def main(): print("\nConfiguring Augment managed hooks...") if not setup_managed_hooks(gateway_url=gateway_url): print("Failed to configure managed hooks") + report("deferred", "Failed to configure managed hooks") return False managed_dir = get_managed_settings_dir() print(f"Created managed hooks in {managed_dir}") @@ -1696,14 +1708,15 @@ def main(): if not config_ok: print("Could not write ~/.unbound/config.json for every user") + report("deferred", "Could not write ~/.unbound/config.json for every user") return False print("\n" + "=" * 60) print("Setup Complete!") print("=" * 60) - notify_setup_complete(api_key, "augment_code", backend_url=base_url, install_state=state, serial_number=device_id, - hook_hash=hook_script_hash(get_managed_settings_dir() / "hooks" / "unbound.py"), install_mode="mdm") + report("configured", install_state=state, hook_hash=hook_script_hash(get_managed_settings_dir() / "hooks" / "unbound.py"), + written_to=str(get_managed_settings_dir() / "settings.json")) return True diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 3b23a3348..dae45def7 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3499,6 +3499,16 @@ def main(): return False print("API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(api_key, "claude-code", backend_url=base_url, serial_number=device_id, + install_mode="mdm-skip" if skip_managed_settings else "mdm", status=status, reason=reason, **fields) + print("\nSetting environment variables system-wide...") _freeze_ownership_evidence() @@ -3513,6 +3523,7 @@ def main(): url_ok, _ = set_env_var_system_wide("UNBOUND_BACKEND_URL", base_url) if not url_ok: print("Failed to set UNBOUND_BACKEND_URL") + report("deferred", "Failed to set UNBOUND_BACKEND_URL") return False # Remove gateway artifacts, strip leftover user-level Unbound hooks @@ -3536,19 +3547,22 @@ def main(): print(f"Created managed hooks in {managed_dir}") else: print("Failed to configure managed hooks") + report("deferred", "Failed to configure managed hooks") return False if not config_ok: print("Could not write ~/.unbound/config.json for every user") + report("deferred", "Could not write ~/.unbound/config.json for every user") return False print("\n" + "=" * 60) print("Setup Complete!") print("=" * 60) - notify_setup_complete(api_key, "claude-code", backend_url=base_url, install_state=state, serial_number=device_id, - hook_hash=hook_script_hash(get_managed_settings_dir() / "hooks" / "unbound.py"), - install_mode="mdm-skip" if skip_managed_settings else "mdm") + managed_dir = get_managed_settings_dir() + report("configured", install_state=state, hook_hash=hook_script_hash(managed_dir / "hooks" / "unbound.py"), + written_to=str(managed_dir / "hooks" / "unbound.py" if skip_managed_settings + else managed_dir / "managed-settings.json")) if backfill_mode: _run_backfill_bounded(api_key, base_url, get_all_user_homes()) diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 8a0cc6655..7467aacfb 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2669,6 +2669,16 @@ def main(): return False print("API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(api_key, "codex", backend_url=base_url, serial_number=device_id, + install_mode="mdm", status=status, reason=reason, **fields) + print("\nSetting environment variables system-wide...") # Remove leftover gateway setup env vars for username, home_dir in get_all_user_homes(): @@ -2678,6 +2688,7 @@ def main(): url_ok, _ = set_env_var_system_wide("UNBOUND_BACKEND_URL", base_url) if not url_ok: print("Failed to set UNBOUND_BACKEND_URL") + report("deferred", "Failed to set UNBOUND_BACKEND_URL") return False state = detect_install_state() @@ -2687,6 +2698,7 @@ def main(): system_wide = platform.system().lower() != "windows" if system_wide and not setup_managed_hooks(gateway_url): print("Failed to set up codex managed hooks") + report("deferred", "Failed to set up codex managed hooks") return False print("\nConfiguring Codex user hooks...") @@ -2706,11 +2718,14 @@ def main(): success = bool(user_homes) and installed == len(user_homes) and config_ok if not user_homes: - print("No user home directories found") - elif success: - print(f"Registered codex hooks for {installed} user(s)") + failure = "No user home directories found" + elif installed < len(user_homes): + failure = f"Registered codex hooks for {installed} of {len(user_homes)} user(s) — {len(user_homes) - installed} failed" + elif not config_ok: + failure = "Could not write ~/.unbound/config.json for every user" else: - print(f"Registered codex hooks for {installed} of {len(user_homes)} user(s) — {len(user_homes) - installed} failed") + failure = None + print(failure or f"Registered codex hooks for {installed} user(s)") print("\n" + "=" * 60) print("Setup Complete!" if success else "Setup Failed") @@ -2719,8 +2734,10 @@ def main(): if success: # After the new hooks are in place: an older codex hook reads only the per-tool var. remove_legacy_key_env() - notify_setup_complete(api_key, "codex", backend_url=base_url, install_state=state, serial_number=device_id, - hook_hash=hook_script_hash(_installed_hook_script()), install_mode="mdm") + report("configured", install_state=state, hook_hash=hook_script_hash(_installed_hook_script()), + written_to=str(get_managed_settings_dir() / "hooks.json") if system_wide else "~/.codex/hooks.json") + else: + report("deferred", failure) if success and backfill_mode: with _backfill_soft_stop(BACKFILL_SOFT_STOP_SECONDS): diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index af1e2cb0a..e77c6e443 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2898,17 +2898,29 @@ def main(): return False print("API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(api_key, "copilot", backend_url=base_url, serial_number=device_id, + install_mode="mdm", status=status, reason=reason, **fields) + print("\nSetting environment variables system-wide...") url_ok, _ = set_env_var_system_wide("UNBOUND_BACKEND_URL", base_url) if not url_ok: print("Failed to set UNBOUND_BACKEND_URL") + report("deferred", "Failed to set UNBOUND_BACKEND_URL") return False print("\nDownloading hook script...") script_text = _fetch_hook_script(gateway_url) if script_text is None: print("Failed to download unbound.py") + report("deferred", "Failed to download unbound.py") return False state = detect_install_state() @@ -2939,11 +2951,15 @@ def main(): success = bool(user_homes) and installed_count == len(user_homes) and config_ok if not user_homes: - print("No user home directories found") - elif success: - print(f"Installed Copilot hooks for {installed_count} user(s)") + failure = "No user home directories found" + elif installed_count < len(user_homes): + failure = (f"Installed Copilot hooks for {installed_count} of {len(user_homes)} user(s)" + f" — {len(user_homes) - installed_count} failed") + elif not config_ok: + failure = "Could not write ~/.unbound/config.json for every user" else: - print(f"Installed Copilot hooks for {installed_count} of {len(user_homes)} user(s) — {len(user_homes) - installed_count} failed") + failure = None + print(failure or f"Installed Copilot hooks for {installed_count} user(s)") print("\n" + "=" * 60) print("Setup Complete!" if success else "Setup Failed") @@ -2951,9 +2967,15 @@ def main(): if success: # Every user gets the same script bytes, so the first copy identifies the version. - notify_setup_complete(api_key, "copilot", backend_url=base_url, install_state=state, serial_number=device_id, - hook_hash=hook_script_hash(user_homes[0][1] / ".copilot" / "hooks" / "unbound.py"), - install_mode="mdm") + report("configured", install_state=state, + hook_hash=hook_script_hash(user_homes[0][1] / ".copilot" / "hooks" / "unbound.py"), + written_to="~/.copilot/hooks/unbound.json") + elif user_homes and installed_count < len(user_homes): + # A user can make every install fail: the report carries the state found, and the backend counts + # a tamper on a deferred report without marking the tool connected or deployed. + report("deferred", failure, install_state=state) + else: + report("deferred", failure) # Before the re-walk: onboard.py allows one installer 600s and the re-walk is bounded # by session count, not time. Visual Studio fires no hook, so the sweep is the only diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index c2cae3b5e..b7c4f89bc 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1435,9 +1435,20 @@ def main(): return False print("✅ API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(cursor_api_key, "cursor", backend_url=base_url, serial_number=serial_number, + install_mode="mdm", status=status, reason=reason, **fields) + url_ok, _, url_message = set_env_var("UNBOUND_BACKEND_URL", base_url) if not url_ok: print(f"❌ Failed to set UNBOUND_BACKEND_URL: {url_message}") + report("deferred", f"Failed to set UNBOUND_BACKEND_URL: {url_message}") return False # Write API key to ~/.unbound/config.json for each user and remove user-level hooks @@ -1461,19 +1472,21 @@ def main(): hooks_success, hooks_changed = setup_hooks(gateway_url=gateway_url) if not hooks_success: print("\n❌ Failed to setup hooks") + report("deferred", "Failed to setup hooks") return False debug_print("Hooks setup complete") if config_count < len(user_homes): print("Could not write ~/.unbound/config.json for every user") + report("deferred", "Could not write ~/.unbound/config.json for every user") return False print("\n" + "=" * 60) print("Setup Complete!") print("=" * 60) - notify_setup_complete(cursor_api_key, "cursor", backend_url=base_url, install_state=state, serial_number=serial_number, - hook_hash=hook_script_hash(get_enterprise_hooks_dir() / "hooks" / "unbound.py"), install_mode="mdm") + report("configured", install_state=state, hook_hash=hook_script_hash(get_enterprise_hooks_dir() / "hooks" / "unbound.py"), + written_to=str(get_enterprise_hooks_dir() / "hooks.json")) if hooks_changed: debug_print("Restart needed: hooks changed") diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py new file mode 100644 index 000000000..3a99f4a2e --- /dev/null +++ b/tests/test_mdm_setup_status.py @@ -0,0 +1,212 @@ +"""WEB-6392: the python MDM scripts (mdm/onboard.py on Linux and Windows) report every tool every run. + +Each script's real main() runs with only the root-only and network primitives stubbed: every run sends +one setup/complete with status configured (and where its config went), skipped " is not installed" +(the config still written, the exit code unchanged), or deferred with the reason the script prints.""" + +import sys +from pathlib import Path + +import pytest + +from tests.conftest import load_module + +MODULES = { + "claude-code": "claude-code/hooks/mdm/setup.py", + "cursor": "cursor/mdm/setup.py", + "codex": "codex/hooks/mdm/setup.py", + "copilot": "copilot/hooks/mdm/setup.py", + "augment": "augment/hooks/mdm/setup.py", +} +TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", + "augment": "augment_code"} + + +class Run: + """One tool's main() over a sandbox: a home, a managed folder, recorded reports and writes.""" + + def __init__(self, tool, tmp_path, monkeypatch): + self.tool, self.m = tool, load_module(MODULES[tool]) + self.home, self.managed = tmp_path / "home", tmp_path / "managed" + self.home.mkdir() + self.managed.mkdir() + self.reports, self.writes, self.installed = [], [], True + self.mp = monkeypatch + m = self.m + monkeypatch.setattr(sys, "argv", ["setup.py", "--api-key", "admin-key"]) + monkeypatch.setattr(m.platform, "system", lambda: "Linux") + self.stub("check_admin_privileges", True) + self.stub("get_device_identifier", "SERIAL1") + self.stub("fetch_api_key_from_mdm", "device-key") + self.stub("get_all_user_homes", [("u", self.home)]) + self.stub("write_unbound_config_for_user", True) + self.stub("remove_legacy_key_env", None) + self.stub("detect_install_state", "fresh") + self.stub("hook_script_hash", "h" * 64) + monkeypatch.setattr(m, "notify_setup_complete", lambda key, tool_type, **k: self.reports.append( + dict(k, api_key=key, tool_type=tool_type))) + monkeypatch.setattr(m, "tool_installed", lambda homes, *a, **k: self.installed) + for name in ("set_env_var_system_wide",): + if hasattr(m, name): + self.stub(name, (True, False)) + for name in ("remove_env_var_from_user", "remove_gateway_artifacts_for_user", "remove_user_level_hooks", + "remove_user_level_hooks_for_user", "_freeze_ownership_evidence", "clear_otel_export_for_user", + "enable_codex_hooks_feature_for_user", "restart_cursor", "run_visual_studio_sweep"): + if hasattr(m, name): + self.stub(name, None) + for name in ("get_managed_settings_dir", "get_enterprise_hooks_dir"): + if hasattr(m, name): + self.stub(name, self.managed) + getattr(self, "_" + tool.replace("-", "_"))() + + def stub(self, name, result): + self.mp.setattr(self.m, name, lambda *a, _r=result, **k: _r) + + def writer(self, name, result=True): + self.mp.setattr(self.m, name, lambda *a, _n=name, _r=result, **k: self.writes.append(_n) or _r) + + def _claude_code(self): + self.writer("setup_managed_hooks") + self.stub("_unbound_base_url_matcher", None) + + def _cursor(self): + self.stub("set_env_var", (True, False, "ok")) + self.writer("setup_hooks", (True, False)) + + def _codex(self): + self.writer("setup_managed_hooks") + self.writer("configure_codex_hooks_for_user") + self.stub("_installed_hook_script", None) + + def _copilot(self): + self.stub("_fetch_hook_script", "# hook") + self.writer("install_hooks_for_user") + self.stub("configure_managed_telemetry", True) + + def _augment(self): + self.writer("setup_managed_hooks") + self.stub("verify_managed_hooks_installed", True) + + def __call__(self): + return self.m.main() + + @property + def report(self): + assert len(self.reports) == 1, self.reports + return self.reports[0] + + +@pytest.fixture +def run(tmp_path, monkeypatch): + return lambda tool: Run(tool, tmp_path, monkeypatch) + + +WRITTEN_TO = { + "claude-code": lambda r: str(r.managed / "managed-settings.json"), + "cursor": lambda r: str(r.managed / "hooks.json"), + "codex": lambda r: str(r.managed / "hooks.json"), + "copilot": lambda r: "~/.copilot/hooks/unbound.json", + "augment": lambda r: str(r.managed / "settings.json"), +} + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_an_installed_tool_reports_configured_and_where_its_config_went(run, tool): + r = run(tool) + assert r() is True + report = r.report + assert (report["tool_type"], report["status"], report["reason"]) == (TOOL_TYPES[tool], "configured", None) + assert report["written_to"] == WRITTEN_TO[tool](r) + assert (report["install_state"], report["serial_number"], report["api_key"]) == ("fresh", "SERIAL1", "device-key") + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_a_tool_that_is_not_installed_is_reported_skipped_and_still_set_up(run, tool): + r = run(tool) + r.installed = False + assert r() is True # the exit code doesn't change + report = r.report + assert (report["status"], report["reason"]) == ("skipped", f"{r.m.TOOL_NAME} is not installed") + assert r.writes, "reporting only: everything is still written" + + +DEFERRED = [ + ("claude-code", "set_env_var_system_wide", (False, False), "Failed to set UNBOUND_BACKEND_URL"), + ("claude-code", "setup_managed_hooks", False, "Failed to configure managed hooks"), + ("claude-code", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), + ("cursor", "set_env_var", (False, False, "denied"), "Failed to set UNBOUND_BACKEND_URL: denied"), + ("cursor", "setup_hooks", (False, False), "Failed to setup hooks"), + ("cursor", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), + ("codex", "set_env_var_system_wide", (False, False), "Failed to set UNBOUND_BACKEND_URL"), + ("codex", "setup_managed_hooks", False, "Failed to set up codex managed hooks"), + ("codex", "get_all_user_homes", [], "No user home directories found"), + ("codex", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), + ("copilot", "set_env_var_system_wide", (False, False), "Failed to set UNBOUND_BACKEND_URL"), + ("copilot", "_fetch_hook_script", None, "Failed to download unbound.py"), + ("copilot", "get_all_user_homes", [], "No user home directories found"), + ("copilot", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), + ("augment", "set_env_var_system_wide", (False, False), "Failed to set UNBOUND_BACKEND_URL"), + ("augment", "setup_managed_hooks", False, "Failed to configure managed hooks"), + ("augment", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), +] + + +@pytest.mark.parametrize("tool,name,result,reason", DEFERRED) +def test_a_failure_after_the_key_is_reported_deferred_with_its_reason(run, tool, name, result, reason): + r = run(tool) + r.stub(name, result) + assert r() is False # the exit code doesn't change + report = r.report + assert (report["status"], report["reason"]) == ("deferred", reason) + + +def test_codex_on_windows_reports_the_per_user_hooks_file(run): + r = run("codex") + r.mp.setattr(r.m.platform, "system", lambda: "Windows") + assert r() is True + assert r.report["written_to"] == "~/.codex/hooks.json" + + +def test_codex_on_windows_reports_a_failed_per_user_install(run): + r = run("codex") + r.mp.setattr(r.m.platform, "system", lambda: "Windows") + r.writer("configure_codex_hooks_for_user", False) + assert r() is False + assert (r.report["status"], r.report["reason"]) == ("deferred", "Registered codex hooks for 0 of 1 user(s) — 1 failed") + + +def test_claude_code_without_managed_settings_reports_the_hook_script(run): + r = run("claude-code") + r.mp.setattr(sys, "argv", ["setup.py", "--api-key", "admin-key", "--skip-managed-settings"]) + assert r() is True + assert (r.report["written_to"], r.report["install_mode"]) == (str(r.managed / "hooks" / "unbound.py"), "mdm-skip") + + +def test_copilot_with_every_install_failed_sends_one_deferred_report_with_the_tamper(run): + r = run("copilot") + r.stub("detect_install_state", "tampered") + r.writer("install_hooks_for_user", False) + assert r() is False + report = r.report + assert (report["status"], report["reason"], report["install_state"]) == ( + "deferred", "Installed Copilot hooks for 0 of 1 user(s) — 1 failed", "tampered") + + +def test_copilot_with_some_installs_failed_reports_how_many(run): + r = run("copilot") + other = r.home.parent / "other" + other.mkdir() + r.stub("get_all_user_homes", [("u", r.home), ("v", other)]) + answers = iter([True, False]) + r.mp.setattr(r.m, "install_hooks_for_user", lambda *a, **k: next(answers)) + assert r() is False + assert (r.report["status"], r.report["reason"]) == ("deferred", "Installed Copilot hooks for 1 of 2 user(s) — 1 failed") + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_a_failure_before_the_key_sends_nothing(run, tool): + """Without the device key there is nothing to report with; the exit code says it.""" + r = run(tool) + r.stub("fetch_api_key_from_mdm", None) + assert r() is False + assert r.reports == [] From 0cb055df6ba0bc643def6f5af5a57f1c415de5f7 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 17:27:41 +0530 Subject: [PATCH 25/53] fix(setup): skip only the home whose key the gateway refuses [WEB-6392] --- binary/README.md | 4 ++-- binary/src/unbound_hook/setup_cmd.py | 12 +++++++----- binary/tests/test_setup_reporting.py | 22 ++++++++++++++++++++++ 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/binary/README.md b/binary/README.md index e2eeb216c..f06bc137a 100644 --- a/binary/README.md +++ b/binary/README.md @@ -92,8 +92,8 @@ the python path, by design: at most the newest 25 per tool and home, none older than seven days, with `category: forwarded_error_log`), recording the newest accepted timestamp in `.error_log_forwarded` beside the - log; a gateway that is down ends forwarding for the run, a refused key ends - it for that tool, and neither saves anything. + log; a gateway that is down ends forwarding for the run, a refused key skips + that home (each home has its own key), and neither saves anything. - **`detect_install_state`** is adapted: the python version checked for the managed `unbound.py`, which no longer exists. Binary semantics: settings file absent → `fresh`; present and referencing the binary → `persisted`; diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 0802d80ce..43564f919 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -389,8 +389,8 @@ def _home_device_key(home: Path): def _forward_hook_errors(m, tool, opts) -> None: """Forward every home's unsent error.log entries for this tool, with that home's own device key. Runs before the migration sweep, which removes ~/.cursor/hooks and its log. A gateway that is down ends - forwarding for the whole run, so it costs one short timeout; a refused key ends it for this tool only. - Either way nothing is marked sent, and the next run retries.""" + forwarding for the whole run, so it costs one short timeout; a refused key is that home's own and skips + only that home. Either way nothing is marked sent, and the next run retries.""" if opts.get("hook_errors_held"): return relpath, hook_source = _HOOK_ERROR_LOGS[tool] @@ -408,9 +408,11 @@ def _forward_hook_errors(m, tool, opts) -> None: api_key, hook_source, hook_sha) count, verdict = _forward_home_errors(m, username, log, send) sent += count - if verdict != "sent": - opts["hook_errors_held"] = opts.get("hook_errors_held") or verdict == "down" - print(f"[errors] {tool} hook errors not forwarded (gateway {verdict}); the next run retries") + if verdict == "refused": + print(f"[errors] {tool} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + opts["hook_errors_held"] = True + print(f"[errors] {tool} hook errors not forwarded (gateway down); the next run retries") break except Exception as e: print(f"[errors] {tool} hook errors not forwarded: {e}") diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index d0b68cddf..dd0aae15d 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -724,3 +724,25 @@ def test_a_home_with_no_key_yet_forwards_nothing(env, backend): _log(env["home"], "codex", [f"{_utc(0)}: codex broke"], key=None) _run(backend) assert _forwarded(backend) == [] + + +# --- Final review #1: one home's refused key doesn't stop the other homes --------- + +def test_a_refused_key_in_one_home_leaves_the_other_homes_forwarding(env, backend, monkeypatch, tmp_path): + other = tmp_path / "other-home" + other.mkdir() + for m in env["modules"].values(): + monkeypatch.setattr(m, "get_all_user_homes", lambda: [("alice", env["home"]), ("bob", other)]) + _log(env["home"], "codex", [f"{_utc(0)}: alice's codex broke"], key="revoked-key") + _log(other, "codex", [f"{_utc(1)}: bob's codex broke"], key="bob-key") + ok = {"status": "ok", "success": True, "accepted": 1} + + def answer(path): + revoked = backend.requests[-1]["headers"].get("Authorization") == "Bearer revoked-key" + return (200, {"success": False, "reason": "invalid_key"}) if revoked else (200, ok) + + backend.answer = answer + _run(backend) + assert _messages(backend) == ["alice's codex broke", "bob's codex broke"] + assert (other / ".codex/hooks" / STATE).exists() + assert not (env["home"] / ".codex/hooks" / STATE).exists() From 8f3e7fadf86066bae485ec95e7df1c4663183007 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 17:28:57 +0530 Subject: [PATCH 26/53] fix(setup): forward hook errors with the key the hooks read first [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 3 ++- binary/tests/test_setup_reporting.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 43564f919..c5fcaa195 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -382,7 +382,8 @@ def _home_device_key(home: Path): config = json.loads(_read_user_file(home / ".unbound" / "config.json", follow=False).decode("utf-8")) except (OSError, ValueError): return None - key = (config.get("device_token") or config.get("api_key")) if isinstance(config, dict) else None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + key = (config.get("api_key") or config.get("device_token")) if isinstance(config, dict) else None return key if isinstance(key, str) and key else None diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index dd0aae15d..f64a5b849 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -746,3 +746,18 @@ def answer(path): assert _messages(backend) == ["alice's codex broke", "bob's codex broke"] assert (other / ".codex/hooks" / STATE).exists() assert not (env["home"] / ".codex/hooks" / STATE).exists() + + +# --- Final review #2: the key the hooks use, and redacted ------------------------ + +def test_forwarding_uses_and_redacts_the_key_the_hooks_read_first(env, backend): + """The hooks read cfg.get('api_key') or cfg.get('device_token'); when both are there and differ, + that is the key their errors belong to.""" + (env["home"] / ".unbound").mkdir(exist_ok=True) + (env["home"] / ".unbound" / "config.json").write_text( + json.dumps({"device_token": "token-key-2", "api_key": "api-key-1"})) + _log(env["home"], "codex", [f"{_utc(0)}: request with api-key-1 failed"], key=None) + _run(backend) + [request] = _forwarded(backend) + assert request["headers"]["Authorization"] == "Bearer api-key-1" + assert _messages(backend) == ["request with [REDACTED] failed"] From 7722b84c30afd9c557bb36f6e2fc16422680e0fd Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 17:29:25 +0530 Subject: [PATCH 27/53] fix(setup): send copilot's tamper state only when every install fails, as the binary does [WEB-6392] --- copilot/hooks/mdm/setup.py | 5 +++-- tests/test_mdm_setup_status.py | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index e77c6e443..d789c8b9f 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2970,9 +2970,10 @@ def report(status, reason=None, **fields): report("configured", install_state=state, hook_hash=hook_script_hash(user_homes[0][1] / ".copilot" / "hooks" / "unbound.py"), written_to="~/.copilot/hooks/unbound.json") - elif user_homes and installed_count < len(user_homes): + elif user_homes and installed_count == 0: # A user can make every install fail: the report carries the state found, and the backend counts - # a tamper on a deferred report without marking the tool connected or deployed. + # a tamper on a deferred report without marking the tool connected or deployed. Same rule as the + # unbound-hook binary. report("deferred", failure, install_state=state) else: report("deferred", failure) diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py index 3a99f4a2e..a1f3ac9de 100644 --- a/tests/test_mdm_setup_status.py +++ b/tests/test_mdm_setup_status.py @@ -201,6 +201,8 @@ def test_copilot_with_some_installs_failed_reports_how_many(run): r.mp.setattr(r.m, "install_hooks_for_user", lambda *a, **k: next(answers)) assert r() is False assert (r.report["status"], r.report["reason"]) == ("deferred", "Installed Copilot hooks for 1 of 2 user(s) — 1 failed") + # As in the binary, the tamper state rides only on a run where every install failed. + assert "install_state" not in r.report @pytest.mark.parametrize("tool", sorted(MODULES)) From 0634eaa3fe000c181fa838229589828d24d244d0 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 17:30:18 +0530 Subject: [PATCH 28/53] fix(setup): count Copilot in Visual Studio and JetBrains as installed [WEB-6392] --- copilot/hooks/mdm/setup.py | 20 ++++++++++++++------ tests/test_tool_installed.py | 13 +++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index d789c8b9f..d6eef376a 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2088,18 +2088,26 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "GitHub Copilot", "copilot" -# The Copilot CLI, or VS Code (Copilot ships in it) or its Copilot extensions. +# The Copilot CLI; VS Code (Copilot ships in it) or its Copilot extensions; Visual Studio (Copilot ships in +# it: the installer's instance registry, as the hook's _vs_installed reads it, and the Copilot chat log its +# sweep reads); or the JetBrains Copilot plugin: its own config (the hook and discovery read it) and its +# folder in an IDE's per-user config (the JetBrains and Google vendor folders discovery scans). _VSCODE_MAC = ("Applications/Visual Studio Code.app", "Applications/Visual Studio Code - Insiders.app") _COPILOT_EXTENSIONS = (".vscode/extensions/github.copilot-*", ".vscode-insiders/extensions/github.copilot-*") +_JETBRAINS_PLUGIN = tuple(f"{{root}}/{vendor}/*/plugins/github-copilot-intellij" for vendor in ("JetBrains", "Google")) # Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. TOOL_FOOTPRINTS = { - "darwin": (_VSCODE_MAC, _VSCODE_MAC + _COPILOT_EXTENSIONS), + "darwin": (_VSCODE_MAC, _VSCODE_MAC + _COPILOT_EXTENSIONS + (".config/github-copilot/intellij",) + + tuple(p.format(root="Library/Application Support") for p in _JETBRAINS_PLUGIN)), "linux": (("usr/share/code", "usr/share/code-insiders", "usr/bin/code", "snap/bin/code", "var/lib/flatpak/app/com.visualstudio.code"), - (".local/share/flatpak/app/com.visualstudio.code",) + _COPILOT_EXTENSIONS), - "windows": (("Program Files/Microsoft VS Code",), - ("AppData/Local/Programs/Microsoft VS Code", "AppData/Local/Programs/Microsoft VS Code Insiders") - + _COPILOT_EXTENSIONS), + (".local/share/flatpak/app/com.visualstudio.code",) + _COPILOT_EXTENSIONS + + (".config/github-copilot/intellij",) + tuple(p.format(root=".config") for p in _JETBRAINS_PLUGIN)), + "windows": (("Program Files/Microsoft VS Code", "ProgramData/Microsoft/VisualStudio/Packages/_Instances/*"), + ("AppData/Local/Programs/Microsoft VS Code", "AppData/Local/Programs/Microsoft VS Code Insiders", + "AppData/Local/Temp/VSGitHubCopilotLogs/*_VSGitHubCopilot.chat.log", + "AppData/Local/github-copilot/intellij") + _COPILOT_EXTENSIONS + + tuple(p.format(root="AppData/Roaming") for p in _JETBRAINS_PLUGIN)), } # --- Whether the tool is installed (WEB-6392) --------------------------------------------- diff --git a/tests/test_tool_installed.py b/tests/test_tool_installed.py index aa656de57..6d5de6a52 100644 --- a/tests/test_tool_installed.py +++ b/tests/test_tool_installed.py @@ -72,6 +72,19 @@ def _installed(tool, system, box): ("copilot", "linux", "home", ".local/share/flatpak/app/com.visualstudio.code"), ("copilot", "windows", "home", "AppData/Local/Programs/Microsoft VS Code"), ("copilot", "windows", "machine", "Program Files/Microsoft VS Code"), + # Visual Studio: the installer's instance registry (what the hook's _vs_installed reads) and the + # Copilot chat log the hook's sweep reads. + ("copilot", "windows", "machine", "ProgramData/Microsoft/VisualStudio/Packages/_Instances/3f1e2d4c"), + ("copilot", "windows", "home", "AppData/Local/Temp/VSGitHubCopilotLogs/20261124_VSGitHubCopilot.chat.log"), + # JetBrains: the Copilot plugin's own config (read by the hook and by discovery), and the plugin + # folder in an IDE's per-user config (JetBrains and Google, as discovery scans them). + ("copilot", "darwin", "home", ".config/github-copilot/intellij/mcp.json"), + ("copilot", "linux", "home", ".config/github-copilot/intellij/global-copilot-instructions.md"), + ("copilot", "windows", "home", "AppData/Local/github-copilot/intellij/mcp.json"), + ("copilot", "darwin", "home", "Library/Application Support/JetBrains/IntelliJIdea2025.2/plugins/github-copilot-intellij/lib/x.jar"), + ("copilot", "linux", "home", ".config/JetBrains/PyCharm2025.1/plugins/github-copilot-intellij/lib/x.jar"), + ("copilot", "linux", "home", ".config/Google/AndroidStudio2025.1/plugins/github-copilot-intellij/lib/x.jar"), + ("copilot", "windows", "home", "AppData/Roaming/JetBrains/Rider2025.2/plugins/github-copilot-intellij/lib/x.jar"), ("augment", "darwin", "home", ".vscode/extensions/augment.vscode-augment-0.512.0"), ("augment", "linux", "home", ".local/bin/auggie"), ("augment", "linux", "machine", "usr/bin/auggie"), From 67b2eac490ca6f874977c1d9a0d1215f521a0093 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 17:31:35 +0530 Subject: [PATCH 29/53] fix(setup): find homes and read each home's key once a run when forwarding [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 15 ++++++++++----- binary/tests/test_setup_reporting.py | 12 ++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index c5fcaa195..67b1a650d 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -387,22 +387,26 @@ def _home_device_key(home: Path): return key if isinstance(key, str) and key else None -def _forward_hook_errors(m, tool, opts) -> None: +def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: """Forward every home's unsent error.log entries for this tool, with that home's own device key. Runs before the migration sweep, which removes ~/.cursor/hooks and its log. A gateway that is down ends forwarding for the whole run, so it costs one short timeout; a refused key is that home's own and skips - only that home. Either way nothing is marked sent, and the next run retries.""" + only that home. Either way nothing is marked sent, and the next run retries. user_homes and keys (home + to its key, filled as homes are read) come from run(), so each home is found and read once a run.""" if opts.get("hook_errors_held"): return relpath, hook_source = _HOOK_ERROR_LOGS[tool] sent = 0 try: hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] - for username, home_dir in m.get_all_user_homes(): + keys = {} if keys is None else keys + for username, home_dir in user_homes if user_homes is not None else m.get_all_user_homes(): log = home_dir / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - api_key = _as_user(m, username, _home_device_key, home_dir) + if str(home_dir) not in keys: + keys[str(home_dir)] = _as_user(m, username, _home_device_key, home_dir) + api_key = keys[str(home_dir)] if not api_key: continue # no hook here has a key to report with yet send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", @@ -1909,9 +1913,10 @@ def run(argv) -> int: {}, "installed tools") _send_run_report(opts, serial, "start", _start_fields) # Before the sweep: it removes ~/.cursor/hooks, and with it Cursor's error.log. + home_keys = {} for tool in opts["tools"]: if tool in _HOOK_ERROR_LOGS: - _forward_hook_errors(m0, tool, opts) + _forward_hook_errors(m0, tool, opts, user_homes, home_keys) statuses = {} diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index f64a5b849..075199472 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -761,3 +761,15 @@ def test_forwarding_uses_and_redacts_the_key_the_hooks_read_first(env, backend): [request] = _forwarded(backend) assert request["headers"]["Authorization"] == "Bearer api-key-1" assert _messages(backend) == ["request with [REDACTED] failed"] + + +# --- Final review #6: each home's key is read once a run ------------------------- + +def test_each_homes_key_is_read_once_however_many_tools_log_there(env, backend, monkeypatch): + reads, real = [], setup_cmd._home_device_key + monkeypatch.setattr(setup_cmd, "_home_device_key", lambda home: reads.append(home) or real(home)) + for tool in ("claude-code", "codex", "copilot"): + _log(env["home"], tool, [f"{_utc(0)}: {tool} broke"]) + _run(backend) + assert {r["body"]["hook_source"] for r in _forwarded(backend)} == {"claude-code", "codex", "copilot"} + assert reads == [env["home"]] From 5732c7f65e6482570ca88be4932f06e39f628901 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Wed, 25 Nov 2026 19:29:54 +0530 Subject: [PATCH 30/53] fix(setup): report the claude code settings file actually written, drop-in on windows [WEB-6392] --- claude-code/hooks/mdm/setup.py | 13 +++++++++++-- tests/test_mdm_setup_status.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index dae45def7..8905fd4ea 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -1166,9 +1166,16 @@ def rewrite_gateway_url_in_file(path: Path, gateway_url: str) -> None: path.write_text(new_text, encoding="utf-8") +# The settings file setup_managed_hooks last wrote: managed-settings.json, or on Windows the +# managed-settings.d drop-in when its folder could be made. main reports it as written_to. +_managed_settings_written: Optional[Path] = None + + def setup_managed_hooks(gateway_url: str = DEFAULT_GATEWAY_URL, skip_settings: bool = False) -> bool: """Set up system-wide managed hooks for Claude Code: download unbound.py and configure managed-settings.json. With skip_settings, install only the script.""" + global _managed_settings_written + _managed_settings_written = None system = platform.system().lower() try: managed_dir = get_managed_settings_dir() @@ -1361,6 +1368,7 @@ def _hook(entry: dict) -> dict: if _is_reparse_point(settings_path): raise OSError(f"{settings_path} is a link; refusing to write through it as root") settings_path.write_text(json.dumps(settings, indent=2), encoding="utf-8") + _managed_settings_written = settings_path debug_print(f"Created managed settings: {settings_path}") # Delete the gateway key helper only after the hooks settings are @@ -3560,9 +3568,10 @@ def report(status, reason=None, **fields): print("=" * 60) managed_dir = get_managed_settings_dir() + # The file the write actually went to: on Windows that is the managed-settings.d drop-in. + written = managed_dir / "hooks" / "unbound.py" if skip_managed_settings else _managed_settings_written report("configured", install_state=state, hook_hash=hook_script_hash(managed_dir / "hooks" / "unbound.py"), - written_to=str(managed_dir / "hooks" / "unbound.py" if skip_managed_settings - else managed_dir / "managed-settings.json")) + written_to=str(written) if written else None) if backfill_mode: _run_backfill_bounded(api_key, base_url, get_all_user_homes()) diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py index a1f3ac9de..392a38229 100644 --- a/tests/test_mdm_setup_status.py +++ b/tests/test_mdm_setup_status.py @@ -66,7 +66,11 @@ def writer(self, name, result=True): self.mp.setattr(self.m, name, lambda *a, _n=name, _r=result, **k: self.writes.append(_n) or _r) def _claude_code(self): - self.writer("setup_managed_hooks") + # The real writer, so the report names the file it wrote; only the script download is faked. + real = self.m.setup_managed_hooks + self.mp.setattr(self.m, "setup_managed_hooks", + lambda *a, **k: self.writes.append("setup_managed_hooks") or real(*a, **k)) + self.mp.setattr(self.m, "download_file", lambda url, dest, *a, **k: Path(dest).write_text("# hook") or True) self.stub("_unbound_base_url_matcher", None) def _cursor(self): @@ -212,3 +216,31 @@ def test_a_failure_before_the_key_sends_nothing(run, tool): r.stub("fetch_api_key_from_mdm", None) assert r() is False assert r.reports == [] + + +# --- Claude Code reports the settings file it actually wrote (found on a Windows VM) --- + +REAL_CLAUDE_SETUP_MANAGED_HOOKS = load_module(MODULES["claude-code"]).setup_managed_hooks + + +def _claude_on_windows(run): + r = run("claude-code") + r.mp.setattr(r.m.platform, "system", lambda: "Windows") + r.mp.setattr(r.m, "setup_managed_hooks", REAL_CLAUDE_SETUP_MANAGED_HOOKS) + r.mp.setattr(r.m, "download_file", lambda url, dest, *a, **k: Path(dest).write_text("# hook") or True) + return r + + +def test_claude_code_on_windows_reports_the_drop_in_it_wrote(run): + r = _claude_on_windows(run) + assert r() is True + assert Path(r.report["written_to"]) == r.managed / "managed-settings.d" / "unbound.json" + assert (r.managed / "managed-settings.d" / "unbound.json").is_file() + + +def test_claude_code_on_windows_reports_managed_settings_when_the_drop_in_cannot_be_made(run): + r = _claude_on_windows(run) + (r.managed / "managed-settings.d").write_text("") # a file where the folder would go + assert r() is True + assert Path(r.report["written_to"]) == r.managed / "managed-settings.json" + assert (r.managed / "managed-settings.json").is_file() From c7651d24b1e8bba0c862567e527d0c19c40add26 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 17:36:39 +0530 Subject: [PATCH 31/53] fix(backfill): report a run with an unreadable home as failed [WEB-6392] --- claude-code/hooks/mdm/setup.py | 3 ++- tests/claude_code/hooks/test_backfill_outcome.py | 7 +++++++ .../hooks/test_backfill_uploader_stats_matrix.py | 3 ++- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 8905fd4ea..b4dab0d03 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -2983,7 +2983,8 @@ def out_of_time(self) -> bool: return True def outcome(self, statuses: set) -> str: - if 'failed' in statuses: + # A home whose history could not be read was never processed, so the run did not complete. + if statuses & {'failed', 'unreadable'}: return 'failed' if self.stopped_by_time: return 'stopped_by_time_limit' diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index 989b47c8e..b37e8b49c 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -114,6 +114,13 @@ def test_the_mdm_run_keeps_time_back_for_its_closing_report(self): self.assertEqual([b["sessions"] for b in backend.bodies], [[]]) self.assertEqual([s["outcome"] for s in backend.stats()], ["stopped_by_time_limit"]) + def test_an_mdm_home_whose_history_cannot_be_read_ends_with_failed(self): + for name, unreadable in (("collect fails", patch.object(mdm, "_backfill_collect_sessions", return_value=None)), + ("linked root", patch.object(mdm, "_backfill_root_is_linked", return_value=True))): + with self.subTest(name): + backend = _run(mdm, self._home(("a",)), _Backend(), [unreadable]) + self.assertEqual([s["outcome"] for s in backend.stats()], ["failed"]) + def test_data_uploads_carry_no_outcome(self): for up in (mdm, setup): with self.subTest(up.__name__): diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py index 1189020be..8a3bf9299 100644 --- a/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py +++ b/tests/claude_code/hooks/test_backfill_uploader_stats_matrix.py @@ -357,7 +357,8 @@ def lstat(path, *args, **kwargs): return result bodies = _run(mdm, [alice, bob], [patch("os.lstat", side_effect=lstat), patch.object(mdm.platform, "system", return_value="Windows")]) - self.assertEqual(bodies[-1]["uploader_stats"], _closing(counted)) + # The refused profile's history was never read, so the run reports failed rather than completed. + self.assertEqual(bodies[-1]["uploader_stats"], _closing(counted, outcome="failed")) self.assertEqual(sorted(s["session_id"] for b in bodies for s in b["sessions"]), ["a"]) self.assertEqual(list(hooks.iterdir()), []) self.assertTrue((alice / ".claude" / "hooks" / mdm.BACKFILL_STATE_FILE).exists()) From c8651ce4ecedd936791f0bf7c768f5575b56c804 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 18:14:41 +0530 Subject: [PATCH 32/53] fix(setup): redact every config key and common credential shapes from forwarded hook errors [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 40 +++++++++++++++++++++------- binary/tests/test_setup_reporting.py | 19 +++++++++++++ 2 files changed, 49 insertions(+), 10 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 67b1a650d..3152578a4 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -338,13 +338,29 @@ def _save_forwarded(log: Path, state: str) -> bool: return True -def _post_hook_errors(url, api_key, hook_source, hook_sha, batch) -> str: +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a 4xx), never an entry, so a refusal is about this tool's key and not about what the log holds.""" errors = [{**{k: v for k, v in entry.items() if k != "state"}, - "message": re.sub(r"(?i)\bBearer\s+\S+", "Bearer [REDACTED]", - entry["message"].replace(api_key, "[REDACTED]"))} + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} for entry in batch] code, answer = _post_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, {"Authorization": f"Bearer {api_key}"}) @@ -376,15 +392,18 @@ def _forward_home_errors(m, username, log, send): def _home_device_key(home: Path): - """Runs as the profile's user: the device key in ~/.unbound/config.json, the one its hooks report - errors with, or None before setup first wrote it.""" + """Runs as the profile's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" try: config = json.loads(_read_user_file(home / ".unbound" / "config.json", follow=False).decode("utf-8")) except (OSError, ValueError): return None # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. - key = (config.get("api_key") or config.get("device_token")) if isinstance(config, dict) else None - return key if isinstance(key, str) and key else None + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: @@ -406,11 +425,12 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: continue if str(home_dir) not in keys: keys[str(home_dir)] = _as_user(m, username, _home_device_key, home_dir) - api_key = keys[str(home_dir)] - if not api_key: + found = keys[str(home_dir)] + if not found: continue # no hook here has a key to report with yet + api_key, secrets = found send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", - api_key, hook_source, hook_sha) + api_key, hook_source, hook_sha, secrets=secrets) count, verdict = _forward_home_errors(m, username, log, send) sent += count if verdict == "refused": diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 075199472..1192bf4e0 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -763,6 +763,25 @@ def test_forwarding_uses_and_redacts_the_key_the_hooks_read_first(env, backend): assert _messages(backend) == ["request with [REDACTED] failed"] +def test_the_homes_other_token_and_common_credential_shapes_are_redacted(env, backend): + vendor_key = "sk-" + "fake-" + "0" * 16 # built at runtime so secret scanners skip this fixture + (env["home"] / ".unbound").mkdir(exist_ok=True) + (env["home"] / ".unbound" / "config.json").write_text( + json.dumps({"device_token": "token-key-2", "api_key": "api-key-1"})) + _log(env["home"], "codex", [ + f"{_utc(0)}: old token token-key-2 was refused", + f"{_utc(1)}: header X-API-KEY: hdr-secret-9 and ANTHROPIC_API_KEY=env-secret-8 set", + f"{_utc(2)}: vendor key {vendor_key} leaked", + f"{_utc(3)}: GET https://api.example.com/v1?key=url-secret-7&page=2 failed", + f'{_utc(4)}: config {{"password": "pw-secret-6", "token":"tok-secret-5"}}'], key=None) + _run(backend) + body = json.dumps(_forwarded(backend)[0]["body"]) + for secret in ("token-key-2", "hdr-secret-9", "env-secret-8", vendor_key, + "url-secret-7", "pw-secret-6", "tok-secret-5"): + assert secret not in body, secret + assert _messages(backend)[3] == "GET https://api.example.com/v1?key=[REDACTED]&page=2 failed" + + # --- Final review #6: each home's key is read once a run ------------------------- def test_each_homes_key_is_read_once_however_many_tools_log_there(env, backend, monkeypatch): From 999c0fc8fe787fab09c2ccac76b9519479ee805e Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 18:26:31 +0530 Subject: [PATCH 33/53] fix(setup): keep a hook error log the gateway has not taken across the cursor sweep [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 58 ++++++++++++++++++++++------ binary/tests/test_setup_reporting.py | 15 +++++++ 2 files changed, 61 insertions(+), 12 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 3152578a4..eba213786 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -374,21 +374,45 @@ def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> def _forward_home_errors(m, username, log, send): - """(entries sent, 'sent' or the verdict that stopped it). The place is saved after each accepted - request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" if _as_user(m, username, _writable_dir, log.parent) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") - return 0, "sent" - entries = _as_user(m, username, _unsent_hook_errors, log) or [] + return 0, "sent", False + entries = _as_user(m, username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] verdict = send(batch) if verdict != "sent": - return start, verdict + return start, verdict, False if _as_user(m, username, _save_forwarded, log, batch[-1]["state"]) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") - return start + len(batch), "sent" - return len(entries), "sent" + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def _read_unsent_log(log: Path) -> dict: + """Runs as the profile's user: the log and its forwarded place, by name, to put back after the sweep.""" + kept = {} + for path in (log, log.with_name(FORWARDED_STATE_NAME)): + try: + kept[path.name] = _read_user_file(path, follow=False) + except OSError: + continue + return kept + + +def _restore_unsent_log(log: Path, kept: dict) -> bool: + """Runs as the profile's user: put a log the sweep removed back, with its place, for the next run.""" + if os.path.lexists(log): + return False + log.parent.mkdir(mode=0o700, exist_ok=True) + for name, data in kept.items(): + _replace_user_file(log.with_name(name), data, 0o600) + return True def _home_device_key(home: Path): @@ -412,9 +436,8 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: forwarding for the whole run, so it costs one short timeout; a refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next run retries. user_homes and keys (home to its key, filled as homes are read) come from run(), so each home is found and read once a run.""" - if opts.get("hook_errors_held"): - return relpath, hook_source = _HOOK_ERROR_LOGS[tool] + unsent = opts.setdefault("unsent_hook_logs", []) sent = 0 try: hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] @@ -423,22 +446,27 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: log = home_dir / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue + if opts.get("hook_errors_held"): + unsent.append((username, log)) # the gateway is down: keep it for the next run + continue if str(home_dir) not in keys: keys[str(home_dir)] = _as_user(m, username, _home_device_key, home_dir) found = keys[str(home_dir)] if not found: - continue # no hook here has a key to report with yet + unsent.append((username, log)) # no hook here has a key to report with yet + continue api_key, secrets = found send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", api_key, hook_source, hook_sha, secrets=secrets) - count, verdict = _forward_home_errors(m, username, log, send) + count, verdict, done = _forward_home_errors(m, username, log, send) sent += count + if not done: + unsent.append((username, log)) if verdict == "refused": print(f"[errors] {tool} hook errors in {home_dir} not forwarded (key refused); the next run retries") elif verdict == "down": opts["hook_errors_held"] = True print(f"[errors] {tool} hook errors not forwarded (gateway down); the next run retries") - break except Exception as e: print(f"[errors] {tool} hook errors not forwarded: {e}") if sent: @@ -1941,6 +1969,8 @@ def run(argv) -> int: statuses = {} print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") + # The sweep and Cursor's step remove ~/.cursor/hooks: a log the gateway has not taken is put back after. + kept = [(u, log, _as_user(m0, u, _read_unsent_log, log)) for u, log in opts.get("unsent_hook_logs", [])] statuses["migration"] = migration.run_sweep(tools=opts["tools"]) for tool in opts["tools"]: @@ -1956,6 +1986,10 @@ def run(argv) -> int: except Exception as e: statuses[tool] = ("deferred", f"error: {e}") + for username, log, data in kept: + if data and _as_user(m0, username, _restore_unsent_log, log, data) is not True and not os.path.lexists(log): + print(f"[errors] {log}: unsent hook errors could not be kept for the next run") + print(f"\n{'=' * 60}\n[discovery] coding-tool scan\n{'=' * 60}") try: statuses["discovery"] = _run_discovery(opts) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 1192bf4e0..1ef80fa14 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -710,6 +710,21 @@ def test_cursor_errors_go_out_before_the_sweep_removes_their_log(env, backend): assert [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] == [] +def test_cursor_errors_the_gateway_did_not_take_survive_the_sweep_for_the_next_run(env, backend): + """The sweep still clears ~/.cursor/hooks, but an unsent log is put back so 'the next run retries' holds.""" + _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + ok = backend.answer + backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) + _run(backend) + assert (env["home"] / ".cursor/hooks/error.log").exists() + assert not (env["home"] / ".cursor/hooks/unbound.py").exists() # the rest of the sweep still ran + backend.answer = ok + backend.requests.clear() + _run(backend) + sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] + assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] + + def test_errors_go_out_with_the_key_the_hooks_use(env, backend): """Forwarding runs before any tool fetches its key, so it uses the one the home's hooks report with.""" (env["home"] / ".unbound").mkdir(exist_ok=True) From b4bbbf0e15816fdf7874d7e13e91a57f4393f031 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 18:35:38 +0530 Subject: [PATCH 34/53] fix(backfill): send a failed outcome when the run crashes before its closing report [WEB-6392] --- claude-code/hooks/mdm/setup.py | 16 ++++++++++++++-- claude-code/hooks/setup.py | 11 +++++++++-- tests/claude_code/hooks/test_backfill_outcome.py | 9 +++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index b4dab0d03..477f27479 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3214,7 +3214,7 @@ def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Pat debug_print("UNBOUND_BACKFILL_DISABLED=1 — skipping backfill") return - reported = False + reported, run, previous = False, None, None try: if not user_homes: debug_print("no user homes found — skipping backfill") @@ -3243,7 +3243,19 @@ def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Pat except Exception as e: print(f"[backfill] Skipped due to error: {e}", file=sys.stderr) if user_homes and not reported: - _backfill_save_outcome(user_homes, 'failed') + _backfill_report_crash(run, user_homes, previous) + + +def _backfill_report_crash(run, user_homes, previous) -> None: + """A run that raised before its closing upload sends 'failed' now, with any earlier unsent outcome; what + can't go is saved for the next run.""" + try: + if run is not None: + _backfill_send_outcome(run, user_homes, 'failed', previous) + return + except Exception as e: + debug_print(f"backfill failed outcome not sent: {e}") + _backfill_save_outcome(user_homes, 'failed') def detect_install_state(skip_settings: bool = False) -> Optional[str]: diff --git a/claude-code/hooks/setup.py b/claude-code/hooks/setup.py index d789f0723..0d3e57e80 100644 --- a/claude-code/hooks/setup.py +++ b/claude-code/hooks/setup.py @@ -2128,7 +2128,7 @@ def run_backfill(api_key: str, backend_url: str, config_dir: Path = None) -> Non except (OSError, AttributeError) as e: debug_print(f"lowering backfill priority failed: {e}") - reported = False + reported, previous = False, None try: # The signed-in email and the desktop session cache are keyed off the home # dir; only the transcripts and the cutoff follow the config dir. @@ -2230,7 +2230,14 @@ def _flush(): except Exception as e: print(f"[backfill] Skipped due to error: {e}", file=sys.stderr) if not reported and config_dir is not None: - _backfill_save_outcome(config_dir, 'failed') + # Sent now with any earlier unsent outcome; saved for the next run if it can't go. + try: + if _backfill_uploader_stats is None: + _backfill_uploader_stats = _backfill_empty_stats() + _backfill_send_outcome(api_key, backend_url, config_dir, 'failed', 0, previous) + except Exception as send_error: + debug_print(f"backfill failed outcome not sent: {send_error}") + _backfill_save_outcome(config_dir, 'failed') def _wsl_distros(): diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index b37e8b49c..737d84f49 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -140,6 +140,15 @@ def test_an_outcome_that_could_not_be_sent_is_sent_once_by_the_next_run(self): [third] = _run(up, home, _Backend()).stats() self.assertNotIn("previous_outcome", third) + def test_a_run_that_crashes_sends_failed_in_the_same_run(self): + crashes = {mdm: patch.object(mdm._BackfillRun, "outcome", side_effect=RuntimeError("boom")), + setup: patch.object(setup, "_backfill_read_session", side_effect=RuntimeError("boom"))} + for up, crash in crashes.items(): + with self.subTest(up.__name__): + with redirect_stderr(io.StringIO()): + backend = _run(up, self._home(("a",)), _Backend(), [crash]) + self.assertEqual([s["outcome"] for s in backend.stats()], ["failed"]) + def test_an_mdm_run_killed_before_it_reported_reads_as_stopped_by_time_limit(self): home = self._home(("a",)) From fc0b1efc74c0a78a9d9bb4e870694850886ae255 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 18:45:40 +0530 Subject: [PATCH 35/53] fix(setup): report a tool setup that raises, and a backfill that fails before its run starts [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 52 +++++++++++++------ binary/tests/test_setup_reporting.py | 10 ++++ claude-code/hooks/mdm/setup.py | 9 ++-- .../hooks/test_backfill_outcome.py | 11 ++-- 4 files changed, 56 insertions(+), 26 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index eba213786..3be14c20e 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -235,6 +235,24 @@ def _tool_installed(tool, user_homes) -> bool: return True +def _tool_reporter(opts, m, tool, api_key, **fields): + """This tool's report call, kept in opts so run() can still report a setup that raises after it.""" + report = functools.partial(_report, m, tool, api_key, **fields) + opts.setdefault("tool_reporters", {})[tool] = report + return report + + +def _report_failed_setup(opts, tool, reason) -> tuple: + """A tool's setup raised: send 'deferred' when it got far enough to report, and keep it as the status.""" + report = opts.get("tool_reporters", {}).get(tool) + if report is not None: + try: + return report("deferred", reason) + except Exception as e: + print(f"[{tool}] deferred status not reported: {e}") + return "deferred", reason + + def _report(m, tool, api_key, status, reason=None, installed=True, **fields): """This tool's setup/complete call for the run; returns the (status, reason) it sent. Configured on a Mac without the tool (installed False, from the run's one check) reads skipped: its config is still written, @@ -1382,9 +1400,9 @@ def _setup_claude_code(opts): if not api_key: return ("deferred", "MDM api key fetch failed") skip_settings = opts["skip_managed_settings"] - report = functools.partial(_report, m, "claude-code", api_key, backend_url=base, serial_number=device_id, - installed=opts.get("installed", {}).get("claude-code", True), - install_mode="binary-skip" if skip_settings else "binary") + report = _tool_reporter(opts, m, "claude-code", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("claude-code", True), + install_mode="binary-skip" if skip_settings else "binary") for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "UNBOUND_API_KEY") @@ -1443,9 +1461,9 @@ def _setup_augment(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") - report = functools.partial(_report, m, "augment", api_key, backend_url=base, serial_number=device_id, - installed=opts.get("installed", {}).get("augment", True), - install_mode="binary") + report = _tool_reporter(opts, m, "augment", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("augment", True), + install_mode="binary") # Write the per-user unbound config now (needed by the managed hook). User # hook removal is deferred until the managed write succeeds (parity with @@ -1483,9 +1501,9 @@ def _setup_codex(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") - report = functools.partial(_report, m, "codex", api_key, backend_url=base, serial_number=device_id, - installed=opts.get("installed", {}).get("codex", True), - install_mode="binary") + report = _tool_reporter(opts, m, "codex", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("codex", True), + install_mode="binary") for username, home_dir in m.get_all_user_homes(): m.remove_env_var_from_user(username, home_dir, "OPENAI_API_KEY") @@ -1694,9 +1712,9 @@ def _setup_cursor(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") - report = functools.partial(_report, m, "cursor", api_key, backend_url=base, serial_number=device_id, - installed=opts.get("installed", {}).get("cursor", True), - install_mode="binary") + report = _tool_reporter(opts, m, "cursor", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("cursor", True), + install_mode="binary") config_ok = True for username, home_dir in m.get_all_user_homes(): @@ -1782,9 +1800,9 @@ def _setup_copilot(opts): api_key = m.fetch_api_key_from_mdm(base, opts["app_name"], opts["api_key"], device_id) if not api_key: return ("deferred", "MDM api key fetch failed") - report = functools.partial(_report, m, "copilot", api_key, backend_url=base, serial_number=device_id, - installed=opts.get("installed", {}).get("copilot", True), - install_mode="binary") + report = _tool_reporter(opts, m, "copilot", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("copilot", True), + install_mode="binary") user_homes = m.get_all_user_homes() state = _copilot_detect_state(m, user_homes) @@ -1982,9 +2000,9 @@ def run(argv) -> int: try: statuses[tool] = adapter(opts) except SystemExit as e: - statuses[tool] = ("deferred", f"component exited early: {e}") + statuses[tool] = _report_failed_setup(opts, tool, f"component exited early: {e}") except Exception as e: - statuses[tool] = ("deferred", f"error: {e}") + statuses[tool] = _report_failed_setup(opts, tool, f"error: {e}") for username, log, data in kept: if data and _as_user(m0, username, _restore_unsent_log, log, data) is not True and not os.path.lexists(log): diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 1ef80fa14..c45b682c7 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -175,6 +175,16 @@ def _reports(env, tool): return [k for a, k in env["notified"] if a[1] == TOOL_TYPES[tool]] +def test_a_tool_whose_setup_raises_after_its_key_reports_deferred(env, machine, monkeypatch): + """Otherwise the backend keeps the last run's 'configured' for a tool whose setup just failed.""" + def boom(m): + raise RuntimeError("disk full") + monkeypatch.setattr(setup_cmd, "_write_cursor_enterprise_hooks", boom) + setup_cmd.run(["--api-key", "admin-key"]) + [cursor] = _reports(env, "cursor") + assert (cursor["status"], cursor["reason"]) == ("deferred", "error: disk full") + + def test_every_installed_tool_reports_configured_and_where_it_wrote(env, machine): for relpath in FOOTPRINTS.values(): _install(machine, relpath) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 477f27479..5ecc5b1c6 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3243,19 +3243,18 @@ def run_backfill(api_key: str, backend_url: str, user_homes: List[Tuple[str, Pat except Exception as e: print(f"[backfill] Skipped due to error: {e}", file=sys.stderr) if user_homes and not reported: - _backfill_report_crash(run, user_homes, previous) + _backfill_report_crash(run or _BackfillRun(api_key, backend_url, None, (None, None), time.time()), + user_homes, previous) def _backfill_report_crash(run, user_homes, previous) -> None: """A run that raised before its closing upload sends 'failed' now, with any earlier unsent outcome; what can't go is saved for the next run.""" try: - if run is not None: - _backfill_send_outcome(run, user_homes, 'failed', previous) - return + _backfill_send_outcome(run, user_homes, 'failed', previous) except Exception as e: debug_print(f"backfill failed outcome not sent: {e}") - _backfill_save_outcome(user_homes, 'failed') + _backfill_save_outcome(user_homes, 'failed') def detect_install_state(skip_settings: bool = False) -> Optional[str]: diff --git a/tests/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py index 737d84f49..70d8717f8 100644 --- a/tests/claude_code/hooks/test_backfill_outcome.py +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -141,10 +141,13 @@ def test_an_outcome_that_could_not_be_sent_is_sent_once_by_the_next_run(self): self.assertNotIn("previous_outcome", third) def test_a_run_that_crashes_sends_failed_in_the_same_run(self): - crashes = {mdm: patch.object(mdm._BackfillRun, "outcome", side_effect=RuntimeError("boom")), - setup: patch.object(setup, "_backfill_read_session", side_effect=RuntimeError("boom"))} - for up, crash in crashes.items(): - with self.subTest(up.__name__): + crashes = [("mdm, mid-run", mdm, patch.object(mdm._BackfillRun, "outcome", side_effect=RuntimeError("boom"))), + ("mdm, before the run is set up", mdm, + patch.object(mdm, "get_device_identifier", side_effect=RuntimeError("boom"))), + ("per-user, mid-run", setup, + patch.object(setup, "_backfill_read_session", side_effect=RuntimeError("boom")))] + for name, up, crash in crashes: + with self.subTest(name): with redirect_stderr(io.StringIO()): backend = _run(up, self._home(("a",)), _Backend(), [crash]) self.assertEqual([s["outcome"] for s in backend.stats()], ["failed"]) From f26394be329e75c4b46ddf49bdb0569432d60db6 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Thu, 26 Nov 2026 20:15:36 +0530 Subject: [PATCH 36/53] fix(setup): forward an oversized hook error log from its end and keep it by rename across the sweep [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 54 ++++++++++++++++++++-------- binary/tests/test_setup_reporting.py | 17 +++++++++ 2 files changed, 57 insertions(+), 14 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 3be14c20e..dae2bfc6b 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -289,6 +289,8 @@ def _end_fields(opts, user_homes, warnings) -> dict: # Beside each error.log: " ", the newest entry the gateway accepted and how many entries # stamped exactly then were sent (two can share a stamp, and a request can end between them). FORWARDED_STATE_NAME = ".error_log_forwarded" +# Tools whose error.log lives in a folder the migration sweep and the tool step remove (~/.cursor/hooks). +_SWEPT_HOOK_LOG_TOOLS = ("cursor",) HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten # error.log is the user's to write: per tool and home, a run sends at most the newest 25 (what a hook keeps) # and nothing older than a week, so a flooded or first-seen log costs at most three requests. @@ -326,7 +328,7 @@ def _unsent_hook_errors(log: Path) -> list: floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE last, sent_then = _forwarded_place(log) entries, seen_then, current = [], 0, None - for line in _read_user_file(log, follow=False).decode("utf-8", "replace").splitlines(): + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow if current is not None: @@ -412,24 +414,31 @@ def _forward_home_errors(m, username, log, send): return len(entries), "sent", True -def _read_unsent_log(log: Path) -> dict: - """Runs as the profile's user: the log and its forwarded place, by name, to put back after the sweep.""" - kept = {} +def _set_aside_name(path: Path) -> Path: + return path.parent.parent / f".unbound-unsent-{path.parent.name}-{path.name}" + + +def _set_aside_unsent_log(log: Path) -> list: + """Runs as the profile's user: move the log and its forwarded place out of the folder the sweep removes, + by rename so any size moves. Returns the names moved.""" + moved = [] for path in (log, log.with_name(FORWARDED_STATE_NAME)): try: - kept[path.name] = _read_user_file(path, follow=False) + if os.path.lexists(path): + os.rename(path, _set_aside_name(path)) + moved.append(path.name) except OSError: continue - return kept + return moved -def _restore_unsent_log(log: Path, kept: dict) -> bool: - """Runs as the profile's user: put a log the sweep removed back, with its place, for the next run.""" - if os.path.lexists(log): - return False +def _restore_unsent_log(log: Path, names: list) -> bool: + """Runs as the profile's user: move a set-aside log and its place back for the next run.""" log.parent.mkdir(mode=0o700, exist_ok=True) - for name, data in kept.items(): - _replace_user_file(log.with_name(name), data, 0o600) + for name in names: + path = log.with_name(name) + if not os.path.lexists(path): + os.rename(_set_aside_name(path), path) return True @@ -455,7 +464,8 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: only that home. Either way nothing is marked sent, and the next run retries. user_homes and keys (home to its key, filled as homes are read) come from run(), so each home is found and read once a run.""" relpath, hook_source = _HOOK_ERROR_LOGS[tool] - unsent = opts.setdefault("unsent_hook_logs", []) + # Only a log in a folder the migration sweep removes needs keeping; the others stay where they are. + unsent = opts.setdefault("unsent_hook_logs", []) if tool in _SWEPT_HOOK_LOG_TOOLS else [] sent = 0 try: hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] @@ -1064,6 +1074,22 @@ def _read_user_file(path: Path, follow: bool) -> bytes: return data +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user-owned regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(str(path), flags) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + class _JsonObject(dict): """A parsed JSON object that remembers which keys appeared more than once, and its nesting depth as serde_json reads it, including values a repeated key replaced.""" @@ -1988,7 +2014,7 @@ def run(argv) -> int: print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") # The sweep and Cursor's step remove ~/.cursor/hooks: a log the gateway has not taken is put back after. - kept = [(u, log, _as_user(m0, u, _read_unsent_log, log)) for u, log in opts.get("unsent_hook_logs", [])] + kept = [(u, log, _as_user(m0, u, _set_aside_unsent_log, log)) for u, log in opts.get("unsent_hook_logs", [])] statuses["migration"] = migration.run_sweep(tools=opts["tools"]) for tool in opts["tools"]: diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index c45b682c7..c22fc8beb 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -735,6 +735,23 @@ def test_cursor_errors_the_gateway_did_not_take_survive_the_sweep_for_the_next_r assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] +def test_an_oversized_cursor_log_is_kept_and_its_newest_errors_still_go_out(env, backend): + """Bigger than the 4 MiB read cap: kept across the sweep by moving it, and forwarded from its tail.""" + old = [f"{_pacific(-800000)}: ancient {'x' * 200}"] * 25000 # over 5 MiB, all past the 7-day limit + log = _log(env["home"], "cursor", old + [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + size = log.stat().st_size + assert size > setup_cmd._USER_FILE_MAX_BYTES + ok = backend.answer + backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) + _run(backend) + assert log.exists() and log.stat().st_size == size + backend.answer = ok + backend.requests.clear() + _run(backend) + sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] + assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] + + def test_errors_go_out_with_the_key_the_hooks_use(env, backend): """Forwarding runs before any tool fetches its key, so it uses the one the home's hooks report with.""" (env["home"] / ".unbound").mkdir(exist_ok=True) From 07984f5b54d8d00e67ec9e28c1d08b5f5bd3f490 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 01:22:38 +0530 Subject: [PATCH 37/53] fix(mdm): forward stuck hook errors from the python mdm scripts as the binary does [WEB-6392] --- augment/hooks/mdm/setup.py | 268 ++++++++++++++++ claude-code/hooks/mdm/setup.py | 270 +++++++++++++++- codex/hooks/mdm/setup.py | 268 ++++++++++++++++ copilot/hooks/mdm/setup.py | 269 +++++++++++++++- cursor/mdm/setup.py | 335 +++++++++++++++++++- tests/test_mdm_hook_errors.py | 557 +++++++++++++++++++++++++++++++++ 6 files changed, 1959 insertions(+), 8 deletions(-) create mode 100644 tests/test_mdm_hook_errors.py diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 6f88a9152..37de44590 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -9,9 +9,11 @@ import subprocess import hashlib import json +import re import tempfile import time import urllib.parse +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple, List, Optional, Dict try: @@ -1442,6 +1444,7 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "Augment", "auggie" +HOOK_ERROR_LOG = (".augment/hooks/error.log", "augment_code") # this tool's log under a home, and its hook_source # The Auggie CLI, or the Augment extension alone in VS Code, VS Code Insiders or Cursor. _AUGMENT_EXTENSIONS = tuple(f"{editor}/extensions/augment.vscode-augment-*" for editor in (".vscode", ".vscode-insiders", ".cursor")) @@ -1535,6 +1538,268 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio return True +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then, current = [], 0, None + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None + try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -1644,6 +1909,9 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. + forward_hook_errors(get_all_user_homes(), gateway_url, get_managed_settings_dir() / "hooks" / "unbound.py") + print("\nGetting device identifier...") device_id = get_device_identifier() if not device_id: diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 5ecc5b1c6..e71106610 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -13,7 +13,9 @@ import hashlib import bisect import json -from datetime import datetime, timezone +import re +import tempfile +from datetime import datetime, timedelta, timezone import shlex from pathlib import Path from typing import Tuple, List, Optional, Dict @@ -3297,6 +3299,7 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "Claude Code", "claude" +HOOK_ERROR_LOG = (".claude/hooks/error.log", "claude-code") # this tool's log under a home, and its hook_source # Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. TOOL_FOOTPRINTS = { "darwin": (("Applications/Claude.app",), (".claude/local/claude", ".claude.json", "Applications/Claude.app")), @@ -3391,6 +3394,268 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio return True +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then, current = [], 0, None + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None + try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -3505,6 +3770,9 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. + forward_hook_errors(get_all_user_homes(), gateway_url, get_managed_settings_dir() / "hooks" / "unbound.py") + print("\nGetting device identifier...") device_id = get_device_identifier() if not device_id: diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 7467aacfb..807f9ee66 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -14,7 +14,9 @@ import hashlib import json import shlex +import tempfile from contextlib import contextmanager +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple, List, Optional, Dict try: @@ -2450,6 +2452,7 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "Codex", "codex" +HOOK_ERROR_LOG = (".codex/hooks/error.log", "codex") # this tool's log under a home, and its hook_source _CODEX_HOME_FILES = (".codex/auth.json", ".codex/sessions") # codex's own, never setup's # Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. TOOL_FOOTPRINTS = { @@ -2545,6 +2548,268 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio return True +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then, current = [], 0, None + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None + try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -2655,6 +2920,9 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. + forward_hook_errors(get_all_user_homes(), gateway_url, _installed_hook_script()) + print("\nGetting device identifier...") device_id = get_device_identifier() if not device_id: diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index d6eef376a..8228894b6 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -16,7 +16,7 @@ import json import types import sqlite3 -from datetime import datetime +from datetime import datetime, timedelta, timezone import tempfile import urllib.parse from contextlib import contextmanager @@ -2088,6 +2088,7 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "GitHub Copilot", "copilot" +HOOK_ERROR_LOG = (".copilot/hooks/error.log", "copilot") # this tool's log under a home, and its hook_source # The Copilot CLI; VS Code (Copilot ships in it) or its Copilot extensions; Visual Studio (Copilot ships in # it: the installer's instance registry, as the hook's _vs_installed reads it, and the Copilot chat log its # sweep reads); or the JetBrains Copilot plugin: its own config (the hook and discovery read it) and its @@ -2197,6 +2198,268 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio return True +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then, current = [], 0, None + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None + try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -2892,6 +3155,10 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. + homes = get_all_user_homes() + forward_hook_errors(homes, gateway_url, homes[0][1] / ".copilot" / "hooks" / "unbound.py" if homes else None) + print("\nGetting device identifier...") device_id = get_device_identifier() if not device_id: diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index b7c4f89bc..696658cb2 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -10,7 +10,10 @@ import subprocess import hashlib import json +import re +import tempfile import time +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple, List, Optional try: @@ -1208,6 +1211,7 @@ def hook_script_hash(script_path) -> Optional[str]: TOOL_NAME, TOOL_CLI = "Cursor", "cursor-agent" +HOOK_ERROR_LOG = (".cursor/hooks/error.log", "cursor") # this tool's log under a home, and its hook_source # Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. TOOL_FOOTPRINTS = { "darwin": (("Applications/Cursor.app",), ("Applications/Cursor.app",)), @@ -1303,6 +1307,317 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio return True +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. + A bare timestamp, as written before the count, means every entry stamped then was sent.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0 + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") + return last, sent_then if last else 0 + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then = _forwarded_place(log) + entries, seen_then, current = [], 0, None + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if current is not None: + current["message"] = (current["message"] + "\n" + line)[:2000] + continue + when, current = _log_time(match.group(1)), None + if when is None or when <= floor: + continue + if last is not None and when <= last: + seen_then += when == last + if when < last or seen_then <= sent_then: + continue # sent already + current = {"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY} + entries.append((when, current)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) + entry["state"] = f"{entry['timestamp']} {same}" + return [entry for _, entry in chosen] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None + try: + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer + except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): + return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent + + +# Cursor only: remove_user_level_hooks removes ~/.cursor/hooks, and the error.log in it. A log the gateway +# has not taken all of is moved out of that folder by rename (so any size moves) and put back after. +def _set_aside_name(path: Path) -> Path: + return path.parent.parent / f".unbound-unsent-{path.parent.name}-{path.name}" + + +def _set_aside_unsent_log(log: Path) -> list: + """Runs as the home's user: move the log and its forwarded place out of ~/.cursor/hooks. Returns the + names moved.""" + moved = [] + for path in (log, log.with_name(FORWARDED_STATE_NAME)): + try: + if os.path.lexists(path): + os.replace(path, _set_aside_name(path)) + moved.append(path.name) + except OSError: + continue + return moved + + +def _restore_unsent_log(log: Path, names: list) -> bool: + """Runs as the home's user: move a set-aside log and its place back for the next run.""" + log.parent.mkdir(mode=0o700, exist_ok=True) + for name in names: + path = log.with_name(name) + if not os.path.lexists(path): + os.rename(_set_aside_name(path), path) + return True + + +def keep_unsent_hook_logs(unsent) -> list: + """Set aside each (username, log) not fully sent: [(username, log, names moved)]. Never raises.""" + try: + return [(username, log, _run_as_user(username, _set_aside_unsent_log, log)) for username, log in unsent] + except Exception as e: + print(f"[errors] unsent hook errors not set aside: {e}") + return [] + + +def restore_unsent_hook_logs(kept) -> None: + """Put back what keep_unsent_hook_logs set aside. Never raises.""" + for username, log, names in kept: + try: + if names and _run_as_user(username, _restore_unsent_log, log, names) is not True and not os.path.lexists(log): + print(f"[errors] {log}: unsent hook errors could not be kept for the next run") + except Exception as e: + print(f"[errors] {log}: unsent hook errors could not be kept for the next run: {e}") + + def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -1419,6 +1734,10 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. A log not + # fully sent is kept across remove_user_level_hooks below, which removes ~/.cursor/hooks. + unsent_logs = forward_hook_errors(get_all_user_homes(), gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") + # Get device identifier print("\n🔍 Getting device serial number...") serial_number = get_device_identifier() @@ -1455,12 +1774,16 @@ def report(status, reason=None, **fields): print("\n📝 Writing config for all users...") user_homes = get_all_user_homes() config_count = 0 - for username, home_dir in user_homes: - if write_unbound_config_for_user(username, home_dir, cursor_api_key, urls={"base_url": base_url, "gateway_url": gateway_url, "frontend_url": frontend_url}): - config_count += 1 - remove_user_level_hooks(username, home_dir) - else: - print(f"⚠️ Skipping hook removal for {username}: config write failed") + kept_logs = keep_unsent_hook_logs(unsent_logs) + try: + for username, home_dir in user_homes: + if write_unbound_config_for_user(username, home_dir, cursor_api_key, urls={"base_url": base_url, "gateway_url": gateway_url, "frontend_url": frontend_url}): + config_count += 1 + remove_user_level_hooks(username, home_dir) + else: + print(f"⚠️ Skipping hook removal for {username}: config write failed") + finally: + restore_unsent_hook_logs(kept_logs) if config_count > 0: print(f"✅ Config written for {config_count} user(s)") remove_legacy_key_env() diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py new file mode 100644 index 000000000..f7c04bfeb --- /dev/null +++ b/tests/test_mdm_hook_errors.py @@ -0,0 +1,557 @@ +"""WEB-6392: the python MDM scripts (Linux and Windows) forward each tool's stuck hook errors, as the binary does. + +A hook reports an error at most once a minute and never retries, so the rest wait in its error.log. Each +script's real main() runs over a sandbox home (the Run harness of test_mdm_setup_status) and sends to a real +HTTP server on 127.0.0.1, so the curl requests are the ones a device sends. Every script carries the same +forwarding code, kept equal by the parity tests at the end, so most behaviour is pinned through one tool.""" + +import inspect +import json +import os +import re +import stat +import sys +import threading +from datetime import datetime, timedelta, timezone +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +from tests.conftest import REPO, load_module +from tests.test_mdm_setup_status import MODULES, Run + +ERROR_LOGS = {"claude-code": ".claude/hooks/error.log", "cursor": ".cursor/hooks/error.log", + "codex": ".codex/hooks/error.log", "copilot": ".copilot/hooks/error.log", + "augment": ".augment/hooks/error.log"} +HOOK_SOURCES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", + "augment": "augment_code"} +STATE = ".error_log_forwarded" +OK = {"status": "ok", "success": True, "accepted": 1} +REFUSED = {"success": False, "reason": "invalid_key"} +DEAD_GATEWAY = "http://127.0.0.1:9" + + +class _Recorder(BaseHTTPRequestHandler): + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + try: + body = json.loads(raw.decode("utf-8")) + except ValueError: + body = raw + request = {"path": self.path, "headers": dict(self.headers), "body": body} + self.server.requests.append(request) + status, answer = self.server.answer(request) + data = json.dumps(answer).encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def log_message(self, *args): + pass + + +@pytest.fixture +def gateway(): + server = ThreadingHTTPServer(("127.0.0.1", 0), _Recorder) + server.requests = [] + server.answer = lambda request: (200, OK) + threading.Thread(target=server.serve_forever, daemon=True).start() + server.url = "http://127.0.0.1:%d" % server.server_address[1] + yield server + server.shutdown() + server.server_close() + + +def _like_the_real_run_as_user(username, fn, *args, **kwargs): + """The real one answers None when fn raises in the user's child.""" + try: + return fn(*args, **kwargs) + except Exception: + return None + + +@pytest.fixture +def setup(tmp_path, monkeypatch, gateway): + """One tool's main() over a sandbox home, pointed at the local gateway.""" + def make(tool): + r = Run(tool, tmp_path, monkeypatch) + monkeypatch.setattr(r.m, "_run_as_user", _like_the_real_run_as_user) + point(r, gateway.url) + return r + return make + + +def point(r, gateway_url): + r.mp.setattr(sys, "argv", ["setup.py", "--api-key", "admin-key", "--gateway-url", gateway_url]) + + +REAL_CURSOR_CLEANUP = load_module(MODULES["cursor"]).remove_user_level_hooks + + +def real_cursor_cleanup(r): + """The harness stubs it; these tests need the rmtree of ~/.cursor/hooks it does.""" + r.mp.setattr(r.m, "remove_user_level_hooks", REAL_CURSOR_CLEANUP) + + +def _log(home, tool, lines, key="per-device-key"): + """An error.log for the tool, and (unless key is None) the key a previous run left in the home's config.""" + path = home / ERROR_LOGS[tool] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("".join(line + "\n" for line in lines)) + config = home / ".unbound" / "config.json" + if key is not None and not config.exists(): + config.parent.mkdir(parents=True, exist_ok=True) + config.write_text(json.dumps({"api_key": key, "device_token": key})) + return path + + +# Entries are stamped an hour before the test run, so the seven-day limit never ages them out. +BASE = datetime.now(timezone.utc).replace(microsecond=123) - timedelta(hours=1) + + +def _utc(n, days_ago=0): + return (BASE + timedelta(seconds=n) - timedelta(days=days_ago)).isoformat().replace("+00:00", "Z") + + +def _pacific(n, days_ago=0): + """How Cursor's and Copilot's hooks stamp: local time with its offset.""" + return (BASE + timedelta(seconds=n) - timedelta(days=days_ago)).astimezone(timezone(timedelta(hours=-8))).isoformat() + + +def _forwarded(gateway): + return [r for r in gateway.requests if r["path"] == "/v1/hooks/errors"] + + +def _messages(gateway): + return [e["message"] for r in _forwarded(gateway) for e in r["body"]["errors"]] + + +def _other_home(r, name="bob"): + other = r.home.parent / name + other.mkdir() + r.stub("get_all_user_homes", [("alice", r.home), (name, other)]) + return other + + +# --- Each script forwards its own tool's log ------------------------------------- + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_each_script_sends_only_its_own_tools_errors_newer_than_the_last_sent(setup, gateway, tool): + r = setup(tool) + for other in MODULES: + _log(r.home, other, [f"{_utc(n)}: {other} e{n}" for n in range(3)]) + log = r.home / ERROR_LOGS[tool] + log.with_name(STATE).write_text(_utc(0)) + assert r() is True + [request] = _forwarded(gateway) + # The key the home's hooks report with, not the one this run fetched. + assert request["headers"]["Authorization"] == "Bearer per-device-key" + body = request["body"] + assert (body["hook_source"], body["hook_sha"]) == (HOOK_SOURCES[tool], "h" * 12) + assert [(e["timestamp"], e["message"], e["category"]) for e in body["errors"]] == [ + (_utc(1), f"{tool} e1", "forwarded_error_log"), (_utc(2), f"{tool} e2", "forwarded_error_log")] + assert log.with_name(STATE).read_text() == f"{_utc(2)} 1" + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_an_unreachable_gateway_changes_nothing_about_the_run_and_the_next_run_sends_it_all(setup, gateway, tool): + r = setup(tool) + log = _log(r.home, tool, [f"{_utc(n)}: e{n}" for n in range(3)]) + point(r, DEAD_GATEWAY) + assert r() is True + assert r.report["status"] == "configured" + assert not log.with_name(STATE).exists() + point(r, gateway.url) + assert r() is True + assert _messages(gateway) == ["e0", "e1", "e2"] + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_forwarding_that_fails_never_changes_the_exit_code(setup, gateway, monkeypatch, tool): + r = setup(tool) + _log(r.home, tool, [f"{_utc(0)}: e0"]) + + def broken(*a, **k): + raise RuntimeError("forwarding broke") + + monkeypatch.setattr(r.m, "_forward_home_errors", broken) + assert r() is True + assert r.report["status"] == "configured" + + +def test_errors_go_out_before_this_runs_key_is_fetched(setup, gateway): + """Forwarding needs only the key the home already has, so a failed fetch doesn't hold it back.""" + r = setup("claude-code") + r.stub("fetch_api_key_from_mdm", None) + _log(r.home, "claude-code", [f"{_utc(0)}: e0"]) + assert r() is False + assert _messages(gateway) == ["e0"] + + +# --- Batches, caps and the saved place -------------------------------------------- + +def test_errors_go_ten_to_a_request_and_none_is_sent_twice(setup, gateway): + r = setup("claude-code") + log = _log(r.home, "claude-code", [f"{_utc(n)}: e{n}" for n in range(25)]) + r() + assert [len(req["body"]["errors"]) for req in _forwarded(gateway)] == [10, 10, 5] + assert _messages(gateway) == [f"e{n}" for n in range(25)] + assert log.with_name(STATE).read_text() == f"{_utc(24)} 1" + gateway.requests.clear() + r() + assert _forwarded(gateway) == [] + + +def test_a_flooded_log_sends_only_its_25_newest_and_nothing_older_than_a_week(setup, gateway): + r = setup("claude-code") + old = [f"{_utc(n, days_ago=8)}: old{n}" for n in range(2)] + _log(r.home, "claude-code", old + [f"{_utc(n)}: e{n}" for n in range(30)]) + r() + assert _messages(gateway) == [f"e{n}" for n in range(5, 30)] + assert len(_forwarded(gateway)) == 3 + + +def test_entries_older_than_seven_days_are_never_sent_even_after_an_older_place(setup, gateway): + r = setup("claude-code") + log = _log(r.home, "claude-code", [f"{_utc(0, days_ago=8)}: stale", f"{_utc(1)}: fresh"]) + log.with_name(STATE).write_text(_utc(0, days_ago=9)) + r() + assert _messages(gateway) == ["fresh"] + + +def test_a_gateway_that_fails_stops_forwarding_for_the_run(setup, gateway): + r = setup("claude-code") + other = _other_home(r) + _log(r.home, "claude-code", [f"{_utc(0)}: alice e0"]) + _log(other, "claude-code", [f"{_utc(1)}: bob e1"]) + gateway.answer = lambda request: (503, {}) + assert r() is True + assert len(_forwarded(gateway)) == 1 # one short failure, not one per home + assert not (r.home / ".claude/hooks" / STATE).exists() and not (other / ".claude/hooks" / STATE).exists() + + +def test_a_refused_key_skips_only_that_home(setup, gateway): + r = setup("codex") + other = _other_home(r) + _log(r.home, "codex", [f"{_utc(0)}: alice's codex broke"], key="revoked-key") + _log(other, "codex", [f"{_utc(1)}: bob's codex broke"], key="bob-key") + gateway.answer = lambda request: (200, REFUSED) if request["headers"].get( + "Authorization") == "Bearer revoked-key" else (200, OK) + assert r() is True + assert _messages(gateway) == ["alice's codex broke", "bob's codex broke"] + assert (other / ".codex/hooks" / STATE).exists() + assert not (r.home / ".codex/hooks" / STATE).exists() # refused: retried next run + + +def test_a_4xx_is_a_refusal_and_saves_nothing(setup, gateway): + r = setup("claude-code") + log = _log(r.home, "claude-code", [f"{_utc(0)}: e0"]) + gateway.answer = lambda request: (401, {"error": "unauthorized"}) + assert r() is True + assert len(_forwarded(gateway)) == 1 + assert not log.with_name(STATE).exists() + + +def test_an_entry_sharing_the_last_sent_timestamp_is_still_sent(setup, gateway): + r = setup("claude-code") + same = _utc(9) + _log(r.home, "claude-code", [f"{_utc(n)}: e{n}" for n in range(9)] + [f"{same}: e9", f"{same}: e10"]) + # The batch boundary (ten a request) falls between e9 and e10; the second request fails. + gateway.answer = lambda request: (503, {}) if len(_forwarded(gateway)) == 2 else (200, OK) + r() + assert _messages(gateway) == [f"e{n}" for n in range(11)] # e10 was tried, not taken + gateway.requests.clear() + gateway.answer = lambda request: (200, OK) + r() + assert _messages(gateway) == ["e10"] + gateway.requests.clear() + r() + assert _messages(gateway) == [] + + +def test_a_log_whose_place_cannot_be_saved_is_not_forwarded_run_after_run(setup, gateway): + r = setup("claude-code") + other = _other_home(r) + log = _log(r.home, "claude-code", [f"{_utc(n)}: e{n}" for n in range(3)]) + _log(other, "claude-code", [f"{_utc(5)}: bob's error"]) + log.parent.chmod(0o555) # the user can't write .error_log_forwarded beside it + try: + r() + r() + finally: + log.parent.chmod(0o755) + assert _messages(gateway) == ["bob's error"] # once: bob's place was saved + assert not log.with_name(STATE).exists() + + +def test_a_save_that_fails_after_a_send_stops_that_home(setup, gateway, monkeypatch): + r = setup("claude-code") + _log(r.home, "claude-code", [f"{_utc(n)}: e{n}" for n in range(15)]) + # What the real privilege drop hands back when the write inside it fails. + monkeypatch.setattr(r.m, "_save_forwarded", lambda log, state: None) + r() + # The first ten went out; with their place unsaved the rest wait rather than pile up repeats. + assert [len(req["body"]["errors"]) for req in _forwarded(gateway)] == [10] + + +def test_a_home_with_no_key_yet_forwards_nothing(setup, gateway): + r = setup("claude-code") + other = _other_home(r) + _log(r.home, "claude-code", [f"{_utc(0)}: e0"], key=None) + _log(other, "claude-code", [f"{_utc(1)}: bob's error"]) + r() + assert _messages(gateway) == ["bob's error"] + + +def test_errors_go_out_with_the_key_the_hooks_read_first(setup, gateway): + """The hooks read cfg.get('api_key') or cfg.get('device_token').""" + r = setup("copilot") + (r.home / ".unbound").mkdir() + (r.home / ".unbound" / "config.json").write_text(json.dumps({"device_token": "token-key-2", "api_key": "api-key-1"})) + _log(r.home, "copilot", [f"{_pacific(0)}: request with api-key-1 failed"], key=None) + r() + [request] = _forwarded(gateway) + assert request["headers"]["Authorization"] == "Bearer api-key-1" + assert _messages(gateway) == ["request with [REDACTED] failed"] + + +# --- What reaches the gateway ---------------------------------------------------- + +def test_lines_before_the_first_entry_are_skipped_and_later_ones_continue_it(setup, gateway): + r = setup("claude-code") + _log(r.home, "claude-code", ["not an entry", f"{_utc(5)}: real one", " continued text"]) + r() + assert _messages(gateway) == ["real one\n continued text"] + + +def test_a_multi_line_entry_goes_up_whole_cut_and_redacted(setup, gateway): + r = setup("claude-code") + vendor_key = "sk-" + "live-" + "1" * 12 # built at runtime so secret scanners skip this fixture + _log(r.home, "claude-code", [ + f"{_utc(0)}: Traceback (most recent call last):", + ' File "unbound.py", line 9, in post', + f" Authorization: Bearer {vendor_key}", + "ValueError: boom " + "x" * 3000, + f"{_utc(1)}: next entry", + f"{_utc(2)}: " + "y" * 5000, + ]) + r() + first, second, third = _messages(gateway) + assert first.startswith('Traceback (most recent call last):\n File "unbound.py", line 9, in post\n') + assert "Bearer [REDACTED]" in first and vendor_key not in first + assert len(first) <= 2000 + assert (second, third) == ("next entry", "y" * 2000) + + +def test_the_homes_keys_and_common_credential_shapes_are_redacted(setup, gateway): + r = setup("augment") + vendor_key = "sk-" + "fake-" + "0" * 16 # built at runtime so secret scanners skip this fixture + (r.home / ".unbound").mkdir() + (r.home / ".unbound" / "config.json").write_text(json.dumps({"device_token": "token-key-2", "api_key": "api-key-1"})) + _log(r.home, "augment", [ + f"{_utc(0)}: old token token-key-2 was refused for api-key-1", + f"{_utc(1)}: header X-API-KEY: hdr-secret-9 and ANTHROPIC_API_KEY=env-secret-8 set", + f"{_utc(2)}: vendor key {vendor_key} leaked", + f"{_utc(3)}: GET https://api.example.com/v1?key=url-secret-7&page=2 failed", + f'{_utc(4)}: config {{"password": "pw-secret-6", "token":"tok-secret-5"}}', + f"{_utc(5)}: retry said bearer tok_lower and gave up"], key=None) + r() + body = json.dumps(_forwarded(gateway)[0]["body"]) + for secret in ("token-key-2", "api-key-1", "hdr-secret-9", "env-secret-8", vendor_key, + "url-secret-7", "pw-secret-6", "tok-secret-5", "tok_lower"): + assert secret not in body, secret + messages = _messages(gateway) + assert messages[3] == "GET https://api.example.com/v1?key=[REDACTED]&page=2 failed" + assert messages[5] == "retry said Bearer [REDACTED] and gave up" + + +def test_an_oversized_log_is_read_from_its_end(setup, gateway): + r = setup("claude-code") + old = [f"{_utc(0, days_ago=9)}: ancient {'x' * 200}"] * 25000 # over 5 MiB, all past the 7-day limit + log = _log(r.home, "claude-code", old + [f"{_utc(0)}: broke", f"{_utc(1)}: broke again"]) + assert log.stat().st_size > r.m._USER_FILE_MAX_BYTES + r() + assert _messages(gateway) == ["broke", "broke again"] + + +def test_no_key_reaches_a_curl_command_line(setup, gateway, monkeypatch): + """Any local user can read a process's argv with ps; the headers go in a 0600 file instead.""" + r = setup("claude-code") + real_run, argvs, modes = r.m.subprocess.run, [], [] + + def recording_run(cmd, *a, **k): + if cmd and cmd[0] == "curl": + argvs.append(list(cmd)) + for arg in cmd: + if arg.startswith("@") and os.path.exists(arg[1:]): + modes.append(stat.S_IMODE(os.stat(arg[1:]).st_mode)) + return real_run(cmd, *a, **k) + + monkeypatch.setattr(r.m.subprocess, "run", recording_run) + _log(r.home, "claude-code", [f"{_utc(0)}: e0"]) + assert r() is True + assert argvs, "the run made no curl calls" + assert not [a for argv in argvs for a in argv if "per-device-key" in a] + assert modes and set(modes) == {0o600} + assert _forwarded(gateway)[0]["headers"]["Authorization"] == "Bearer per-device-key" + + +# --- Setup runs as root over paths the user controls ------------------------------ + +def test_an_error_log_that_is_a_link_is_never_read_through(setup, gateway, tmp_path): + r = setup("claude-code") + other = _other_home(r) + # alice points her log at a file she must not be able to make setup read and send. + secret = tmp_path / "root-only.txt" + secret.write_text(f"{_utc(0)}: root secret\n") + log = r.home / ERROR_LOGS["claude-code"] + _log(r.home, "codex", []) # alice's key + log.parent.mkdir(parents=True) + log.symlink_to(secret) + _log(other, "claude-code", [f"{_utc(1)}: bob's error"]) + r() + assert _messages(gateway) == ["bob's error"] + assert not log.with_name(STATE).exists() + + +def test_a_state_file_that_is_a_link_is_replaced_not_followed(setup, gateway, tmp_path): + r = setup("claude-code") + log = _log(r.home, "claude-code", [f"{_utc(0)}: e0", f"{_utc(1)}: e1"]) + # Read through, the link's target would say everything was already sent; written through, it gets overwritten. + victim = tmp_path / "victim.txt" + victim.write_text(_utc(100)) + log.with_name(STATE).symlink_to(victim) + r() + assert _messages(gateway) == ["e0", "e1"] + assert victim.read_text() == _utc(100) + state = log.with_name(STATE) + assert not state.is_symlink() and state.read_text() == f"{_utc(1)} 1" + + +def test_a_config_that_is_a_link_gives_no_key(setup, gateway, tmp_path): + r = setup("claude-code") + elsewhere = tmp_path / "someone-elses-config.json" + elsewhere.write_text(json.dumps({"api_key": "not-this-homes-key"})) + (r.home / ".unbound").mkdir() + (r.home / ".unbound" / "config.json").symlink_to(elsewhere) + _log(r.home, "claude-code", [f"{_utc(0)}: e0"], key=None) + other = _other_home(r) + _log(other, "claude-code", [f"{_utc(1)}: bob's error"]) + r() + assert _messages(gateway) == ["bob's error"] + assert [req["headers"]["Authorization"] for req in _forwarded(gateway)] == ["Bearer per-device-key"] + + +# --- Cursor: its cleanup removes ~/.cursor/hooks, error.log and all ---------------- + +def test_cursor_errors_go_out_before_its_cleanup_removes_their_log(setup, gateway): + r = setup("cursor") + real_cursor_cleanup(r) + _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + assert r() is True + assert not (r.home / ".cursor/hooks").exists() # the cleanup did run + assert _messages(gateway) == ["cursor broke", "cursor broke again"] + # Gone with its log, so nothing can be sent twice. + gateway.requests.clear() + r() + assert _forwarded(gateway) == [] + + +def test_cursor_errors_the_gateway_did_not_take_survive_its_cleanup_for_the_next_run(setup, gateway): + r = setup("cursor") + real_cursor_cleanup(r) + log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + (log.parent / "unbound.py").write_text("# python-era hook") + gateway.answer = lambda request: (503, {}) + assert r() is True + assert log.exists() + assert not (log.parent / "unbound.py").exists() # the rest of the cleanup still ran + assert [p.name for p in (r.home / ".cursor").iterdir()] == ["hooks"] # nothing left set aside + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke", "cursor broke again"] + + +def test_a_partly_sent_cursor_log_keeps_its_place_across_the_cleanup(setup, gateway): + r = setup("cursor") + real_cursor_cleanup(r) + log = _log(r.home, "cursor", [f"{_pacific(n)}: e{n}" for n in range(15)]) + gateway.answer = lambda request: (503, {}) if len(_forwarded(gateway)) == 2 else (200, OK) + r() + assert log.with_name(STATE).read_text() == f"{_pacific(9)} 1" + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == [f"e{n}" for n in range(10, 15)] + + +def test_an_oversized_cursor_log_survives_its_cleanup_whole(setup, gateway): + r = setup("cursor") + real_cursor_cleanup(r) + old = [f"{_pacific(0, days_ago=9)}: ancient {'x' * 200}"] * 25000 # over 5 MiB, all past the 7-day limit + log = _log(r.home, "cursor", old + [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + size = log.stat().st_size + gateway.answer = lambda request: (503, {}) + r() + assert log.exists() and log.stat().st_size == size + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke", "cursor broke again"] + + +def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gateway): + r = setup("cursor") + real_cursor_cleanup(r) + log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke"], key=None) + r() + assert _forwarded(gateway) == [] + assert log.exists() + + +# --- The five copies stay equal, and equal to the binary --------------------------- + +SHARED_FUNCTIONS = ("_log_time", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", + "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", + "_post_hook_errors", "_writable_dir", "_home_device_key", "_forward_home_errors", + "forward_hook_errors") +SHARED_DATA = ("FORWARDED_STATE_NAME", "HOOK_ERRORS_PER_REQUEST", "HOOK_ERRORS_PER_RUN", "HOOK_ERROR_MAX_AGE", + "FORWARDED_ERROR_CATEGORY", "HOOK_ERROR_TIMEOUT_SECONDS", "_HOOK_ERROR_LINE", "_USER_FILE_MAX_BYTES", + "_USER_FILE_FLAGS", "_BEARER", "_NAMED_SECRET", "_URL_SECRET", "_VENDOR_KEY") +# What must read the same as the binary's (setup_cmd), so a Linux or Windows device forwards as a Mac does. +AS_THE_BINARY = ("FORWARDED_STATE_NAME", "HOOK_ERRORS_PER_REQUEST", "HOOK_ERRORS_PER_RUN", "HOOK_ERROR_MAX_AGE", + "FORWARDED_ERROR_CATEGORY", "_HOOK_ERROR_LINE", "_USER_FILE_MAX_BYTES", "_BEARER", "_NAMED_SECRET", + "_URL_SECRET", "_VENDOR_KEY") + + +@pytest.fixture(scope="module") +def binary(): + sys.path.insert(0, str(REPO / "binary" / "src")) + from unbound_hook import setup_cmd + return setup_cmd + + +def _value(module, name): + obj = getattr(module, name) + if isinstance(obj, re.Pattern): + return obj.pattern, obj.flags + return inspect.getsource(obj) if callable(obj) else obj + + +@pytest.mark.parametrize("name", SHARED_FUNCTIONS + SHARED_DATA) +def test_the_five_copies_are_identical(name): + first = _value(load_module(MODULES["claude-code"]), name) + assert all(_value(load_module(MODULES[tool]), name) == first for tool in MODULES), name + + +@pytest.mark.parametrize("name", AS_THE_BINARY) +def test_the_limits_and_redaction_are_the_binarys(binary, name): + assert _value(load_module(MODULES["claude-code"]), name) == _value(binary, name) + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_each_script_forwards_the_log_the_binary_does_for_its_tool(binary, tool): + assert load_module(MODULES[tool]).HOOK_ERROR_LOG == binary._HOOK_ERROR_LOGS[tool] From c3b5498b1d34d1284354bbd871c5ac7d200ee731 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 01:51:54 +0530 Subject: [PATCH 38/53] fix(setup): run claude-code, cursor and augment user checks through a runner that takes the timeout [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 6 +++++- binary/tests/test_setup_reporting.py | 11 +++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index dae2bfc6b..54c32a789 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -1319,7 +1319,11 @@ def _drop_out_of_range(value): def _as_user(m, username, fn, *args): - """The module's _run_as_user, bounded: an answer of None (unknown) after the timeout.""" + """The module's _run_as_user, bounded: an answer of None (unknown) after the timeout. The claude-code, + cursor and augment copies take no timeout (one passed would reach fn and fail every call), so those + checks run through codex's copy, the same privilege drop with the bound.""" + if not hasattr(m, "_RUN_AS_USER_TIMEOUT"): # set only where _run_as_user takes _timeout + m = load_mdm_setup_module("codex") return m._run_as_user(username, fn, *args, _timeout=_USER_CHECK_TIMEOUT) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index c22fc8beb..6f2ed12af 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -523,6 +523,17 @@ def run_as(username, fn, *args, _timeout=None, **kwargs): monkeypatch.setattr(m, "_run_as_user", run_as) +@pytest.mark.parametrize("tool", ["claude-code", "cursor", "codex", "copilot", "augment"]) +def test_a_check_run_as_the_user_answers_through_each_tools_own_runner(tool, monkeypatch): + """setup_cmd hands every tool's module to _as_user, claude-code's included (the error forwarding and + Cursor's log keeping use it). Each module's real _run_as_user must take the bounded call and answer.""" + from unbound_hook._loader import load_mdm_setup_module + m = load_mdm_setup_module(tool) + # The Windows branch runs fn in this process, so the real runner answers without root. + monkeypatch.setattr(m.platform, "system", lambda: "Windows") + assert setup_cmd._as_user(m, "alice", lambda a, b: a + b, 2, 3) == 5 + + def test_an_error_log_that_is_a_link_is_never_read_through(env, backend, monkeypatch, tmp_path): _as_user_like_the_real_one(env, monkeypatch) other = tmp_path / "other-home" From f85c86c3b9785037f43f5110b990e4f6cd99e8fa Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 01:51:55 +0530 Subject: [PATCH 39/53] fix(mdm): hash the copilot hook as a user's file before setup replaces it [WEB-6392] --- copilot/hooks/mdm/setup.py | 8 ++++++-- tests/test_mdm_hook_errors.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 8228894b6..8183f3828 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2080,9 +2080,13 @@ def detect_install_state() -> Optional[str]: def hook_script_hash(script_path) -> Optional[str]: """sha256 of the hook script this run installed, so the backend can tell which - hook version a device is running. None when absent or unreadable.""" + hook version a device is running. None when absent or unreadable. + + The script sits in a user's home, and error forwarding hashes it before this run + replaces it, so it is read as a user's file: not through a link, never a FIFO + or device, and within a size cap.""" try: - return hashlib.sha256(Path(script_path).read_bytes()).hexdigest() + return hashlib.sha256(_read_user_file(Path(script_path))).hexdigest() except Exception: return None diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index f7c04bfeb..8f5d64e3d 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -555,3 +555,31 @@ def test_the_limits_and_redaction_are_the_binarys(binary, name): @pytest.mark.parametrize("tool", sorted(MODULES)) def test_each_script_forwards_the_log_the_binary_does_for_its_tool(binary, tool): assert load_module(MODULES[tool]).HOOK_ERROR_LOG == binary._HOOK_ERROR_LOGS[tool] + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFOs are POSIX") +@pytest.mark.parametrize("tool", ["copilot", "codex"]) +def test_the_hook_hashed_before_install_is_read_as_a_users_file(tool, tmp_path): + """Copilot and codex hash a hook in a user's home, before this run has replaced it, and root reads it. + A FIFO there must not hang the run, and a link must not make root hash a file the user can't read.""" + m = load_module(MODULES[tool]) + hooks = tmp_path / "hooks" + hooks.mkdir() + real = hooks / "real.py" + real.write_bytes(b"print('hook')\n") + assert m.hook_script_hash(real) == "a1000e5bd44e3cdc4bfe2631b9dffa642fa8fd55bc86f07c2823eb7bdd4aacab" + root_only = tmp_path / "root-only.py" + root_only.write_bytes(b"secret\n") + link = hooks / "link.py" + link.symlink_to(root_only) + assert m.hook_script_hash(link) is None + fifo = hooks / "unbound.py" + os.mkfifo(fifo) + answer = [] + reader = threading.Thread(target=lambda: answer.append(m.hook_script_hash(fifo)), daemon=True) + reader.start() + reader.join(5) + if reader.is_alive(): # release the blocked open before failing + os.close(os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)) + pytest.fail("hashing a FIFO blocked the run") + assert answer == [None] From d0fcd16552b310a503634385cd2fb7d111f9056b Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 02:28:04 +0530 Subject: [PATCH 40/53] fix(setup): keep a set-aside cursor log when a hook writes a new one during setup [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 34 ++++++++++++++++++-- binary/tests/test_setup_reporting.py | 37 +++++++++++++++++++++ cursor/mdm/setup.py | 48 +++++++++++++++++++++++++--- tests/test_mdm_hook_errors.py | 32 +++++++++++++++++++ 4 files changed, 144 insertions(+), 7 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 54c32a789..6cff23920 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -432,16 +432,42 @@ def _set_aside_unsent_log(log: Path) -> list: return moved +def _append_user_file(path: Path, data: bytes) -> None: + """Runs as the profile's user: add data to the end of a regular file, on a line of its own.""" + fd = os.open(str(path), os.O_RDWR | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + size = os.fstat(fd).st_size + if size: + os.lseek(fd, size - 1, os.SEEK_SET) + if os.read(fd, 1) != b"\n": + data = b"\n" + data + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + finally: + os.close(fd) + + def _restore_unsent_log(log: Path, names: list) -> bool: - """Runs as the profile's user: move a set-aside log and its place back for the next run.""" + """Runs as the profile's user: move a set-aside log and its place back for the next run. A hook can + write a new log while the old one is aside: its entries go after the set-aside ones, so both are kept.""" log.parent.mkdir(mode=0o700, exist_ok=True) for name in names: path = log.with_name(name) - if not os.path.lexists(path): - os.rename(_set_aside_name(path), path) + if os.path.lexists(path): + if name != log.name: + continue # setup writes the forwarded place, never a hook + _append_user_file(_set_aside_name(path), _read_user_file(path, follow=False)) + os.replace(_set_aside_name(path), path) return True +def _recover_set_aside_log(log: Path) -> bool: + """Runs as the profile's user: put back a log an earlier run set aside and could not restore.""" + return _restore_unsent_log(log, [p.name for p in (log, log.with_name(FORWARDED_STATE_NAME)) + if os.path.lexists(_set_aside_name(p))]) + + def _home_device_key(home: Path): """Runs as the profile's user: (the key its hooks report errors with, every key in ~/.unbound/config.json to redact), or None before setup first wrote it.""" @@ -472,6 +498,8 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: keys = {} if keys is None else keys for username, home_dir in user_homes if user_homes is not None else m.get_all_user_homes(): log = home_dir / relpath if home_dir is not None else None + if log is not None and tool in _SWEPT_HOOK_LOG_TOOLS and os.path.lexists(_set_aside_name(log)): + _as_user(m, username, _recover_set_aside_log, log) # an earlier run could not put it back if log is None or not os.path.lexists(log): continue if opts.get("hook_errors_held"): diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 6f2ed12af..4c3ed0ec2 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -746,6 +746,43 @@ def test_cursor_errors_the_gateway_did_not_take_survive_the_sweep_for_the_next_r assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] +def test_cursor_errors_set_aside_survive_a_new_log_a_hook_writes_during_setup(env, backend, monkeypatch): + """Cursor can run a hook while setup runs: its new error.log and the set-aside one are both kept.""" + _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + ok = backend.answer + backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) + real = setup_cmd._ADAPTERS["cursor"] + + def cursor_runs_a_hook_meanwhile(opts): + status = real(opts) + log = env["home"] / ".cursor/hooks/error.log" + log.parent.mkdir(parents=True, exist_ok=True) + log.write_text(f"{_pacific(2)}: cursor broke during setup\n") + return status + + monkeypatch.setitem(setup_cmd._ADAPTERS, "cursor", cursor_runs_a_hook_meanwhile) + _run(backend) + monkeypatch.setitem(setup_cmd._ADAPTERS, "cursor", real) + backend.answer = ok + backend.requests.clear() + _run(backend) + sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] + assert [e["message"] for r in sent for e in r["body"]["errors"]] == [ + "cursor broke", "cursor broke again", "cursor broke during setup"] + + +def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(env, backend): + """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" + aside = env["home"] / ".cursor" / ".unbound-unsent-hooks-error.log" + _log(env["home"], "cursor", [f"{_pacific(2)}: cursor broke later"]) + aside.write_text(f"{_pacific(0)}: cursor broke\n{_pacific(1)}: cursor broke again\n") + _run(backend) + sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] + assert [e["message"] for r in sent for e in r["body"]["errors"]] == [ + "cursor broke", "cursor broke again", "cursor broke later"] + assert not aside.exists() + + def test_an_oversized_cursor_log_is_kept_and_its_newest_errors_still_go_out(env, backend): """Bigger than the 4 MiB read cap: kept across the sweep by moving it, and forwarded from its tail.""" old = [f"{_pacific(-800000)}: ancient {'x' * 200}"] * 25000 # over 5 MiB, all past the 7-day limit diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 696658cb2..e837a6a92 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1589,16 +1589,54 @@ def _set_aside_unsent_log(log: Path) -> list: return moved +def _append_user_file(path: Path, data: bytes) -> None: + """Runs as the home's user: add data to the end of a regular file, on a line of its own.""" + fd = os.open(str(path), os.O_RDWR | os.O_APPEND | _USER_FILE_FLAGS) + try: + size = os.fstat(fd).st_size + if size: + os.lseek(fd, size - 1, os.SEEK_SET) + if os.read(fd, 1) != b"\n": + data = b"\n" + data + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + finally: + os.close(fd) + + def _restore_unsent_log(log: Path, names: list) -> bool: - """Runs as the home's user: move a set-aside log and its place back for the next run.""" + """Runs as the home's user: move a set-aside log and its place back for the next run. A hook can write + a new log while the old one is aside: its entries go after the set-aside ones, so both are kept.""" log.parent.mkdir(mode=0o700, exist_ok=True) for name in names: path = log.with_name(name) - if not os.path.lexists(path): - os.rename(_set_aside_name(path), path) + if os.path.lexists(path): + if name != log.name: + continue # setup writes the forwarded place, never a hook + _append_user_file(_set_aside_name(path), _read_user_file(path)) + os.replace(_set_aside_name(path), path) return True +def _recover_set_aside_log(log: Path) -> bool: + """Runs as the home's user: put back a log an earlier run set aside and could not restore.""" + return _restore_unsent_log(log, [p.name for p in (log, log.with_name(FORWARDED_STATE_NAME)) + if os.path.lexists(_set_aside_name(p))]) + + +def recover_set_aside_hook_logs(user_homes) -> None: + """Before forwarding: a log an earlier run set aside and could not put back goes back, so it is sent. + Never raises.""" + for username, home_dir in user_homes: + try: + log = Path(home_dir) / HOOK_ERROR_LOG[0] + if os.path.lexists(_set_aside_name(log)): + _run_as_user(username, _recover_set_aside_log, log) + except Exception as e: + print(f"[errors] set-aside hook errors in {home_dir} not put back: {e}") + + def keep_unsent_hook_logs(unsent) -> list: """Set aside each (username, log) not fully sent: [(username, log, names moved)]. Never raises.""" try: @@ -1736,7 +1774,9 @@ def main(): # Before this run changes anything, with the key each home's hooks already report with. A log not # fully sent is kept across remove_user_level_hooks below, which removes ~/.cursor/hooks. - unsent_logs = forward_hook_errors(get_all_user_homes(), gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") + homes = get_all_user_homes() + recover_set_aside_hook_logs(homes) + unsent_logs = forward_hook_errors(homes, gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") # Get device identifier print("\n🔍 Getting device serial number...") diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 8f5d64e3d..4ae196131 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -475,6 +475,38 @@ def test_cursor_errors_the_gateway_did_not_take_survive_its_cleanup_for_the_next assert _messages(gateway) == ["cursor broke", "cursor broke again"] +def test_cursor_errors_set_aside_survive_a_new_log_a_hook_writes_during_its_cleanup(setup, gateway): + """Cursor can run a hook while setup runs: its new error.log and the set-aside one are both kept.""" + r = setup("cursor") + _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + + def cleanup_then_a_hook_writes(username, home_dir): + REAL_CURSOR_CLEANUP(username, home_dir) + log = home_dir / ERROR_LOGS["cursor"] + log.parent.mkdir(parents=True, exist_ok=True) + log.write_text(f"{_pacific(2)}: cursor broke during setup\n") + + r.mp.setattr(r.m, "remove_user_level_hooks", cleanup_then_a_hook_writes) + gateway.answer = lambda request: (503, {}) + assert r() is True + real_cursor_cleanup(r) + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke during setup"] + + +def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(setup, gateway): + """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" + r = setup("cursor") + _log(r.home, "cursor", [f"{_pacific(2)}: cursor broke later"]) + aside = r.home / ".cursor" / ".unbound-unsent-hooks-error.log" + aside.write_text(f"{_pacific(0)}: cursor broke\n{_pacific(1)}: cursor broke again\n") + assert r() is True + assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke later"] + assert not aside.exists() + + def test_a_partly_sent_cursor_log_keeps_its_place_across_the_cleanup(setup, gateway): r = setup("cursor") real_cursor_cleanup(r) From e205c87293643d7573716f2eaf75f76453665fd9 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 02:45:25 +0530 Subject: [PATCH 41/53] fix(setup): keep an unsent cursor log in place when it cannot be set aside before the cleanup [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 5 ++++ binary/tests/test_setup_reporting.py | 17 +++++++++++ cursor/mdm/setup.py | 44 +++++++++++++++++++++++----- tests/test_mdm_hook_errors.py | 18 ++++++++++++ 4 files changed, 76 insertions(+), 8 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 6cff23920..5604bfae1 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -2047,6 +2047,10 @@ def run(argv) -> int: print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") # The sweep and Cursor's step remove ~/.cursor/hooks: a log the gateway has not taken is put back after. kept = [(u, log, _as_user(m0, u, _set_aside_unsent_log, log)) for u, log in opts.get("unsent_hook_logs", [])] + # One the user can't move (they may not be able to write ~/.cursor) stays where it is: Cursor's + # cleanup, which removes ~/.cursor/hooks as root, keeps it. + cursor_hooks = load_mdm_setup_module("cursor").KEEP_UNSENT_HOOK_LOGS if kept else set() + cursor_hooks.update(log for _, log, data in kept if not data and os.path.lexists(log)) statuses["migration"] = migration.run_sweep(tools=opts["tools"]) for tool in opts["tools"]: @@ -2062,6 +2066,7 @@ def run(argv) -> int: except Exception as e: statuses[tool] = _report_failed_setup(opts, tool, f"error: {e}") + cursor_hooks.clear() for username, log, data in kept: if data and _as_user(m0, username, _restore_unsent_log, log, data) is not True and not os.path.lexists(log): print(f"[errors] {log}: unsent hook errors could not be kept for the next run") diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 4c3ed0ec2..d0c012802 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -771,6 +771,23 @@ def cursor_runs_a_hook_meanwhile(opts): "cursor broke", "cursor broke again", "cursor broke during setup"] +def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_the_cleanup(env, backend, monkeypatch): + """The user may not be able to write ~/.cursor (a sudo'd Cursor run leaves it root's), so the move aside + fails; the cleanup, which removes ~/.cursor/hooks as root, then keeps that log and removes the rest.""" + log = _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke"]) + (log.parent / "unbound.py").write_text("# python-era hook") + monkeypatch.setattr(setup_cmd, "_set_aside_unsent_log", lambda log: []) + ok = backend.answer + backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) + _run(backend) + assert sorted(p.name for p in log.parent.iterdir()) == ["error.log"] + backend.answer = ok + backend.requests.clear() + _run(backend) + assert [e["message"] for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor" + for e in r["body"]["errors"]] == ["cursor broke"] + + def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(env, backend): """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" aside = env["home"] / ".cursor" / ".unbound-unsent-hooks-error.log" diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index e837a6a92..6f7131f57 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -418,6 +418,27 @@ def _write(): return True +# Unsent hook error logs this run could not move out of ~/.cursor/hooks before removing it (WEB-6392). +KEEP_UNSENT_HOOK_LOGS = set() + + +def _remove_hooks_dir(hooks_dir: Path) -> None: + """Remove ~/.cursor/hooks, all but an unsent error.log and its forwarded place when one is kept here.""" + import shutil + keep = {log.name for log in KEEP_UNSENT_HOOK_LOGS if log.parent == hooks_dir} + if not keep: + shutil.rmtree(hooks_dir) + return + keep.add(FORWARDED_STATE_NAME) + for entry in os.scandir(hooks_dir): + if entry.name in keep: + continue + if entry.is_dir(follow_symlinks=False): + shutil.rmtree(entry.path) + else: + os.unlink(entry.path) + + def remove_user_level_hooks(username: str, home_dir: Path) -> bool: """Remove user-level Cursor hooks (from normal setup) to prevent duplicate execution.""" hooks_json = home_dir / ".cursor" / "hooks.json" @@ -431,8 +452,7 @@ def remove_user_level_hooks(username: str, home_dir: Path) -> bool: debug_print(f"Failed to remove {hooks_json}: {e}") if hooks_dir.exists(): try: - import shutil - shutil.rmtree(hooks_dir) + _remove_hooks_dir(hooks_dir) removed = True except Exception as e: debug_print(f"Failed to remove {hooks_dir}: {e}") @@ -1638,16 +1658,24 @@ def recover_set_aside_hook_logs(user_homes) -> None: def keep_unsent_hook_logs(unsent) -> list: - """Set aside each (username, log) not fully sent: [(username, log, names moved)]. Never raises.""" - try: - return [(username, log, _run_as_user(username, _set_aside_unsent_log, log)) for username, log in unsent] - except Exception as e: - print(f"[errors] unsent hook errors not set aside: {e}") - return [] + """Set aside each (username, log) not fully sent: [(username, log, names moved)]. A log that can't be + moved (the user may not be able to write ~/.cursor) is kept in place by the cleanup. Never raises.""" + kept = [] + for username, log in unsent: + try: + names = _run_as_user(username, _set_aside_unsent_log, log) + except Exception as e: + print(f"[errors] {log}: unsent hook errors not set aside: {e}") + names = None + if not names and os.path.lexists(log): + KEEP_UNSENT_HOOK_LOGS.add(log) + kept.append((username, log, names)) + return kept def restore_unsent_hook_logs(kept) -> None: """Put back what keep_unsent_hook_logs set aside. Never raises.""" + KEEP_UNSENT_HOOK_LOGS.clear() for username, log, names in kept: try: if names and _run_as_user(username, _restore_unsent_log, log, names) is not True and not os.path.lexists(log): diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 4ae196131..16aac2ec2 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -496,6 +496,24 @@ def cleanup_then_a_hook_writes(username, home_dir): assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke during setup"] +def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_its_cleanup(setup, gateway): + """The user may not be able to write ~/.cursor, so the move aside fails; the cleanup, which removes + ~/.cursor/hooks as root, then keeps that log and removes the rest.""" + r = setup("cursor") + real_cursor_cleanup(r) + log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke"]) + (log.parent / "unbound.py").write_text("# python-era hook") + r.mp.setattr(r.m, "_set_aside_unsent_log", lambda log: []) + gateway.answer = lambda request: (503, {}) + assert r() is True + assert sorted(p.name for p in log.parent.iterdir()) == ["error.log"] + assert r.m.KEEP_UNSENT_HOOK_LOGS == set() + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke"] + + def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(setup, gateway): """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" r = setup("cursor") From 77b7e4bc5b1b3c11a3a42c407f4d2db082f01472 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 03:10:29 +0530 Subject: [PATCH 42/53] fix(mdm): bound every step error forwarding runs as the user, and keep a cursor log whose own move failed [WEB-6392] --- augment/hooks/mdm/setup.py | 36 +++++++++++++--- binary/src/unbound_hook/setup_cmd.py | 2 +- binary/tests/test_setup_reporting.py | 19 +++++++-- claude-code/hooks/mdm/setup.py | 35 ++++++++++++--- codex/hooks/mdm/setup.py | 10 +++-- copilot/hooks/mdm/setup.py | 10 +++-- cursor/mdm/setup.py | 45 ++++++++++++++----- tests/test_mdm_hook_errors.py | 64 +++++++++++++++++++++++++--- 8 files changed, 180 insertions(+), 41 deletions(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 37de44590..7462a4908 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -12,6 +12,8 @@ import re import tempfile import time +import signal +import select import urllib.parse from datetime import datetime, timedelta, timezone from pathlib import Path @@ -165,7 +167,7 @@ def curl_with_auth(auth_headers: List[str], curl_args: List[str], *, pass -def _run_as_user(username, fn, *args, **kwargs): +def _run_as_user(username, fn, *args, _timeout=None, **kwargs): """Fork and execute fn(*args, **kwargs) as the unprivileged user `username`. Returns whatever fn returns on success, or None on failure. @@ -220,7 +222,16 @@ def _run_as_user(username, fn, *args, **kwargs): # A list, not bytes +=: bytes concatenation copies the whole buffer per chunk, # so a multi-GB pickle made this read quadratic and pinned a core past the timeout. chunks = [] + # The child runs as the user, who can pause it: a caller can bound the wait (WEB-6392). + deadline = None if _timeout is None else time.monotonic() + _timeout while True: + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and (remaining <= 0 or not select.select([r_fd], [], [], remaining)[0]): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + break try: chunk = os.read(r_fd, 1 << 20) except OSError: @@ -232,7 +243,18 @@ def _run_as_user(username, fn, *args, **kwargs): data = b''.join(chunks) del chunks try: - _, status = os.waitpid(pid, 0) + if deadline is None: + _, status = os.waitpid(pid, 0) + else: # paused after closing the pipe, it would still hold the wait + while True: + done, status = os.waitpid(pid, os.WNOHANG) + if done: + break + if time.monotonic() > deadline: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + return None + time.sleep(0.05) except OSError: return None if os.WEXITSTATUS(status) != 0: @@ -1554,6 +1576,7 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio # Sentry groups by category: forwarded entries group together, apart from the hook's live reports. FORWARDED_ERROR_CATEGORY = "forwarded_error_log" HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. @@ -1747,10 +1770,10 @@ def _forward_home_errors(username, log, send): """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place is saved after each accepted request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" - if _run_as_user(username, _writable_dir, log.parent) is not True: + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") return 0, "sent", False - entries = _run_as_user(username, _unsent_hook_errors, log) + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) if entries is None: return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): @@ -1758,7 +1781,7 @@ def _forward_home_errors(username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict, False - if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent", False return len(entries), "sent", True @@ -1778,7 +1801,8 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: log = Path(home_dir) / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) if not found: unsent.append((username, log)) # the gateway is down, or no hook here has a key yet continue diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 5604bfae1..9e66b922b 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -2050,7 +2050,7 @@ def run(argv) -> int: # One the user can't move (they may not be able to write ~/.cursor) stays where it is: Cursor's # cleanup, which removes ~/.cursor/hooks as root, keeps it. cursor_hooks = load_mdm_setup_module("cursor").KEEP_UNSENT_HOOK_LOGS if kept else set() - cursor_hooks.update(log for _, log, data in kept if not data and os.path.lexists(log)) + cursor_hooks.update(log for _, log, data in kept if log.name not in (data or ()) and os.path.lexists(log)) statuses["migration"] = migration.run_sweep(tools=opts["tools"]) for tool in opts["tools"]: diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index d0c012802..7f4cf094e 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -771,16 +771,27 @@ def cursor_runs_a_hook_meanwhile(opts): "cursor broke", "cursor broke again", "cursor broke during setup"] -def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_the_cleanup(env, backend, monkeypatch): +@pytest.mark.parametrize("moved", ["nothing", "only its place"]) +def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_the_cleanup(env, backend, monkeypatch, moved): """The user may not be able to write ~/.cursor (a sudo'd Cursor run leaves it root's), so the move aside - fails; the cleanup, which removes ~/.cursor/hooks as root, then keeps that log and removes the rest.""" + fails, for the log or for the log alone; the cleanup, which removes ~/.cursor/hooks as root, then keeps + that log and removes the rest.""" log = _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke"]) (log.parent / "unbound.py").write_text("# python-era hook") - monkeypatch.setattr(setup_cmd, "_set_aside_unsent_log", lambda log: []) + (log.parent / STATE).write_text("2000-01-01T00:00:00 1") + + def set_aside(log): + if moved == "nothing": + return [] + os.rename(log.with_name(STATE), setup_cmd._set_aside_name(log.with_name(STATE))) + return [STATE] + + monkeypatch.setattr(setup_cmd, "_set_aside_unsent_log", set_aside) ok = backend.answer backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) _run(backend) - assert sorted(p.name for p in log.parent.iterdir()) == ["error.log"] + assert "error.log" in [p.name for p in log.parent.iterdir()] + assert not (log.parent / "unbound.py").exists() backend.answer = ok backend.requests.clear() _run(backend) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index e71106610..64140af72 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -6,6 +6,7 @@ import shutil import sys import time +import select import platform import subprocess import signal @@ -87,7 +88,7 @@ def debug_print(message: str) -> None: print(f"[DEBUG] {message}") -def _run_as_user(username, fn, *args, **kwargs): +def _run_as_user(username, fn, *args, _timeout=None, **kwargs): """Fork and execute fn(*args, **kwargs) as the unprivileged user `username`. Returns whatever fn returns on success, or None on failure. @@ -143,7 +144,16 @@ def _run_as_user(username, fn, *args, **kwargs): # A list, not bytes +=: bytes concatenation copies the whole buffer per chunk, # so a multi-GB pickle made this read quadratic and pinned a core past the timeout. chunks = [] + # The child runs as the user, who can pause it: a caller can bound the wait (WEB-6392). + deadline = None if _timeout is None else time.monotonic() + _timeout while True: + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and (remaining <= 0 or not select.select([r_fd], [], [], remaining)[0]): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + break try: chunk = os.read(r_fd, 1 << 20) except OSError: @@ -155,7 +165,18 @@ def _run_as_user(username, fn, *args, **kwargs): data = b''.join(chunks) del chunks try: - _, status = os.waitpid(pid, 0) + if deadline is None: + _, status = os.waitpid(pid, 0) + else: # paused after closing the pipe, it would still hold the wait + while True: + done, status = os.waitpid(pid, os.WNOHANG) + if done: + break + if time.monotonic() > deadline: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + return None + time.sleep(0.05) except OSError: return None if os.WEXITSTATUS(status) != 0: @@ -3410,6 +3431,7 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio # Sentry groups by category: forwarded entries group together, apart from the hook's live reports. FORWARDED_ERROR_CATEGORY = "forwarded_error_log" HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. @@ -3603,10 +3625,10 @@ def _forward_home_errors(username, log, send): """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place is saved after each accepted request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" - if _run_as_user(username, _writable_dir, log.parent) is not True: + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") return 0, "sent", False - entries = _run_as_user(username, _unsent_hook_errors, log) + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) if entries is None: return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): @@ -3614,7 +3636,7 @@ def _forward_home_errors(username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict, False - if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent", False return len(entries), "sent", True @@ -3634,7 +3656,8 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: log = Path(home_dir) / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) if not found: unsent.append((username, log)) # the gateway is down, or no hook here has a key yet continue diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 807f9ee66..84f3d4aff 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2564,6 +2564,7 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio # Sentry groups by category: forwarded entries group together, apart from the hook's live reports. FORWARDED_ERROR_CATEGORY = "forwarded_error_log" HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. @@ -2757,10 +2758,10 @@ def _forward_home_errors(username, log, send): """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place is saved after each accepted request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" - if _run_as_user(username, _writable_dir, log.parent) is not True: + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") return 0, "sent", False - entries = _run_as_user(username, _unsent_hook_errors, log) + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) if entries is None: return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): @@ -2768,7 +2769,7 @@ def _forward_home_errors(username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict, False - if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent", False return len(entries), "sent", True @@ -2788,7 +2789,8 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: log = Path(home_dir) / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) if not found: unsent.append((username, log)) # the gateway is down, or no hook here has a key yet continue diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 8183f3828..04d69bf3d 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2218,6 +2218,7 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio # Sentry groups by category: forwarded entries group together, apart from the hook's live reports. FORWARDED_ERROR_CATEGORY = "forwarded_error_log" HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. @@ -2411,10 +2412,10 @@ def _forward_home_errors(username, log, send): """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place is saved after each accepted request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" - if _run_as_user(username, _writable_dir, log.parent) is not True: + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") return 0, "sent", False - entries = _run_as_user(username, _unsent_hook_errors, log) + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) if entries is None: return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): @@ -2422,7 +2423,7 @@ def _forward_home_errors(username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict, False - if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent", False return len(entries), "sent", True @@ -2442,7 +2443,8 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: log = Path(home_dir) / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) if not found: unsent.append((username, log)) # the gateway is down, or no hook here has a key yet continue diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 6f7131f57..e29bf797b 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -13,6 +13,8 @@ import re import tempfile import time +import signal +import select from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple, List, Optional @@ -56,7 +58,7 @@ def debug_print(message: str) -> None: print(f"[DEBUG] {message}") -def _run_as_user(username, fn, *args, **kwargs): +def _run_as_user(username, fn, *args, _timeout=None, **kwargs): """Fork and execute fn(*args, **kwargs) as the unprivileged user `username`. Returns whatever fn returns on success, or None on failure. @@ -112,7 +114,16 @@ def _run_as_user(username, fn, *args, **kwargs): # A list, not bytes +=: bytes concatenation copies the whole buffer per chunk, # so a multi-GB pickle made this read quadratic and pinned a core past the timeout. chunks = [] + # The child runs as the user, who can pause it: a caller can bound the wait (WEB-6392). + deadline = None if _timeout is None else time.monotonic() + _timeout while True: + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and (remaining <= 0 or not select.select([r_fd], [], [], remaining)[0]): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + break try: chunk = os.read(r_fd, 1 << 20) except OSError: @@ -124,7 +135,18 @@ def _run_as_user(username, fn, *args, **kwargs): data = b''.join(chunks) del chunks try: - _, status = os.waitpid(pid, 0) + if deadline is None: + _, status = os.waitpid(pid, 0) + else: # paused after closing the pipe, it would still hold the wait + while True: + done, status = os.waitpid(pid, os.WNOHANG) + if done: + break + if time.monotonic() > deadline: + os.kill(pid, signal.SIGKILL) + os.waitpid(pid, 0) + return None + time.sleep(0.05) except OSError: return None if os.WEXITSTATUS(status) != 0: @@ -1343,6 +1365,7 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio # Sentry groups by category: forwarded entries group together, apart from the hook's live reports. FORWARDED_ERROR_CATEGORY = "forwarded_error_log" HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this _HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. @@ -1536,10 +1559,10 @@ def _forward_home_errors(username, log, send): """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place is saved after each accepted request; where it can't be saved nothing more is sent, or every run would send the same entries again.""" - if _run_as_user(username, _writable_dir, log.parent) is not True: + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") return 0, "sent", False - entries = _run_as_user(username, _unsent_hook_errors, log) + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) if entries is None: return 0, "sent", False for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): @@ -1547,7 +1570,7 @@ def _forward_home_errors(username, log, send): verdict = send(batch) if verdict != "sent": return start, verdict, False - if _run_as_user(username, _save_forwarded, log, batch[-1]["state"]) is not True: + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") return start + len(batch), "sent", False return len(entries), "sent", True @@ -1567,7 +1590,8 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: log = Path(home_dir) / relpath if home_dir is not None else None if log is None or not os.path.lexists(log): continue - found = None if down else _run_as_user(username, _home_device_key, Path(home_dir)) + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) if not found: unsent.append((username, log)) # the gateway is down, or no hook here has a key yet continue @@ -1652,7 +1676,7 @@ def recover_set_aside_hook_logs(user_homes) -> None: try: log = Path(home_dir) / HOOK_ERROR_LOG[0] if os.path.lexists(_set_aside_name(log)): - _run_as_user(username, _recover_set_aside_log, log) + _run_as_user(username, _recover_set_aside_log, log, _timeout=HOOK_ERROR_USER_TIMEOUT) except Exception as e: print(f"[errors] set-aside hook errors in {home_dir} not put back: {e}") @@ -1663,11 +1687,11 @@ def keep_unsent_hook_logs(unsent) -> list: kept = [] for username, log in unsent: try: - names = _run_as_user(username, _set_aside_unsent_log, log) + names = _run_as_user(username, _set_aside_unsent_log, log, _timeout=HOOK_ERROR_USER_TIMEOUT) except Exception as e: print(f"[errors] {log}: unsent hook errors not set aside: {e}") names = None - if not names and os.path.lexists(log): + if log.name not in (names or ()) and os.path.lexists(log): KEEP_UNSENT_HOOK_LOGS.add(log) kept.append((username, log, names)) return kept @@ -1678,7 +1702,8 @@ def restore_unsent_hook_logs(kept) -> None: KEEP_UNSENT_HOOK_LOGS.clear() for username, log, names in kept: try: - if names and _run_as_user(username, _restore_unsent_log, log, names) is not True and not os.path.lexists(log): + if (names and _run_as_user(username, _restore_unsent_log, log, names, _timeout=HOOK_ERROR_USER_TIMEOUT) + is not True and not os.path.lexists(log)): print(f"[errors] {log}: unsent hook errors could not be kept for the next run") except Exception as e: print(f"[errors] {log}: unsent hook errors could not be kept for the next run: {e}") diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 16aac2ec2..b2ce62e23 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -64,7 +64,7 @@ def gateway(): server.server_close() -def _like_the_real_run_as_user(username, fn, *args, **kwargs): +def _like_the_real_run_as_user(username, fn, *args, _timeout=None, **kwargs): """The real one answers None when fn raises in the user's child.""" try: return fn(*args, **kwargs) @@ -88,6 +88,7 @@ def point(r, gateway_url): REAL_CURSOR_CLEANUP = load_module(MODULES["cursor"]).remove_user_level_hooks +REAL_RUN_AS_USER = {tool: load_module(path)._run_as_user for tool, path in MODULES.items()} def real_cursor_cleanup(r): @@ -496,17 +497,27 @@ def cleanup_then_a_hook_writes(username, home_dir): assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke during setup"] -def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_its_cleanup(setup, gateway): - """The user may not be able to write ~/.cursor, so the move aside fails; the cleanup, which removes - ~/.cursor/hooks as root, then keeps that log and removes the rest.""" +@pytest.mark.parametrize("moved", ["nothing", "only its place"]) +def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_its_cleanup(setup, gateway, moved): + """The user may not be able to write ~/.cursor, so the move aside fails, for the log or for the log + alone; the cleanup, which removes ~/.cursor/hooks as root, then keeps that log and removes the rest.""" r = setup("cursor") real_cursor_cleanup(r) log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke"]) (log.parent / "unbound.py").write_text("# python-era hook") - r.mp.setattr(r.m, "_set_aside_unsent_log", lambda log: []) + (log.parent / STATE).write_text("2000-01-01T00:00:00 1") + + def set_aside(log): + if moved == "nothing": + return [] + os.rename(log.with_name(STATE), r.m._set_aside_name(log.with_name(STATE))) + return [STATE] + + r.mp.setattr(r.m, "_set_aside_unsent_log", set_aside) gateway.answer = lambda request: (503, {}) assert r() is True - assert sorted(p.name for p in log.parent.iterdir()) == ["error.log"] + assert "error.log" in [p.name for p in log.parent.iterdir()] + assert not (log.parent / "unbound.py").exists() assert r.m.KEEP_UNSENT_HOOK_LOGS == set() gateway.answer = lambda request: (200, OK) gateway.requests.clear() @@ -633,3 +644,44 @@ def test_the_hook_hashed_before_install_is_read_as_a_users_file(tool, tmp_path): os.close(os.open(fifo, os.O_WRONLY | os.O_NONBLOCK)) pytest.fail("hashing a FIFO blocked the run") assert answer == [None] + + + +def _fork_as_this_user(monkeypatch, m, tool): + """The real fork-and-drop runner, as a non-root test can run it: the drop to this same user is a no-op.""" + for name in ("setgroups", "setgid", "setuid"): + monkeypatch.setattr(os, name, lambda *a: None) + monkeypatch.setattr(m, "_run_as_user", REAL_RUN_AS_USER[tool]) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="the runner forks on POSIX only") +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_a_step_run_as_the_user_ends_at_its_timeout(tool, monkeypatch): + """The user can pause the child it runs in: a bounded call answers None (unknown) when the time is up.""" + import getpass + import time + m = load_module(MODULES[tool]) + _fork_as_this_user(monkeypatch, m, tool) + monkeypatch.setattr(m.platform, "system", lambda: "Linux") + started = time.monotonic() + assert m._run_as_user(getpass.getuser(), time.sleep, 30, _timeout=1) is None + assert time.monotonic() - started < 10 + assert m._run_as_user(getpass.getuser(), lambda a, b: a + b, 2, 3, _timeout=5) == 5 + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="the runner forks on POSIX only") +def test_forwarding_a_user_pauses_does_not_hold_setup_up(setup, gateway, monkeypatch): + """Forwarding runs before setup fetches its key: a paused read of the user's log ends at the bound.""" + import getpass + import time + r = setup("claude-code") + _fork_as_this_user(monkeypatch, r.m, "claude-code") + r.stub("get_all_user_homes", [(getpass.getuser(), r.home)]) + _log(r.home, "claude-code", [f"{_utc(0)}: claude broke"]) + r.mp.setattr(r.m, "_unsent_hook_errors", lambda log: time.sleep(60)) + r.mp.setattr(r.m, "HOOK_ERROR_USER_TIMEOUT", 1, raising=False) + started = time.monotonic() + assert r() is True + assert time.monotonic() - started < 20 + assert _forwarded(gateway) == [] + From aa983c0e48ab77221feeee7e34a0e26ab94886b3 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 03:19:54 +0530 Subject: [PATCH 43/53] fix(mdm): refuse a user's file reached through a link or junction on windows [WEB-6392] --- augment/hooks/mdm/setup.py | 30 ++++++++++++++++++++++++++ claude-code/hooks/mdm/setup.py | 30 ++++++++++++++++++++++++++ codex/hooks/mdm/setup.py | 30 ++++++++++++++++++++++++++ copilot/hooks/mdm/setup.py | 30 ++++++++++++++++++++++++++ cursor/mdm/setup.py | 31 +++++++++++++++++++++++++++ tests/test_mdm_hook_errors.py | 2 +- tests/test_windows_paths.py | 39 ++++++++++++++++++++++++++++++++++ 7 files changed, 191 insertions(+), 1 deletion(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 7462a4908..8b960433a 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1596,9 +1596,37 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + if not (0 < got < len(final) and 0 < wanted < len(asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): os.close(fd) raise OSError(f"{path} is not a regular file") @@ -1612,6 +1640,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): os.close(fd) @@ -1632,6 +1661,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) try: + _refuse_if_redirected(fd, tmp) with os.fdopen(fd, "wb") as f: f.write(data) os.replace(tmp, path) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 64140af72..a2ca72ca8 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3451,9 +3451,37 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + if not (0 < got < len(final) and 0 < wanted < len(asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): os.close(fd) raise OSError(f"{path} is not a regular file") @@ -3467,6 +3495,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): os.close(fd) @@ -3487,6 +3516,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) try: + _refuse_if_redirected(fd, tmp) with os.fdopen(fd, "wb") as f: f.write(data) os.replace(tmp, path) diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 84f3d4aff..46380861b 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2584,9 +2584,37 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + if not (0 < got < len(final) and 0 < wanted < len(asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): os.close(fd) raise OSError(f"{path} is not a regular file") @@ -2600,6 +2628,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): os.close(fd) @@ -2620,6 +2649,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) try: + _refuse_if_redirected(fd, tmp) with os.fdopen(fd, "wb") as f: f.write(data) os.replace(tmp, path) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 04d69bf3d..5422a8f88 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2238,9 +2238,37 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + if not (0 < got < len(final) and 0 < wanted < len(asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): os.close(fd) raise OSError(f"{path} is not a regular file") @@ -2254,6 +2282,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): os.close(fd) @@ -2274,6 +2303,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) try: + _refuse_if_redirected(fd, tmp) with os.fdopen(fd, "wb") as f: f.write(data) os.replace(tmp, path) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index e29bf797b..8a969349a 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1385,9 +1385,37 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + if not (0 < got < len(final) and 0 < wanted < len(asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): os.close(fd) raise OSError(f"{path} is not a regular file") @@ -1401,6 +1429,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) st = os.fstat(fd) if not stat.S_ISREG(st.st_mode): os.close(fd) @@ -1421,6 +1450,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) try: + _refuse_if_redirected(fd, tmp) with os.fdopen(fd, "wb") as f: f.write(data) os.replace(tmp, path) @@ -1636,6 +1666,7 @@ def _set_aside_unsent_log(log: Path) -> list: def _append_user_file(path: Path, data: bytes) -> None: """Runs as the home's user: add data to the end of a regular file, on a line of its own.""" fd = os.open(str(path), os.O_RDWR | os.O_APPEND | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) try: size = os.fstat(fd).st_size if size: diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index b2ce62e23..5d5f289cf 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -575,7 +575,7 @@ def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gatewa # --- The five copies stay equal, and equal to the binary --------------------------- -SHARED_FUNCTIONS = ("_log_time", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", +SHARED_FUNCTIONS = ("_log_time", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", "_post_hook_errors", "_writable_dir", "_home_device_key", "_forward_home_errors", "forward_hook_errors") diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index bb5ec5f73..e3270b11d 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -187,3 +187,42 @@ def test_a_patch_into_a_spaced_repo_is_judged(self, tmp_path): patch_text = "*** Begin Patch\n*** Update File: %s\n@@\n-a\n+b\n*** End Patch\n" % (spaced / "a.py") candidates = m._repo_gate_candidates("Edit", {"input": patch_text}, str(tmp_path)) assert m._repo_gate_violating_repo(candidates, ALLOWED_ONLY, {}) == "acme/web" + + +# --- WEB-6392: MDM setup runs as SYSTEM and opens users' files itself on Windows --------------------- + +MDM_SCRIPTS = { + "claude-code": "claude-code/hooks/mdm", + "cursor": "cursor/mdm", + "codex": "codex/hooks/mdm", + "copilot": "copilot/hooks/mdm", + "augment": "augment/hooks/mdm", +} + + +@windows_only +@pytest.mark.parametrize("tool", sorted(MDM_SCRIPTS)) +def test_setup_never_reads_or_writes_a_users_file_through_a_junction(tool, tmp_path): + """A user can point their hooks folder at one only SYSTEM can read: error forwarding must not read the + error.log there, nor save its forwarded place there. A file at its own path still reads.""" + import _winapi + m = tool_module(MDM_SCRIPTS[tool], "setup") + private = tmp_path / "private" + private.mkdir() + (private / "error.log").write_text("2026-01-01T00:00:00.000Z: system secret\n") + hooks = tmp_path / "home" / ".cursor" / "hooks" + hooks.parent.mkdir(parents=True) + _winapi.CreateJunction(str(private), str(hooks)) + with pytest.raises(OSError): + m._read_user_file(hooks / "error.log") + with pytest.raises(OSError): + m._read_user_file_tail(hooks / "error.log", 1024) + with pytest.raises(OSError): + m._replace_user_file(hooks / ".error_log_forwarded", b"2026-01-01T00:00:00.000Z 1") + assert sorted(p.name for p in private.iterdir()) == ["error.log"] + plain = tmp_path / "plain.log" + plain.write_bytes(b"ok\n") + assert m._read_user_file(plain) == b"ok\n" + assert m._read_user_file_tail(plain, 1024) == b"ok\n" + m._replace_user_file(tmp_path / "state", b"saved") + assert (tmp_path / "state").read_bytes() == b"saved" From e46bdb9c344b1949ec6c7ac1833df2eab65e3628 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 03:52:10 +0530 Subject: [PATCH 44/53] fix(setup): keep every cursor log across the sweep and refuse hard links on windows [WEB-6392] --- augment/hooks/mdm/setup.py | 3 ++- binary/src/unbound_hook/setup_cmd.py | 18 ++++++-------- binary/tests/test_setup_reporting.py | 37 ++++++++++++++++++++++++---- claude-code/hooks/mdm/setup.py | 3 ++- codex/hooks/mdm/setup.py | 3 ++- copilot/hooks/mdm/setup.py | 3 ++- cursor/mdm/setup.py | 14 +++++++---- tests/test_mdm_hook_errors.py | 33 ++++++++++++++++++++++--- tests/test_windows_paths.py | 3 +++ 9 files changed, 90 insertions(+), 27 deletions(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 8b960433a..f60be0812 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1617,7 +1617,8 @@ def plain(name): got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) - if not (0 < got < len(final) and 0 < wanted < len(asked) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): os.close(fd) raise OSError(f"{path} is reached through a link or junction") diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 9e66b922b..8a675c17a 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -490,8 +490,6 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: only that home. Either way nothing is marked sent, and the next run retries. user_homes and keys (home to its key, filled as homes are read) come from run(), so each home is found and read once a run.""" relpath, hook_source = _HOOK_ERROR_LOGS[tool] - # Only a log in a folder the migration sweep removes needs keeping; the others stay where they are. - unsent = opts.setdefault("unsent_hook_logs", []) if tool in _SWEPT_HOOK_LOG_TOOLS else [] sent = 0 try: hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] @@ -503,21 +501,17 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: if log is None or not os.path.lexists(log): continue if opts.get("hook_errors_held"): - unsent.append((username, log)) # the gateway is down: keep it for the next run - continue + continue # the gateway is down: the next run retries if str(home_dir) not in keys: keys[str(home_dir)] = _as_user(m, username, _home_device_key, home_dir) found = keys[str(home_dir)] if not found: - unsent.append((username, log)) # no hook here has a key to report with yet - continue + continue # no hook here has a key to report with yet api_key, secrets = found send = functools.partial(_post_hook_errors, opts["gateway_url"] + "/v1/hooks/errors", api_key, hook_source, hook_sha, secrets=secrets) - count, verdict, done = _forward_home_errors(m, username, log, send) + count, verdict, _ = _forward_home_errors(m, username, log, send) sent += count - if not done: - unsent.append((username, log)) if verdict == "refused": print(f"[errors] {tool} hook errors in {home_dir} not forwarded (key refused); the next run retries") elif verdict == "down": @@ -2046,7 +2040,11 @@ def run(argv) -> int: print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") # The sweep and Cursor's step remove ~/.cursor/hooks: a log the gateway has not taken is put back after. - kept = [(u, log, _as_user(m0, u, _set_aside_unsent_log, log)) for u, log in opts.get("unsent_hook_logs", [])] + # Every such log is kept across them, sent or not, and listed now: a hook can add an error after + # forwarding read the log (or start one), and the saved place keeps what went out from going again. + swept = [(u, h / _HOOK_ERROR_LOGS[t][0]) for t in opts["tools"] if t in _SWEPT_HOOK_LOG_TOOLS + for u, h in user_homes or [] if h is not None and os.path.lexists(h / _HOOK_ERROR_LOGS[t][0])] + kept = [(u, log, _as_user(m0, u, _set_aside_unsent_log, log)) for u, log in swept] # One the user can't move (they may not be able to write ~/.cursor) stays where it is: Cursor's # cleanup, which removes ~/.cursor/hooks as root, keeps it. cursor_hooks = load_mdm_setup_module("cursor").KEEP_UNSENT_HOOK_LOGS if kept else set() diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 7f4cf094e..fb523864b 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -384,8 +384,8 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, "claude-code": ["bob's claude broke"], "augment_code": ["auggie broke"]} assert (env["home"] / ".copilot/hooks" / STATE).read_text() == f"{_pacific(1)} 1" assert (other / ".claude/hooks" / STATE).exists() and not (env["home"] / ".claude/hooks" / STATE).exists() - # Cursor's setup removes the python-era ~/.cursor/hooks, log and all, after its errors went out. - assert not (env["home"] / ".cursor/hooks").exists() + # Cursor's setup removes the python-era ~/.cursor/hooks; its sent log comes back with its place. + assert sorted(p.name for p in (env["home"] / ".cursor/hooks").iterdir()) == [STATE, "error.log"] def test_lines_before_the_first_entry_are_skipped_and_later_ones_continue_it(env, backend): @@ -718,10 +718,11 @@ def test_installed_tools_are_found_once_before_the_first_report(env, machine, mo def test_cursor_errors_go_out_before_the_sweep_removes_their_log(env, backend): """env's one home belongs to the real user running the tests, so the migration sweep runs on it and - removes ~/.cursor/hooks, error.log and all, before Cursor's own setup step.""" - _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + removes ~/.cursor/hooks before Cursor's own setup step; the log and its place are kept across it.""" + log = _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + (log.parent / "unbound.py").write_text("# python-era hook") _run(backend) - assert not (env["home"] / ".cursor/hooks").exists() # the sweep did run + assert not (log.parent / "unbound.py").exists() # the sweep did run sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] assert sent[0]["headers"]["Authorization"] == "Bearer per-device-key" @@ -746,6 +747,32 @@ def test_cursor_errors_the_gateway_did_not_take_survive_the_sweep_for_the_next_r assert [e["message"] for r in sent for e in r["body"]["errors"]] == ["cursor broke", "cursor broke again"] +@pytest.mark.parametrize("before", [["cursor broke"], []]) +def test_a_cursor_error_written_after_a_full_send_survives_the_sweep(env, backend, monkeypatch, before): + """Everything in the log went out (or there was no log yet), then a hook added an error before the sweep: + that error is kept and goes out next run, and nothing already sent goes again.""" + log = _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke"]) + if not before: + log.unlink() + real = setup_cmd._forward_hook_errors + + def a_hook_writes_after_forwarding(m, tool, *args, **kwargs): + real(m, tool, *args, **kwargs) + if tool == "cursor": + with open(log, "a") as f: + f.write(f"{_pacific(1)}: cursor broke after the send\n") + + monkeypatch.setattr(setup_cmd, "_forward_hook_errors", a_hook_writes_after_forwarding) + _run(backend) + monkeypatch.setattr(setup_cmd, "_forward_hook_errors", real) + assert [e["message"] for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor" + for e in r["body"]["errors"]] == before + backend.requests.clear() + _run(backend) + assert [e["message"] for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor" + for e in r["body"]["errors"]] == ["cursor broke after the send"] + + def test_cursor_errors_set_aside_survive_a_new_log_a_hook_writes_during_setup(env, backend, monkeypatch): """Cursor can run a hook while setup runs: its new error.log and the set-aside one are both kept.""" _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index a2ca72ca8..e460c0974 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3472,7 +3472,8 @@ def plain(name): got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) - if not (0 < got < len(final) and 0 < wanted < len(asked) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): os.close(fd) raise OSError(f"{path} is reached through a link or junction") diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 46380861b..a87633c1b 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2605,7 +2605,8 @@ def plain(name): got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) - if not (0 < got < len(final) and 0 < wanted < len(asked) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): os.close(fd) raise OSError(f"{path} is reached through a link or junction") diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 5422a8f88..67a4b73e5 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2259,7 +2259,8 @@ def plain(name): got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) - if not (0 < got < len(final) and 0 < wanted < len(asked) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): os.close(fd) raise OSError(f"{path} is reached through a link or junction") diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 8a969349a..a537b9d13 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1406,7 +1406,8 @@ def plain(name): got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) - if not (0 < got < len(final) and 0 < wanted < len(asked) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): os.close(fd) raise OSError(f"{path} is reached through a link or junction") @@ -1856,11 +1857,11 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False - # Before this run changes anything, with the key each home's hooks already report with. A log not - # fully sent is kept across remove_user_level_hooks below, which removes ~/.cursor/hooks. + # Before this run changes anything, with the key each home's hooks already report with. The log is kept + # across remove_user_level_hooks below, which removes ~/.cursor/hooks. homes = get_all_user_homes() recover_set_aside_hook_logs(homes) - unsent_logs = forward_hook_errors(homes, gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") + forward_hook_errors(homes, gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") # Get device identifier print("\n🔍 Getting device serial number...") @@ -1898,7 +1899,10 @@ def report(status, reason=None, **fields): print("\n📝 Writing config for all users...") user_homes = get_all_user_homes() config_count = 0 - kept_logs = keep_unsent_hook_logs(unsent_logs) + # Every log is kept across remove_user_level_hooks, sent or not, and listed now: a hook can add an error + # after forwarding read the log (or start one), and the saved place keeps what went out from going again. + kept_logs = keep_unsent_hook_logs([(username, Path(home_dir) / HOOK_ERROR_LOG[0]) for username, home_dir in homes + if home_dir is not None and os.path.lexists(Path(home_dir) / HOOK_ERROR_LOG[0])]) try: for username, home_dir in user_homes: if write_unbound_config_for_user(username, home_dir, cursor_api_key, urls={"base_url": base_url, "gateway_url": gateway_url, "frontend_url": frontend_url}): diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 5d5f289cf..de87b0cb5 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -450,16 +450,43 @@ def test_a_config_that_is_a_link_gives_no_key(setup, gateway, tmp_path): def test_cursor_errors_go_out_before_its_cleanup_removes_their_log(setup, gateway): r = setup("cursor") real_cursor_cleanup(r) - _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) + (log.parent / "unbound.py").write_text("# python-era hook") assert r() is True - assert not (r.home / ".cursor/hooks").exists() # the cleanup did run + assert not (log.parent / "unbound.py").exists() # the cleanup did run assert _messages(gateway) == ["cursor broke", "cursor broke again"] - # Gone with its log, so nothing can be sent twice. + # Kept with its forwarded place, so nothing is sent twice. gateway.requests.clear() r() assert _forwarded(gateway) == [] +@pytest.mark.parametrize("before", [["cursor broke"], []]) +def test_a_cursor_error_written_after_a_full_send_survives_its_cleanup(setup, gateway, before): + """Everything in the log went out (or there was no log yet), then a hook added an error before the + cleanup: that error is kept and goes out next run, and nothing already sent goes again.""" + r = setup("cursor") + real_cursor_cleanup(r) + log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke"]) + if not before: + log.unlink() + real = r.m.forward_hook_errors + + def a_hook_writes_after_forwarding(*args): + unsent = real(*args) + with open(log, "a") as f: + f.write(f"{_pacific(1)}: cursor broke after the send\n") + return unsent + + r.mp.setattr(r.m, "forward_hook_errors", a_hook_writes_after_forwarding) + assert r() is True + r.mp.setattr(r.m, "forward_hook_errors", real) + assert _messages(gateway) == before + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke after the send"] + + def test_cursor_errors_the_gateway_did_not_take_survive_its_cleanup_for_the_next_run(setup, gateway): r = setup("cursor") real_cursor_cleanup(r) diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index e3270b11d..9dccd7dd9 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -220,6 +220,9 @@ def test_setup_never_reads_or_writes_a_users_file_through_a_junction(tool, tmp_p with pytest.raises(OSError): m._replace_user_file(hooks / ".error_log_forwarded", b"2026-01-01T00:00:00.000Z 1") assert sorted(p.name for p in private.iterdir()) == ["error.log"] + os.link(private / "error.log", hooks.parent / "hard-linked.log") # a second name for the same file + with pytest.raises(OSError): + m._read_user_file(hooks.parent / "hard-linked.log") plain = tmp_path / "plain.log" plain.write_bytes(b"ok\n") assert m._read_user_file(plain) == b"ok\n" From 2b03cdff67f28b26e266f82445e327371859d85d Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 04:06:28 +0530 Subject: [PATCH 45/53] refactor(setup): keep the cursor error log in place through cleanup instead of moving it aside [WEB-6392] --- augment/hooks/mdm/setup.py | 18 ++++ binary/src/unbound_hook/setup_cmd.py | 77 +------------ binary/tests/test_setup_reporting.py | 47 +------- claude-code/hooks/mdm/setup.py | 18 ++++ codex/hooks/mdm/setup.py | 18 ++++ copilot/hooks/mdm/setup.py | 18 ++++ cursor/mdm/setup.py | 156 ++++++--------------------- tests/test_mdm_hook_errors.py | 50 ++------- 8 files changed, 116 insertions(+), 286 deletions(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index f60be0812..3b3e4a018 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1596,6 +1596,21 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + def _refuse_if_redirected(fd: int, path: Path) -> None: """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" @@ -1626,6 +1641,7 @@ def plain(name): def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -1640,6 +1656,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) st = os.fstat(fd) @@ -1658,6 +1675,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written through, and a failed write leaves the old file in place.""" tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 8a675c17a..a305eba76 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -289,8 +289,6 @@ def _end_fields(opts, user_homes, warnings) -> dict: # Beside each error.log: " ", the newest entry the gateway accepted and how many entries # stamped exactly then were sent (two can share a stamp, and a request can end between them). FORWARDED_STATE_NAME = ".error_log_forwarded" -# Tools whose error.log lives in a folder the migration sweep and the tool step remove (~/.cursor/hooks). -_SWEPT_HOOK_LOG_TOOLS = ("cursor",) HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten # error.log is the user's to write: per tool and home, a run sends at most the newest 25 (what a hook keeps) # and nothing older than a week, so a flooded or first-seen log costs at most three requests. @@ -414,60 +412,6 @@ def _forward_home_errors(m, username, log, send): return len(entries), "sent", True -def _set_aside_name(path: Path) -> Path: - return path.parent.parent / f".unbound-unsent-{path.parent.name}-{path.name}" - - -def _set_aside_unsent_log(log: Path) -> list: - """Runs as the profile's user: move the log and its forwarded place out of the folder the sweep removes, - by rename so any size moves. Returns the names moved.""" - moved = [] - for path in (log, log.with_name(FORWARDED_STATE_NAME)): - try: - if os.path.lexists(path): - os.rename(path, _set_aside_name(path)) - moved.append(path.name) - except OSError: - continue - return moved - - -def _append_user_file(path: Path, data: bytes) -> None: - """Runs as the profile's user: add data to the end of a regular file, on a line of its own.""" - fd = os.open(str(path), os.O_RDWR | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) - try: - size = os.fstat(fd).st_size - if size: - os.lseek(fd, size - 1, os.SEEK_SET) - if os.read(fd, 1) != b"\n": - data = b"\n" + data - view = memoryview(data) - while view: - view = view[os.write(fd, view):] - finally: - os.close(fd) - - -def _restore_unsent_log(log: Path, names: list) -> bool: - """Runs as the profile's user: move a set-aside log and its place back for the next run. A hook can - write a new log while the old one is aside: its entries go after the set-aside ones, so both are kept.""" - log.parent.mkdir(mode=0o700, exist_ok=True) - for name in names: - path = log.with_name(name) - if os.path.lexists(path): - if name != log.name: - continue # setup writes the forwarded place, never a hook - _append_user_file(_set_aside_name(path), _read_user_file(path, follow=False)) - os.replace(_set_aside_name(path), path) - return True - - -def _recover_set_aside_log(log: Path) -> bool: - """Runs as the profile's user: put back a log an earlier run set aside and could not restore.""" - return _restore_unsent_log(log, [p.name for p in (log, log.with_name(FORWARDED_STATE_NAME)) - if os.path.lexists(_set_aside_name(p))]) - - def _home_device_key(home: Path): """Runs as the profile's user: (the key its hooks report errors with, every key in ~/.unbound/config.json to redact), or None before setup first wrote it.""" @@ -485,7 +429,7 @@ def _home_device_key(home: Path): def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: """Forward every home's unsent error.log entries for this tool, with that home's own device key. Runs - before the migration sweep, which removes ~/.cursor/hooks and its log. A gateway that is down ends + before the migration sweep and the tool steps. A gateway that is down ends forwarding for the whole run, so it costs one short timeout; a refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next run retries. user_homes and keys (home to its key, filled as homes are read) come from run(), so each home is found and read once a run.""" @@ -496,8 +440,6 @@ def _forward_hook_errors(m, tool, opts, user_homes=None, keys=None) -> None: keys = {} if keys is None else keys for username, home_dir in user_homes if user_homes is not None else m.get_all_user_homes(): log = home_dir / relpath if home_dir is not None else None - if log is not None and tool in _SWEPT_HOOK_LOG_TOOLS and os.path.lexists(_set_aside_name(log)): - _as_user(m, username, _recover_set_aside_log, log) # an earlier run could not put it back if log is None or not os.path.lexists(log): continue if opts.get("hook_errors_held"): @@ -2039,16 +1981,8 @@ def run(argv) -> int: statuses = {} print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") - # The sweep and Cursor's step remove ~/.cursor/hooks: a log the gateway has not taken is put back after. - # Every such log is kept across them, sent or not, and listed now: a hook can add an error after - # forwarding read the log (or start one), and the saved place keeps what went out from going again. - swept = [(u, h / _HOOK_ERROR_LOGS[t][0]) for t in opts["tools"] if t in _SWEPT_HOOK_LOG_TOOLS - for u, h in user_homes or [] if h is not None and os.path.lexists(h / _HOOK_ERROR_LOGS[t][0])] - kept = [(u, log, _as_user(m0, u, _set_aside_unsent_log, log)) for u, log in swept] - # One the user can't move (they may not be able to write ~/.cursor) stays where it is: Cursor's - # cleanup, which removes ~/.cursor/hooks as root, keeps it. - cursor_hooks = load_mdm_setup_module("cursor").KEEP_UNSENT_HOOK_LOGS if kept else set() - cursor_hooks.update(log for _, log, data in kept if log.name not in (data or ()) and os.path.lexists(log)) + # Cursor's step clears ~/.cursor/hooks but keeps error.log and its forwarded place, so what the gateway + # has not taken, or a hook writes during the run, goes out on a later run and nothing goes twice. statuses["migration"] = migration.run_sweep(tools=opts["tools"]) for tool in opts["tools"]: @@ -2064,11 +1998,6 @@ def run(argv) -> int: except Exception as e: statuses[tool] = _report_failed_setup(opts, tool, f"error: {e}") - cursor_hooks.clear() - for username, log, data in kept: - if data and _as_user(m0, username, _restore_unsent_log, log, data) is not True and not os.path.lexists(log): - print(f"[errors] {log}: unsent hook errors could not be kept for the next run") - print(f"\n{'=' * 60}\n[discovery] coding-tool scan\n{'=' * 60}") try: statuses["discovery"] = _run_discovery(opts) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index fb523864b..224c8faa3 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -773,8 +773,8 @@ def a_hook_writes_after_forwarding(m, tool, *args, **kwargs): for e in r["body"]["errors"]] == ["cursor broke after the send"] -def test_cursor_errors_set_aside_survive_a_new_log_a_hook_writes_during_setup(env, backend, monkeypatch): - """Cursor can run a hook while setup runs: its new error.log and the set-aside one are both kept.""" +def test_cursor_errors_unsent_survive_an_error_a_hook_writes_during_setup(env, backend, monkeypatch): + """Cursor can run a hook while setup runs: what it adds and what the gateway had not taken both go out.""" _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) ok = backend.answer backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) @@ -784,7 +784,8 @@ def cursor_runs_a_hook_meanwhile(opts): status = real(opts) log = env["home"] / ".cursor/hooks/error.log" log.parent.mkdir(parents=True, exist_ok=True) - log.write_text(f"{_pacific(2)}: cursor broke during setup\n") + with open(log, "a") as f: # a hook appends to its log + f.write(f"{_pacific(2)}: cursor broke during setup\n") return status monkeypatch.setitem(setup_cmd._ADAPTERS, "cursor", cursor_runs_a_hook_meanwhile) @@ -798,46 +799,6 @@ def cursor_runs_a_hook_meanwhile(opts): "cursor broke", "cursor broke again", "cursor broke during setup"] -@pytest.mark.parametrize("moved", ["nothing", "only its place"]) -def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_the_cleanup(env, backend, monkeypatch, moved): - """The user may not be able to write ~/.cursor (a sudo'd Cursor run leaves it root's), so the move aside - fails, for the log or for the log alone; the cleanup, which removes ~/.cursor/hooks as root, then keeps - that log and removes the rest.""" - log = _log(env["home"], "cursor", [f"{_pacific(0)}: cursor broke"]) - (log.parent / "unbound.py").write_text("# python-era hook") - (log.parent / STATE).write_text("2000-01-01T00:00:00 1") - - def set_aside(log): - if moved == "nothing": - return [] - os.rename(log.with_name(STATE), setup_cmd._set_aside_name(log.with_name(STATE))) - return [STATE] - - monkeypatch.setattr(setup_cmd, "_set_aside_unsent_log", set_aside) - ok = backend.answer - backend.answer = lambda path: (503, {}) if "/v1/hooks/errors" in path else ok(path) - _run(backend) - assert "error.log" in [p.name for p in log.parent.iterdir()] - assert not (log.parent / "unbound.py").exists() - backend.answer = ok - backend.requests.clear() - _run(backend) - assert [e["message"] for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor" - for e in r["body"]["errors"]] == ["cursor broke"] - - -def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(env, backend): - """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" - aside = env["home"] / ".cursor" / ".unbound-unsent-hooks-error.log" - _log(env["home"], "cursor", [f"{_pacific(2)}: cursor broke later"]) - aside.write_text(f"{_pacific(0)}: cursor broke\n{_pacific(1)}: cursor broke again\n") - _run(backend) - sent = [r for r in _forwarded(backend) if r["body"]["hook_source"] == "cursor"] - assert [e["message"] for r in sent for e in r["body"]["errors"]] == [ - "cursor broke", "cursor broke again", "cursor broke later"] - assert not aside.exists() - - def test_an_oversized_cursor_log_is_kept_and_its_newest_errors_still_go_out(env, backend): """Bigger than the 4 MiB read cap: kept across the sweep by moving it, and forwarded from its tail.""" old = [f"{_pacific(-800000)}: ancient {'x' * 200}"] * 25000 # over 5 MiB, all past the 7-day limit diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index e460c0974..754d05b72 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3451,6 +3451,21 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + def _refuse_if_redirected(fd: int, path: Path) -> None: """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" @@ -3481,6 +3496,7 @@ def plain(name): def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -3495,6 +3511,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) st = os.fstat(fd) @@ -3513,6 +3530,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written through, and a failed write leaves the old file in place.""" tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index a87633c1b..5c3935bfe 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2584,6 +2584,21 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + def _refuse_if_redirected(fd: int, path: Path) -> None: """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" @@ -2614,6 +2629,7 @@ def plain(name): def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -2628,6 +2644,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) st = os.fstat(fd) @@ -2646,6 +2663,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written through, and a failed write leaves the old file in place.""" tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 67a4b73e5..95cdf2ae1 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2238,6 +2238,21 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + def _refuse_if_redirected(fd: int, path: Path) -> None: """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" @@ -2268,6 +2283,7 @@ def plain(name): def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -2282,6 +2298,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) st = os.fstat(fd) @@ -2300,6 +2317,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written through, and a failed write leaves the old file in place.""" tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index a537b9d13..b4ff7ab40 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -440,18 +440,11 @@ def _write(): return True -# Unsent hook error logs this run could not move out of ~/.cursor/hooks before removing it (WEB-6392). -KEEP_UNSENT_HOOK_LOGS = set() - - def _remove_hooks_dir(hooks_dir: Path) -> None: - """Remove ~/.cursor/hooks, all but an unsent error.log and its forwarded place when one is kept here.""" + """Remove ~/.cursor/hooks, all but its error.log and the log's forwarded place (WEB-6392): errors the + gateway has not taken, or a hook writes while setup runs, go out on a later run, and nothing twice.""" import shutil - keep = {log.name for log in KEEP_UNSENT_HOOK_LOGS if log.parent == hooks_dir} - if not keep: - shutil.rmtree(hooks_dir) - return - keep.add(FORWARDED_STATE_NAME) + keep = {Path(HOOK_ERROR_LOG[0]).name, FORWARDED_STATE_NAME} for entry in os.scandir(hooks_dir): if entry.name in keep: continue @@ -459,6 +452,8 @@ def _remove_hooks_dir(hooks_dir: Path) -> None: shutil.rmtree(entry.path) else: os.unlink(entry.path) + if not any(os.scandir(hooks_dir)): + os.rmdir(hooks_dir) def remove_user_level_hooks(username: str, home_dir: Path) -> bool: @@ -1385,6 +1380,21 @@ def _log_time(text): return when if when.tzinfo else None +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + def _refuse_if_redirected(fd: int, path: Path) -> None: """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" @@ -1415,6 +1425,7 @@ def plain(name): def _read_user_file(path: Path) -> bytes: """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) if not stat.S_ISREG(os.fstat(fd).st_mode): @@ -1429,6 +1440,7 @@ def _read_user_file(path: Path) -> bytes: def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) _refuse_if_redirected(fd, path) st = os.fstat(fd) @@ -1447,6 +1459,7 @@ def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written through, and a failed write leaves the old file in place.""" tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): tmp.unlink() fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) @@ -1644,103 +1657,6 @@ def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: return unsent -# Cursor only: remove_user_level_hooks removes ~/.cursor/hooks, and the error.log in it. A log the gateway -# has not taken all of is moved out of that folder by rename (so any size moves) and put back after. -def _set_aside_name(path: Path) -> Path: - return path.parent.parent / f".unbound-unsent-{path.parent.name}-{path.name}" - - -def _set_aside_unsent_log(log: Path) -> list: - """Runs as the home's user: move the log and its forwarded place out of ~/.cursor/hooks. Returns the - names moved.""" - moved = [] - for path in (log, log.with_name(FORWARDED_STATE_NAME)): - try: - if os.path.lexists(path): - os.replace(path, _set_aside_name(path)) - moved.append(path.name) - except OSError: - continue - return moved - - -def _append_user_file(path: Path, data: bytes) -> None: - """Runs as the home's user: add data to the end of a regular file, on a line of its own.""" - fd = os.open(str(path), os.O_RDWR | os.O_APPEND | _USER_FILE_FLAGS) - _refuse_if_redirected(fd, path) - try: - size = os.fstat(fd).st_size - if size: - os.lseek(fd, size - 1, os.SEEK_SET) - if os.read(fd, 1) != b"\n": - data = b"\n" + data - view = memoryview(data) - while view: - view = view[os.write(fd, view):] - finally: - os.close(fd) - - -def _restore_unsent_log(log: Path, names: list) -> bool: - """Runs as the home's user: move a set-aside log and its place back for the next run. A hook can write - a new log while the old one is aside: its entries go after the set-aside ones, so both are kept.""" - log.parent.mkdir(mode=0o700, exist_ok=True) - for name in names: - path = log.with_name(name) - if os.path.lexists(path): - if name != log.name: - continue # setup writes the forwarded place, never a hook - _append_user_file(_set_aside_name(path), _read_user_file(path)) - os.replace(_set_aside_name(path), path) - return True - - -def _recover_set_aside_log(log: Path) -> bool: - """Runs as the home's user: put back a log an earlier run set aside and could not restore.""" - return _restore_unsent_log(log, [p.name for p in (log, log.with_name(FORWARDED_STATE_NAME)) - if os.path.lexists(_set_aside_name(p))]) - - -def recover_set_aside_hook_logs(user_homes) -> None: - """Before forwarding: a log an earlier run set aside and could not put back goes back, so it is sent. - Never raises.""" - for username, home_dir in user_homes: - try: - log = Path(home_dir) / HOOK_ERROR_LOG[0] - if os.path.lexists(_set_aside_name(log)): - _run_as_user(username, _recover_set_aside_log, log, _timeout=HOOK_ERROR_USER_TIMEOUT) - except Exception as e: - print(f"[errors] set-aside hook errors in {home_dir} not put back: {e}") - - -def keep_unsent_hook_logs(unsent) -> list: - """Set aside each (username, log) not fully sent: [(username, log, names moved)]. A log that can't be - moved (the user may not be able to write ~/.cursor) is kept in place by the cleanup. Never raises.""" - kept = [] - for username, log in unsent: - try: - names = _run_as_user(username, _set_aside_unsent_log, log, _timeout=HOOK_ERROR_USER_TIMEOUT) - except Exception as e: - print(f"[errors] {log}: unsent hook errors not set aside: {e}") - names = None - if log.name not in (names or ()) and os.path.lexists(log): - KEEP_UNSENT_HOOK_LOGS.add(log) - kept.append((username, log, names)) - return kept - - -def restore_unsent_hook_logs(kept) -> None: - """Put back what keep_unsent_hook_logs set aside. Never raises.""" - KEEP_UNSENT_HOOK_LOGS.clear() - for username, log, names in kept: - try: - if (names and _run_as_user(username, _restore_unsent_log, log, names, _timeout=HOOK_ERROR_USER_TIMEOUT) - is not True and not os.path.lexists(log)): - print(f"[errors] {log}: unsent hook errors could not be kept for the next run") - except Exception as e: - print(f"[errors] {log}: unsent hook errors could not be kept for the next run: {e}") - - def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, hook_hash: Optional[str] = None, install_mode: Optional[str] = None, status: Optional[str] = None, reason: Optional[str] = None, @@ -1857,11 +1773,8 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False - # Before this run changes anything, with the key each home's hooks already report with. The log is kept - # across remove_user_level_hooks below, which removes ~/.cursor/hooks. - homes = get_all_user_homes() - recover_set_aside_hook_logs(homes) - forward_hook_errors(homes, gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") + # Before this run changes anything, with the key each home's hooks already report with. + forward_hook_errors(get_all_user_homes(), gateway_url, get_enterprise_hooks_dir() / "hooks" / "unbound.py") # Get device identifier print("\n🔍 Getting device serial number...") @@ -1899,19 +1812,12 @@ def report(status, reason=None, **fields): print("\n📝 Writing config for all users...") user_homes = get_all_user_homes() config_count = 0 - # Every log is kept across remove_user_level_hooks, sent or not, and listed now: a hook can add an error - # after forwarding read the log (or start one), and the saved place keeps what went out from going again. - kept_logs = keep_unsent_hook_logs([(username, Path(home_dir) / HOOK_ERROR_LOG[0]) for username, home_dir in homes - if home_dir is not None and os.path.lexists(Path(home_dir) / HOOK_ERROR_LOG[0])]) - try: - for username, home_dir in user_homes: - if write_unbound_config_for_user(username, home_dir, cursor_api_key, urls={"base_url": base_url, "gateway_url": gateway_url, "frontend_url": frontend_url}): - config_count += 1 - remove_user_level_hooks(username, home_dir) - else: - print(f"⚠️ Skipping hook removal for {username}: config write failed") - finally: - restore_unsent_hook_logs(kept_logs) + for username, home_dir in user_homes: + if write_unbound_config_for_user(username, home_dir, cursor_api_key, urls={"base_url": base_url, "gateway_url": gateway_url, "frontend_url": frontend_url}): + config_count += 1 + remove_user_level_hooks(username, home_dir) + else: + print(f"⚠️ Skipping hook removal for {username}: config write failed") if config_count > 0: print(f"✅ Config written for {config_count} user(s)") remove_legacy_key_env() diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index de87b0cb5..4fd3c0ac8 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -496,15 +496,15 @@ def test_cursor_errors_the_gateway_did_not_take_survive_its_cleanup_for_the_next assert r() is True assert log.exists() assert not (log.parent / "unbound.py").exists() # the rest of the cleanup still ran - assert [p.name for p in (r.home / ".cursor").iterdir()] == ["hooks"] # nothing left set aside + assert [p.name for p in (r.home / ".cursor").iterdir()] == ["hooks"] # nothing left beside it gateway.answer = lambda request: (200, OK) gateway.requests.clear() r() assert _messages(gateway) == ["cursor broke", "cursor broke again"] -def test_cursor_errors_set_aside_survive_a_new_log_a_hook_writes_during_its_cleanup(setup, gateway): - """Cursor can run a hook while setup runs: its new error.log and the set-aside one are both kept.""" +def test_cursor_errors_unsent_survive_an_error_a_hook_writes_during_its_cleanup(setup, gateway): + """Cursor can run a hook while setup runs: what it adds and what the gateway had not taken both go out.""" r = setup("cursor") _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke", f"{_pacific(1)}: cursor broke again"]) @@ -512,7 +512,8 @@ def cleanup_then_a_hook_writes(username, home_dir): REAL_CURSOR_CLEANUP(username, home_dir) log = home_dir / ERROR_LOGS["cursor"] log.parent.mkdir(parents=True, exist_ok=True) - log.write_text(f"{_pacific(2)}: cursor broke during setup\n") + with open(log, "a") as f: # a hook appends to its log + f.write(f"{_pacific(2)}: cursor broke during setup\n") r.mp.setattr(r.m, "remove_user_level_hooks", cleanup_then_a_hook_writes) gateway.answer = lambda request: (503, {}) @@ -524,45 +525,6 @@ def cleanup_then_a_hook_writes(username, home_dir): assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke during setup"] -@pytest.mark.parametrize("moved", ["nothing", "only its place"]) -def test_a_cursor_log_that_cannot_be_set_aside_is_kept_by_its_cleanup(setup, gateway, moved): - """The user may not be able to write ~/.cursor, so the move aside fails, for the log or for the log - alone; the cleanup, which removes ~/.cursor/hooks as root, then keeps that log and removes the rest.""" - r = setup("cursor") - real_cursor_cleanup(r) - log = _log(r.home, "cursor", [f"{_pacific(0)}: cursor broke"]) - (log.parent / "unbound.py").write_text("# python-era hook") - (log.parent / STATE).write_text("2000-01-01T00:00:00 1") - - def set_aside(log): - if moved == "nothing": - return [] - os.rename(log.with_name(STATE), r.m._set_aside_name(log.with_name(STATE))) - return [STATE] - - r.mp.setattr(r.m, "_set_aside_unsent_log", set_aside) - gateway.answer = lambda request: (503, {}) - assert r() is True - assert "error.log" in [p.name for p in log.parent.iterdir()] - assert not (log.parent / "unbound.py").exists() - assert r.m.KEEP_UNSENT_HOOK_LOGS == set() - gateway.answer = lambda request: (200, OK) - gateway.requests.clear() - r() - assert _messages(gateway) == ["cursor broke"] - - -def test_a_cursor_log_an_earlier_run_could_not_put_back_is_forwarded(setup, gateway): - """A restore that failed leaves the log at its set-aside name; the next run puts it back and sends it.""" - r = setup("cursor") - _log(r.home, "cursor", [f"{_pacific(2)}: cursor broke later"]) - aside = r.home / ".cursor" / ".unbound-unsent-hooks-error.log" - aside.write_text(f"{_pacific(0)}: cursor broke\n{_pacific(1)}: cursor broke again\n") - assert r() is True - assert _messages(gateway) == ["cursor broke", "cursor broke again", "cursor broke later"] - assert not aside.exists() - - def test_a_partly_sent_cursor_log_keeps_its_place_across_the_cleanup(setup, gateway): r = setup("cursor") real_cursor_cleanup(r) @@ -602,7 +564,7 @@ def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gatewa # --- The five copies stay equal, and equal to the binary --------------------------- -SHARED_FUNCTIONS = ("_log_time", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", +SHARED_FUNCTIONS = ("_log_time", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", "_post_hook_errors", "_writable_dir", "_home_device_key", "_forward_home_errors", "forward_hook_errors") From 93b17fd9acbd6893b3f10cabedc3cd8fb634d0ac Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 04:32:44 +0530 Subject: [PATCH 46/53] fix(setup): tell sent hook errors apart by digest at the saved timestamp so rotation cannot hide one [WEB-6392] --- augment/hooks/mdm/setup.py | 62 ++++++++++++++++++--------- binary/src/unbound_hook/setup_cmd.py | 63 +++++++++++++++++++--------- binary/tests/test_setup_reporting.py | 38 ++++++++++++++--- claude-code/hooks/mdm/setup.py | 62 ++++++++++++++++++--------- codex/hooks/mdm/setup.py | 62 ++++++++++++++++++--------- copilot/hooks/mdm/setup.py | 62 ++++++++++++++++++--------- cursor/mdm/setup.py | 62 ++++++++++++++++++--------- tests/test_mdm_hook_errors.py | 40 +++++++++++++++--- 8 files changed, 321 insertions(+), 130 deletions(-) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 3b3e4a018..f60a4bcc3 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1693,47 +1693,69 @@ def _replace_user_file(path: Path, data: bytes) -> None: def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the home's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index a305eba76..698feff95 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -19,6 +19,7 @@ """ import functools +import hashlib import json import math import os @@ -309,47 +310,69 @@ def _log_time(text): def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME), follow=False).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the profile's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the profile's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8"), 0o600) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index 224c8faa3..53a133a62 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -334,7 +334,7 @@ def test_errors_newer_than_the_last_forwarded_one_go_to_the_gateway(env, backend assert body["hook_source"] == "claude-code" and len(body["hook_sha"]) == 12 assert [(e["timestamp"], e["message"]) for e in body["errors"]] == [ (_utc(1), "gateway unreachable 1"), (_utc(2), "gateway unreachable 2")] - assert log.with_name(STATE).read_text() == f"{_utc(2)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_utc(2)} 1" def test_errors_go_ten_to_a_request_and_none_is_sent_twice(env, backend): @@ -342,7 +342,7 @@ def test_errors_go_ten_to_a_request_and_none_is_sent_twice(env, backend): _run(backend) assert [len(r["body"]["errors"]) for r in _forwarded(backend)] == [10, 10, 5] assert [e["message"] for r in _forwarded(backend) for e in r["body"]["errors"]] == [f"e{n}" for n in range(25)] - assert log.with_name(STATE).read_text() == f"{_utc(24)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_utc(24)} 1" backend.requests.clear() _run(backend) assert _forwarded(backend) == [] @@ -382,7 +382,7 @@ def test_each_tool_and_each_home_keeps_its_own_place(env, backend, monkeypatch, sent = {r["body"]["hook_source"]: [e["message"] for e in r["body"]["errors"]] for r in _forwarded(backend)} assert sent == {"cursor": ["cursor broke"], "copilot": ["copilot broke"], "codex": ["codex broke"], "claude-code": ["bob's claude broke"], "augment_code": ["auggie broke"]} - assert (env["home"] / ".copilot/hooks" / STATE).read_text() == f"{_pacific(1)} 1" + assert (env["home"] / ".copilot/hooks" / STATE).read_text().rsplit(" ", 1)[0] == f"{_pacific(1)} 1" assert (other / ".claude/hooks" / STATE).exists() and not (env["home"] / ".claude/hooks" / STATE).exists() # Cursor's setup removes the python-era ~/.cursor/hooks; its sent log comes back with its place. assert sorted(p.name for p in (env["home"] / ".cursor/hooks").iterdir()) == [STATE, "error.log"] @@ -469,7 +469,7 @@ def test_a_huge_log_sends_only_its_25_newest_entries(env, backend): _run(backend) assert len(_forwarded(backend)) <= 3 assert [m.split()[1] for m in _messages(backend)] == [str(n) for n in range(39975, 40000)] - assert log.with_name(STATE).read_text() == f"{_utc(39999 / 100)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_utc(39999 / 100)} 1" def test_entries_older_than_seven_days_are_never_sent(env, backend): @@ -562,7 +562,7 @@ def test_a_state_file_that_is_a_link_is_replaced_not_followed(env, backend, tmp_ assert _messages(backend) == ["e0", "e1"] assert victim.read_text() == _utc(100) state = log.with_name(STATE) - assert not state.is_symlink() and state.read_text() == f"{_utc(1)} 1" + assert not state.is_symlink() and state.read_text().rsplit(" ", 1)[0] == f"{_utc(1)} 1" # --- S-U5: what reaches the gateway, and Sentry behind it ------------------------ @@ -649,6 +649,34 @@ def answer(path): # --- Review #9: entries sharing the saved timestamp aren't lost ------------------ +def test_an_entry_sharing_the_saved_timestamp_is_sent_after_the_log_rotates(env, backend): + """The hook keeps its last 25 entries: after rotation drops one already sent at the saved stamp, a new + entry stamped the same is still told apart from the sent one beside it.""" + same = _utc(9) + log = _log(env["home"], "claude-code", [f"{same}: e1", f"{same}: e2"]) + _run(backend) + assert _messages(backend) == ["e1", "e2"] + log.write_text(f"{same}: e2\n{same}: e3\n") # e1 rotated out, e3 added with the same stamp + backend.requests.clear() + _run(backend) + assert _messages(backend) == ["e3"] + backend.requests.clear() + _run(backend) + assert _messages(backend) == [] + + +def test_a_place_saved_before_digests_still_reads(env, backend): + """A place saved as ' ' (or a bare stamp) reads as before.""" + same = _utc(9) + log = _log(env["home"], "claude-code", [f"{same}: e1", f"{same}: e2", f"{_utc(10)}: e3"]) + log.with_name(STATE).write_text(f"{same} 1") + _run(backend) + assert _messages(backend) == ["e2", "e3"] + backend.requests.clear() + _run(backend) + assert _messages(backend) == [] # e1, sent by the old count, is not sent again + + def test_an_entry_sharing_the_last_sent_timestamp_is_still_sent(env, backend): same = _utc(9) lines = [f"{_utc(n)}: e{n}" for n in range(9)] + [f"{same}: e9", f"{same}: e10"] diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 754d05b72..0d96e9181 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3548,47 +3548,69 @@ def _replace_user_file(path: Path, data: bytes) -> None: def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the home's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 5c3935bfe..c4450c4a2 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2681,47 +2681,69 @@ def _replace_user_file(path: Path, data: bytes) -> None: def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the home's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 95cdf2ae1..1bf566da2 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2335,47 +2335,69 @@ def _replace_user_file(path: Path, data: bytes) -> None: def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the home's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index b4ff7ab40..902d41133 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1477,47 +1477,69 @@ def _replace_user_file(path: Path, data: bytes) -> None: def _forwarded_place(log: Path): - """(timestamp, how many entries stamped then were sent) from the state file; (None, 0) for none. - A bare timestamp, as written before the count, means every entry stamped then was sent.""" + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" try: parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() except (OSError, UnicodeDecodeError): - return None, 0 + return None, 0, None last = _log_time(parts[0]) if parts else None - sent_then = int(parts[1]) if len(parts) == 2 and parts[1].isdigit() else float("inf") - return last, sent_then if last else 0 + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) def _unsent_hook_errors(log: Path) -> list: """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE - last, sent_then = _forwarded_place(log) - entries, seen_then, current = [], 0, None + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): match = _HOOK_ERROR_LINE.match(line) if not match: # a message's own later lines (a traceback); they go with the entry they follow - if current is not None: - current["message"] = (current["message"] + "\n" + line)[:2000] + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] continue - when, current = _log_time(match.group(1)), None - if when is None or when <= floor: + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): continue - if last is not None and when <= last: - seen_then += when == last - if when < last or seen_then <= sent_then: - continue # sent already - current = {"timestamp": match.group(1), "message": match.group(2)[:2000], - "category": FORWARDED_ERROR_CATEGORY} - entries.append((when, current)) + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order chosen = entries[-HOOK_ERRORS_PER_RUN:] for i, (when, entry) in enumerate(chosen): - same = sum(1 for other, _ in chosen[:i + 1] if other == when) + (sent_then if when == last else 0) - entry["state"] = f"{entry['timestamp']} {same}" + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" return [entry for _, entry in chosen] +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + def _save_forwarded(log: Path, state: str) -> bool: """Runs as the home's user.""" _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 4fd3c0ac8..7b6b3dd3f 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -153,7 +153,7 @@ def test_each_script_sends_only_its_own_tools_errors_newer_than_the_last_sent(se assert (body["hook_source"], body["hook_sha"]) == (HOOK_SOURCES[tool], "h" * 12) assert [(e["timestamp"], e["message"], e["category"]) for e in body["errors"]] == [ (_utc(1), f"{tool} e1", "forwarded_error_log"), (_utc(2), f"{tool} e2", "forwarded_error_log")] - assert log.with_name(STATE).read_text() == f"{_utc(2)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_utc(2)} 1" @pytest.mark.parametrize("tool", sorted(MODULES)) @@ -199,7 +199,7 @@ def test_errors_go_ten_to_a_request_and_none_is_sent_twice(setup, gateway): r() assert [len(req["body"]["errors"]) for req in _forwarded(gateway)] == [10, 10, 5] assert _messages(gateway) == [f"e{n}" for n in range(25)] - assert log.with_name(STATE).read_text() == f"{_utc(24)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_utc(24)} 1" gateway.requests.clear() r() assert _forwarded(gateway) == [] @@ -255,6 +255,36 @@ def test_a_4xx_is_a_refusal_and_saves_nothing(setup, gateway): assert not log.with_name(STATE).exists() +def test_an_entry_sharing_the_saved_timestamp_is_sent_after_the_log_rotates(setup, gateway): + """The hook keeps its last 25 entries: after rotation drops one already sent at the saved stamp, a new + entry stamped the same is still told apart from the sent one beside it.""" + r = setup("claude-code") + same = _utc(9) + log = _log(r.home, "claude-code", [f"{same}: e1", f"{same}: e2"]) + r() + assert _messages(gateway) == ["e1", "e2"] + log.write_text(f"{same}: e2\n{same}: e3\n") # e1 rotated out, e3 added with the same stamp + gateway.requests.clear() + r() + assert _messages(gateway) == ["e3"] + gateway.requests.clear() + r() + assert _messages(gateway) == [] + + +def test_a_place_saved_before_digests_still_reads(setup, gateway): + """A place saved as ' ' (or a bare stamp) reads as before.""" + r = setup("claude-code") + same = _utc(9) + log = _log(r.home, "claude-code", [f"{same}: e1", f"{same}: e2", f"{_utc(10)}: e3"]) + log.with_name(STATE).write_text(f"{same} 1") + r() + assert _messages(gateway) == ["e2", "e3"] + gateway.requests.clear() + r() + assert _messages(gateway) == [] # e1, sent by the old count, is not sent again + + def test_an_entry_sharing_the_last_sent_timestamp_is_still_sent(setup, gateway): r = setup("claude-code") same = _utc(9) @@ -428,7 +458,7 @@ def test_a_state_file_that_is_a_link_is_replaced_not_followed(setup, gateway, tm assert _messages(gateway) == ["e0", "e1"] assert victim.read_text() == _utc(100) state = log.with_name(STATE) - assert not state.is_symlink() and state.read_text() == f"{_utc(1)} 1" + assert not state.is_symlink() and state.read_text().rsplit(" ", 1)[0] == f"{_utc(1)} 1" def test_a_config_that_is_a_link_gives_no_key(setup, gateway, tmp_path): @@ -531,7 +561,7 @@ def test_a_partly_sent_cursor_log_keeps_its_place_across_the_cleanup(setup, gate log = _log(r.home, "cursor", [f"{_pacific(n)}: e{n}" for n in range(15)]) gateway.answer = lambda request: (503, {}) if len(_forwarded(gateway)) == 2 else (200, OK) r() - assert log.with_name(STATE).read_text() == f"{_pacific(9)} 1" + assert log.with_name(STATE).read_text().rsplit(" ", 1)[0] == f"{_pacific(9)} 1" gateway.answer = lambda request: (200, OK) gateway.requests.clear() r() @@ -564,7 +594,7 @@ def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gatewa # --- The five copies stay equal, and equal to the binary --------------------------- -SHARED_FUNCTIONS = ("_log_time", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", +SHARED_FUNCTIONS = ("_log_time", "_entry_digest", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", "_post_hook_errors", "_writable_dir", "_home_device_key", "_forward_home_errors", "forward_hook_errors") From 10fd96a097ef771050b479f99c8c442a5eb2b189 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 04:46:33 +0530 Subject: [PATCH 47/53] fix(mdm): clear cursor's user hooks without following a link out of the home [WEB-6392] --- cursor/mdm/setup.py | 93 +++++++++++++++++++++++++---------- tests/test_mdm_hook_errors.py | 20 ++++++++ 2 files changed, 88 insertions(+), 25 deletions(-) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index 902d41133..de7162eb6 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -440,39 +440,82 @@ def _write(): return True -def _remove_hooks_dir(hooks_dir: Path) -> None: - """Remove ~/.cursor/hooks, all but its error.log and the log's forwarded place (WEB-6392): errors the - gateway has not taken, or a hook writes while setup runs, go out on a later run, and nothing twice.""" - import shutil - keep = {Path(HOOK_ERROR_LOG[0]).name, FORWARDED_STATE_NAME} - for entry in os.scandir(hooks_dir): - if entry.name in keep: +_NO_LINK_DIR = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + + +def _clear_dir_at(dir_fd: int, keep=frozenset()) -> None: + """Remove everything in the open folder but the names in keep, relative to it and never through a link.""" + for name in os.listdir(dir_fd): + if name in keep: continue - if entry.is_dir(follow_symlinks=False): - shutil.rmtree(entry.path) + if stat.S_ISDIR(os.stat(name, dir_fd=dir_fd, follow_symlinks=False).st_mode): + sub = os.open(name, _NO_LINK_DIR, dir_fd=dir_fd) + try: + _clear_dir_at(sub) + finally: + os.close(sub) + os.rmdir(name, dir_fd=dir_fd) else: - os.unlink(entry.path) - if not any(os.scandir(hooks_dir)): - os.rmdir(hooks_dir) + os.unlink(name, dir_fd=dir_fd) -def remove_user_level_hooks(username: str, home_dir: Path) -> bool: - """Remove user-level Cursor hooks (from normal setup) to prevent duplicate execution.""" - hooks_json = home_dir / ".cursor" / "hooks.json" - hooks_dir = home_dir / ".cursor" / "hooks" +def _remove_cursor_hooks(home_dir: Path) -> bool: + """Remove ~/.cursor/hooks.json and ~/.cursor/hooks, all but the folder's error.log and the log's + forwarded place (WEB-6392): errors the gateway has not taken, or a hook writes while setup runs, go out + on a later run, and nothing twice. Root does this in a folder the user owns, so ~/.cursor and its hooks + folder are opened without following a link and every removal is made relative to them: a link at either, + or one swapped in, can't point root at another folder. True when anything was removed.""" + keep = {Path(HOOK_ERROR_LOG[0]).name, FORWARDED_STATE_NAME} + if os.name == "nt": # no dir_fd here: SYSTEM checks the path for links and junctions first + import shutil + _refuse_links_on_the_way(home_dir / ".cursor" / "hooks") + removed = False + if (home_dir / ".cursor" / "hooks.json").exists(): + (home_dir / ".cursor" / "hooks.json").unlink() + removed = True + hooks_dir = home_dir / ".cursor" / "hooks" + if hooks_dir.exists(): + for entry in os.scandir(hooks_dir): + if entry.name not in keep: + shutil.rmtree(entry.path) if entry.is_dir(follow_symlinks=False) else os.unlink(entry.path) + if not any(os.scandir(hooks_dir)): + os.rmdir(hooks_dir) + removed = True + return removed + try: + cursor_dir = os.open(str(home_dir / ".cursor"), _NO_LINK_DIR) + except FileNotFoundError: + return False removed = False - if hooks_json.exists(): + try: try: - hooks_json.unlink() + os.unlink("hooks.json", dir_fd=cursor_dir) removed = True - except Exception as e: - debug_print(f"Failed to remove {hooks_json}: {e}") - if hooks_dir.exists(): + except FileNotFoundError: + pass try: - _remove_hooks_dir(hooks_dir) - removed = True - except Exception as e: - debug_print(f"Failed to remove {hooks_dir}: {e}") + hooks = os.open("hooks", _NO_LINK_DIR, dir_fd=cursor_dir) + except FileNotFoundError: + return removed + try: + _clear_dir_at(hooks, keep) + empty = not os.listdir(hooks) + finally: + os.close(hooks) + if empty: + os.rmdir("hooks", dir_fd=cursor_dir) + return True + finally: + os.close(cursor_dir) + + +def remove_user_level_hooks(username: str, home_dir: Path) -> bool: + """Remove user-level Cursor hooks (from normal setup) to prevent duplicate execution.""" + removed = False + try: + removed = _remove_cursor_hooks(home_dir) + except Exception as e: + debug_print(f"Failed to remove the user-level hooks in {home_dir / '.cursor'}: {e}") if removed: print(f" Removed user-level hooks for {username} (replaced by enterprise hooks)") return removed diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index 7b6b3dd3f..d43906bf2 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -491,6 +491,26 @@ def test_cursor_errors_go_out_before_its_cleanup_removes_their_log(setup, gatewa assert _forwarded(gateway) == [] +@pytest.mark.skipif(os.name == "nt", reason="POSIX symlinks; Windows is covered in test_windows_paths") +@pytest.mark.parametrize("linked", [".cursor/hooks", ".cursor"]) +def test_cursor_cleanup_never_follows_a_link_out_of_the_home(setup, gateway, tmp_path, linked): + """The cleanup runs as root over a folder the user owns: a link at ~/.cursor/hooks, or at ~/.cursor, + must not send it into another folder to delete what is there.""" + r = setup("cursor") + real_cursor_cleanup(r) + elsewhere = tmp_path / "elsewhere" + (elsewhere / "hooks").mkdir(parents=True) + for target in (elsewhere, elsewhere / "hooks"): + (target / "precious.txt").write_text("root's") + (target / "unbound.py").write_text("root's") + link = r.home / linked + link.parent.mkdir(parents=True, exist_ok=True) + link.symlink_to(elsewhere / "hooks" if linked == ".cursor/hooks" else elsewhere) + assert r() is True + for target in (elsewhere, elsewhere / "hooks"): + assert sorted(p.name for p in target.iterdir() if p.is_file()) == ["precious.txt", "unbound.py"] + + @pytest.mark.parametrize("before", [["cursor broke"], []]) def test_a_cursor_error_written_after_a_full_send_survives_its_cleanup(setup, gateway, before): """Everything in the log went out (or there was no log yet), then a hook added an error before the From 8b31eab42582608d3f1d7b2d88c55b7ac8bb7c42 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Fri, 27 Nov 2026 04:51:00 +0530 Subject: [PATCH 48/53] fix(mdm): delete cursor's user hooks on windows through handles checked to be the path asked for [WEB-6392] --- cursor/mdm/setup.py | 75 +++++++++++++++++++++++++++++++------ tests/test_windows_paths.py | 40 ++++++++++++++++++++ 2 files changed, 104 insertions(+), 11 deletions(-) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index de7162eb6..a787499db 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -459,6 +459,63 @@ def _clear_dir_at(dir_fd: int, keep=frozenset()) -> None: os.unlink(name, dir_fd=dir_fd) +def _delete_where_asked(path: Path) -> None: + """Windows: delete the file or empty folder at path itself (a link there, not what it points at). It is + opened for delete without following a link, its final path must be the path asked for, and the delete + goes through that same handle: a link or junction swapped in on the way can't point SYSTEM elsewhere.""" + import ctypes + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + asked = os.path.abspath(str(path)) + handle = kernel32.CreateFileW(asked, 0x00010000 | 0x0080, # DELETE | FILE_READ_ATTRIBUTES + 0x7, None, 3, # share all, OPEN_EXISTING + 0x00200000 | 0x02000000, None) # OPEN_REPARSE_POINT | BACKUP_SEMANTICS + if handle in (None, wintypes.HANDLE(-1).value): + raise ctypes.WinError(ctypes.get_last_error()) + try: + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + if not (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))): + raise OSError(f"{path} is reached through a link or junction") + disposition = _Disposition(True) + if not kernel32.SetFileInformationByHandle(handle, 4, ctypes.byref(disposition), ctypes.sizeof(disposition)): + raise ctypes.WinError(ctypes.get_last_error()) # FileDispositionInfo above + finally: + kernel32.CloseHandle(handle) + + +def _clear_dir_where_asked(folder: Path, keep=frozenset()) -> None: + """Windows: remove everything in folder but the names in keep, each through _delete_where_asked. A + real subfolder is emptied first; a link or junction is removed itself, never entered.""" + for name in os.listdir(folder): + if name in keep: + continue + child = folder / name + st = os.lstat(child) + if stat.S_ISDIR(st.st_mode) and not getattr(st, "st_file_attributes", 0) & 0x400: + _clear_dir_where_asked(child) + _delete_where_asked(child) + + def _remove_cursor_hooks(home_dir: Path) -> bool: """Remove ~/.cursor/hooks.json and ~/.cursor/hooks, all but the folder's error.log and the log's forwarded place (WEB-6392): errors the gateway has not taken, or a hook writes while setup runs, go out @@ -466,20 +523,16 @@ def _remove_cursor_hooks(home_dir: Path) -> bool: folder are opened without following a link and every removal is made relative to them: a link at either, or one swapped in, can't point root at another folder. True when anything was removed.""" keep = {Path(HOOK_ERROR_LOG[0]).name, FORWARDED_STATE_NAME} - if os.name == "nt": # no dir_fd here: SYSTEM checks the path for links and junctions first - import shutil - _refuse_links_on_the_way(home_dir / ".cursor" / "hooks") + if os.name == "nt": # no dir_fd: each removal goes through a handle checked to be the one asked for removed = False - if (home_dir / ".cursor" / "hooks.json").exists(): - (home_dir / ".cursor" / "hooks.json").unlink() + if os.path.lexists(home_dir / ".cursor" / "hooks.json"): + _delete_where_asked(home_dir / ".cursor" / "hooks.json") removed = True hooks_dir = home_dir / ".cursor" / "hooks" - if hooks_dir.exists(): - for entry in os.scandir(hooks_dir): - if entry.name not in keep: - shutil.rmtree(entry.path) if entry.is_dir(follow_symlinks=False) else os.unlink(entry.path) - if not any(os.scandir(hooks_dir)): - os.rmdir(hooks_dir) + if os.path.lexists(hooks_dir): + _clear_dir_where_asked(hooks_dir, keep) + if not os.listdir(hooks_dir): + _delete_where_asked(hooks_dir) removed = True return removed try: diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index 9dccd7dd9..809843a45 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -229,3 +229,43 @@ def test_setup_never_reads_or_writes_a_users_file_through_a_junction(tool, tmp_p assert m._read_user_file_tail(plain, 1024) == b"ok\n" m._replace_user_file(tmp_path / "state", b"saved") assert (tmp_path / "state").read_bytes() == b"saved" + + +@windows_only +def test_cursor_cleanup_keeps_only_the_log_and_its_place(tmp_path): + m = tool_module("cursor/mdm", "setup") + home = tmp_path / "home" + hooks = home / ".cursor" / "hooks" + (hooks / "old").mkdir(parents=True) + (hooks / "old" / "x.txt").write_text("x") + for name in ("unbound.py", "error.log", ".error_log_forwarded"): + (hooks / name).write_text(name) + (home / ".cursor" / "hooks.json").write_text("{}") + assert m.remove_user_level_hooks("u", home) is True + assert not (home / ".cursor" / "hooks.json").exists() + assert sorted(p.name for p in hooks.iterdir()) == [".error_log_forwarded", "error.log"] + + +@windows_only +@pytest.mark.parametrize("where", ["hooks", "inside"]) +def test_cursor_cleanup_never_deletes_through_a_junction(tmp_path, where): + """SYSTEM clears ~/.cursor/hooks: a junction there, or inside it, is never followed to delete elsewhere.""" + import _winapi + m = tool_module("cursor/mdm", "setup") + private = tmp_path / "private" + private.mkdir() + for name in ("precious.txt", "unbound.py"): + (private / name).write_text("SYSTEM's") + home = tmp_path / "home" + hooks = home / ".cursor" / "hooks" + if where == "hooks": + hooks.parent.mkdir(parents=True) + _winapi.CreateJunction(str(private), str(hooks)) + else: + hooks.mkdir(parents=True) + (hooks / "unbound.py").write_text("old hook") + _winapi.CreateJunction(str(private), str(hooks / "inner")) + m.remove_user_level_hooks("u", home) + assert sorted(p.name for p in private.iterdir()) == ["precious.txt", "unbound.py"] + if where == "inside": + assert not os.path.lexists(hooks / "inner") and not (hooks / "unbound.py").exists() From a374341cb77bcbca1c2e0bf71f2335728a26c83d Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Mon, 30 Nov 2026 14:47:49 +0530 Subject: [PATCH 49/53] feat(mdm): report antigravity's setup outcome and forward its hook errors like the other scripts [WEB-6392] --- antigravity/hooks/mdm/setup.py | 493 +++++++++++++++++++++- tests/antigravity/hooks/mdm/test_setup.py | 7 +- tests/test_mdm_hook_errors.py | 18 +- tests/test_mdm_setup_status.py | 36 +- tests/test_tool_installed.py | 26 +- tests/test_windows_paths.py | 1 + 6 files changed, 557 insertions(+), 24 deletions(-) diff --git a/antigravity/hooks/mdm/setup.py b/antigravity/hooks/mdm/setup.py index de82a411a..706fd7b06 100644 --- a/antigravity/hooks/mdm/setup.py +++ b/antigravity/hooks/mdm/setup.py @@ -11,6 +11,8 @@ import subprocess import hashlib import json +import re +from datetime import datetime, timedelta, timezone import tempfile import time from pathlib import Path @@ -740,16 +742,458 @@ def clear_setup() -> bool: def hook_script_hash(script_path) -> Optional[str]: """sha256 of the hook script this run installed, so the backend can tell which - hook version a device is running. None when absent or unreadable.""" + hook version a device is running. None when absent or unreadable. + + The script sits in a user's home, and error forwarding hashes it before this run + replaces it, so it is read as a user's file: not through a link, never a FIFO + or device, and within a size cap.""" + try: + return hashlib.sha256(_read_user_file(Path(script_path))).hexdigest() + except Exception: + return None + + +TOOL_NAME, TOOL_CLI = "Antigravity", "antigravity" +HOOK_ERROR_LOG = (".gemini/antigravity-hooks/error.log", "antigravity") # this tool's log under a home, and its hook_source +# The Antigravity app, or its data folder under a home (~/.gemini/antigravity, which the app writes on first +# run; setup's own ~/.gemini/antigravity-hooks and the Gemini CLI's ~/.gemini don't count). +_ANTIGRAVITY_DATA = (".gemini/antigravity",) +# Per OS: (machine-wide paths, paths under a home), beside the CLI's own folders. +TOOL_FOOTPRINTS = { + "darwin": (("Applications/Antigravity.app",), ("Applications/Antigravity.app",) + _ANTIGRAVITY_DATA), + "linux": (("opt/Antigravity", "opt/antigravity", "usr/share/antigravity", "usr/bin/antigravity", + "usr/local/bin/antigravity"), + ("Applications/Antigravity*.AppImage", ".local/bin/antigravity") + _ANTIGRAVITY_DATA), + "windows": (("Program Files/Antigravity",), ("AppData/Local/Programs/Antigravity",) + _ANTIGRAVITY_DATA), +} + +# --- Whether the tool is installed (WEB-6392) --------------------------------------------- +# For the setup/complete status only: a tool with none of its files on disk is reported skipped, +# " is not installed", and its config is written all the same. Existence checks only (and +# ~/.npmrc, read without following a link, for its prefix); a check that fails counts as installed. +# Every tool's MDM script runs on its own, so each one carries this same code with its own +# footprints, kept equal by tests/test_tool_installed.py; the unbound-hook binary calls it too. +_UNIX_HOME_CLI_DIRS = ( + ".local/bin", ".bun/bin", ".npm-global/bin", ".nvm/versions/node/*/bin", ".volta/bin", + ".local/share/fnm/node-versions/*/installation/bin", ".fnm/node-versions/*/installation/bin", + ".asdf/shims", ".local/share/mise/shims", ".local/share/mise/installs/*/*/bin", + ".nodenv/shims", ".nodenv/versions/*/bin", ".yarn/bin", ".config/yarn/global/node_modules/.bin") +# Where a CLI lands, per OS: (machine-wide folders, folders under a user's home). +_CLI_DIRS = { + "darwin": (("opt/homebrew/bin", "usr/local/bin", "opt/local/bin"), _UNIX_HOME_CLI_DIRS + ("Library/pnpm",)), + "linux": (("usr/local/bin", "usr/bin", "snap/bin", "var/lib/flatpak/exports/bin"), + _UNIX_HOME_CLI_DIRS + (".local/share/pnpm", ".local/share/flatpak/exports/bin")), + "windows": (("ProgramData/chocolatey/bin", "Program Files/nodejs"), + ("AppData/Roaming/npm", "AppData/Local/pnpm", "AppData/Local/Volta/bin", "AppData/Roaming/nvm/*", + "scoop/shims", ".local/bin", ".bun/bin")), +} +_CLI_SUFFIXES = {"windows": ("", ".exe", ".cmd", ".ps1")} + + +def _install_root(system: str) -> Path: + return Path((os.environ.get("SystemDrive") or "C:") + "\\") if system == "windows" else Path("/") + + +def _found(root: Path, relpath: str) -> bool: + """Something is at relpath; a place that can't be looked at counts as found.""" + try: + return any(root.glob(relpath)) if "*" in relpath else (root / relpath).exists() + except OSError: + return True + + +def _npmrc_cli_dir(home: Path, system: str) -> Optional[Path]: + """Where npm puts CLIs for a prefix the user set in ~/.npmrc, or None.""" + try: + fd = os.open(str(home / ".npmrc"), os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + except OSError: + return None + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + return None + text = os.read(fd, 65536).decode("utf-8", "replace") + except OSError: + return None + finally: + os.close(fd) + for line in text.splitlines(): + key, sep, value = line.partition("=") + if sep and key.strip() == "prefix": + value = value.strip().strip("\"'") + for token in ("${HOME}", "$HOME"): + value = value.replace(token, str(home)) + if value.startswith("~/"): + value = str(home) + value[1:] + if not os.path.isabs(value): + return None + return Path(value) if system == "windows" else Path(value) / "bin" + return None + + +def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optional[Path] = None) -> bool: + """Whether any of this tool's footprints is on the machine or in a user's home.""" + try: + system = system or platform.system().lower() + root = machine_root if machine_root is not None else _install_root(system) + machine_dirs, home_dirs = _CLI_DIRS.get(system, ((), ())) + machine_files, home_files = TOOL_FOOTPRINTS.get(system, ((), ())) + names = [TOOL_CLI + suffix for suffix in _CLI_SUFFIXES.get(system, ("",))] + machine = [f"{d}/{n}" for d in machine_dirs for n in names] + list(machine_files) + per_home = [f"{d}/{n}" for d in home_dirs for n in names] + list(home_files) + if any(_found(root, rel) for rel in machine): + return True + for _, home in user_homes: + if home is None: + continue + npm_dir = _npmrc_cli_dir(Path(home), system) + if any(_found(Path(home), rel) for rel in per_home) or ( + npm_dir is not None and any(_found(npm_dir, n) for n in names)): + return True + return False + except Exception: + return True + + +# --- Stuck hook errors (WEB-6392) ----------------------------------------------------------- +# A hook reports an error to the gateway at most once a minute and never retries, so the rest wait in +# its error.log. Each run sends this tool's entries (HOOK_ERROR_LOG) newer than the last one forwarded, +# per home and with that home's own key, as the unbound-hook binary does on a Mac. Every tool's MDM script +# runs on its own, so each one carries this same code, kept equal by tests/test_mdm_hook_errors.py. +# Beside each error.log: " ", the newest entry the gateway accepted and how many entries +# stamped exactly then were sent (two can share a stamp, and a request can end between them). +FORWARDED_STATE_NAME = ".error_log_forwarded" +HOOK_ERRORS_PER_REQUEST = 10 # the gateway takes at most ten +# error.log is the user's to write: per home, a run sends at most the newest 25 (what a hook keeps) and +# nothing older than a week, so a flooded or first-seen log costs at most three requests. +HOOK_ERRORS_PER_RUN = 25 +HOOK_ERROR_MAX_AGE = timedelta(days=7) +# Sentry groups by category: forwarded entries group together, apart from the hook's live reports. +FORWARDED_ERROR_CATEGORY = "forwarded_error_log" +HOOK_ERROR_TIMEOUT_SECONDS = 5 # forwarding must never hold setup up +HOOK_ERROR_USER_TIMEOUT = 30 # a step run as the user, who can pause it, ends after this +_HOOK_ERROR_LINE = re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})): (.*)$") +_USER_FILE_MAX_BYTES = 4 * 1024 * 1024 +# A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. +_USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) +_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") +_URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") +_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") + + +def _log_time(text): + """An entry's timestamp as an aware datetime (hooks write UTC 'Z' or local time with its offset), else None.""" + try: + when = datetime.fromisoformat(text.replace("Z", "+00:00")) + except (TypeError, ValueError): + return None + return when if when.tzinfo else None + + +def _refuse_links_on_the_way(path: Path) -> None: + """Windows: SYSTEM opens a user's path itself, so a link or junction anywhere on it is refused before the + open, and _refuse_if_redirected checks the opened file after it. A part not made yet is skipped.""" + if os.name != "nt": + return + path = Path(os.path.abspath(str(path))) + for part in (path, *path.parents): + try: + st = os.lstat(part) + except FileNotFoundError: + continue + if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & 0x400: # a reparse point + raise OSError(f"{part} is a link or junction") + + +def _refuse_if_redirected(fd: int, path: Path) -> None: + """Windows has no O_NOFOLLOW, and SYSTEM opens a user's files itself: the file opened must be the one at + the path asked for, with no link or junction anywhere on the way. Closes fd and raises OSError if not.""" + if os.name != "nt": + return + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + final, asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(msvcrt.get_osfhandle(fd), final, len(final), 0) + # The path asked for in its long form (a temp folder is often given as C:\\Users\\RUNNER~1\\...). + wanted = kernel32.GetLongPathNameW(os.path.abspath(str(path)), asked, len(asked)) + # A hard link has no other path to find, so a file with more than one name is refused as well. + if not (0 < got < len(final) and 0 < wanted < len(asked) and os.fstat(fd).st_nlink == 1 + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(asked.value))): + os.close(fd) + raise OSError(f"{path} is reached through a link or junction") + + +def _read_user_file(path: Path) -> bytes: + """A user's regular file, whole and within _USER_FILE_MAX_BYTES. Raises OSError for anything else.""" + _refuse_links_on_the_way(path) + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + data = f.read(_USER_FILE_MAX_BYTES + 1) + if len(data) > _USER_FILE_MAX_BYTES: + raise OSError(f"{path} is larger than {_USER_FILE_MAX_BYTES} bytes") + return data + + +def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: + """A user's regular file's last max_bytes, from a whole line on: a long log is read from its end.""" + _refuse_links_on_the_way(path) + fd = os.open(str(path), os.O_RDONLY | _USER_FILE_FLAGS) + _refuse_if_redirected(fd, path) + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + os.close(fd) + raise OSError(f"{path} is not a regular file") + with os.fdopen(fd, "rb") as f: + if st.st_size <= max_bytes: + return f.read(max_bytes) + f.seek(st.st_size - max_bytes) + data = f.read(max_bytes) + return data.split(b"\n", 1)[1] if b"\n" in data else b"" + + +def _replace_user_file(path: Path, data: bytes) -> None: + """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written + through, and a failed write leaves the old file in place.""" + tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") + _refuse_links_on_the_way(tmp) + if os.path.lexists(tmp): + tmp.unlink() + fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL | _USER_FILE_FLAGS, 0o600) + try: + _refuse_if_redirected(fd, tmp) + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) + except BaseException: + try: + tmp.unlink() + except OSError: + pass + raise + + +def _forwarded_place(log: Path): + """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; + (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, + and a bare timestamp means every entry stamped then was.""" + try: + parts = _read_user_file(log.with_name(FORWARDED_STATE_NAME)).decode().split() + except (OSError, UnicodeDecodeError): + return None, 0, None + last = _log_time(parts[0]) if parts else None + sent_then = int(parts[1]) if len(parts) >= 2 and parts[1].isdigit() else float("inf") + digests = parts[2].split(",") if len(parts) == 3 and parts[1].isdigit() else None + return (last, sent_then, digests) if last else (None, 0, None) + + +def _unsent_hook_errors(log: Path) -> list: + """Runs as the home's user: the newest HOOK_ERRORS_PER_RUN entries after the last one forwarded and + newer than HOOK_ERROR_MAX_AGE, oldest first. Each carries the 'state' to save once it is sent.""" + floor = datetime.now(timezone.utc) - HOOK_ERROR_MAX_AGE + last, sent_then, sent_digests = _forwarded_place(log) + parsed = [] + for line in _read_user_file_tail(log, _USER_FILE_MAX_BYTES).decode("utf-8", "replace").splitlines(): + match = _HOOK_ERROR_LINE.match(line) + if not match: # a message's own later lines (a traceback); they go with the entry they follow + if parsed: + parsed[-1]["message"] = (parsed[-1]["message"] + "\n" + line)[:2000] + continue + parsed.append({"timestamp": match.group(1), "message": match.group(2)[:2000], + "category": FORWARDED_ERROR_CATEGORY}) + # Entries stamped with the saved time are told apart by digest: the hook keeps only its last 25, so + # rotation can drop a sent one and leave a count that no longer lines up. + unmatched = list(sent_digests or ()) + entries, seen_then, kept_then = [], 0, [] + for entry in parsed: + when = _log_time(entry["timestamp"]) + if when is None or when <= floor or (last is not None and when < last): + continue + if last is not None and when == last: + digest = _entry_digest(entry["message"]) + if sent_digests is not None: + if digest in unmatched: + unmatched.remove(digest) + kept_then.append(digest) + continue # sent already + else: + seen_then += 1 + if seen_then <= sent_then: + kept_then.append(digest) + continue # sent already, by the count a place without digests carries + entries.append((when, entry)) + entries.sort(key=lambda entry: entry[0]) # stable: entries sharing a stamp keep the log's order + chosen = entries[-HOOK_ERRORS_PER_RUN:] + for i, (when, entry) in enumerate(chosen): + stamped = [e for other, e in chosen[:i + 1] if other == when] + earlier = kept_then if when == last else [] + digests = earlier + [_entry_digest(e["message"]) for e in stamped] + entry["state"] = f"{entry['timestamp']} {len(digests)} {','.join(digests)}" + return [entry for _, entry in chosen] + + +def _entry_digest(message: str) -> str: + """A short digest that tells one sent entry from another stamped at the same time.""" + return hashlib.sha256(message.encode("utf-8", "replace")).hexdigest()[:12] + + +def _save_forwarded(log: Path, state: str) -> bool: + """Runs as the home's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8")) + return True + + +def _redact_hook_error(message: str, secrets) -> str: + """The home's own keys, then common credential shapes, each value replaced and its name kept.""" + for secret in secrets: + if secret: + message = message.replace(secret, "[REDACTED]") + message = _BEARER.sub("Bearer [REDACTED]", message) + message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) + message = _URL_SECRET.sub(r"\1[REDACTED]", message) + return _VENDOR_KEY.sub("[REDACTED]", message) + + +def _post_hook_json(url, body, headers): + """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, + response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" + header_file = None try: - return hashlib.sha256(Path(script_path).read_bytes()).hexdigest() + fd, header_file = tempfile.mkstemp(prefix=".unbound-headers.") + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write("".join(f"{name}: {value}\n" for name, value in + {"Content-Type": "application/json", **headers}.items())) + cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + "-H", f"@{header_file}", "--data-binary", "@-", "--", url] + result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), + capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + answer, _, code = (result.stdout or b"").rpartition(b"\n") + return int(code.strip() or 0), answer except Exception: + return 0, b"" + finally: + if header_file: + try: + os.unlink(header_file) + except OSError: + pass + + +def _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets=()) -> str: + """The hook's own request shape and auth. 'sent' when the gateway took them; 'down' when it gave no + answer or a 5xx; 'refused' when it answered no. It refuses only a key (200 with success false, or a + 4xx), never an entry, so a refusal is about this home's key and not about what the log holds.""" + errors = [{**{k: v for k, v in entry.items() if k != "state"}, + "message": _redact_hook_error(entry["message"], (api_key, *secrets))} + for entry in batch] + code, answer = _post_hook_json(url, {"errors": errors, "hook_source": hook_source, "hook_sha": hook_sha}, + {"Authorization": f"Bearer {api_key}"}) + if code <= 0 or code >= 500: + return "down" + try: + taken = 200 <= code < 300 and json.loads(answer.decode("utf-8")).get("success") is True + except (ValueError, AttributeError): + taken = False + return "sent" if taken else "refused" + + +def _writable_dir(path: Path) -> bool: + """Runs as the home's user: the forwarded place can be saved in this folder.""" + return os.access(path, os.W_OK | os.X_OK) + + +def _home_device_key(home: Path): + """Runs as the home's user: (the key its hooks report errors with, every key in ~/.unbound/config.json + to redact), or None before setup first wrote it.""" + try: + config = json.loads(_read_user_file(home / ".unbound" / "config.json").decode("utf-8")) + except (OSError, ValueError): + return None + # The hooks' own order (cfg.get('api_key') or cfg.get('device_token')): their errors are this key's. + if not isinstance(config, dict): return None + key = config.get("api_key") or config.get("device_token") + secrets = tuple(v for v in (config.get("api_key"), config.get("device_token")) if isinstance(v, str) and v) + return (key, secrets) if isinstance(key, str) and key else None + + +def _forward_home_errors(username, log, send): + """(entries sent, 'sent' or the verdict that stopped it, whether every unsent entry went out). The place + is saved after each accepted request; where it can't be saved nothing more is sent, or every run would + send the same entries again.""" + if _run_as_user(username, _writable_dir, log.parent, _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: + print(f"[errors] {log} skipped: its forwarded place can't be saved beside it") + return 0, "sent", False + entries = _run_as_user(username, _unsent_hook_errors, log, _timeout=HOOK_ERROR_USER_TIMEOUT) + if entries is None: + return 0, "sent", False + for start in range(0, len(entries), HOOK_ERRORS_PER_REQUEST): + batch = entries[start:start + HOOK_ERRORS_PER_REQUEST] + verdict = send(batch) + if verdict != "sent": + return start, verdict, False + if _run_as_user(username, _save_forwarded, log, batch[-1]["state"], _timeout=HOOK_ERROR_USER_TIMEOUT) is not True: + print(f"[errors] {log}: forwarded place not saved; the rest waits for the next run") + return start + len(batch), "sent", False + return len(entries), "sent", True + + +def forward_hook_errors(user_homes, gateway_url, hook_path) -> list: + """Forward every home's unsent error.log entries for this tool, with that home's own key, before this run + changes anything. A gateway that is down ends forwarding for the run, so it costs one short timeout; a + refused key is that home's own and skips only that home. Either way nothing is marked sent, and the next + run retries. Never raises. Returns the (username, log) of every log not fully sent.""" + relpath, hook_source = HOOK_ERROR_LOG + unsent, sent, down = [], 0, False + try: + hook_sha = (hook_script_hash(hook_path) or "unknown")[:12] + url = gateway_url.rstrip("/") + "/v1/hooks/errors" + for username, home_dir in user_homes: + log = Path(home_dir) / relpath if home_dir is not None else None + if log is None or not os.path.lexists(log): + continue + found = None if down else _run_as_user(username, _home_device_key, Path(home_dir), + _timeout=HOOK_ERROR_USER_TIMEOUT) + if not found: + unsent.append((username, log)) # the gateway is down, or no hook here has a key yet + continue + api_key, secrets = found + count, verdict, done = _forward_home_errors( + username, log, lambda batch: _post_hook_errors(url, api_key, hook_source, hook_sha, batch, secrets)) + sent += count + if not done: + unsent.append((username, log)) + if verdict == "refused": + print(f"[errors] {TOOL_NAME} hook errors in {home_dir} not forwarded (key refused); the next run retries") + elif verdict == "down": + down = True + print(f"[errors] {TOOL_NAME} hook errors not forwarded (gateway down); the next run retries") + except Exception as e: + print(f"[errors] {TOOL_NAME} hook errors not forwarded: {e}") + if sent: + print(f"[errors] forwarded {sent} {TOOL_NAME} hook errors") + return unsent def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "https://backend.getunbound.ai", install_state: Optional[str] = None, serial_number: Optional[str] = None, - hook_hash: Optional[str] = None, install_mode: Optional[str] = None): - """Notify backend that tool setup completed. Never fails the setup.""" + hook_hash: Optional[str] = None, install_mode: Optional[str] = None, + status: Optional[str] = None, reason: Optional[str] = None, + written_to: Optional[str] = None): + """Notify backend of this run's outcome for the tool: configured, skipped or deferred (WEB-6392). Never fails the setup.""" try: url = f"{backend_url.rstrip('/')}/api/v1/setup/complete/" body = {"tool_type": tool_type, "managed": True} @@ -761,6 +1205,9 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http body["hook_hash"] = hook_hash if install_mode is not None: body["install_mode"] = install_mode + for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): + if value is not None: + body[key] = str(value)[:500] # the backend's limit data = json.dumps(body) subprocess.run( ["curl", "-fsSL", "-X", "POST", @@ -846,6 +1293,10 @@ def main(): print(" Or: sudo python3 setup.py --clear [--debug]") return False + # Before this run changes anything, with the key each home's hooks already report with. + homes = get_all_user_homes() + forward_hook_errors(homes, gateway_url, hook_script_path(homes[0][1]) if homes else None) + print("\nGetting device identifier...") device_id = get_device_identifier() if not device_id: @@ -860,10 +1311,21 @@ def main(): return False print("API key received") + tool_present = tool_installed(get_all_user_homes()) # before this run writes anything + + def report(status, reason=None, **fields): + """This tool's setup/complete for the run, whatever happened (WEB-6392). Configured on a device + without the tool reads skipped: its config is written all the same.""" + if status == "configured" and not tool_present: + status, reason = "skipped", f"{TOOL_NAME} is not installed" + notify_setup_complete(api_key, "antigravity", backend_url=base_url, serial_number=device_id, + install_mode="mdm", status=status, reason=reason, **fields) + print("\nDownloading hook script...") script_text = _fetch_hook_script(gateway_url) if script_text is None: print("Failed to download unbound.py") + report("deferred", "Failed to download unbound.py") return False state = detect_install_state() @@ -879,11 +1341,15 @@ def main(): success = bool(user_homes) and installed_count == len(user_homes) and config_ok if not user_homes: - print("No user home directories found") - elif success: - print(f"Installed Antigravity hooks for {installed_count} user(s)") + failure = "No user home directories found" + elif installed_count < len(user_homes): + failure = (f"Installed Antigravity hooks for {installed_count} of {len(user_homes)} user(s);" + f" {len(user_homes) - installed_count} failed") + elif not config_ok: + failure = "Could not write ~/.unbound/config.json for every user" else: - print(f"Installed Antigravity hooks for {installed_count} of {len(user_homes)} user(s); {len(user_homes) - installed_count} failed") + failure = None + print(failure or f"Installed Antigravity hooks for {installed_count} user(s)") print("\n" + "=" * 60) print("Setup Complete!" if success else "Setup Failed") @@ -891,9 +1357,14 @@ def main(): if success: # Every user gets the same script bytes, so the first copy identifies the version. - notify_setup_complete(api_key, "antigravity", backend_url=base_url, install_state=state, serial_number=device_id, - hook_hash=hook_script_hash(hook_script_path(user_homes[0][1])), - install_mode="mdm") + report("configured", install_state=state, hook_hash=hook_script_hash(hook_script_path(user_homes[0][1])), + written_to="~/.gemini/config/hooks.json") + elif user_homes and installed_count == 0: + # A user can make every install fail: the report carries the state found, and the backend counts + # a tamper on a deferred report without marking the tool connected or deployed. Same rule as Copilot. + report("deferred", failure, install_state=state) + else: + report("deferred", failure) return success diff --git a/tests/antigravity/hooks/mdm/test_setup.py b/tests/antigravity/hooks/mdm/test_setup.py index e0c2a5fc7..03a3b1df7 100644 --- a/tests/antigravity/hooks/mdm/test_setup.py +++ b/tests/antigravity/hooks/mdm/test_setup.py @@ -156,11 +156,14 @@ def test_main_installs_for_every_user_and_reports_an_mdm_install(self): self.assertEqual(notify.call_args.kwargs["install_state"], "fresh") self.assertEqual(notify.call_args.kwargs["hook_hash"], hashlib.sha256(SCRIPT.encode()).hexdigest()) - def test_main_fails_and_does_not_report_when_a_user_fails(self): + def test_main_fails_and_reports_deferred_when_a_user_fails(self): + """WEB-6392: every run reports, so a failed install says why instead of going quiet.""" self.write_hooks([]) ok, notify = self.run_main() self.assertFalse(ok) - notify.assert_not_called() + notify.assert_called_once() + self.assertEqual(notify.call_args.kwargs["status"], "deferred") + self.assertIn("0 of 1 user(s)", notify.call_args.kwargs["reason"]) if __name__ == "__main__": diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index d43906bf2..b1e54f043 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -22,9 +22,9 @@ ERROR_LOGS = {"claude-code": ".claude/hooks/error.log", "cursor": ".cursor/hooks/error.log", "codex": ".codex/hooks/error.log", "copilot": ".copilot/hooks/error.log", - "augment": ".augment/hooks/error.log"} + "augment": ".augment/hooks/error.log", "antigravity": ".gemini/antigravity-hooks/error.log"} HOOK_SOURCES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", - "augment": "augment_code"} + "augment": "augment_code", "antigravity": "antigravity"} STATE = ".error_log_forwarded" OK = {"status": "ok", "success": True, "accepted": 1} REFUSED = {"success": False, "reason": "invalid_key"} @@ -612,7 +612,7 @@ def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gatewa assert log.exists() -# --- The five copies stay equal, and equal to the binary --------------------------- +# --- The copies stay equal, and equal to the binary --------------------------- SHARED_FUNCTIONS = ("_log_time", "_entry_digest", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", @@ -642,7 +642,7 @@ def _value(module, name): @pytest.mark.parametrize("name", SHARED_FUNCTIONS + SHARED_DATA) -def test_the_five_copies_are_identical(name): +def test_every_copy_is_identical(name): first = _value(load_module(MODULES["claude-code"]), name) assert all(_value(load_module(MODULES[tool]), name) == first for tool in MODULES), name @@ -652,11 +652,19 @@ def test_the_limits_and_redaction_are_the_binarys(binary, name): assert _value(load_module(MODULES["claude-code"]), name) == _value(binary, name) -@pytest.mark.parametrize("tool", sorted(MODULES)) +# Antigravity has no unbound-hook binary install yet: its MDM script is the only one that forwards its log. +@pytest.mark.parametrize("tool", sorted(set(MODULES) - {"antigravity"})) def test_each_script_forwards_the_log_the_binary_does_for_its_tool(binary, tool): assert load_module(MODULES[tool]).HOOK_ERROR_LOG == binary._HOOK_ERROR_LOGS[tool] +def test_antigravity_forwards_the_log_its_hook_writes(): + hook = load_module("antigravity/hooks/unbound.py") + log, source = load_module(MODULES["antigravity"]).HOOK_ERROR_LOG + assert hook.ERROR_LOG == __import__("pathlib").Path.home() / log + assert source == "antigravity" + + @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="FIFOs are POSIX") @pytest.mark.parametrize("tool", ["copilot", "codex"]) def test_the_hook_hashed_before_install_is_read_as_a_users_file(tool, tmp_path): diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py index 392a38229..0952d044b 100644 --- a/tests/test_mdm_setup_status.py +++ b/tests/test_mdm_setup_status.py @@ -17,9 +17,10 @@ "codex": "codex/hooks/mdm/setup.py", "copilot": "copilot/hooks/mdm/setup.py", "augment": "augment/hooks/mdm/setup.py", + "antigravity": "antigravity/hooks/mdm/setup.py", } TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", - "augment": "augment_code"} + "augment": "augment_code", "antigravity": "antigravity"} class Run: @@ -40,7 +41,6 @@ def __init__(self, tool, tmp_path, monkeypatch): self.stub("fetch_api_key_from_mdm", "device-key") self.stub("get_all_user_homes", [("u", self.home)]) self.stub("write_unbound_config_for_user", True) - self.stub("remove_legacy_key_env", None) self.stub("detect_install_state", "fresh") self.stub("hook_script_hash", "h" * 64) monkeypatch.setattr(m, "notify_setup_complete", lambda key, tool_type, **k: self.reports.append( @@ -49,7 +49,7 @@ def __init__(self, tool, tmp_path, monkeypatch): for name in ("set_env_var_system_wide",): if hasattr(m, name): self.stub(name, (True, False)) - for name in ("remove_env_var_from_user", "remove_gateway_artifacts_for_user", "remove_user_level_hooks", + for name in ("remove_legacy_key_env", "remove_env_var_from_user", "remove_gateway_artifacts_for_user", "remove_user_level_hooks", "remove_user_level_hooks_for_user", "_freeze_ownership_evidence", "clear_otel_export_for_user", "enable_codex_hooks_feature_for_user", "restart_cursor", "run_visual_studio_sweep"): if hasattr(m, name): @@ -91,6 +91,10 @@ def _augment(self): self.writer("setup_managed_hooks") self.stub("verify_managed_hooks_installed", True) + def _antigravity(self): + self.stub("_fetch_hook_script", "# hook") + self.writer("install_hooks_for_user") + def __call__(self): return self.m.main() @@ -111,6 +115,7 @@ def run(tmp_path, monkeypatch): "codex": lambda r: str(r.managed / "hooks.json"), "copilot": lambda r: "~/.copilot/hooks/unbound.json", "augment": lambda r: str(r.managed / "settings.json"), + "antigravity": lambda r: "~/.gemini/config/hooks.json", } @@ -152,6 +157,9 @@ def test_a_tool_that_is_not_installed_is_reported_skipped_and_still_set_up(run, ("augment", "set_env_var_system_wide", (False, False), "Failed to set UNBOUND_BACKEND_URL"), ("augment", "setup_managed_hooks", False, "Failed to configure managed hooks"), ("augment", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), + ("antigravity", "_fetch_hook_script", None, "Failed to download unbound.py"), + ("antigravity", "get_all_user_homes", [], "No user home directories found"), + ("antigravity", "write_unbound_config_for_user", False, "Could not write ~/.unbound/config.json for every user"), ] @@ -209,6 +217,28 @@ def test_copilot_with_some_installs_failed_reports_how_many(run): assert "install_state" not in r.report +def test_antigravity_with_every_install_failed_sends_one_deferred_report_with_the_tamper(run): + r = run("antigravity") + r.stub("detect_install_state", "tampered") + r.writer("install_hooks_for_user", False) + assert r() is False + report = r.report + assert (report["status"], report["reason"], report["install_state"]) == ( + "deferred", "Installed Antigravity hooks for 0 of 1 user(s); 1 failed", "tampered") + + +def test_antigravity_with_some_installs_failed_reports_how_many(run): + r = run("antigravity") + other = r.home.parent / "other" + other.mkdir() + r.stub("get_all_user_homes", [("u", r.home), ("v", other)]) + answers = iter([True, False]) + r.mp.setattr(r.m, "install_hooks_for_user", lambda *a, **k: next(answers)) + assert r() is False + assert (r.report["status"], r.report["reason"]) == ("deferred", "Installed Antigravity hooks for 1 of 2 user(s); 1 failed") + assert "install_state" not in r.report + + @pytest.mark.parametrize("tool", sorted(MODULES)) def test_a_failure_before_the_key_sends_nothing(run, tool): """Without the device key there is nothing to report with; the exit code says it.""" diff --git a/tests/test_tool_installed.py b/tests/test_tool_installed.py index 6d5de6a52..7045fe236 100644 --- a/tests/test_tool_installed.py +++ b/tests/test_tool_installed.py @@ -2,7 +2,7 @@ Every tool's MDM script is fetched and run on its own, so each carries the same check with its own footprints; the unbound-hook binary calls the same function. These tests pin the footprints per OS, the -shared CLI folders, and that the five copies stay identical.""" +shared CLI folders, and that the copies stay identical.""" import inspect from pathlib import Path @@ -17,9 +17,10 @@ "codex": "codex/hooks/mdm/setup.py", "copilot": "copilot/hooks/mdm/setup.py", "augment": "augment/hooks/mdm/setup.py", + "antigravity": "antigravity/hooks/mdm/setup.py", } NAMES = {"claude-code": "Claude Code", "cursor": "Cursor", "codex": "Codex", "copilot": "GitHub Copilot", - "augment": "Augment"} + "augment": "Augment", "antigravity": "Antigravity"} def _mod(tool): @@ -90,6 +91,17 @@ def _installed(tool, system, box): ("augment", "linux", "machine", "usr/bin/auggie"), ("augment", "windows", "home", ".cursor/extensions/augment.vscode-augment-0.512.0"), ("augment", "windows", "home", "AppData/Roaming/npm/auggie.ps1"), + ("antigravity", "darwin", "machine", "Applications/Antigravity.app"), + ("antigravity", "darwin", "home", "Applications/Antigravity.app"), + ("antigravity", "linux", "machine", "usr/share/antigravity"), + ("antigravity", "linux", "machine", "opt/Antigravity"), + ("antigravity", "linux", "machine", "usr/bin/antigravity"), + ("antigravity", "windows", "home", "AppData/Local/Programs/Antigravity"), + ("antigravity", "windows", "machine", "Program Files/Antigravity"), + # Its own data folder, on every OS: what the app writes on first run, beside our hooks folder. + ("antigravity", "darwin", "home", ".gemini/antigravity"), + ("antigravity", "linux", "home", ".gemini/antigravity"), + ("antigravity", "windows", "home", ".gemini/antigravity"), ] @@ -126,6 +138,14 @@ def test_a_tool_is_not_found_by_another_tools_footprint(box): assert _installed("copilot", "darwin", box) is False +def test_our_own_antigravity_hook_and_gemini_cli_do_not_count_as_antigravity(box): + """Setup writes ~/.gemini/antigravity-hooks and ~/.gemini/config itself, and the Gemini CLI uses ~/.gemini.""" + _, home = box + for relpath in (".gemini/antigravity-hooks/unbound.py", ".gemini/config/hooks.json", ".gemini/settings.json"): + _plant(home, relpath) + assert _installed("antigravity", "darwin", box) is False + + @pytest.mark.parametrize("prefix", ["~/.npm-packages", "$HOME/.npm-packages", "${HOME}/.npm-packages"]) def test_an_npm_prefix_from_npmrc_counts_on_unix(box, prefix): _, home = box @@ -163,7 +183,7 @@ def test_each_module_names_its_tool(): @pytest.mark.parametrize("name", SHARED_FUNCTIONS + SHARED_DATA) -def test_the_five_copies_are_identical(name): +def test_every_copy_is_identical(name): def value(tool): obj = getattr(_mod(tool), name) return inspect.getsource(obj) if callable(obj) else obj diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index 809843a45..9bef4f469 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -197,6 +197,7 @@ def test_a_patch_into_a_spaced_repo_is_judged(self, tmp_path): "codex": "codex/hooks/mdm", "copilot": "copilot/hooks/mdm", "augment": "augment/hooks/mdm", + "antigravity": "antigravity/hooks/mdm", } From d43c8a05439089da05e279034b2c4baba1f57ea9 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Mon, 30 Nov 2026 14:54:20 +0530 Subject: [PATCH 50/53] fix(setup): report copilot deferred when its hook installs for only some users [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 6 ++++++ binary/tests/test_setup_migration.py | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 698feff95..39b9577a2 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -1856,6 +1856,12 @@ def _setup_copilot(opts): # tamper on a deferred report without marking the tool connected or deployed. return report("deferred", "hook install failed for all users", install_state=state) + # A user whose install failed has no hook, so the tool isn't configured here; the MDM script reports the same. + eligible = sum(1 for _username, home_dir in user_homes if home_dir is not None) + if installed < eligible: + return report("deferred", f"Installed Copilot hooks for {installed} of {eligible} user(s)" + f" — {eligible - installed} failed") + if not config_ok: return report("deferred", "config.json write failed for some users") diff --git a/binary/tests/test_setup_migration.py b/binary/tests/test_setup_migration.py index b53147f23..87ab47c77 100644 --- a/binary/tests/test_setup_migration.py +++ b/binary/tests/test_setup_migration.py @@ -1832,6 +1832,24 @@ def _as_user(_u, fn, *a, _timeout=None, **k): # the real helper returns None wh assert (report["status"], report["reason"]) == ("deferred", "hook install failed for all users") +def test_copilot_failing_for_one_of_two_users_is_deferred_not_configured(env, monkeypatch): + """The MDM script says the same: the failed user has no hook, so the tool isn't configured on this device.""" + second = env["tmp"] / "home2" + second.mkdir() + monkeypatch.setattr(env["modules"]["copilot"], "get_all_user_homes", + lambda: [(ME, env["home"]), (ME, second)]) + monkeypatch.setattr(setup_cmd, "_tool_installed", lambda tool, homes: True) + real_install = setup_cmd._install_copilot_hooks_for_user + monkeypatch.setattr(setup_cmd, "_install_copilot_hooks_for_user", + lambda m, u, home: False if home == second else real_install(m, u, home)) + + setup_cmd.run(["--api-key", "admin-key"]) + + [report] = [k for a, k in env["notified"] if a[1] == "copilot"] + assert (report["status"], report["reason"]) == ( + "deferred", "Installed Copilot hooks for 1 of 2 user(s) — 1 failed") + + @pytest.mark.parametrize("tool", ["claude-code", "augment_code"]) def test_the_managed_writer_drops_a_nan_it_would_otherwise_write_back(env, tool): assert setup_cmd.run(["--api-key", "admin-key"]) == 0 From 0925caf72e58436a3bf2339ad6a4bbd0e7f7e907 Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Mon, 30 Nov 2026 15:13:47 +0530 Subject: [PATCH 51/53] fix(mdm): save a user's file on windows by handle into the checked folder and redact github and basic credentials [WEB-6392] --- antigravity/hooks/mdm/setup.py | 83 ++++++++++++++++++++++++++-- augment/hooks/mdm/setup.py | 83 ++++++++++++++++++++++++++-- binary/src/unbound_hook/setup_cmd.py | 7 ++- claude-code/hooks/mdm/setup.py | 83 ++++++++++++++++++++++++++-- codex/hooks/mdm/setup.py | 83 ++++++++++++++++++++++++++-- copilot/hooks/mdm/setup.py | 83 ++++++++++++++++++++++++++-- cursor/mdm/setup.py | 83 ++++++++++++++++++++++++++-- tests/test_mdm_hook_errors.py | 12 +++- tests/test_windows_paths.py | 44 +++++++++++++++ 9 files changed, 531 insertions(+), 30 deletions(-) diff --git a/antigravity/hooks/mdm/setup.py b/antigravity/hooks/mdm/setup.py index 706fd7b06..8a670dad5 100644 --- a/antigravity/hooks/mdm/setup.py +++ b/antigravity/hooks/mdm/setup.py @@ -875,10 +875,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -967,7 +967,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -986,6 +988,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -1061,7 +1135,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index f60a4bcc3..0c89a7e90 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1581,10 +1581,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -1673,7 +1673,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -1692,6 +1694,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -1767,7 +1841,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 39b9577a2..fa138ee78 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -379,10 +379,10 @@ def _save_forwarded(log: Path, state: str) -> bool: return True -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _redact_hook_error(message: str, secrets) -> str: @@ -390,7 +390,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index 0d96e9181..bf458d2ef 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3436,10 +3436,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -3528,7 +3528,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -3547,6 +3549,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -3622,7 +3696,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index c4450c4a2..cdbc0d6ea 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2569,10 +2569,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -2661,7 +2661,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -2680,6 +2682,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -2755,7 +2829,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 1bf566da2..3a3d060f9 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2223,10 +2223,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -2315,7 +2315,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -2334,6 +2336,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -2409,7 +2483,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index a787499db..e50c80b87 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1461,10 +1461,10 @@ def tool_installed(user_homes, system: Optional[str] = None, machine_root: Optio _USER_FILE_MAX_BYTES = 4 * 1024 * 1024 # A user's file: never followed if it is a link, never waited on if it is a FIFO, never text-mode on Windows. _USER_FILE_FLAGS = getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) -_BEARER = re.compile(r"(?i)\bBearer\s+\S+") +_BEARER = re.compile(r"""(?i)\b(Bearer|(?:Proxy-)?Authorization\s*[:=]\s*"?Basic)\s+[^\s"',;]+""") _NAMED_SECRET = re.compile(r"""(?i)\b([A-Za-z0-9_-]*(?:api[_-]?key|token|secret|password|passwd))("?\s*[:=]\s*"?)([^\s"',;&}]+)""") _URL_SECRET = re.compile(r"(?i)([?&](?:key|token|api_key|access_token|sig|signature)=)[^&\s\"]+") -_VENDOR_KEY = re.compile(r"\bsk-[A-Za-z0-9_-]{10,}") +_VENDOR_KEY = re.compile(r"\b(?:sk-[A-Za-z0-9_-]{10,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})") def _log_time(text): @@ -1553,7 +1553,9 @@ def _read_user_file_tail(path: Path, max_bytes: int) -> bytes: def _replace_user_file(path: Path, data: bytes) -> None: """Write data (0600) beside path and rename it over: a link or FIFO there is replaced, not written - through, and a failed write leaves the old file in place.""" + through, and a failed write leaves the old file in place. Windows goes through _replace_user_file_nt.""" + if os.name == "nt": + return _replace_user_file_nt(path, data) tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp") _refuse_links_on_the_way(tmp) if os.path.lexists(tmp): @@ -1572,6 +1574,78 @@ def _replace_user_file(path: Path, data: bytes) -> None: raise +def _replace_user_file_nt(path: Path, data: bytes) -> None: + """Windows, where SYSTEM writes a user's file itself: the folder is opened and checked first, the temporary + file is created new in it and checked, and the rename goes by handle into that same opened folder, so a + link or junction swapped in after a check can't move the write anywhere else. A failure deletes the + temporary file by its handle and leaves the old file in place.""" + import ctypes + import msvcrt + from ctypes import wintypes + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.CreateFileW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, + wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE) + kernel32.CreateFileW.restype = wintypes.HANDLE + kernel32.GetFinalPathNameByHandleW.argtypes = (wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, wintypes.DWORD) + kernel32.GetFinalPathNameByHandleW.restype = wintypes.DWORD + kernel32.GetLongPathNameW.argtypes = (wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD) + kernel32.GetLongPathNameW.restype = wintypes.DWORD + kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) + kernel32.SetFileInformationByHandle.restype = wintypes.BOOL + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + invalid = wintypes.HANDLE(-1).value + + def plain(name): + return "\\\\" + name[8:] if name.startswith("\\\\?\\UNC\\") else name[4:] if name.startswith("\\\\?\\") else name + + def is_at(handle, asked): + final, long_asked = ctypes.create_unicode_buffer(32768), ctypes.create_unicode_buffer(32768) + got = kernel32.GetFinalPathNameByHandleW(handle, final, len(final), 0) + wanted = kernel32.GetLongPathNameW(asked, long_asked, len(long_asked)) + return (0 < got < len(final) and 0 < wanted < len(long_asked) + and os.path.normcase(plain(final.value)) == os.path.normcase(plain(long_asked.value))) + + class _Disposition(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + class _Rename(ctypes.Structure): + _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), + ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] + + folder = os.path.abspath(str(path.parent)) + # FILE_TRAVERSE | FILE_ADD_FILE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, a link on the way followed so the check sees it. + folder_handle = kernel32.CreateFileW(folder, 0x20 | 0x2 | 0x80 | 0x100000, 0x7, None, 3, 0x02000000, None) + if folder_handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd, renamed = None, False + try: + if not is_at(folder_handle, folder): + raise OSError(f"{path.parent} is reached through a link or junction") + tmp = os.path.join(folder, f".{path.name}.{os.getpid()}.{os.urandom(4).hex()}.tmp") + # GENERIC_WRITE | DELETE | FILE_READ_ATTRIBUTES, CREATE_NEW, never opened through a link already there. + handle = kernel32.CreateFileW(tmp, 0x40000000 | 0x10000 | 0x80, 0x7, None, 1, 0x80 | 0x00200000, None) + if handle in (None, invalid): + raise ctypes.WinError(ctypes.get_last_error()) + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + if not is_at(handle, tmp): + raise OSError(f"{tmp} is reached through a link or junction") + view = memoryview(data) + while view: + view = view[os.write(fd, view):] + rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) + if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): + raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + renamed = True + finally: + if fd is not None: + if not renamed: + disposition = _Disposition(True) + kernel32.SetFileInformationByHandle(msvcrt.get_osfhandle(fd), 4, ctypes.byref(disposition), + ctypes.sizeof(disposition)) # FileDispositionInfo + os.close(fd) + kernel32.CloseHandle(folder_handle) + + def _forwarded_place(log: Path): """(timestamp, how many entries stamped then were sent, their digests or None) from the state file; (None, 0, None) for none. Without digests (written before them) the count alone says which were sent, @@ -1647,7 +1721,8 @@ def _redact_hook_error(message: str, secrets) -> str: for secret in secrets: if secret: message = message.replace(secret, "[REDACTED]") - message = _BEARER.sub("Bearer [REDACTED]", message) + message = _BEARER.sub(lambda found: ("Bearer" if found.group(1).lower() == "bearer" else found.group(1)) + " [REDACTED]", + message) message = _NAMED_SECRET.sub(r"\1\2[REDACTED]", message) message = _URL_SECRET.sub(r"\1[REDACTED]", message) return _VENDOR_KEY.sub("[REDACTED]", message) diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index b1e54f043..cdd37ebcf 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -379,6 +379,7 @@ def test_a_multi_line_entry_goes_up_whole_cut_and_redacted(setup, gateway): def test_the_homes_keys_and_common_credential_shapes_are_redacted(setup, gateway): r = setup("augment") vendor_key = "sk-" + "fake-" + "0" * 16 # built at runtime so secret scanners skip this fixture + github_token, github_pat = "ghp" + "_" + "F" * 36, "github" + "_pat_" + "F" * 40 # fake, built the same way (r.home / ".unbound").mkdir() (r.home / ".unbound" / "config.json").write_text(json.dumps({"device_token": "token-key-2", "api_key": "api-key-1"})) _log(r.home, "augment", [ @@ -387,15 +388,20 @@ def test_the_homes_keys_and_common_credential_shapes_are_redacted(setup, gateway f"{_utc(2)}: vendor key {vendor_key} leaked", f"{_utc(3)}: GET https://api.example.com/v1?key=url-secret-7&page=2 failed", f'{_utc(4)}: config {{"password": "pw-secret-6", "token":"tok-secret-5"}}', - f"{_utc(5)}: retry said bearer tok_lower and gave up"], key=None) + f"{_utc(5)}: retry said bearer tok_lower and gave up", + f"{_utc(6)}: git push used {github_token} and {github_pat}", + f"{_utc(7)}: proxy sent Authorization: Basic dXNlcjpiYXNpYy1zZWNyZXQ= and got 407"], key=None) r() body = json.dumps(_forwarded(gateway)[0]["body"]) for secret in ("token-key-2", "api-key-1", "hdr-secret-9", "env-secret-8", vendor_key, - "url-secret-7", "pw-secret-6", "tok-secret-5", "tok_lower"): + "url-secret-7", "pw-secret-6", "tok-secret-5", "tok_lower", github_token, github_pat, + "dXNlcjpiYXNpYy1zZWNyZXQ="): assert secret not in body, secret messages = _messages(gateway) assert messages[3] == "GET https://api.example.com/v1?key=[REDACTED]&page=2 failed" assert messages[5] == "retry said Bearer [REDACTED] and gave up" + assert messages[6] == "git push used [REDACTED] and [REDACTED]" + assert messages[7] == "proxy sent Authorization: Basic [REDACTED] and got 407" def test_an_oversized_log_is_read_from_its_end(setup, gateway): @@ -614,7 +620,7 @@ def test_a_cursor_log_in_a_home_without_a_key_survives_its_cleanup(setup, gatewa # --- The copies stay equal, and equal to the binary --------------------------- -SHARED_FUNCTIONS = ("_log_time", "_entry_digest", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_forwarded_place", +SHARED_FUNCTIONS = ("_log_time", "_entry_digest", "_refuse_links_on_the_way", "_refuse_if_redirected", "_read_user_file", "_read_user_file_tail", "_replace_user_file", "_replace_user_file_nt", "_forwarded_place", "_unsent_hook_errors", "_save_forwarded", "_redact_hook_error", "_post_hook_json", "_post_hook_errors", "_writable_dir", "_home_device_key", "_forward_home_errors", "forward_hook_errors") diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index 9bef4f469..794d36f96 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -232,6 +232,50 @@ def test_setup_never_reads_or_writes_a_users_file_through_a_junction(tool, tmp_p assert (tmp_path / "state").read_bytes() == b"saved" +@windows_only +@pytest.mark.parametrize("tool", sorted(MDM_SCRIPTS)) +def test_saving_the_place_stays_in_the_folder_checked_when_a_junction_is_swapped_in(tool, tmp_path, monkeypatch): + """SYSTEM saves the forwarded place: swapping the hooks folder for a junction after setup checked it, + while the file is being written, must not move the write into a folder only SYSTEM can write.""" + import _winapi + m = tool_module(MDM_SCRIPTS[tool], "setup") + private = tmp_path / "private" + private.mkdir() + hooks = tmp_path / "home" / "hooks" + hooks.mkdir(parents=True) + real_write, swapped = os.write, [] + + def write(fd, data): + if not swapped: + try: + os.rename(hooks, tmp_path / "home" / "moved") + _winapi.CreateJunction(str(private), str(hooks)) + swapped.append(True) + except OSError: # Windows refused to move the folder, so nothing could be swapped in + swapped.append(False) + return real_write(fd, data) + + monkeypatch.setattr(os, "write", write) + try: + m._replace_user_file(hooks / ".error_log_forwarded", b"2026-01-01T00:00:00.000Z 1") + except OSError: + pass + monkeypatch.undo() + assert swapped, "the write must run between the checks and the rename" + assert list(private.iterdir()) == [] + + +@windows_only +@pytest.mark.parametrize("tool", sorted(MDM_SCRIPTS)) +def test_saving_the_place_replaces_the_old_one_and_leaves_no_temporary_file(tool, tmp_path): + m = tool_module(MDM_SCRIPTS[tool], "setup") + state = tmp_path / ".error_log_forwarded" + state.write_bytes(b"old") + m._replace_user_file(state, b"new") + assert state.read_bytes() == b"new" + assert [p.name for p in tmp_path.iterdir()] == [".error_log_forwarded"] + + @windows_only def test_cursor_cleanup_keeps_only_the_log_and_its_place(tmp_path): m = tool_module("cursor/mdm", "setup") From 65d25be1497925a73b0bacfda4afda98c5e02bfb Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Mon, 30 Nov 2026 15:24:07 +0530 Subject: [PATCH 52/53] fix(mdm): keep setup report keys off curl's arguments and rename on windows through ntdll [WEB-6392] --- antigravity/hooks/mdm/setup.py | 39 ++++++++++++++++++++-------------- augment/hooks/mdm/setup.py | 27 +++++++++++++++++------ claude-code/hooks/mdm/setup.py | 39 ++++++++++++++++++++-------------- codex/hooks/mdm/setup.py | 39 ++++++++++++++++++++-------------- copilot/hooks/mdm/setup.py | 39 ++++++++++++++++++++-------------- cursor/mdm/setup.py | 39 ++++++++++++++++++++-------------- tests/test_mdm_setup_status.py | 24 +++++++++++++++++++++ 7 files changed, 160 insertions(+), 86 deletions(-) diff --git a/antigravity/hooks/mdm/setup.py b/antigravity/hooks/mdm/setup.py index 8a670dad5..bf7e283f9 100644 --- a/antigravity/hooks/mdm/setup.py +++ b/antigravity/hooks/mdm/setup.py @@ -1007,6 +1007,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -1022,6 +1030,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -1047,8 +1058,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -1142,9 +1155,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -1152,10 +1166,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: @@ -1283,16 +1298,8 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): if value is not None: body[key] = str(value)[:500] # the backend's limit - data = json.dumps(body) - subprocess.run( - ["curl", "-fsSL", "-X", "POST", - "-H", f"X-API-KEY: {api_key}", - "-H", "Content-Type: application/json", - "--data-binary", "@-", url], - input=data.encode(), - capture_output=True, - timeout=10, - ) + # The key goes to curl in a 0600 header file: any local user can read a process's arguments. + _post_hook_json(url, body, {"X-API-KEY": api_key}, seconds=10) debug_print("Setup completion notification sent") except Exception as e: debug_print(f"Could not notify backend: {e}") diff --git a/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index 0c89a7e90..3e15b3eee 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -1713,6 +1713,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -1728,6 +1736,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -1753,8 +1764,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -1848,9 +1861,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -1858,10 +1872,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index bf458d2ef..28719e4ce 100644 --- a/claude-code/hooks/mdm/setup.py +++ b/claude-code/hooks/mdm/setup.py @@ -3568,6 +3568,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -3583,6 +3591,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -3608,8 +3619,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -3703,9 +3716,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -3713,10 +3727,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: @@ -3845,16 +3860,8 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): if value is not None: body[key] = str(value)[:500] # the backend's limit - data = json.dumps(body) - subprocess.run( - ["curl", "-fsSL", "-X", "POST", - "-H", f"X-API-KEY: {api_key}", - "-H", "Content-Type: application/json", - "--data-binary", "@-", url], - input=data.encode(), - capture_output=True, - timeout=10, - ) + # The key goes to curl in a 0600 header file: any local user can read a process's arguments. + _post_hook_json(url, body, {"X-API-KEY": api_key}, seconds=10) debug_print("Setup completion notification sent") except Exception as e: debug_print(f"Could not notify backend: {e}") diff --git a/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index cdbc0d6ea..0e924bf69 100644 --- a/codex/hooks/mdm/setup.py +++ b/codex/hooks/mdm/setup.py @@ -2701,6 +2701,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -2716,6 +2724,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -2741,8 +2752,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -2836,9 +2849,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -2846,10 +2860,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: @@ -2978,16 +2993,8 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): if value is not None: body[key] = str(value)[:500] # the backend's limit - data = json.dumps(body) - subprocess.run( - ["curl", "-fsSL", "-X", "POST", - "-H", f"X-API-KEY: {api_key}", - "-H", "Content-Type: application/json", - "--data-binary", "@-", url], - input=data.encode(), - capture_output=True, - timeout=10, - ) + # The key goes to curl in a 0600 header file: any local user can read a process's arguments. + _post_hook_json(url, body, {"X-API-KEY": api_key}, seconds=10) debug_print("Setup completion notification sent") except Exception as e: debug_print(f"Could not notify backend: {e}") diff --git a/copilot/hooks/mdm/setup.py b/copilot/hooks/mdm/setup.py index 3a3d060f9..135674e3a 100644 --- a/copilot/hooks/mdm/setup.py +++ b/copilot/hooks/mdm/setup.py @@ -2355,6 +2355,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -2370,6 +2378,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -2395,8 +2406,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -2490,9 +2503,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -2500,10 +2514,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: @@ -2632,16 +2647,8 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): if value is not None: body[key] = str(value)[:500] # the backend's limit - data = json.dumps(body) - subprocess.run( - ["curl", "-fsSL", "-X", "POST", - "-H", f"X-API-KEY: {api_key}", - "-H", "Content-Type: application/json", - "--data-binary", "@-", url], - input=data.encode(), - capture_output=True, - timeout=10, - ) + # The key goes to curl in a 0600 header file: any local user can read a process's arguments. + _post_hook_json(url, body, {"X-API-KEY": api_key}, seconds=10) debug_print("Setup completion notification sent") except Exception as e: debug_print(f"Could not notify backend: {e}") diff --git a/cursor/mdm/setup.py b/cursor/mdm/setup.py index e50c80b87..6b5f0c001 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -1593,6 +1593,14 @@ def _replace_user_file_nt(path: Path, data: bytes) -> None: kernel32.SetFileInformationByHandle.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD) kernel32.SetFileInformationByHandle.restype = wintypes.BOOL kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + # kernel32's FileRenameInfo makes the name a full path, which a RootDirectory then rejects (error 87), so the + # rename goes to ntdll, which takes the name relative to the folder handle as given. + ntdll = ctypes.WinDLL("ntdll") + ntdll.NtSetInformationFile.argtypes = (wintypes.HANDLE, ctypes.c_void_p, ctypes.c_void_p, wintypes.ULONG, + ctypes.c_int) + ntdll.NtSetInformationFile.restype = wintypes.LONG + ntdll.RtlNtStatusToDosError.argtypes = (wintypes.LONG,) + ntdll.RtlNtStatusToDosError.restype = wintypes.ULONG invalid = wintypes.HANDLE(-1).value def plain(name): @@ -1608,6 +1616,9 @@ def is_at(handle, asked): class _Disposition(ctypes.Structure): _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + class _IoStatus(ctypes.Structure): + _fields_ = [("Status", ctypes.c_void_p), ("Information", ctypes.c_size_t)] + class _Rename(ctypes.Structure): _fields_ = [("ReplaceIfExists", wintypes.DWORD), ("RootDirectory", wintypes.HANDLE), ("FileNameLength", wintypes.DWORD), ("FileName", ctypes.c_wchar * (len(path.name) + 1))] @@ -1633,8 +1644,10 @@ class _Rename(ctypes.Structure): while view: view = view[os.write(fd, view):] rename = _Rename(1, folder_handle, len(path.name) * 2, path.name) - if not kernel32.SetFileInformationByHandle(handle, 3, ctypes.byref(rename), ctypes.sizeof(rename)): - raise ctypes.WinError(ctypes.get_last_error()) # FileRenameInfo, relative to the folder opened above + status = ntdll.NtSetInformationFile(handle, ctypes.byref(_IoStatus()), ctypes.byref(rename), + ctypes.sizeof(rename), 10) # FileRenameInformation, relative to the folder + if status != 0: + raise ctypes.WinError(ntdll.RtlNtStatusToDosError(status)) renamed = True finally: if fd is not None: @@ -1728,9 +1741,10 @@ def _redact_hook_error(message: str, secrets) -> str: return _VENDOR_KEY.sub("[REDACTED]", message) -def _post_hook_json(url, body, headers): +def _post_hook_json(url, body, headers, seconds=None): """POST a JSON body with curl (the system trust store, as every call here uses). Returns (http status, - response bytes); status 0 when nothing came back. Never raises. The headers carry the key, and any local + response bytes); status 0 when nothing came back. Never raises. seconds defaults to HOOK_ERROR_TIMEOUT_SECONDS. + The headers carry the key, and any local user can read a process's argv, so they go to curl in a 0600 file (-H @file) that is removed afterwards.""" header_file = None try: @@ -1738,10 +1752,11 @@ def _post_hook_json(url, body, headers): with os.fdopen(fd, "w", encoding="utf-8") as f: f.write("".join(f"{name}: {value}\n" for name, value in {"Content-Type": "application/json", **headers}.items())) - cmd = ["curl", "-sS", "-m", str(HOOK_ERROR_TIMEOUT_SECONDS), "-X", "POST", "-w", "\n%{http_code}", + seconds = seconds or HOOK_ERROR_TIMEOUT_SECONDS + cmd = ["curl", "-sS", "-m", str(seconds), "-X", "POST", "-w", "\n%{http_code}", "-H", f"@{header_file}", "--data-binary", "@-", "--", url] result = subprocess.run(cmd, input=json.dumps(body).encode("utf-8"), - capture_output=True, timeout=HOOK_ERROR_TIMEOUT_SECONDS + 3) + capture_output=True, timeout=seconds + 3) answer, _, code = (result.stdout or b"").rpartition(b"\n") return int(code.strip() or 0), answer except Exception: @@ -1870,16 +1885,8 @@ def notify_setup_complete(api_key: str, tool_type: str, backend_url: str = "http for key, value in (("status", status), ("reason", reason), ("written_to", written_to)): if value is not None: body[key] = str(value)[:500] # the backend's limit - data = json.dumps(body) - subprocess.run( - ["curl", "-fsSL", "-X", "POST", - "-H", f"X-API-KEY: {api_key}", - "-H", "Content-Type: application/json", - "--data-binary", "@-", url], - input=data.encode(), - capture_output=True, - timeout=10, - ) + # The key goes to curl in a 0600 header file: any local user can read a process's arguments. + _post_hook_json(url, body, {"X-API-KEY": api_key}, seconds=10) debug_print("Setup completion notification sent") except Exception as e: debug_print(f"Could not notify backend: {e}") diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py index 0952d044b..97a9c7b4d 100644 --- a/tests/test_mdm_setup_status.py +++ b/tests/test_mdm_setup_status.py @@ -274,3 +274,27 @@ def test_claude_code_on_windows_reports_managed_settings_when_the_drop_in_cannot assert r() is True assert Path(r.report["written_to"]) == r.managed / "managed-settings.json" assert (r.managed / "managed-settings.json").is_file() + + +@pytest.mark.parametrize("tool", sorted(MODULES)) +def test_the_setup_report_keeps_the_device_key_off_curls_arguments(tool, monkeypatch): + """Any local user can read a running process's arguments, so the key goes to curl in a 0600 header file.""" + m = load_module(MODULES[tool]) + calls = [] + + def fake_run(cmd, **kwargs): + headers = [Path(arg[1:]).read_text() for arg in cmd if isinstance(arg, str) and arg.startswith("@/")] + calls.append((list(cmd), headers)) + + class Done: + returncode, stdout, stderr = 0, b"{}\n200", b"" + return Done() + + monkeypatch.setattr(m.subprocess, "run", fake_run) + m.notify_setup_complete("device-key-SECRET", TOOL_TYPES[tool], backend_url="https://backend.test", + serial_number="SERIAL1", status="deferred", reason="r") + + [(cmd, headers)] = calls + assert not any("device-key-SECRET" in str(arg) for arg in cmd) + assert any("X-API-KEY: device-key-SECRET" in h for h in headers) + assert "https://backend.test/api/v1/setup/complete/" in cmd From d560a3dbd3e3098167b00813fb7a8c97a321de6d Mon Sep 17 00:00:00 2001 From: Iyad Zargar Date: Mon, 30 Nov 2026 15:48:52 +0530 Subject: [PATCH 53/53] fix(setup): count antigravity's config writes and forward its hook errors from the binary [WEB-6392] --- binary/src/unbound_hook/setup_cmd.py | 5 ++--- binary/tests/test_setup_reporting.py | 13 ++++++++++++- tests/test_mdm_hook_errors.py | 2 +- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/binary/src/unbound_hook/setup_cmd.py b/binary/src/unbound_hook/setup_cmd.py index 42abe0f61..8cdc017b6 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -286,6 +286,7 @@ def _end_fields(opts, user_homes, warnings) -> dict: "codex": (".codex/hooks/error.log", "codex"), "copilot": (".copilot/hooks/error.log", "copilot"), "augment": (".augment/hooks/error.log", "augment_code"), + "antigravity": (".gemini/antigravity-hooks/error.log", "antigravity"), } # Beside each error.log: " ", the newest entry the gateway accepted and how many entries # stamped exactly then were sent (two can share a stamp, and a request can end between them). @@ -1927,9 +1928,7 @@ def _setup_antigravity(opts): if home_dir is None: continue eligible += 1 - config_ok = m.write_unbound_config_for_user( - username, home_dir, api_key, - urls={"base_url": base, "gateway_url": gateway, "frontend_url": opts["frontend_url"]}) and config_ok + config_ok = _write_user_config(m, opts, username, home_dir, api_key) and config_ok if _install_antigravity_hooks_for_user(m, username, home_dir): installed += 1 diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py index e510abb44..43407b01e 100644 --- a/binary/tests/test_setup_reporting.py +++ b/binary/tests/test_setup_reporting.py @@ -90,6 +90,17 @@ def test_setup_reports_its_start_first_and_its_end_last(env, backend): assert all(r["headers"]["X-API-KEY"] == "admin-key" for r in reports) +def test_antigravity_counts_the_homes_it_configured(env, backend, monkeypatch): + """Antigravity's config writes are tallied like every other tool's: alone it counts its home configured, + and a failed write there counts the home skipped.""" + _run(backend, "--tools", "antigravity") + assert _run_reports(backend)[-1]["body"]["user_homes"] == {"configured": 1, "skipped": 0} + backend.requests.clear() + monkeypatch.setattr(env["modules"]["antigravity"], "write_unbound_config_for_user", lambda *a, **k: False) + _run(backend) + assert _run_reports(backend)[-1]["body"]["user_homes"] == {"configured": 0, "skipped": 1} + + def test_a_run_without_managed_settings_reports_that_mode(env, backend): assert _run(backend, "--skip-managed-settings") == 0 assert {r["body"]["install_mode"] for r in _run_reports(backend)} == {"binary-skip"} @@ -525,7 +536,7 @@ def run_as(username, fn, *args, _timeout=None, **kwargs): monkeypatch.setattr(m, "_run_as_user", run_as) -@pytest.mark.parametrize("tool", ["claude-code", "cursor", "codex", "copilot", "augment"]) +@pytest.mark.parametrize("tool", ["claude-code", "cursor", "codex", "copilot", "augment", "antigravity"]) def test_a_check_run_as_the_user_answers_through_each_tools_own_runner(tool, monkeypatch): """setup_cmd hands every tool's module to _as_user, claude-code's included (the error forwarding and Cursor's log keeping use it). Each module's real _run_as_user must take the bounded call and answer.""" diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py index cdd37ebcf..81fcce57b 100644 --- a/tests/test_mdm_hook_errors.py +++ b/tests/test_mdm_hook_errors.py @@ -659,7 +659,7 @@ def test_the_limits_and_redaction_are_the_binarys(binary, name): # Antigravity has no unbound-hook binary install yet: its MDM script is the only one that forwards its log. -@pytest.mark.parametrize("tool", sorted(set(MODULES) - {"antigravity"})) +@pytest.mark.parametrize("tool", sorted(MODULES)) def test_each_script_forwards_the_log_the_binary_does_for_its_tool(binary, tool): assert load_module(MODULES[tool]).HOOK_ERROR_LOG == binary._HOOK_ERROR_LOGS[tool]