| 1 | """Per-build tool-boundary audit for the grok CLI. |
| 2 | |
| 3 | Grok X research runs the CLI with permissions bypassed and an untrusted topic |
| 4 | in the prompt, so last30days must know the child has no local tools. Grok |
| 5 | ships a new build most days, so instead of pinning one audited build, each |
| 6 | build is audited once per machine before it receives credentials: |
| 7 | |
| 8 | * the real native binary runs the exact research command line against a local |
| 9 | fake xAI endpoint (``127.0.0.1``) with a dummy key and a throwaway HOME, so |
| 10 | the audit costs nothing and never contacts xAI; |
| 11 | * the main model request must declare hosted X search and no other tool; |
| 12 | * the fake model then forces a shell call and a file read, and the CLI must |
| 13 | refuse both (no canary file, no secret in any later request); |
| 14 | * the same run with a permissive profile must execute both calls, proving the |
| 15 | fixture can detect a leak (otherwise the result is inconclusive); |
| 16 | * all HTTP(S) traffic goes through a refusing proxy, and any host other than |
| 17 | the fixture fails the audit. |
| 18 | |
| 19 | Pass and fail verdicts are cached on disk keyed by the native binary's sha256, |
| 20 | its ``--version`` line, and ``AUDIT_SCHEMA``. Inconclusive results are only |
| 21 | memoized for this process, so the next run audits again. |
| 22 | """ |
| 23 | |
| 24 | import base64 |
| 25 | import hashlib |
| 26 | import json |
| 27 | import os |
| 28 | import platform |
| 29 | import shutil |
| 30 | import subprocess |
| 31 | import sys |
| 32 | import tempfile |
| 33 | import threading |
| 34 | import time |
| 35 | from dataclasses import dataclass |
| 36 | from datetime import datetime, timezone |
| 37 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 38 | from pathlib import Path |
| 39 | from typing import Any, Dict, List, Optional |
| 40 | |
| 41 | from . import env, log, subproc |
| 42 | |
| 43 | # Bump when the checks change so verdicts recorded by older checks re-audit. |
| 44 | AUDIT_SCHEMA = 5 |
| 45 | CACHE_FILENAME = "grok-audit.json" |
| 46 | |
| 47 | PASS = "pass" |
| 48 | FAIL = "fail" |
| 49 | INCONCLUSIVE = "inconclusive" |
| 50 | |
| 51 | # A single forced turn takes 2-6s on a warm machine; the cap keeps a wedged |
| 52 | # child from consuming the whole X lane. |
| 53 | _CHILD_TIMEOUT_SECONDS = 45 |
| 54 | _EXPECTED_TOOLS = [{"type": "x_search"}] |
| 55 | _DUMMY_KEY = "xai-last30days-audit-dummy" |
| 56 | # grok's public OIDC client id, used when the user's store names none. |
| 57 | _DEFAULT_OIDC_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828" |
| 58 | |
| 59 | |
| 60 | def _log(msg: str) -> None: |
| 61 | log.source_log("Grok", msg, tty_only=False) |
| 62 | |
| 63 | |
| 64 | @dataclass(frozen=True) |
| 65 | class Verdict: |
| 66 | status: str |
| 67 | check: str = "" |
| 68 | |
| 69 | @property |
| 70 | def passed(self) -> bool: |
| 71 | return self.status == PASS |
| 72 | |
| 73 | |
| 74 | # --- native binary resolution ---------------------------------------------- |
| 75 | |
| 76 | def _npm_package_dir(binary: Path) -> Optional[Path]: |
| 77 | """The @xai-official/grok package behind an npm launcher, if this is one.""" |
| 78 | if binary.suffix.lower() in (".cmd", ".ps1", ".bat"): |
| 79 | candidate = binary.parent / "node_modules" / "@xai-official" / "grok" |
| 80 | else: |
| 81 | try: |
| 82 | with open(binary, "rb") as fh: |
| 83 | if fh.read(2) != b"#!": |
| 84 | return None |
| 85 | except OSError: |
| 86 | return None |
| 87 | candidate = binary.parent.parent |
| 88 | try: |
| 89 | meta = json.loads((candidate / "package.json").read_text(encoding="utf-8")) |
| 90 | except (OSError, ValueError): |
| 91 | return None |
| 92 | return candidate if meta.get("name") == "@xai-official/grok" else None |
| 93 | |
| 94 | |
| 95 | def _platform_tag() -> str: |
| 96 | machine = platform.machine().lower() |
| 97 | arch = {"x86_64": "x64", "amd64": "x64", "aarch64": "arm64"}.get(machine, machine) |
| 98 | return f"{sys.platform}-{arch}" |
| 99 | |
| 100 | |
| 101 | def _decompress_brotli(src: Path, dest: Path, timeout: float) -> bool: |
| 102 | """Decompress the npm-shipped ``grok.br`` with node (Python has no brotli).""" |
| 103 | node = shutil.which("node") |
| 104 | if node is None or timeout <= 1: |
| 105 | return False |
| 106 | tmp = dest.with_name(dest.name + f".tmp.{os.getpid()}.{os.urandom(4).hex()}") |
| 107 | script = ( |
| 108 | "const z=require('zlib'),f=require('fs');" |
| 109 | "f.writeFileSync(process.argv[2],z.brotliDecompressSync(f.readFileSync(process.argv[1])))" |
| 110 | ) |
| 111 | try: |
| 112 | dest.parent.mkdir(parents=True, exist_ok=True) |
| 113 | result = subproc.run_with_timeout( |
| 114 | [node, "-e", script, str(src), str(tmp)], |
| 115 | timeout=min(60.0, timeout), |
| 116 | ) |
| 117 | if result.returncode != 0: |
| 118 | return False |
| 119 | os.chmod(tmp, 0o755) |
| 120 | os.replace(tmp, dest) |
| 121 | return True |
| 122 | except (OSError, subproc.SubprocTimeout, subprocess.SubprocessError): |
| 123 | return False |
| 124 | finally: |
| 125 | try: |
| 126 | tmp.unlink() |
| 127 | except OSError: |
| 128 | pass |
| 129 | |
| 130 | |
| 131 | def resolve_native(binary: str, decompress: bool = True, timeout: float = 60.0) -> Optional[str]: |
| 132 | """The native grok executable that ``binary`` would run, or None. |
| 133 | |
| 134 | A native install resolves to itself. The npm package installs a node |
| 135 | launcher that is byte-identical across releases and picks the real binary |
| 136 | at run time from HOME, so hashing or exec'ing the launcher would let one |
| 137 | audit cover every later build. Resolve the build the package ships |
| 138 | instead: the copy its launcher writes to ``$GROK_HOME/bin``, else the |
| 139 | platform package binary, decompressing the brotli copy into the |
| 140 | last30days config dir once (skipped when ``decompress`` is False, so |
| 141 | no-subprocess callers like doctor only find an existing copy). |
| 142 | """ |
| 143 | path = Path(binary) |
| 144 | package = _npm_package_dir(path) |
| 145 | if package is None: |
| 146 | return binary |
| 147 | try: |
| 148 | version = json.loads((package / "package.json").read_text(encoding="utf-8"))["version"] |
| 149 | except (OSError, ValueError, KeyError): |
| 150 | return None |
| 151 | exe = ".exe" if os.name == "nt" else "" |
| 152 | grok_home = Path(os.environ.get("GROK_HOME") or Path.home() / ".grok") |
| 153 | installed = grok_home / "bin" / f"grok-{version}{exe}" |
| 154 | if installed.is_file(): |
| 155 | return str(installed) |
| 156 | platform_pkg = f"grok-{_platform_tag()}" |
| 157 | for base in (package / "node_modules" / "@xai-official", package.parent): |
| 158 | native = base / platform_pkg / "bin" / f"grok{exe}" |
| 159 | if native.is_file(): |
| 160 | return str(native) |
| 161 | compressed = native.with_name(native.name + ".br") |
| 162 | if compressed.is_file(): |
| 163 | # The launcher's own cache dir when last30days has no config dir. |
| 164 | cache = env.CONFIG_DIR / "grok-bin" if env.CONFIG_DIR is not None else grok_home / "bin" |
| 165 | dest = cache / f"grok-{version}{exe}" |
| 166 | if dest.is_file() or (decompress and _decompress_brotli(compressed, dest, timeout)): |
| 167 | return str(dest) |
| 168 | return None |
| 169 | |
| 170 | |
| 171 | def _file_digest(binary: str) -> str: |
| 172 | digest = hashlib.sha256() |
| 173 | with open(binary, "rb") as fh: |
| 174 | for chunk in iter(lambda: fh.read(1 << 20), b""): |
| 175 | digest.update(chunk) |
| 176 | return digest.hexdigest() |
| 177 | |
| 178 | |
| 179 | def build_key(binary: str, version_line: str) -> str: |
| 180 | return f"{_file_digest(binary)}|{version_line}|{AUDIT_SCHEMA}" |
| 181 | |
| 182 | |
| 183 | # --- verdict cache ---------------------------------------------------------- |
| 184 | |
| 185 | _MEMO: Dict[str, Verdict] = {} |
| 186 | _LOCK = threading.Lock() |
| 187 | |
| 188 | |
| 189 | def _cache_path() -> Optional[Path]: |
| 190 | return env.CONFIG_DIR / CACHE_FILENAME if env.CONFIG_DIR is not None else None |
| 191 | |
| 192 | |
| 193 | def _read_cache() -> Dict[str, Any]: |
| 194 | path = _cache_path() |
| 195 | if path is None: |
| 196 | return {} |
| 197 | try: |
| 198 | data = json.loads(path.read_text(encoding="utf-8")) |
| 199 | except (OSError, ValueError): |
| 200 | return {} |
| 201 | return data if isinstance(data, dict) else {} |
| 202 | |
| 203 | |
| 204 | def _write_cache(data: Dict[str, Any]) -> None: |
| 205 | path = _cache_path() |
| 206 | if path is None: |
| 207 | return |
| 208 | try: |
| 209 | path.parent.mkdir(parents=True, exist_ok=True) |
| 210 | tmp = path.with_name(path.name + f".tmp.{os.getpid()}") |
| 211 | tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8") |
| 212 | os.replace(tmp, path) |
| 213 | except OSError as exc: |
| 214 | _log(f"could not save grok audit verdict: {exc}") |
| 215 | |
| 216 | |
| 217 | def cached_verdict(key: str) -> Optional[Verdict]: |
| 218 | entry = _read_cache().get(key) |
| 219 | if not isinstance(entry, dict) or entry.get("verdict") not in (PASS, FAIL): |
| 220 | return None |
| 221 | return Verdict(entry["verdict"], str(entry.get("failed_check") or "")) |
| 222 | |
| 223 | |
| 224 | def cached_status(binary: str) -> Optional[Dict[str, str]]: |
| 225 | """Doctor's view: the cached verdict for the build on PATH, if any. |
| 226 | |
| 227 | File reads only, no subprocess: the native build is located without |
| 228 | decompressing and matched by hash, since its ``--version`` line needs a |
| 229 | run. |
| 230 | """ |
| 231 | native = resolve_native(binary, decompress=False) |
| 232 | if native is None: |
| 233 | return None |
| 234 | try: |
| 235 | digest = _file_digest(native) |
| 236 | except OSError: |
| 237 | return None |
| 238 | for key, entry in _read_cache().items(): |
| 239 | parts = key.split("|") |
| 240 | if (len(parts) == 3 and parts[0] == digest and parts[2] == str(AUDIT_SCHEMA) |
| 241 | and isinstance(entry, dict) and entry.get("verdict") in (PASS, FAIL)): |
| 242 | return {"verdict": entry["verdict"], "version": str(entry.get("version") or ""), |
| 243 | "check": str(entry.get("failed_check") or "")} |
| 244 | return None |
| 245 | |
| 246 | |
| 247 | def clear_failed() -> int: |
| 248 | """Drop cached fail verdicts so the next run re-audits. Returns the count.""" |
| 249 | with _LOCK: |
| 250 | data = _read_cache() |
| 251 | kept = {k: v for k, v in data.items() if not (isinstance(v, dict) and v.get("verdict") == FAIL)} |
| 252 | removed = len(data) - len(kept) |
| 253 | if removed: |
| 254 | _write_cache(kept) |
| 255 | _MEMO.clear() |
| 256 | return removed |
| 257 | |
| 258 | |
| 259 | def verdict_for(binary: str, version_line: str, deadline: float) -> Verdict: |
| 260 | """Cached or fresh audit verdict for one native build.""" |
| 261 | try: |
| 262 | key = build_key(binary, version_line) |
| 263 | except OSError as exc: |
| 264 | return Verdict(INCONCLUSIVE, f"could not read the grok binary: {exc}") |
| 265 | with _LOCK: |
| 266 | if key in _MEMO: |
| 267 | return _MEMO[key] |
| 268 | verdict = cached_verdict(key) |
| 269 | if verdict is None: |
| 270 | _log(f"auditing new grok build {version_line} (local, no credits)") |
| 271 | verdict = run_audit(binary, deadline) |
| 272 | _log(f"grok build audit: {verdict.status}" + (f" ({verdict.check})" if verdict.check else "")) |
| 273 | if verdict.status in (PASS, FAIL): |
| 274 | data = _read_cache() |
| 275 | data[key] = { |
| 276 | "verdict": verdict.status, |
| 277 | "failed_check": verdict.check, |
| 278 | "version": version_line, |
| 279 | "audited_at": datetime.now(timezone.utc).isoformat(), |
| 280 | } |
| 281 | _write_cache(data) |
| 282 | _MEMO[key] = verdict |
| 283 | return verdict |
| 284 | |
| 285 | |
| 286 | # --- local fixture ---------------------------------------------------------- |
| 287 | |
| 288 | def _model_info(base: str) -> Dict[str, Any]: |
| 289 | # Field set mirrors the catalog entries cli-chat-proxy serves; the CLI |
| 290 | # rejects entries missing any of them. |
| 291 | return { |
| 292 | "id": "grok-4.7", "model": "grok-4.7", "model_family": "xai", "base_url": base, |
| 293 | "name": "Grok 4.7", "description": "last30days audit fixture", |
| 294 | "max_completion_tokens": None, "temperature": None, "top_p": None, |
| 295 | "api_backend": "responses", "auth_scheme": "bearer", "extra_headers": {}, |
| 296 | "context_window": 256000, "context_windows": [256000], |
| 297 | "auto_compact_threshold_percent": 80, "system_prompt_label": "Grok 4.7", |
| 298 | "use_concise": False, "agent_type": "grok-build-plan", |
| 299 | "inference_idle_timeout_secs": None, "max_retries": None, |
| 300 | "subagent_rate_limit_max_attempts": None, "hidden": False, "supported_in_api": True, |
| 301 | "reasoning_effort": "high", "supports_reasoning_effort": True, |
| 302 | "reasoning_efforts": [{"id": "high", "value": "high", "label": "High", |
| 303 | "description": "", "default": True}], |
| 304 | "supports_backend_search": True, "compactions_remaining": 1, |
| 305 | "compaction_at_tokens": True, "show_model_fingerprint": False, |
| 306 | "stream_tool_calls": None, |
| 307 | "laziness_detector": {"enabled": False, "max_nudges_per_session": 0, |
| 308 | "idle_threshold_ms": None, "min_confidence": None, |
| 309 | "include_reasoning": None}, |
| 310 | } |
| 311 | |
| 312 | |
| 313 | def _sse(output: List[Dict[str, Any]], rid: str) -> bytes: |
| 314 | resp = { |
| 315 | "id": rid, "object": "response", "created_at": int(time.time()), "status": "completed", |
| 316 | "model": "grok-4.7", "output": output, |
| 317 | "usage": {"input_tokens": 1, "input_tokens_details": {"cached_tokens": 0}, |
| 318 | "output_tokens": 1, "output_tokens_details": {"reasoning_tokens": 0}, |
| 319 | "total_tokens": 2}, |
| 320 | } |
| 321 | events = [{"type": "response.created", "response": dict(resp, status="in_progress", output=[])}] |
| 322 | for index, item in enumerate(output): |
| 323 | events.append({"type": "response.output_item.added", "output_index": index, "item": item}) |
| 324 | events.append({"type": "response.output_item.done", "output_index": index, "item": item}) |
| 325 | events.append({"type": "response.completed", "response": resp}) |
| 326 | chunks = [] |
| 327 | for seq, event in enumerate(events): |
| 328 | event["sequence_number"] = seq |
| 329 | chunks.append(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n") |
| 330 | return "".join(chunks).encode() |
| 331 | |
| 332 | |
| 333 | class _FixtureServer(ThreadingHTTPServer): |
| 334 | """Local audit-fixture server with a listen backlog sized for the |
| 335 | concurrent probes. The default backlog (5) drops simultaneous |
| 336 | connections on macOS, resetting healthy probes and making an |
| 337 | otherwise healthy audit inconclusive. Audit-specific: the global |
| 338 | server class is untouched.""" |
| 339 | |
| 340 | request_queue_size = 64 |
| 341 | |
| 342 | |
| 343 | class _Fixture: |
| 344 | """Fake xAI endpoint plus a refusing proxy, both on 127.0.0.1.""" |
| 345 | |
| 346 | def __init__(self, forced_calls: List[Dict[str, Any]]): |
| 347 | self.forced_calls = forced_calls |
| 348 | self.requests: List[Dict[str, Any]] = [] |
| 349 | self.proxy_hosts: List[str] = [] |
| 350 | self._lock = threading.Lock() |
| 351 | fixture = self |
| 352 | |
| 353 | class Api(BaseHTTPRequestHandler): |
| 354 | protocol_version = "HTTP/1.1" |
| 355 | |
| 356 | def log_message(self, *args): |
| 357 | pass |
| 358 | |
| 359 | def _send(self, code, payload, ctype="application/json"): |
| 360 | data = payload if isinstance(payload, bytes) else json.dumps(payload).encode() |
| 361 | self.send_response(code) |
| 362 | self.send_header("content-type", ctype) |
| 363 | self.send_header("content-length", str(len(data))) |
| 364 | self.end_headers() |
| 365 | self.wfile.write(data) |
| 366 | |
| 367 | def do_GET(self): |
| 368 | if self.path.rstrip("/").endswith("/models"): |
| 369 | info = _model_info(fixture.base) |
| 370 | return self._send(200, {"object": "list", "data": [info], "models": [info]}) |
| 371 | self._send(404, {"error": "not found"}) |
| 372 | |
| 373 | def do_POST(self): |
| 374 | length = int(self.headers.get("content-length") or 0) |
| 375 | raw = self.rfile.read(length) if length else b"" |
| 376 | try: |
| 377 | body = json.loads(raw or b"{}") |
| 378 | except ValueError: |
| 379 | body = {} |
| 380 | if not self.path.endswith("/responses"): |
| 381 | return self._send(404, {"error": "not found"}) |
| 382 | tools = body.get("tools") or [] |
| 383 | if any(isinstance(t, dict) and t.get("name") == "session_title" for t in tools): |
| 384 | item = {"type": "function_call", "id": "fc_title", "call_id": "call_title", |
| 385 | "name": "session_title", "status": "completed", |
| 386 | "arguments": json.dumps({"session_title": "audit"})} |
| 387 | return self._send(200, _sse([item], "resp_title"), "text/event-stream") |
| 388 | auth_header = self.headers.get("authorization") or "" |
| 389 | with fixture._lock: |
| 390 | fixture.requests.append({ |
| 391 | "raw": raw.decode("utf-8", "replace"), |
| 392 | "body": body, |
| 393 | "authorization": auth_header, |
| 394 | }) |
| 395 | req_num = len(fixture.requests) |
| 396 | if req_num == 1: |
| 397 | output = [dict(call, type="function_call", status="completed", id=f"fc_{i}") |
| 398 | for i, call in enumerate(fixture.forced_calls)] |
| 399 | else: |
| 400 | output = [{"type": "message", "id": "msg_done", "role": "assistant", |
| 401 | "status": "completed", |
| 402 | "content": [{"type": "output_text", "text": "no posts", "annotations": []}]}] |
| 403 | self._send(200, _sse(output, f"resp_{req_num}"), "text/event-stream") |
| 404 | |
| 405 | class Proxy(BaseHTTPRequestHandler): |
| 406 | def log_message(self, *args): |
| 407 | pass |
| 408 | |
| 409 | def _refuse(self): |
| 410 | with fixture._lock: |
| 411 | fixture.proxy_hosts.append(self.path) |
| 412 | self.send_response(403) |
| 413 | self.send_header("content-length", "0") |
| 414 | self.end_headers() |
| 415 | |
| 416 | do_CONNECT = do_GET = do_POST = do_PUT = do_HEAD = _refuse |
| 417 | |
| 418 | self._api = _FixtureServer(("127.0.0.1", 0), Api) |
| 419 | self._proxy = _FixtureServer(("127.0.0.1", 0), Proxy) |
| 420 | self.base = f"http://127.0.0.1:{self._api.server_address[1]}/v1" |
| 421 | self.proxy = f"http://127.0.0.1:{self._proxy.server_address[1]}" |
| 422 | |
| 423 | def __enter__(self): |
| 424 | for server in (self._api, self._proxy): |
| 425 | threading.Thread(target=server.serve_forever, daemon=True).start() |
| 426 | return self |
| 427 | |
| 428 | def __exit__(self, *exc): |
| 429 | for server in (self._api, self._proxy): |
| 430 | server.shutdown() |
| 431 | server.server_close() |
| 432 | |
| 433 | |
| 434 | def _signed_in_client_id() -> str: |
| 435 | """The OIDC client id of the user's own store, so the dummy session takes |
| 436 | the same auth path the real one does. Reads the key name only.""" |
| 437 | from . import grok_x |
| 438 | |
| 439 | try: |
| 440 | data = json.loads(grok_x.token_store_path().read_text(encoding="utf-8")) |
| 441 | for key in data: |
| 442 | if isinstance(key, str) and "::" in key: |
| 443 | return key.rsplit("::", 1)[1] |
| 444 | except (OSError, ValueError, AttributeError): |
| 445 | pass |
| 446 | return _DEFAULT_OIDC_CLIENT_ID |
| 447 | |
| 448 | |
| 449 | def _write_dummy_session(home: str) -> str: |
| 450 | """A signed-in credential store shaped like the one _stage_child_home |
| 451 | copies, holding a fake unexpired token. Production runs in this mode, so |
| 452 | the audit must see the tools the build declares when signed in.""" |
| 453 | def b64(obj: Dict[str, Any]) -> str: |
| 454 | return base64.urlsafe_b64encode(json.dumps(obj).encode()).rstrip(b"=").decode() |
| 455 | |
| 456 | client_id = _signed_in_client_id() |
| 457 | zero = "00000000-0000-0000-0000-000000000000" |
| 458 | token = (b64({"alg": "none", "typ": "JWT"}) + "." |
| 459 | + b64({"sub": zero, "exp": 4070908800, "iat": 1761350400, |
| 460 | "iss": "https://auth.x.ai", "aud": client_id}) + ".audit") |
| 461 | entry = { |
| 462 | "key": token, "auth_mode": "oidc", "create_time": "2026-01-01T00:00:00Z", |
| 463 | "user_id": zero, "email": "audit@example.invalid", "first_name": "Audit", |
| 464 | "profile_image_asset_id": "", "principal_type": "user", "principal_id": zero, |
| 465 | "team_id": zero, "coding_data_retention_opt_out": True, |
| 466 | "refresh_token": "last30days-audit-dummy", "expires_at": "2099-01-01T00:00:00Z", |
| 467 | "oidc_issuer": "https://auth.x.ai", "oidc_client_id": client_id, |
| 468 | } |
| 469 | store = Path(home) / ".grok" |
| 470 | store.mkdir(mode=0o700, parents=True, exist_ok=True) |
| 471 | (store / "auth.json").write_text(json.dumps({f"https://auth.x.ai::{client_id}": entry}), |
| 472 | encoding="utf-8") |
| 473 | return token |
| 474 | |
| 475 | |
| 476 | def _bearer_token(header: str) -> str: |
| 477 | parts = (header or "").strip().split(None, 1) |
| 478 | if len(parts) == 2 and parts[0].lower() == "bearer": |
| 479 | return parts[1].strip() |
| 480 | return "" |
| 481 | |
| 482 | |
| 483 | def _audit_env(home: str, fixture: _Fixture, signed_in: bool = False) -> Dict[str, str]: |
| 484 | from . import grok_x |
| 485 | |
| 486 | child_env = grok_x._subprocess_env(home) |
| 487 | child_env.update({ |
| 488 | "GROK_XAI_API_BASE_URL": fixture.base, |
| 489 | "GROK_CLI_CHAT_PROXY_BASE_URL": fixture.base, |
| 490 | "GROK_MODELS_BASE_URL": fixture.base, |
| 491 | "GROK_MODELS_LIST_URL": fixture.base + "/models", |
| 492 | "HTTPS_PROXY": fixture.proxy, |
| 493 | "HTTP_PROXY": fixture.proxy, |
| 494 | "https_proxy": fixture.proxy, |
| 495 | "http_proxy": fixture.proxy, |
| 496 | "NO_PROXY": "127.0.0.1,localhost", |
| 497 | "no_proxy": "127.0.0.1,localhost", |
| 498 | }) |
| 499 | # Signed-in OIDC runs must omit XAI_API_KEY so CLI key precedence cannot |
| 500 | # silently turn the OIDC audit pass into a second API-key pass. |
| 501 | if signed_in: |
| 502 | child_env.pop("XAI_API_KEY", None) |
| 503 | # A custom models endpoint requires an API key and deliberately won't |
| 504 | # use a session token. Let the signed-in CLI discover the fixture's |
| 505 | # catalog through the redirected session proxy instead. |
| 506 | child_env.pop("GROK_MODELS_BASE_URL", None) |
| 507 | child_env.pop("GROK_MODELS_LIST_URL", None) |
| 508 | else: |
| 509 | child_env["XAI_API_KEY"] = _DUMMY_KEY |
| 510 | return child_env |
| 511 | |
| 512 | |
| 513 | def _run_child(binary: str, permissive: bool, deadline: float, signed_in: bool = False) -> Dict[str, Any]: |
| 514 | """One forced-call turn. Returns what the fixture observed.""" |
| 515 | from . import grok_x |
| 516 | |
| 517 | with tempfile.TemporaryDirectory(prefix="last30days-grok-audit-") as workdir: |
| 518 | home = os.path.join(workdir, "home") |
| 519 | os.makedirs(home) |
| 520 | expected_auth_token = _write_dummy_session(home) if signed_in else _DUMMY_KEY |
| 521 | canary = Path(workdir) / "canary" |
| 522 | secret_value = "l30d-audit-" + os.urandom(8).hex() |
| 523 | secret = Path(workdir) / "secret.txt" |
| 524 | secret.write_text(secret_value, encoding="utf-8") |
| 525 | forced = [ |
| 526 | {"call_id": "call_shell", "name": "run_terminal_command", |
| 527 | "arguments": json.dumps({"command": f'echo audit > "{canary}"', "description": "audit canary"})}, |
| 528 | {"call_id": "call_read", "name": "read_file", |
| 529 | "arguments": json.dumps({"target_file": str(secret)})}, |
| 530 | ] |
| 531 | if permissive: |
| 532 | agent_file = Path(workdir) / "control-agent.md" |
| 533 | agent_file.write_text('---\n{"name":"control","description":"control"}\n---\ncontrol\n', |
| 534 | encoding="utf-8") |
| 535 | argv = [binary, "-p", "run the audit", "--permission-mode", "bypassPermissions", |
| 536 | "--output-format", "json", "--agent", str(agent_file)] |
| 537 | else: |
| 538 | agent_file = grok_x._write_agent_profile(workdir) |
| 539 | argv = grok_x._research_argv(binary, "Use x_keyword_search for audit", agent_file) |
| 540 | with _Fixture(forced) as fixture: |
| 541 | remaining = min(_CHILD_TIMEOUT_SECONDS, deadline - time.monotonic()) |
| 542 | if remaining <= 1: |
| 543 | return {"timeout": True} |
| 544 | try: |
| 545 | subproc.run_with_timeout( |
| 546 | argv, |
| 547 | timeout=remaining, |
| 548 | cwd=workdir, |
| 549 | env=_audit_env(home, fixture, signed_in=signed_in), |
| 550 | ) |
| 551 | except (subproc.SubprocTimeout, subprocess.TimeoutExpired): |
| 552 | return {"timeout": True} |
| 553 | except OSError as exc: |
| 554 | return {"error": f"{type(exc).__name__}: {exc}"} |
| 555 | with fixture._lock: |
| 556 | requests = list(fixture.requests) |
| 557 | hosts = list(fixture.proxy_hosts) |
| 558 | return { |
| 559 | "requests": requests, |
| 560 | "proxy_hosts": hosts, |
| 561 | "canary": canary.exists(), |
| 562 | "leaked": any(secret_value in r["raw"] for r in requests[1:]), |
| 563 | "answered": _answered_call_ids(requests[1:]) >= {c["call_id"] for c in forced}, |
| 564 | "signed_in": signed_in, |
| 565 | "expected_auth_token": expected_auth_token, |
| 566 | } |
| 567 | |
| 568 | |
| 569 | def _answered_call_ids(requests: List[Dict[str, Any]]) -> set: |
| 570 | """Forced calls the CLI reported a result for in a follow-up turn.""" |
| 571 | answered = set() |
| 572 | for request in requests: |
| 573 | for item in request["body"].get("input") or []: |
| 574 | if isinstance(item, dict) and item.get("type") == "function_call_output": |
| 575 | answered.add(item.get("call_id")) |
| 576 | return answered |
| 577 | |
| 578 | |
| 579 | def _check_restricted(run: Dict[str, Any]) -> Optional[Verdict]: |
| 580 | """The verdict one restricted run forces, or None when it refused cleanly.""" |
| 581 | if run.get("timeout"): |
| 582 | return Verdict(INCONCLUSIVE, "audit timed out") |
| 583 | if run.get("error"): |
| 584 | return Verdict(INCONCLUSIVE, run["error"]) |
| 585 | if run["proxy_hosts"]: |
| 586 | return Verdict(FAIL, "contacted a host other than the local fixture: " |
| 587 | + ", ".join(sorted(set(run["proxy_hosts"]))[:3])) |
| 588 | if not run["requests"]: |
| 589 | return Verdict(INCONCLUSIVE, "the CLI sent no research request to the fixture") |
| 590 | # The first turn must declare exactly hosted X search; no later turn may |
| 591 | # add anything to it (a follow-up may resend the same list or omit it). |
| 592 | for index, request in enumerate(run["requests"]): |
| 593 | tools = request["body"].get("tools") or [] |
| 594 | if (tools != _EXPECTED_TOOLS) if index == 0 else any(t != _EXPECTED_TOOLS[0] for t in tools): |
| 595 | names = sorted({str(t.get("name") or t.get("type")) if isinstance(t, dict) else str(t) |
| 596 | for t in tools}) |
| 597 | return Verdict(FAIL, "declared tools other than hosted X search: " + ", ".join(names[:8])) |
| 598 | if run["canary"]: |
| 599 | return Verdict(FAIL, "executed a forced shell command") |
| 600 | if run["leaked"]: |
| 601 | return Verdict(FAIL, "returned a forced file read") |
| 602 | if not run["answered"]: |
| 603 | # A crash or early exit is not evidence the boundary refused the calls. |
| 604 | return Verdict(INCONCLUSIVE, "the CLI did not answer the forced calls") |
| 605 | expected_token = run.get("expected_auth_token") or "" |
| 606 | tokens = [_bearer_token(r.get("authorization", "")) for r in run["requests"]] |
| 607 | if run.get("signed_in"): |
| 608 | if not expected_token or any(tok != expected_token for tok in tokens): |
| 609 | return Verdict( |
| 610 | INCONCLUSIVE, |
| 611 | "signed-in audit run did not authenticate with the OIDC session token", |
| 612 | ) |
| 613 | elif expected_token and any(tok != expected_token for tok in tokens): |
| 614 | return Verdict( |
| 615 | INCONCLUSIVE, |
| 616 | "API-key audit run did not authenticate with the dummy API key", |
| 617 | ) |
| 618 | return None |
| 619 | |
| 620 | |
| 621 | def run_audit(binary: str, deadline: float) -> Verdict: |
| 622 | """Audit one native build against the local fixture. Never raises.""" |
| 623 | try: |
| 624 | # Production runs signed in; the API-key run covers XAI_API_KEY users. |
| 625 | for signed_in in (True, False): |
| 626 | verdict = _check_restricted(_run_child(binary, permissive=False, deadline=deadline, |
| 627 | signed_in=signed_in)) |
| 628 | if verdict is not None: |
| 629 | return verdict |
| 630 | control = _run_child(binary, permissive=True, deadline=deadline) |
| 631 | if control.get("timeout"): |
| 632 | return Verdict(INCONCLUSIVE, "audit timed out") |
| 633 | if control.get("error") or not (control.get("canary") and control.get("leaked")): |
| 634 | return Verdict(INCONCLUSIVE, "positive control did not execute the forced calls") |
| 635 | return Verdict(PASS) |
| 636 | except Exception as exc: # noqa: BLE001 - the audit must never break a run |
| 637 | return Verdict(INCONCLUSIVE, f"{type(exc).__name__}: {exc}") |
| 638 |