返回 last30days-skill
test_grok_audit.py
根目录 / tests / test_grok_audit.py
1 """Per-build grok tool-boundary audit (lib/grok_audit.py).
2
3 A fake grok script stands in for the binary and talks to the audit's real
4 local fixture over HTTP, so every check (declared tools, forced shell call,
5 forced file read, positive control, non-fixture traffic, timeout) runs end to
6 end without the CLI.
7 """
8
9 import json
10 import os
11 import sys
12 import time
13 from pathlib import Path
14
15 import pytest
16
17 from lib import env, grok_audit
18
19 pytestmark = pytest.mark.skipif(os.name == "nt", reason="fake grok is a POSIX script")
20
21 # conftest defaults verdict_for to pass; these tests need the real one.
22 _REAL_VERDICT_FOR = grok_audit.verdict_for
23
24 _FAKE_GROK = r'''#!{python}
25 import json, os, sys, time, urllib.request
26
27 MODE = {mode!r}
28 argv = sys.argv[1:]
29 if argv == ["--version"]:
30 print("grok 1.0.70 (f50904eaee6c)")
31 sys.exit(0)
32 restricted = "--disallowed-tools" in argv
33 base = os.environ["GROK_XAI_API_BASE_URL"]
34 spec = MODE if isinstance(MODE, dict) else {{"restricted": MODE, "control": "obey"}}
35 behavior = spec["restricted"] if restricted else spec["control"]
36 if behavior == "silent":
37 sys.exit(0)
38 if behavior == "hang":
39 time.sleep(30)
40 if behavior == "external":
41 try:
42 urllib.request.urlopen("http://example.invalid/telemetry", timeout=5)
43 except Exception:
44 pass
45
46 def _auth_token():
47 # Match real CLI precedence: XAI_API_KEY wins over auth.json when set.
48 key = os.environ.get("XAI_API_KEY", "")
49 if key:
50 return key
51 auth_path = os.path.join(os.environ["HOME"], ".grok", "auth.json")
52 if os.path.isfile(auth_path):
53 data = json.load(open(auth_path))
54 for entry in data.values():
55 if isinstance(entry, dict) and entry.get("key"):
56 return entry["key"]
57 return ""
58
59 if behavior == "signed_catalog" and not os.environ.get("XAI_API_KEY"):
60 # A custom model endpoint requires an API key; the signed-in client must
61 # instead discover models through the session-authenticated proxy.
62 if os.environ.get("GROK_MODELS_BASE_URL") or os.environ.get("GROK_MODELS_LIST_URL"):
63 sys.exit(1)
64 request = urllib.request.Request(os.environ["GROK_CLI_CHAT_PROXY_BASE_URL"] + "/models", headers={{"authorization": "Bearer " + _auth_token()}})
65 urllib.request.urlopen(request, timeout=10).read()
66
67 def post(body):
68 headers = {{"content-type": "application/json"}}
69 token = _auth_token()
70 if token:
71 headers["authorization"] = "Bearer " + token
72 req = urllib.request.Request(base + "/responses", data=json.dumps(body).encode(),
73 headers=headers)
74 events = urllib.request.urlopen(req, timeout=10).read().decode()
75 for line in events.splitlines():
76 if line.startswith("data: ") and '"response.completed"' in line:
77 return json.loads(line[6:])["response"]["output"]
78 return []
79
80 tools = [{{"type": "x_search"}}]
81 if not restricted:
82 tools = [{{"type": "function", "name": "run_terminal_command"}},
83 {{"type": "function", "name": "read_file"}}] + tools
84 elif behavior == "extra_tool" or (
85 behavior == "signed_in_extra"
86 and os.path.isfile(os.path.join(os.environ["HOME"], ".grok", "auth.json"))):
87 tools = [{{"type": "function", "name": "read_file"}}] + tools
88 output = post({{"model": "grok-4.7", "tools": tools, "input": []}})
89 if behavior == "crash":
90 sys.exit(1)
91 results = []
92 execute = (not restricted and behavior == "obey") or behavior in ("execute", "leak")
93 for item in output:
94 if item.get("type") != "function_call":
95 continue
96 args = json.loads(item["arguments"])
97 text = "Tool not found: " + item["name"]
98 if execute and item["name"] == "run_terminal_command" and behavior != "leak":
99 open(args["command"].split('"')[1], "w").close()
100 text = "exit: 0"
101 if execute and item["name"] == "read_file":
102 text = open(args["target_file"]).read()
103 results.append({{"type": "function_call_output", "call_id": item["call_id"], "output": text}})
104 if behavior == "late_tool":
105 tools = tools + [{{"type": "function", "name": "run_terminal_command"}}]
106 post({{"model": "grok-4.7", "tools": tools, "input": results}})
107 '''
108
109
110 def _fake_grok(tmp_path, mode, control="obey"):
111 script = tmp_path / "grok"
112 spec = mode if control == "obey" else {"restricted": mode, "control": control}
113 script.write_text(_FAKE_GROK.format(python=sys.executable, mode=spec))
114 script.chmod(0o755)
115 return str(script)
116
117
118 @pytest.fixture
119 def config_dir(monkeypatch, tmp_path):
120 cfg = tmp_path / "config"
121 monkeypatch.setattr(env, "CONFIG_DIR", cfg)
122 monkeypatch.setattr(grok_audit, "verdict_for", _REAL_VERDICT_FOR)
123 grok_audit._MEMO.clear()
124 yield cfg
125 grok_audit._MEMO.clear()
126
127
128 def _audit(binary, seconds=60):
129 return grok_audit.run_audit(binary, time.monotonic() + seconds)
130
131
132 # --- checks -----------------------------------------------------------------
133
134 def test_build_that_refuses_forced_calls_passes(tmp_path):
135 assert _audit(_fake_grok(tmp_path, "obey")) == grok_audit.Verdict(grok_audit.PASS)
136
137
138 def test_signed_in_catalog_uses_proxy_without_a_custom_model_endpoint(tmp_path):
139 assert _audit(_fake_grok(tmp_path, "signed_catalog")) == grok_audit.Verdict(grok_audit.PASS)
140
141
142 def test_signed_in_catalog_fails_closed_without_the_session_proxy(monkeypatch, tmp_path):
143 original_env = grok_audit._audit_env
144
145 def wrong_proxy(home, fixture, signed_in=False):
146 result = original_env(home, fixture, signed_in=signed_in)
147 if signed_in:
148 result["GROK_CLI_CHAT_PROXY_BASE_URL"] = "http://127.0.0.1:1/v1"
149 return result
150
151 monkeypatch.setattr(grok_audit, "_audit_env", wrong_proxy)
152 assert _audit(_fake_grok(tmp_path, "signed_catalog")).status == grok_audit.INCONCLUSIVE
153
154
155 @pytest.mark.parametrize("mode, check", [
156 ("extra_tool", "declared tools other than hosted X search: read_file, x_search"),
157 ("signed_in_extra", "declared tools other than hosted X search: read_file, x_search"),
158 ("late_tool", "declared tools other than hosted X search: run_terminal_command, x_search"),
159 ("execute", "executed a forced shell command"),
160 ("leak", "returned a forced file read"),
161 ])
162 def test_boundary_breach_fails_with_named_check(tmp_path, mode, check):
163 assert _audit(_fake_grok(tmp_path, mode)) == grok_audit.Verdict(grok_audit.FAIL, check)
164
165
166 def test_traffic_to_another_host_fails(tmp_path):
167 verdict = _audit(_fake_grok(tmp_path, "external"))
168 assert verdict.status == grok_audit.FAIL
169 assert "example.invalid" in verdict.check
170
171
172 @pytest.mark.parametrize("mode, control, check", [
173 ("silent", "obey", "the CLI sent no research request to the fixture"),
174 ("crash", "obey", "the CLI did not answer the forced calls"),
175 ("obey", "silent", "positive control did not execute the forced calls"),
176 ])
177 def test_unproven_audit_is_inconclusive(tmp_path, mode, control, check):
178 verdict = _audit(_fake_grok(tmp_path, mode, control))
179 assert verdict == grok_audit.Verdict(grok_audit.INCONCLUSIVE, check)
180
181
182 def test_audit_past_its_deadline_is_inconclusive(tmp_path):
183 verdict = _audit(_fake_grok(tmp_path, "hang"), seconds=3)
184 assert verdict == grok_audit.Verdict(grok_audit.INCONCLUSIVE, "audit timed out")
185
186
187 # --- verdict cache ----------------------------------------------------------
188
189 def _counting_audit(monkeypatch, verdict):
190 calls = []
191
192 def fake(binary, deadline):
193 calls.append(binary)
194 return verdict
195
196 monkeypatch.setattr(grok_audit, "run_audit", fake)
197 return calls
198
199
200 def test_pass_is_cached_on_disk_and_reused(monkeypatch, tmp_path, config_dir):
201 binary = _fake_grok(tmp_path, "obey")
202 calls = _counting_audit(monkeypatch, grok_audit.Verdict(grok_audit.PASS))
203 assert grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60).passed
204 grok_audit._MEMO.clear()
205 assert grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60).passed
206 assert len(calls) == 1
207 stored = json.loads((config_dir / grok_audit.CACHE_FILENAME).read_text())
208 assert [entry["verdict"] for entry in stored.values()] == ["pass"]
209
210
211 def test_changed_build_or_version_line_reaudits(monkeypatch, tmp_path, config_dir):
212 binary = _fake_grok(tmp_path, "obey")
213 calls = _counting_audit(monkeypatch, grok_audit.Verdict(grok_audit.PASS))
214 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
215 grok_audit.verdict_for(binary, "grok 1.0.71 (0123456789ab)", time.monotonic() + 60)
216 with open(binary, "a") as fh:
217 fh.write("# new build\n")
218 grok_audit.verdict_for(binary, "grok 1.0.71 (0123456789ab)", time.monotonic() + 60)
219 assert len(calls) == 3
220
221
222 def test_schema_bump_reaudits(monkeypatch, tmp_path, config_dir):
223 binary = _fake_grok(tmp_path, "obey")
224 calls = _counting_audit(monkeypatch, grok_audit.Verdict(grok_audit.PASS))
225 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
226 grok_audit._MEMO.clear()
227 monkeypatch.setattr(grok_audit, "AUDIT_SCHEMA", grok_audit.AUDIT_SCHEMA + 1)
228 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
229 assert len(calls) == 2
230
231
232 def test_inconclusive_is_memoized_but_never_written(monkeypatch, tmp_path, config_dir):
233 binary = _fake_grok(tmp_path, "obey")
234 verdict = grok_audit.Verdict(grok_audit.INCONCLUSIVE, "audit timed out")
235 calls = _counting_audit(monkeypatch, verdict)
236 for _ in range(3):
237 assert grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60) == verdict
238 assert len(calls) == 1
239 assert not (config_dir / grok_audit.CACHE_FILENAME).exists()
240 grok_audit._MEMO.clear() # next process
241 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
242 assert len(calls) == 2
243
244
245 def test_clear_failed_drops_only_fail_verdicts(monkeypatch, tmp_path, config_dir):
246 good = _fake_grok(tmp_path, "obey")
247 bad_dir = tmp_path / "bad"
248 bad_dir.mkdir()
249 bad = _fake_grok(bad_dir, "execute")
250 monkeypatch.setattr(grok_audit, "run_audit", lambda b, d: grok_audit.Verdict(
251 grok_audit.PASS if b == good else grok_audit.FAIL, "" if b == good else "executed a forced shell command"))
252 grok_audit.verdict_for(good, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
253 grok_audit.verdict_for(bad, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
254 assert grok_audit.clear_failed() == 1
255 stored = json.loads((config_dir / grok_audit.CACHE_FILENAME).read_text())
256 assert [entry["verdict"] for entry in stored.values()] == ["pass"]
257
258
259 def test_corrupt_cache_is_treated_as_absent(monkeypatch, tmp_path, config_dir):
260 config_dir.mkdir()
261 (config_dir / grok_audit.CACHE_FILENAME).write_text("{not json")
262 binary = _fake_grok(tmp_path, "obey")
263 calls = _counting_audit(monkeypatch, grok_audit.Verdict(grok_audit.PASS))
264 assert grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60).passed
265 assert len(calls) == 1
266
267
268 def test_unreadable_binary_is_inconclusive(config_dir, tmp_path):
269 verdict = grok_audit.verdict_for(str(tmp_path / "missing"), "grok 1.0.70 (f50904eaee6c)",
270 time.monotonic() + 60)
271 assert verdict.status == grok_audit.INCONCLUSIVE
272
273
274 # --- native resolution behind the npm launcher ------------------------------
275
276 def _npm_install(tmp_path, version="1.0.70"):
277 package = tmp_path / "lib" / "node_modules" / "@xai-official" / "grok"
278 (package / "bin").mkdir(parents=True)
279 (package / "package.json").write_text(json.dumps({"name": "@xai-official/grok", "version": version}))
280 launcher = package / "bin" / "grok"
281 launcher.write_text("#!/usr/bin/env node\nrequire('./grok-bootstrap.js');\n")
282 return package, launcher
283
284
285 def test_native_install_resolves_to_itself(tmp_path):
286 native = tmp_path / "grok-1.0.70"
287 native.write_bytes(b"\x7fELF native")
288 assert grok_audit.resolve_native(str(native)) == str(native)
289
290
291 def test_npm_launcher_resolves_to_the_build_its_package_ships(monkeypatch, tmp_path):
292 package, launcher = _npm_install(tmp_path)
293 grok_home = tmp_path / "grok-home"
294 monkeypatch.setenv("GROK_HOME", str(grok_home))
295 platform_bin = package / "node_modules" / "@xai-official" / f"grok-{grok_audit._platform_tag()}" / "bin"
296 platform_bin.mkdir(parents=True)
297 (platform_bin / "grok").write_bytes(b"native 1.0.70")
298 assert grok_audit.resolve_native(str(launcher)) == str(platform_bin / "grok")
299 # The launcher's own versioned copy wins when present, as in grok-bootstrap.js.
300 (grok_home / "bin").mkdir(parents=True)
301 (grok_home / "bin" / "grok-1.0.70").write_bytes(b"native 1.0.70")
302 assert grok_audit.resolve_native(str(launcher)) == str(grok_home / "bin" / "grok-1.0.70")
303
304
305 def test_npm_launcher_without_a_native_build_is_unresolved(monkeypatch, tmp_path):
306 _, launcher = _npm_install(tmp_path)
307 monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok-home"))
308 assert grok_audit.resolve_native(str(launcher)) is None
309
310
311 def test_unrelated_script_on_path_is_not_treated_as_npm(tmp_path):
312 script = tmp_path / "grok"
313 script.write_text("#!/bin/sh\nexec real-grok \"$@\"\n")
314 assert grok_audit.resolve_native(str(script)) == str(script)
315
316
317 # --- doctor surfacing -------------------------------------------------------
318
319 def _probe(monkeypatch, binary):
320 from unittest import mock
321 from lib import backends, grok_x
322
323 with mock.patch("lib.backends.which", lambda name: binary if name == "grok" else None), \
324 mock.patch("lib.grok_x.stored_auth_status",
325 return_value=(grok_x.AUTH_OK, "stored Grok credentials found", None)):
326 return backends._probe_grok({})
327
328
329 def test_doctor_reports_an_unaudited_build(monkeypatch, tmp_path, config_dir):
330 finding = _probe(monkeypatch, _fake_grok(tmp_path, "obey"))
331 assert finding.status == "ok"
332 assert "audited on its first run" in finding.detail
333
334
335 @pytest.mark.parametrize("verdict, status, text", [
336 (grok_audit.Verdict(grok_audit.FAIL, "executed a forced shell command"), "error",
337 "grok 1.0.70 (f50904eaee6c) failed the grok tool-boundary audit (executed a forced shell command)"),
338 (grok_audit.Verdict(grok_audit.PASS), "ok",
339 "grok 1.0.70 (f50904eaee6c) passed the tool-boundary audit"),
340 ])
341 def test_doctor_reports_cached_verdict_without_a_subprocess(monkeypatch, tmp_path, config_dir,
342 verdict, status, text):
343 import subprocess as sp
344
345 binary = _fake_grok(tmp_path, "obey")
346 monkeypatch.setattr(grok_audit, "run_audit", lambda b, d: verdict)
347 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
348
349 def no_subprocess(*args, **kwargs):
350 raise AssertionError("doctor's grok probe must not spawn a process")
351
352 monkeypatch.setattr(sp, "run", no_subprocess)
353 monkeypatch.setattr(grok_audit.subproc, "run_with_timeout", no_subprocess)
354 finding = _probe(monkeypatch, binary)
355 assert finding.status == status
356 assert text in finding.detail
357
358
359 def test_explicit_doctor_clears_a_cached_fail(monkeypatch, tmp_path, config_dir):
360 from lib import doctor
361
362 binary = _fake_grok(tmp_path, "obey")
363 monkeypatch.setattr(grok_audit, "run_audit",
364 lambda b, d: grok_audit.Verdict(grok_audit.FAIL, "executed a forced shell command"))
365 grok_audit.verdict_for(binary, "grok 1.0.70 (f50904eaee6c)", time.monotonic() + 60)
366 monkeypatch.setattr(doctor, "build_report", lambda config: {"run_evidence": {"fresh": True}})
367 monkeypatch.setattr(doctor, "render_text", lambda report: "")
368 monkeypatch.setattr(doctor, "write_cached_report", lambda *a, **k: None, raising=False)
369 doctor.run({}, cached=False)
370 stored = json.loads((config_dir / grok_audit.CACHE_FILENAME).read_text())
371 assert stored == {}
372
373
374 def test_npm_launcher_decompresses_the_shipped_build_once(monkeypatch, tmp_path, config_dir):
375 package, launcher = _npm_install(tmp_path)
376 monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok-home"))
377 platform_bin = package / "node_modules" / "@xai-official" / f"grok-{grok_audit._platform_tag()}" / "bin"
378 platform_bin.mkdir(parents=True)
379 (platform_bin / "grok.br").write_bytes(b"compressed")
380 calls = []
381
382 def fake_decompress(src, dest, timeout):
383 calls.append(timeout)
384 dest.parent.mkdir(parents=True, exist_ok=True)
385 dest.write_bytes(b"native")
386 return True
387
388 monkeypatch.setattr(grok_audit, "_decompress_brotli", fake_decompress)
389 dest = config_dir / "grok-bin" / "grok-1.0.70"
390 assert grok_audit.resolve_native(str(launcher), decompress=False) is None
391 assert grok_audit.resolve_native(str(launcher), timeout=7) == str(dest)
392 assert grok_audit.resolve_native(str(launcher)) == str(dest)
393 assert calls == [7]
394
395
396 def test_decompression_falls_back_to_grok_home_without_a_config_dir(monkeypatch, tmp_path):
397 package, launcher = _npm_install(tmp_path)
398 grok_home = tmp_path / "grok-home"
399 monkeypatch.setenv("GROK_HOME", str(grok_home))
400 monkeypatch.setattr(env, "CONFIG_DIR", None)
401 platform_bin = package / "node_modules" / "@xai-official" / f"grok-{grok_audit._platform_tag()}" / "bin"
402 platform_bin.mkdir(parents=True)
403 (platform_bin / "grok.br").write_bytes(b"compressed")
404
405 def fake_decompress(src, dest, timeout):
406 dest.parent.mkdir(parents=True, exist_ok=True)
407 dest.write_bytes(b"native")
408 return True
409
410 monkeypatch.setattr(grok_audit, "_decompress_brotli", fake_decompress)
411 assert grok_audit.resolve_native(str(launcher)) == str(grok_home / "bin" / "grok-1.0.70")
412
413
414 def test_unwritable_decompression_target_is_unresolved_not_raised(monkeypatch, tmp_path):
415 package, launcher = _npm_install(tmp_path)
416 monkeypatch.setenv("GROK_HOME", str(tmp_path / "grok-home"))
417 blocker = tmp_path / "not-a-dir"
418 blocker.write_text("file")
419 monkeypatch.setattr(env, "CONFIG_DIR", blocker)
420 monkeypatch.setattr(grok_audit.shutil, "which", lambda name: "/usr/bin/node")
421 platform_bin = package / "node_modules" / "@xai-official" / f"grok-{grok_audit._platform_tag()}" / "bin"
422 platform_bin.mkdir(parents=True)
423 (platform_bin / "grok.br").write_bytes(b"compressed")
424 assert grok_audit.resolve_native(str(launcher)) is None
425
426
427 def test_audit_child_registers_with_subproc_cleanup(tmp_path):
428 """Audit subprocesses run via subproc.run_with_timeout so engine SIGTERM
429 (subproc.cleanup_children) terminates an in-flight audit child too."""
430 import threading
431 from lib import subproc
432
433 pid_file = tmp_path / "audit.pid"
434 fake_grok = tmp_path / "grok"
435 fake_grok.write_text(
436 f"#!/bin/sh\n"
437 f"printf '%s' \"$$\" > \"{pid_file}\"\n"
438 f"sleep 30\n",
439 encoding="utf-8",
440 )
441 fake_grok.chmod(0o755)
442
443 worker = threading.Thread(
444 target=lambda: grok_audit._run_child(str(fake_grok), permissive=False, deadline=time.monotonic() + 30),
445 daemon=True,
446 )
447 worker.start()
448
449 try:
450 deadline = time.monotonic() + 5.0
451 child_pid = 0
452 while time.monotonic() < deadline:
453 if pid_file.exists():
454 raw = pid_file.read_text(encoding="utf-8").strip()
455 if raw.isdigit():
456 child_pid = int(raw)
457 break
458 time.sleep(0.02)
459 assert child_pid > 0, "fake grok audit child did not start"
460
461 with subproc._child_pids_lock:
462 registered = child_pid in subproc._child_pids
463 assert registered, f"grok audit pid {child_pid} was not registered with subproc"
464
465 subproc.cleanup_children(grace=0.5)
466 worker.join(timeout=5.0)
467 assert not worker.is_alive(), "grok_audit._run_child did not return after cleanup_children"
468
469 kill_deadline = time.monotonic() + 2.0
470 alive = True
471 while time.monotonic() < kill_deadline:
472 try:
473 os.kill(child_pid, 0)
474 except ProcessLookupError:
475 alive = False
476 break
477 time.sleep(0.02)
478 assert not alive, f"grok audit pid {child_pid} survived subproc.cleanup_children()"
479 finally:
480 with subproc._child_pids_lock:
481 subproc._shutting_down = False
482 if pid_file.exists():
483 raw = pid_file.read_text(encoding="utf-8").strip()
484 if raw.isdigit():
485 try:
486 os.kill(int(raw), 9)
487 except OSError:
488 pass
489
489 lines PYTHON