diff --git a/antigravity/hooks/mdm/setup.py b/antigravity/hooks/mdm/setup.py index 71edf5ee..3c595ea4 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 @@ -748,16 +750,548 @@ 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: - return hashlib.sha256(Path(script_path).read_bytes()).hexdigest() + 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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} @@ -769,16 +1303,11 @@ 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 - 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, - ) + 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 + # 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}") @@ -854,6 +1383,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: @@ -868,10 +1401,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() @@ -887,11 +1431,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") @@ -899,9 +1447,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/augment/hooks/mdm/setup.py b/augment/hooks/mdm/setup.py index d9678c92..3e15b3ee 100644 --- a/augment/hooks/mdm/setup.py +++ b/augment/hooks/mdm/setup.py @@ -9,9 +9,13 @@ import subprocess import hashlib import json +import re import tempfile import time +import signal +import select import urllib.parse +from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Tuple, List, Optional, Dict try: @@ -163,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. @@ -218,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: @@ -230,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: @@ -1441,9 +1465,532 @@ def hook_script_hash(script_path) -> Optional[str]: return None +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")) +# 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 + + +# --- 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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 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 +2002,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( @@ -1544,6 +2094,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: @@ -1558,11 +2111,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 @@ -1579,6 +2143,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}") @@ -1596,14 +2161,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/binary/README.md b/binary/README.md index cc6d9cc4..f06bc137 100644 --- a/binary/README.md +++ b/binary/README.md @@ -79,7 +79,21 @@ 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_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. + 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 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 d69daa77..8cdc017b 100644 --- a/binary/src/unbound_hook/setup_cmd.py +++ b/binary/src/unbound_hook/setup_cmd.py @@ -18,17 +18,24 @@ but never aborts the remaining components. """ +import functools +import hashlib import json import math import os import platform +import re import shlex import stat import subprocess import sys +import tempfile +import threading import time +from datetime import datetime, timedelta, timezone from pathlib import Path +from . import __version__ from ._loader import load_mdm_setup_module from ._resources import ( DISCOVERY_BINARY, @@ -98,6 +105,37 @@ 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. + 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): m = load_mdm_setup_module(tool) m.DEBUG = True # MDM runs always log diagnostics (parity with python path) @@ -110,6 +148,348 @@ 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 _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()} + 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. 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 user_homes == []: + warnings.append("no user homes found") + 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", "antigravity": "antigravity"} + +# The machine root the installed check looks under; tests point it at a sandbox. +_MACHINE_ROOT = Path("/") + + +def _tool_installed(tool, user_homes) -> bool: + """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: + return load_mdm_setup_module(tool).tool_installed(user_homes, system="darwin", machine_root=_MACHINE_ROOT) + except Exception: + 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, + so the hook works once the tool arrives.""" + if status == "configured" and 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 + + +def _end_fields(opts, user_homes, warnings) -> dict: + 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 + + +# --------------------------------------------------------------------------- +# 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"), + "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). +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})): (.*)$") + + +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 _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), follow=False).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 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, 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 profile's user.""" + _replace_user_file(log.with_name(FORWARDED_STATE_NAME), state.encode("utf-8"), 0o600) + return True + + +_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"\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: + """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(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) + + +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": _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}"}) + 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 _forward_home_errors(m, 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 _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", 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, 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", False + return len(entries), "sent", True + + +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.""" + 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. + 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: + """Forward every home's unsent error.log entries for this tool, with that home's own device key. Runs + 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.""" + relpath, hook_source = _HOOK_ERROR_LOGS[tool] + sent = 0 + try: + hook_sha = (m.hook_script_hash(hook_source_path(tool)) or "unknown")[:12] + 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 + if opts.get("hook_errors_held"): + 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: + 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, _ = _forward_home_errors(m, username, log, send) + sent += count + 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") + 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.""" @@ -683,6 +1063,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.""" @@ -912,7 +1308,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) @@ -1042,6 +1442,10 @@ 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 = _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") @@ -1051,18 +1455,15 @@ 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"] # 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. @@ -1071,18 +1472,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): @@ -1103,6 +1504,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 = _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 @@ -1110,14 +1514,12 @@ 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)) 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 @@ -1126,13 +1528,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): @@ -1145,6 +1544,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 = _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") @@ -1156,29 +1558,25 @@ 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) - 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. 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. @@ -1357,12 +1755,13 @@ 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 = _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(): - 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 @@ -1372,19 +1771,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): @@ -1446,6 +1843,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 = _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) @@ -1454,9 +1854,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. @@ -1480,29 +1878,32 @@ 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 ("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) + + # 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 ("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 _setup_antigravity(opts): - """Mirrors antigravity mdm/setup.py main(), minus the script download. Antigravity has no backfill.""" + """Mirrors antigravity mdm/setup.py main(), minus the script download. Antigravity has no backfill. + Every outcome is reported, as the other tools' are (WEB-6392).""" m = _module("antigravity") m._RUN_AS_USER_TIMEOUT = _USER_CHECK_TIMEOUT if opts["backfill"]: @@ -1514,30 +1915,35 @@ def _setup_antigravity(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 = _tool_reporter(opts, m, "antigravity", api_key, backend_url=base, serial_number=device_id, + installed=opts.get("installed", {}).get("antigravity", True), + install_mode="binary") user_homes = m.get_all_user_homes() state = m.detect_install_state() installed = 0 + eligible = 0 config_ok = True for username, home_dir in user_homes: if home_dir is None: continue - 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 + eligible += 1 + 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 if user_homes and installed == 0: - return ("deferred", "hook install failed for all users") + # A user can make every install fail, so the report carries the state found, as Copilot's does. + return report("deferred", "hook install failed for all users", install_state=state) + if installed < eligible: + return report("deferred", f"Installed Antigravity hooks for {installed} of {eligible} user(s);" + f" {eligible - installed} failed") 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, "antigravity", backend_url=base, - install_state=state, serial_number=device_id, - hook_hash=m.hook_script_hash(hook_source_path("antigravity")), - install_mode="binary") - return ("configured", None) + return report("configured", install_state=state, + hook_hash=m.hook_script_hash(hook_source_path("antigravity")), + written_to="~/.gemini/config/hooks.json") def _fetch_device_owner_key(opts): @@ -1554,6 +1960,29 @@ 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. 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") + 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: + pass + + def _run_discovery(opts): """Run the locally installed discovery binary (no install.sh download). Mirrors onboard.py's process-group + backstop-kill discipline.""" @@ -1569,9 +1998,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: @@ -1583,6 +2016,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) @@ -1628,9 +2063,27 @@ def run(argv) -> int: if opts["frontend_url"]: opts["frontend_url"] = m0.normalize_url(opts["frontend_url"]) + opts["config_writes"] = {} + # 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") + # 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_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. + home_keys = {} + for tool in opts["tools"]: + if tool in _HOOK_ERROR_LOGS: + _forward_hook_errors(m0, tool, opts, user_homes, home_keys) + statuses = {} print(f"\n{'=' * 60}\n[migration] python->binary sweep\n{'=' * 60}") + # 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"]: @@ -1642,9 +2095,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}") print(f"\n{'=' * 60}\n[discovery] coding-tool scan\n{'=' * 60}") try: @@ -1661,4 +2114,5 @@ def run(argv) -> int: print(line) if status == "deferred": any_deferred = True + _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_discovery_output.py b/binary/tests/test_setup_discovery_output.py new file mode 100644 index 00000000..b6798d77 --- /dev/null +++ b/binary/tests/test_setup_discovery_output.py @@ -0,0 +1,113 @@ +"""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, a scan that hangs past the backstop, and an MDM log that can no longer be written. +""" + +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" + + +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 diff --git a/binary/tests/test_setup_migration.py b/binary/tests/test_setup_migration.py index 58671a8e..5b5270ae 100644 --- a/binary/tests/test_setup_migration.py +++ b/binary/tests/test_setup_migration.py @@ -80,6 +80,11 @@ 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"")) + # 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} @@ -1848,7 +1853,28 @@ 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) + # 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") + + +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"]) diff --git a/binary/tests/test_setup_reporting.py b/binary/tests/test_setup_reporting.py new file mode 100644 index 00000000..43407b01 --- /dev/null +++ b/binary/tests/test_setup_reporting.py @@ -0,0 +1,941 @@ +"""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 os +import stat +import re +import threading +from datetime import datetime, timedelta, timezone +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_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"} + + +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 + + +# --- 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", + "antigravity": "Applications/Antigravity.app", +} +TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", + "copilot": "copilot", "augment": "augment_code", "antigravity": "antigravity"} +NAMES = {"claude-code": "Claude Code", "cursor": "Cursor", "codex": "Codex", + "copilot": "GitHub Copilot", "augment": "Augment", "antigravity": "Antigravity"} + + +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_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) + 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"), + "antigravity": "~/.gemini/config/hooks.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) + + +# --- 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, 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 + + +# 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): + 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().rsplit(" ", 1)[0] == f"{_utc(2)} 1" + + +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().rsplit(" ", 1)[0] == f"{_utc(24)} 1" + 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", [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"]) + _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().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"] + + +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\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 --------------------------------------- + +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"]) == len(setup_cmd.SETUP_TOOLS) # one report per tool + + +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"] == [] + + +# --- 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().rsplit(" ", 1)[0] == f"{_utc(39999 / 100)} 1" + + +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"] + + +# --- 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" + + +# --- 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) + + +@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.""" + 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" + 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().rsplit(" ", 1)[0] == f"{_utc(1)} 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"])) + + +# --- 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" + + +# --- 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] + + +# --- 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 + + +# --- 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"] + _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) == [] + + +# --- 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" + + +# --- 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) + + +# --- 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 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 (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" + # 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_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"] + + +@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_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) + 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) + 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) + _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_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) + (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) == [] + + +# --- 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() + + +# --- 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"] + + +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): + 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"]] diff --git a/claude-code/hooks/mdm/setup.py b/claude-code/hooks/mdm/setup.py index efcacf85..28719e4c 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 @@ -13,7 +14,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 @@ -44,6 +47,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', '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 @@ -61,6 +67,11 @@ # 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. +# 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: @@ -77,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. @@ -133,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: @@ -145,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: @@ -1158,9 +1189,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() @@ -1353,6 +1391,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 @@ -2057,10 +2096,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.""" @@ -2676,13 +2711,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 +2729,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 +2746,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 +2772,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 +2989,30 @@ 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: + # 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' + # 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.""" @@ -2964,7 +3020,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 +3042,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 +3076,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 +3153,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 +3237,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, run, previous = False, None, None 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 +3260,24 @@ 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_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: + _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') def detect_install_state(skip_settings: bool = False) -> Optional[str]: @@ -3181,9 +3319,533 @@ def hook_script_hash(script_path) -> Optional[str]: return None +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")), + "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 + + +# --- 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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 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,16 +3857,11 @@ 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 - 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, - ) + 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 + # 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}") @@ -3289,6 +3946,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: @@ -3303,6 +3963,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() @@ -3317,6 +3987,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 @@ -3340,19 +4011,23 @@ 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() + # 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(written) if written else None) if backfill_mode: _run_backfill_bounded(api_key, base_url, get_all_user_homes()) diff --git a/claude-code/hooks/setup.py b/claude-code/hooks/setup.py index c54638ae..cf6a92f6 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', '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 @@ -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): @@ -1609,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.""" @@ -2081,12 +2128,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, 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. 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 +2208,16 @@ def _flush(): current_size += slice_bytes + 1 _flush() + failed = chunks_total - chunks_sent + # 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: - 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 +2229,15 @@ 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: + # 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/codex/hooks/mdm/setup.py b/codex/hooks/mdm/setup.py index 48fd0aa6..0e924bf6 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: @@ -2449,9 +2451,534 @@ def hook_script_hash(script_path) -> Optional[str]: os.close(fd) +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 = { + "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 + + +# --- 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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 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,16 +2990,11 @@ 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 - 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, - ) + 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 + # 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}") @@ -2553,6 +3075,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: @@ -2567,6 +3092,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(): @@ -2576,6 +3111,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() @@ -2585,6 +3121,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...") @@ -2604,11 +3141,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") @@ -2617,8 +3157,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 7758a8c6..135674e3 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 @@ -2080,16 +2080,559 @@ 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(_read_user_file(Path(script_path))).hexdigest() + except Exception: + return None + + +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 +# 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 + (".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 + + (".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) --------------------------------------------- +# 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: - return hashlib.sha256(Path(script_path).read_bytes()).hexdigest() + 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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 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,16 +2644,11 @@ 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 - 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, - ) + 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 + # 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}") @@ -2776,6 +3314,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: @@ -2790,17 +3332,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() @@ -2831,11 +3385,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") @@ -2843,9 +3401,16 @@ 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 == 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 the + # unbound-hook binary. + 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 27e16d02..6b5f0c00 100644 --- a/cursor/mdm/setup.py +++ b/cursor/mdm/setup.py @@ -10,7 +10,12 @@ import subprocess import hashlib import json +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 try: @@ -53,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. @@ -109,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: @@ -121,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: @@ -415,24 +440,135 @@ def _write(): return True -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" +_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 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(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 + 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: each removal goes through a handle checked to be the one asked for + removed = False + 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 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: + 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: - import shutil - shutil.rmtree(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 @@ -1207,9 +1343,534 @@ def hook_script_hash(script_path) -> Optional[str]: return None +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",)), + "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 + + +# --- 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)\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"\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): + """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. 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): + 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 _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,) + # 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): + 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 _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))] + + 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) + 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: + 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, + 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(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) + + +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. 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: + 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())) + 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=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 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,16 +1882,11 @@ 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 - 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, - ) + 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 + # 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}") @@ -1317,6 +1973,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_enterprise_hooks_dir() / "hooks" / "unbound.py") + # Get device identifier print("\n🔍 Getting device serial number...") serial_number = get_device_identifier() @@ -1333,9 +1992,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 @@ -1359,19 +2029,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/antigravity/hooks/mdm/test_setup.py b/tests/antigravity/hooks/mdm/test_setup.py index e0c2a5fc..03a3b1df 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/claude_code/hooks/test_backfill_outcome.py b/tests/claude_code/hooks/test_backfill_outcome.py new file mode 100644 index 00000000..70d8717f --- /dev/null +++ b/tests/claude_code/hooks/test_backfill_outcome.py @@ -0,0 +1,264 @@ +"""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_stderr, 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, 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/"): + 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_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__): + 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_a_run_that_crashes_sends_failed_in_the_same_run(self): + 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"]) + + 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) + + +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() + + +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) + + +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") diff --git a/tests/claude_code/hooks/test_backfill_uploader_stats.py b/tests/claude_code/hooks/test_backfill_uploader_stats.py index 7c22d7a9..1d70af8e 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 c8282193..d25c5d98 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 2e8d4be0..8a3bf929 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/"): @@ -249,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)): @@ -318,22 +316,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 +341,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 +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"], 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()) @@ -367,8 +368,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 +386,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 aae0c896..51a95dea 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): @@ -675,13 +676,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 +704,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,20 +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, 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 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", 400)], 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)) diff --git a/tests/test_mdm_hook_errors.py b/tests/test_mdm_hook_errors.py new file mode 100644 index 00000000..81fcce57 --- /dev/null +++ b/tests/test_mdm_hook_errors.py @@ -0,0 +1,740 @@ +"""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", "antigravity": ".gemini/antigravity-hooks/error.log"} +HOOK_SOURCES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", + "augment": "augment_code", "antigravity": "antigravity"} +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, _timeout=None, **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 +REAL_RUN_AS_USER = {tool: load_module(path)._run_as_user for tool, path in MODULES.items()} + + +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().rsplit(" ", 1)[0] == 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().rsplit(" ", 1)[0] == 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_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) + _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 + 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", [ + 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", + 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", 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): + 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().rsplit(" ", 1)[0] == 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 = _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 (log.parent / "unbound.py").exists() # the cleanup did run + assert _messages(gateway) == ["cursor broke", "cursor broke again"] + # Kept with its forwarded place, so nothing is sent twice. + gateway.requests.clear() + r() + 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 + 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) + 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 beside it + gateway.answer = lambda request: (200, OK) + gateway.requests.clear() + r() + assert _messages(gateway) == ["cursor broke", "cursor broke again"] + + +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"]) + + 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) + 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, {}) + 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_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().rsplit(" ", 1)[0] == 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 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", "_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") +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_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 + + +@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) + + +# Antigravity has no unbound-hook binary install yet: its MDM script is the only one that forwards its log. +@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] + + +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): + """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] + + + +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) == [] + diff --git a/tests/test_mdm_setup_status.py b/tests/test_mdm_setup_status.py new file mode 100644 index 00000000..97a9c7b4 --- /dev/null +++ b/tests/test_mdm_setup_status.py @@ -0,0 +1,300 @@ +"""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", + "antigravity": "antigravity/hooks/mdm/setup.py", +} +TOOL_TYPES = {"claude-code": "claude-code", "cursor": "cursor", "codex": "codex", "copilot": "copilot", + "augment": "augment_code", "antigravity": "antigravity"} + + +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("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_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): + 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): + # 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): + 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 _antigravity(self): + self.stub("_fetch_hook_script", "# hook") + self.writer("install_hooks_for_user") + + 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"), + "antigravity": lambda r: "~/.gemini/config/hooks.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"), + ("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"), +] + + +@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") + # As in the binary, the tamper state rides only on a run where every install failed. + 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.""" + r = 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() + + +@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 diff --git a/tests/test_tool_installed.py b/tests/test_tool_installed.py new file mode 100644 index 00000000..7045fe23 --- /dev/null +++ b/tests/test_tool_installed.py @@ -0,0 +1,191 @@ +"""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 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", + "antigravity": "antigravity/hooks/mdm/setup.py", +} +NAMES = {"claude-code": "Claude Code", "cursor": "Cursor", "codex": "Codex", "copilot": "GitHub Copilot", + "augment": "Augment", "antigravity": "Antigravity"} + + +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"), + # 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"), + ("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"), +] + + +@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 + + +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 + (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_every_copy_is_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 diff --git a/tests/test_windows_paths.py b/tests/test_windows_paths.py index bb5ec5f7..794d36f9 100644 --- a/tests/test_windows_paths.py +++ b/tests/test_windows_paths.py @@ -187,3 +187,130 @@ 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", + "antigravity": "antigravity/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"] + 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" + 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 +@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") + 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()