Address Greptile review findings on #276

- tools/summarize_original_live_init.py (4777565678): require an explicit
  boolean messages_truncated field in the frida_session_status record instead
  of defaulting missing values to False.
- tests/offline/test_live_control_and_summary_tools.py (4777565697): add
  mocked main() tests covering first-fd cleanup when second os.open fails,
  failed report emission when rmmod raises OSError or TimeoutExpired, and
  rejection of missing/non-bool messages_truncated.
This commit is contained in:
morebrackets
2026-12-02 16:50:05 -08:00
parent 00139d2d88
commit 87ed88f76e
2 changed files with 77 additions and 2 deletions

View File

@ -4,11 +4,14 @@ summarize_original_dispatch, summarize_original_live_init, and
reconcile_native_fifo_live_bootstrap hardening.
"""
import importlib.util
import io
import json
import os
import subprocess
from pathlib import Path
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
@ -16,8 +19,9 @@ ROOT = Path(__file__).resolve().parents[2]
def _load(name: str, rel: str):
spec = importlib.util.spec_from_file_location(name, ROOT / rel)
if spec is None or spec.loader is None:
raise RuntimeError(f"cannot load module spec for {rel}")
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
return mod
@ -34,6 +38,60 @@ class LiveControlAndSummaryToolsTest(unittest.TestCase):
self.assertTrue(callable(runner.main))
self.assertTrue(callable(runner.bindings))
def test_live_control_closes_first_fd_when_second_open_fails(self):
live = _load("live_control_test", "tools/live_control_test.py")
closed = []
open_calls = []
def fake_open(path, flags):
open_calls.append(path)
if len(open_calls) == 1:
return 42
raise OSError("second open failed")
with (
mock.patch.object(live.os, "open", side_effect=fake_open),
mock.patch.object(live.os, "close", side_effect=lambda fd: closed.append(fd)),
):
with self.assertRaisesRegex(OSError, "second open failed"):
live.main()
self.assertEqual(closed, [42])
def test_run_live_control_emits_failed_report_when_rmmod_raises(self):
runner = _load("run_live_control", "tools/run_live_control.py")
for rmmod_exc in (OSError("rmmod missing"), subprocess.TimeoutExpired(["rmmod", "nvidia_rs"], 30)):
with self.subTest(exc=type(rmmod_exc).__name__), tempfile.TemporaryDirectory() as tmp:
fake_root = Path(tmp)
(fake_root / "kernel-open").mkdir()
(fake_root / "kernel-open" / "nvidia_rs.ko").write_bytes(b"fake-ko")
(fake_root / "target").mkdir()
(fake_root / "target" / "compat32-rust-driver").write_bytes(b"fake-bin")
def fake_run(cmd, **_kwargs):
if cmd[0] == "insmod":
return subprocess.CompletedProcess(cmd, 0, "", "")
if cmd[0] == "rmmod":
raise rmmod_exc
return subprocess.CompletedProcess(cmd, 1, "", "probe failed")
buf = io.StringIO()
with (
mock.patch.object(runner, "R", fake_root),
mock.patch.object(runner.os, "geteuid", return_value=0),
mock.patch.object(runner, "bindings", return_value={}),
mock.patch.object(runner.subprocess, "run", side_effect=fake_run),
mock.patch.object(runner.Path, "exists", return_value=False),
mock.patch.object(runner.Path, "read_text", return_value=""),
redirect_stdout(buf),
):
rc = runner.main()
self.assertEqual(rc, 1)
report = json.loads(buf.getvalue())
self.assertFalse(report["passed"])
self.assertIn("rmmod failed", report["error"])
self.assertEqual(report["runs"][-1]["command"], "rmmod")
self.assertEqual(report["runs"][-1]["exit_code"], -1)
def test_summarize_dispatch_skips_malformed_kallsyms_and_creates_parent(self):
mod = _load("summarize_original_dispatch", "tools/summarize_original_dispatch.py")
with tempfile.TemporaryDirectory() as tmp:
@ -60,6 +118,21 @@ class LiveControlAndSummaryToolsTest(unittest.TestCase):
with self.assertRaisesRegex(SystemExit, "no frida_session_status record"):
mod.main([str(root)])
def test_summarize_live_init_rejects_missing_or_non_bool_messages_truncated(self):
mod = _load("summarize_original_live_init", "tools/summarize_original_live_init.py")
for bad_norm in (
{"messages": []},
{"messages": [], "messages_truncated": "false"},
{"messages": [], "messages_truncated": None},
):
with self.subTest(bad_norm=bad_norm), tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
bundle = {"records": [{"operation": "frida_session_status", "normalized_result": bad_norm}]}
(root / "rea-evidence-bundle.json").write_text(json.dumps(bundle), encoding="utf-8")
(root / "overflow-aware-init-calls.txt").write_text("", encoding="utf-8")
with self.assertRaisesRegex(SystemExit, "missing boolean messages_truncated"):
mod.main([str(root)])
def test_reconcile_fifo_bootstrap_is_importable_and_honors_env(self):
mod = _load("reconcile_fifo", "tools/reconcile_native_fifo_live_bootstrap.py")
with tempfile.TemporaryDirectory() as tmp:

View File

@ -99,7 +99,9 @@ def main(argv=None):
events.append(e)
counts[sym] += 1
first.setdefault(sym, e)
truncated = bool(norm.get('messages_truncated', False))
truncated = norm.get('messages_truncated')
if type(truncated) is not bool:
raise SystemExit('evidence bundle missing boolean messages_truncated')
result = {
'scope': 'Observed source-body callsite markers, not complete function entry list or lossless call chain. Labels are prior static interpretations, execution/timing are live observations. No GPU object/register arguments captured by PT. cuInit enumerates all eight boards; markers cannot identify a particular GPU. Driver already PCI-bound; not boot/cold-probe capture.',
'rea_evidence': [r.get('evidence_id'), 'ev_d9f5b3999e69f43b9cccb62d8a723c6c7feafe021dd09245f1ebb935c18ab963'],