diff --git a/src/mcproof/domain_protocol.py b/src/mcproof/domain_protocol.py index 187413e..2c3d6c5 100644 --- a/src/mcproof/domain_protocol.py +++ b/src/mcproof/domain_protocol.py @@ -1285,21 +1285,45 @@ def _no_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]: ) +MAX_DUAL_OBJECTIVE_BITS = 850 # ~255 decimal digits; blocks quadratic bigint stringification DoS + + +def _format_bounded_fraction( + q: Fraction, + *, + max_bits: int = MAX_DUAL_OBJECTIVE_BITS, + always_ratio: bool = False, +) -> str: + """Format an exact `Fraction` without triggering big-int decimal stringification.""" + n_bits = q.numerator.bit_length() + d_bits = q.denominator.bit_length() + if n_bits > max_bits or d_bits > max_bits: + sign = "-" if q.numerator < 0 else "" + return f"" + if always_ratio or q.denominator != 1: + return f"{q.numerator}/{q.denominator}" + return str(q.numerator) + + def _parse_exact_rational(val: Any, *, max_abs_int: int = MAX_CERT_ABS_INT) -> Fraction: """Parse an exact `int` (`type(val) is int`, never `bool`) or canonical `'p/q'` string into `Fraction`.""" if type(val) is int: if abs(val) > max_abs_int: raise ValueError("integer exceeds cap") return Fraction(val, 1) - if isinstance(val, str) and STRICT_RATIONAL_RE.fullmatch(val): - if "/" in val: - n_str, d_str = val.split("/", 1) - num, den = int(n_str), int(d_str) - else: - num, den = int(val), 1 - if abs(num) > max_abs_int or abs(den) > max_abs_int: - raise ValueError("rational component exceeds cap") - return Fraction(num, den) + max_digits = len(str(max_abs_int)) + 1 + if isinstance(val, str): + if len(val) > (2 * max_digits + 3): + raise ValueError(f"rational string exceeds safe length bound ({len(val)} chars)") + if STRICT_RATIONAL_RE.fullmatch(val): + if "/" in val: + n_str, d_str = val.split("/", 1) + num, den = int(n_str), int(d_str) + else: + num, den = int(val), 1 + if abs(num) > max_abs_int or abs(den) > max_abs_int: + raise ValueError("rational component exceeds cap") + return Fraction(num, den) raise ValueError(f"invalid exact rational token {val!r} (bool/float forbidden)") @@ -1379,7 +1403,10 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]: findings.append( { "rule": "LP_DUAL_INFEASIBLE_COLUMN", - "message": f"column {j}: (y^T A)[{j}] = {yt_a[j]} exceeds c[{j}] = {cost_c[j]}", + "message": ( + f"column {j}: (y^T A)[{j}] = {_format_bounded_fraction(yt_a[j])} " + f"exceeds c[{j}] = {_format_bounded_fraction(cost_c[j])}" + ), } ) break @@ -1387,7 +1414,10 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]: findings.append( { "rule": "LP_DUAL_OBJECTIVE_BELOW_CLAIM", - "message": f"y^T b = {yt_b} < claimed_lower_bound = {claimed_lb}", + "message": ( + f"y^T b = {_format_bounded_fraction(yt_b)} < " + f"claimed_lower_bound = {_format_bounded_fraction(claimed_lb)}" + ), } ) elif mode == "infeasible": @@ -1397,7 +1427,7 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]: findings.append( { "rule": "LP_FARKAS_POSITIVE_COLUMN", - "message": f"Farkas certificate requires (y^T A)[{j}] <= 0, got {yt_a[j]}", + "message": f"Farkas certificate requires (y^T A)[{j}] <= 0, got {_format_bounded_fraction(yt_a[j])}", } ) break @@ -1405,17 +1435,19 @@ def verify_rational_lp_certificate(cert: Mapping[str, Any]) -> dict[str, Any]: findings.append( { "rule": "LP_FARKAS_NONPOSITIVE_WITNESS", - "message": f"Farkas certificate requires y^T b > 0, got {yt_b}", + "message": f"Farkas certificate requires y^T b > 0, got {_format_bounded_fraction(yt_b)}", } ) else: findings.append({"rule": "LP_CERT_UNSUPPORTED_MODE", "message": f"unsupported LP mode {mode!r}"}) + dual_obj_str = _format_bounded_fraction(yt_b, always_ratio=True) + passed = len(findings) == 0 return { "passed": passed, "epistemic_status": "VERIFIED" if passed else "REJECTED", - "dual_objective": f"{yt_b.numerator}/{yt_b.denominator}", + "dual_objective": dual_obj_str, "findings": findings, } diff --git a/src/mcproof/lean_harness.py b/src/mcproof/lean_harness.py index 36a1e6d..8db71c6 100644 --- a/src/mcproof/lean_harness.py +++ b/src/mcproof/lean_harness.py @@ -61,15 +61,33 @@ ), ), ( - # `attribute [init]` is not `@[init]`. It still runs when the module is imported. - # The marker may sit mid-line or be split across a newline (`attribute\n[init]`). + # `attribute [init]`, `@[init]` / `@[builtin_init]`, and `initialize` / + # `builtin_initialize` declarations run IO on import or elaboration. "FORBIDDEN_INIT_ATTRIBUTE", - re.compile(r"attribute\s*\[[^\]]*\b(?:builtin_init|init)\b"), + re.compile( + r"(?:@|attribute\s*)\[[^\]]*\b(?:builtin_init|init)\b" + r"|(? int: def _toolchain_elan_home() -> str: - root = Path(elan_bin_dir()).resolve().parent + try: + root = Path(elan_bin_dir()).resolve().parent + except FileNotFoundError: + return "" return str(root) if (root / "bin").is_dir() else "" -def _sandbox_env_pairs(caller_env: Mapping[str, str] | None) -> list[tuple[str, str]]: - """Allowlist passed to `env -i` and to `bwrap --setenv`. Nothing else crosses.""" +def _sandbox_env_pairs( + caller_env: Mapping[str, str] | None = None, + *, + harness_lean_path: str | None = None, +) -> list[tuple[str, str]]: + """Allowlist passed to `env -i` and to `bwrap --setenv`. Caller env never crosses.""" + _ = caller_env # Intentionally ignored: caller env must never cross the sandbox boundary. elan = _toolchain_elan_home() path_parts = ["/usr/bin", "/bin"] if elan: @@ -182,9 +212,8 @@ def _sandbox_env_pairs(caller_env: Mapping[str, str] | None) -> list[tuple[str, ] if elan: pairs.append(("ELAN_HOME", elan)) - lean_path = (caller_env or {}).get("LEAN_PATH") - if lean_path: - pairs.append(("LEAN_PATH", lean_path)) + if harness_lean_path: + pairs.append(("LEAN_PATH", harness_lean_path)) return pairs @@ -194,6 +223,7 @@ def _confine_argv( cwd: Path, caller_env: Mapping[str, str] | None, readable_dirs: Sequence[Path], + harness_lean_path: str | None = None, ) -> list[str]: """`prlimit` + `env -i` + `bwrap` over the toolchain, not the host root.""" prlimit_bin = shutil.which("prlimit") @@ -206,7 +236,7 @@ def _confine_argv( ) cwd_path = Path(cwd).resolve() cwd_s = str(cwd_path) - pairs = _sandbox_env_pairs(caller_env) + pairs = _sandbox_env_pairs(caller_env, harness_lean_path=harness_lean_path) argv: list[str] = [ prlimit_bin, f"--cpu={_SANDBOX_CPU_SEC}", @@ -269,14 +299,23 @@ def _spawn_confined( caller_env: Mapping[str, str] | None, timeout_sec: float, readable_dirs: Sequence[Path] = (), + harness_lean_path: str | None = None, + host_env: Mapping[str, str] | None = None, ) -> subprocess.CompletedProcess[str]: - argv = _confine_argv(cmd, cwd=cwd, caller_env=caller_env, readable_dirs=readable_dirs) + argv = _confine_argv( + cmd, + cwd=cwd, + caller_env=caller_env, + readable_dirs=readable_dirs, + harness_lean_path=harness_lean_path, + ) return subprocess.run( argv, capture_output=True, text=True, timeout=timeout_sec, check=False, + env=dict(host_env) if host_env is not None else None, ) @@ -297,7 +336,8 @@ def linux_bwrap_functional(*, timeout_sec: float = 15.0) -> bool: _BWRAP_FUNCTIONAL = False return False sentinel = f"mcproof-sentinel-{uuid.uuid4().hex}" - os.environ["MCPROOF_SANDBOX_SENTINEL"] = sentinel + probe_host_env = dict(os.environ) + probe_host_env["MCPROOF_SANDBOX_SENTINEL"] = sentinel try: with tempfile.TemporaryDirectory(prefix="mcproof_bwrap_probe_") as tmp: script = Path(tmp) / "probe.py" @@ -308,13 +348,12 @@ def linux_bwrap_functional(*, timeout_sec: float = 15.0) -> bool: cwd=Path(tmp), caller_env={}, timeout_sec=timeout_sec, + host_env=probe_host_env, ) except (OSError, subprocess.TimeoutExpired, CandidateSandboxUnavailable): _BWRAP_FUNCTIONAL = False return False - finally: - os.environ.pop("MCPROOF_SANDBOX_SENTINEL", None) - _BWRAP_FUNCTIONAL = probe.returncode == 0 + _BWRAP_FUNCTIONAL = probe.returncode == 0 and (probe.stdout or "").strip() == "MCPROOF_PROBE_OK" return _BWRAP_FUNCTIONAL @@ -325,6 +364,7 @@ def run_confined_command( env: Mapping[str, str] | None = None, timeout_sec: float = 300, readable_dirs: Sequence[Path] = (), + harness_lean_path: str | None = None, ) -> subprocess.CompletedProcess[str]: """Run `cmd` where the candidate cannot see the host. @@ -345,6 +385,7 @@ def run_confined_command( caller_env=env, timeout_sec=timeout_sec, readable_dirs=readable_dirs, + harness_lean_path=harness_lean_path, ) @@ -408,7 +449,11 @@ def _load_soko_lean4_auditor() -> Any: raise RuntimeError(f"failed to load lean4_auditor from {soko_path}") mod = importlib.util.module_from_spec(spec) sys.modules["soko_lean4_auditor"] = mod - spec.loader.exec_module(mod) + try: + spec.loader.exec_module(mod) + except Exception as exc: + sys.modules.pop("soko_lean4_auditor", None) + raise RuntimeError(f"failed to execute lean4_auditor from {soko_path}: {exc}") from exc return mod @@ -544,16 +589,42 @@ def _char_lit_end(src: str, i: int) -> int | None: return None -def strip_lean_comments_and_strings(src: str) -> str: +def strip_lean_comments_and_strings(src: str, *, blank_chars: bool = False) -> str: """Strip `--` line comments, nested `/- ... -/` block comments, and string literals while keeping line numbers. Raw strings (`r"..."`, `r#"..."#`, any number of hashes) do not treat `\\` as an escape. - Character literals, including `'"'` and escaped forms, are kept so a following command stays visible. + Interpolated strings (`s!"..."`, `f!"..."`, `m!"..."`, and custom `!"..."` macros) + track nested `{...}` Lean expressions so embedded character literals (`'"'`, `'\\"'`), + strings, comments, and nested interpolations cannot desynchronize quote parity. + Character literals, including `'"'` and escaped forms, are kept by default so definition + comparisons stay exact; pass `blank_chars=True` to replace char literals with `'c'` and + replace `"` inside `«...»` identifiers so downstream line/string scanners (e.g., `soko`) + cannot be desynchronized by `'"'` or `«"»`. """ out: list[str] = [] i = 0 n = len(src) + interp_braces: list[int] = [] while i < n: + if interp_braces and interp_braces[-1] == 0: + ch = src[i] + if ch == "\\" and i + 1 < n: + if src[i + 1] == "\n": + out.append("\n") + i += 2 + elif ch == "{": + out.append('" { ') + interp_braces[-1] = 1 + i += 1 + elif ch == '"': + out.append('"') + interp_braces.pop() + i += 1 + else: + if ch == "\n": + out.append("\n") + i += 1 + continue if src.startswith("/-", i): depth = 1 i += 2 @@ -576,15 +647,41 @@ def strip_lean_comments_and_strings(src: str) -> str: if _is_raw_str_start(src, i): i = _append_raw_string(src, i, out) continue + if src[i] == "{" and interp_braces: + interp_braces[-1] += 1 + out.append("{") + i += 1 + continue + if src[i] == "}" and interp_braces: + interp_braces[-1] -= 1 + if interp_braces[-1] == 0: + out.append(' } "') + else: + out.append("}") + i += 1 + continue if src[i] == "«" or _is_lean_id_first(src[i]): j = _lean_ident_end(src, i) - out.append(src[i:j]) - i = j + ident = src[i:j] + is_interp = j > i and src[j - 1] == "!" and j < n and src[j] == '"' + if blank_chars and '"' in ident: + ident = ident.replace('"', "_") + out.append(ident) + if is_interp: + out.append('"') + interp_braces.append(0) + i = j + 1 + else: + i = j continue if src[i] == "'": end = _char_lit_end(src, i) if end is not None: - out.append(src[i:end]) + if blank_chars: + nl_count = src.count("\n", i, end) + out.append("\n" * nl_count + "'c'") + else: + out.append(src[i:end]) i = end continue if src[i] == '"': @@ -605,6 +702,8 @@ def strip_lean_comments_and_strings(src: str) -> str: continue out.append(src[i]) i += 1 + if interp_braces and interp_braces[-1] == 0: + out.append('"') return "".join(out) @@ -1045,7 +1144,7 @@ def verify_lean4_prompt_obligations( if findings: return findings - proj_dir = (lean_project_dir or (repo_root() / "lean")).resolve() + proj_dir = _checked_project_dir(lean_project_dir or (repo_root() / "lean")) lean_bin = find_lean_tool("lean") env = _lean_env() lib_olean_dir = proj_dir / ".lake" / "build" / "lib" / "lean" @@ -1071,10 +1170,7 @@ def verify_lean4_prompt_obligations( f" let pairs : List (Name × Name × Name) := [{', '.join(pair_entries)}]\n" " for (axN, fullN, shortN) in pairs do\n" " let some specI := env.find? axN | IO.println s!\"MCPROOF_PSPEC_ERR\\tSPEC_ELAB_FAIL\\t{shortN}\"; continue\n" - " let candOpt := match env.find? fullN with\n" - " | some ci => some ci\n" - " | none => env.find? shortN\n" - " let some candI := candOpt | IO.println s!\"MCPROOF_PSPEC_ERR\\tMISSING_PROMPT_THEOREM_NAME\\t{shortN}\"; continue\n" + " let some candI := env.find? fullN | IO.println s!\"MCPROOF_PSPEC_ERR\\tMISSING_PROMPT_THEOREM_NAME\\t{shortN}\"; continue\n" " match candI with\n" " | .thmInfo ct =>\n" " let (ok, _) ← (Meta.isDefEq specI.type ct.type).run' {}\n" @@ -1094,29 +1190,30 @@ def verify_lean4_prompt_obligations( lean_path_parts = [str(tdp)] if lib_olean_dir.is_dir(): lean_path_parts.append(str(lib_olean_dir)) - sysroot_proc = subprocess.run([lean_bin, "--print-libdir"], capture_output=True, text=True, check=False) + sysroot_proc = subprocess.run([lean_bin, "--print-libdir"], capture_output=True, text=True, env=env, check=False) if sysroot_proc.returncode == 0 and sysroot_proc.stdout.strip(): lean_path_parts.append(sysroot_proc.stdout.strip()) - run_env = dict(env) - run_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts) + harness_lp = os.pathsep.join(lean_path_parts) readable = (lib_olean_dir,) if lib_olean_dir.is_dir() else () try: c_proc = run_confined_command( [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)], cwd=tdp, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=readable, + harness_lean_path=harness_lp, ) if c_proc.returncode != 0: return findings d_proc = run_confined_command( [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)], cwd=tdp, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=readable, + harness_lean_path=harness_lp, ) except CandidateSandboxUnavailable as exc: findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)}) @@ -1159,7 +1256,7 @@ def verify_lean4_against_challenge( if findings: return findings - proj_dir = (lean_project_dir or (repo_root() / "lean")).resolve() + proj_dir = _checked_project_dir(lean_project_dir or (repo_root() / "lean")) lean_bin = find_lean_tool("lean") env = _lean_env() lib_olean_dir = proj_dir / ".lake" / "build" / "lib" / "lean" @@ -1179,27 +1276,28 @@ def verify_lean4_against_challenge( lean_path_parts = [str(tdp)] if lib_olean_dir.is_dir(): lean_path_parts.append(str(lib_olean_dir)) - sysroot_proc = subprocess.run([lean_bin, "--print-libdir"], capture_output=True, text=True, check=False) + sysroot_proc = subprocess.run([lean_bin, "--print-libdir"], capture_output=True, text=True, env=env, check=False) if sysroot_proc.returncode == 0 and sysroot_proc.stdout.strip(): lean_path_parts.append(sysroot_proc.stdout.strip()) - run_env = dict(env) - run_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts) + harness_lp = os.pathsep.join(lean_path_parts) readable = (lib_olean_dir,) if lib_olean_dir.is_dir() else () try: s_proc = run_confined_command( [lean_bin, "-j", "1", "-D", "Elab.async=false", str(spec_f), "-o", str(spec_o)], cwd=tdp, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=readable, + harness_lean_path=harness_lp, ) c_proc = run_confined_command( [lean_bin, "-j", "1", "-D", "Elab.async=false", str(cand_f), "-o", str(cand_o)], cwd=tdp, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=readable, + harness_lean_path=harness_lp, ) if s_proc.returncode != 0 or c_proc.returncode != 0: findings.append({ @@ -1211,9 +1309,10 @@ def verify_lean4_against_challenge( cmp_proc = run_confined_command( [lean_bin, "-j", "1", "-D", "Elab.async=false", str(drv_f)], cwd=tdp, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=readable, + harness_lean_path=harness_lp, ) except CandidateSandboxUnavailable as exc: findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)}) @@ -1303,10 +1402,34 @@ def lint_lean4_source( ) -> dict[str, Any]: """Run static Lean 4 source audits combining soko lean4_auditor, Proven-Commons bar rules, and WeakStatement checks.""" soko_mod = _load_soko_lean4_auditor() - soko_rep = soko_mod.audit_lean4_source(source, label=label, strict_init_only=strict_init_only) + soko_source = strip_lean_comments_and_strings(source, blank_chars=True) + soko_rep = soko_mod.audit_lean4_source(soko_source, label=label, strict_init_only=strict_init_only) + if not isinstance(soko_rep, Mapping): + raise RuntimeError(f"soko lean4_auditor returned non-mapping result: {type(soko_rep).__name__}") + raw_soko_findings = soko_rep.get("findings") + if not isinstance(raw_soko_findings, list): + raise RuntimeError("soko lean4_auditor result missing list 'findings' field") + if "ok" in soko_rep: + soko_ok = soko_rep["ok"] + elif "passed" in soko_rep: + soko_ok = soko_rep["passed"] + else: + raise RuntimeError("soko lean4_auditor result missing bool 'ok'/'passed' status field") + if not isinstance(soko_ok, bool): + raise RuntimeError(f"soko lean4_auditor status field must be bool: {soko_ok!r}") + if "finding_count" in soko_rep and soko_rep["finding_count"] != len(raw_soko_findings): + raise RuntimeError( + f"soko lean4_auditor finding_count ({soko_rep['finding_count']!r}) != len(findings) ({len(raw_soko_findings)})" + ) + if soko_ok and len(raw_soko_findings) > 0: + raise RuntimeError("soko lean4_auditor contradiction: ok/passed=True with non-empty findings") + if not soko_ok and len(raw_soko_findings) == 0: + raise RuntimeError("soko lean4_auditor fail-open: ok/passed=False with empty findings") findings: list[dict[str, Any]] = [] - for f in soko_rep.get("findings", []): + for f in raw_soko_findings: + if not isinstance(f, Mapping): + raise RuntimeError(f"soko lean4_auditor finding entry is not a mapping: {type(f).__name__}") if allow_challenge_sorry and f.get("code") == "UNPROVED_SORRY": continue findings.append({ @@ -1350,9 +1473,26 @@ def lint_lean4_source( } +_LEAN_SCRUB_VARS: tuple[str, ...] = ( + "LEAN_PATH", + "LEAN_OPTS", + "LEAN_SRC_PATH", + "LEAN_SYSROOT", + "LEAN_CC", + "ELAN_TOOLCHAIN", + "ELAN_HOME", + "LAKE_HOME", + "LAKE_PKG_PATH", + "LD_PRELOAD", + "LD_LIBRARY_PATH", +) + + def _lean_env() -> dict[str, str]: - env = dict(os.environ) bin_dir = str(elan_bin_dir()) + env = dict(os.environ) + for var in _LEAN_SCRUB_VARS: + env.pop(var, None) cur_path = env.get("PATH", "") env["PATH"] = f"{bin_dir}{os.pathsep}{cur_path}" if cur_path else bin_dir return env @@ -1445,9 +1585,49 @@ def to_dict(self) -> dict[str, Any]: } +def _checked_project_dir(project_dir: Path) -> Path: + """Reject any symlink on `project_dir` or its ancestors without following `.resolve()`.""" + abs_path = Path(os.path.abspath(str(project_dir))) + cur = Path(abs_path.anchor) + for part in abs_path.parts[1:]: + cur = cur / part + try: + st = os.lstat(cur) + except OSError as exc: + raise UntrustedProjectPath(f"project path component unreadable ({cur}): {exc}") from exc + if stat.S_ISLNK(st.st_mode): + raise UntrustedProjectPath(f"project path crosses a symlink: {cur}") + return abs_path + + +def _read_toolchain_nofollow(lean_project_dir: Path, *, default: str = "leanprover/lean4:v4.35.0") -> str: + """Read `lean-toolchain` via O_NOFOLLOW + fstat to prevent symlink check-then-use TOCTOU.""" + if not _nofollow_dir_ops_available(): + return default + try: + dir_fd = os.open(lean_project_dir, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except OSError: + return default + try: + try: + fd = os.open("lean-toolchain", os.O_RDONLY | os.O_NOFOLLOW, dir_fd=dir_fd) + except OSError: + return default + try: + st = os.fstat(fd) + if not stat.S_ISREG(st.st_mode): + return default + raw = os.read(fd, 4096) + finally: + os.close(fd) + finally: + os.close(dir_fd) + text = raw.decode("utf-8", "replace").strip() + return text or default + + def _read_toolchain(lean_project_dir: Path) -> str: - tc = lean_project_dir / "lean-toolchain" - return tc.read_text(encoding="utf-8").strip() if tc.is_file() else "leanprover/lean4:v4.35.0" + return _read_toolchain_nofollow(lean_project_dir) def verify_lean4_source( @@ -1463,7 +1643,7 @@ def verify_lean4_source( max_memory_mib: int | None = 1400, ) -> LeanVerificationResult: """Compile a Lean 4 source string, audit source escape hatches, verify kernel collectAxioms, and run leanchecker.""" - proj_dir = (lean_project_dir or (repo_root() / "lean")).resolve() + proj_dir = _checked_project_dir(lean_project_dir or (repo_root() / "lean")) toolchain = _read_toolchain(proj_dir) lint = lint_lean4_source( source, @@ -1557,8 +1737,7 @@ def verify_lean4_source( lean_path_parts = [str(tmp_dir)] if lib_olean_dir.is_dir(): lean_path_parts.append(str(lib_olean_dir)) - run_env = dict(env) - run_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts) + harness_lp = os.pathsep.join(lean_path_parts) comp_cmd = build_capped_lean_args( lean_bin, @@ -1570,9 +1749,10 @@ def verify_lean4_source( comp = run_confined_command( comp_cmd, cwd=tmp_dir, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (), + harness_lean_path=harness_lp, ) except subprocess.TimeoutExpired as exc: findings.append({ @@ -1662,9 +1842,10 @@ def verify_lean4_source( ax_run = run_confined_command( [lean_bin, str(audit_driver)], cwd=tmp_dir, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (), + harness_lean_path=harness_lp, ) except CandidateSandboxUnavailable as exc: findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)}) @@ -1732,9 +1913,10 @@ def verify_lean4_source( lc_run = run_confined_command( [leanchecker_bin, mod_name], cwd=tmp_dir, - env=run_env, + env=env, timeout_sec=timeout_sec, readable_dirs=(lib_olean_dir,) if lib_olean_dir.is_dir() else (), + harness_lean_path=harness_lp, ) except CandidateSandboxUnavailable as exc: findings.append({"line": 1, "rule": "SANDBOX_UNAVAILABLE", "message": str(exc)}) @@ -1830,12 +2012,24 @@ def finding_blocks_comparator(finding: Mapping[str, Any]) -> bool: message = str(finding.get("message", "")) if rule in {"FORBIDDEN_EVAL_COMMAND", "FORBIDDEN_ELAB_COMMAND"}: return True - tokens = ("run_meta", "run_cmd", "run_elab", "run_tac", "#eval", "#reduce", "#check", "#print", "#synth") + tokens = ( + "run_meta", + "run_cmd", + "run_elab", + "run_tac", + "#eval", + "#reduce", + "#check", + "#print", + "#synth", + "#guard_msgs", + "#guard", + ) return rule in {"METAPROGRAM_ESCAPE", "FORBIDDEN_BUILD_SIDE_EFFECT"} and any(token in message for token in tokens) _LAKE_COMMAND_RE = re.compile( - r"(? tuple[int, int | None]: def _lean_commands_that_may_run(src: str) -> list[str]: - """Commands Lean can elaborate, including one hidden by a short raw-string closer. + """Commands Lean can elaborate, including one hidden by a short raw-string closer or interpolation. - A command inside a terminated string or comment is not included. The comment - stripper is unchanged, so a compile that must still run those payloads is - unchanged too. + A command inside a terminated string or comment is not included, while commands inside + or following `{...}` interpolated string expressions (`s!"..."`, `f!"..."`, `m!"..."`, + `!"..."`) are still scanned. """ found: list[str] = [] n = len(src) i = 0 + interp_braces: list[int] = [] while i < n: + if interp_braces and interp_braces[-1] == 0: + ch = src[i] + if ch == "\\" and i + 1 < n: + i += 2 + elif ch == "{": + interp_braces[-1] = 1 + i += 1 + elif ch == '"': + interp_braces.pop() + i += 1 + else: + i += 1 + continue if src.startswith("/-", i): depth = 1 i += 2 @@ -1909,6 +2117,14 @@ def _lean_commands_that_may_run(src: str) -> list[str]: else: i = end if end > i else i + 1 continue + if src[i] == "{" and interp_braces: + interp_braces[-1] += 1 + i += 1 + continue + if src[i] == "}" and interp_braces: + interp_braces[-1] -= 1 + i += 1 + continue match = _LAKE_COMMAND_RE.match(src, i) if match: cmd = match.group(0) @@ -1932,7 +2148,12 @@ def _lean_commands_that_may_run(src: str) -> list[str]: i = end continue if src[i] == "«" or _is_lean_id_first(src[i]): - i = _lean_ident_end(src, i) + j = _lean_ident_end(src, i) + if j > i and src[j - 1] == "!" and j < n and src[j] == '"': + interp_braces.append(0) + i = j + 1 + else: + i = j continue i += 1 return found @@ -2143,19 +2364,19 @@ def _audit_solution_axioms( MODULE_AXIOM_AUDIT_TEMPLATE.format(module_name=solution_mod), encoding="utf-8", ) - ax_env = dict(env) lean_path_parts = [str(ax_tmp)] olean_rel = ".lake/build/lib/lean" if _real_dir(build_dir, olean_rel): lean_path_parts.append(str(build_dir / olean_rel)) - ax_env["LEAN_PATH"] = os.pathsep.join(lean_path_parts) + harness_lp = os.pathsep.join(lean_path_parts) try: ax_run = run_confined_command( [lean_bin, str(audit_driver)], cwd=ax_tmp, - env=ax_env, + env=env, timeout_sec=timeout_sec, readable_dirs=(build_dir,), + harness_lean_path=harness_lp, ) except CandidateSandboxUnavailable as exc: return measured, sorry_decls, nonstd, str(exc) @@ -2216,8 +2437,11 @@ def verify_lean4_project_comparator( Trusted steps run in a directory built from an in-memory copy. The caller's tree is never written. `allow_unsandboxed` does not run candidate Lean on the host. """ - proj = (project_dir or (repo_root() / "lean")).resolve() + raw_proj = project_dir or (repo_root() / "lean") findings: list[dict[str, Any]] = [] + toolchain = "leanprover/lean4:v4.35.0" + theorem_names: tuple[str, ...] = () + challenge_mod = "" def _stopped(*, sandboxed: bool = False, caveats: tuple[str, ...] = ()) -> LeanVerificationResult: return LeanVerificationResult( @@ -2234,15 +2458,17 @@ def _stopped(*, sandboxed: bool = False, caveats: tuple[str, ...] = ()) -> LeanV challenge_sorry_whitelisted_module=challenge_mod or None, ) + try: + proj = _checked_project_dir(raw_proj) + except UntrustedProjectPath as exc: + findings.append({"line": 1, "rule": exc.rule, "message": str(exc)}) + return _stopped() + lake_hit = _lake_symlink_finding(proj) if lake_hit is not None: # The platform refusal must not stat or read through a candidate path. - if lake_hit.get("rule") == _NOFOLLOW_OPEN_RULE: - toolchain = "leanprover/lean4:v4.35.0" - else: - toolchain = _read_toolchain(proj) if (proj / "lean-toolchain").is_file() and not (proj / "lean-toolchain").is_symlink() else "leanprover/lean4:v4.35.0" - theorem_names = () - challenge_mod = "" + if lake_hit.get("rule") != _NOFOLLOW_OPEN_RULE: + toolchain = _read_toolchain_nofollow(proj) findings.append(lake_hit) return _stopped() diff --git a/src/mcproof/lineage.py b/src/mcproof/lineage.py index 4b2155a..a47c8e6 100644 --- a/src/mcproof/lineage.py +++ b/src/mcproof/lineage.py @@ -65,7 +65,13 @@ class StaleLineageError(ValueError): def canonical_json_bytes(payload: Any) -> bytes: - return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("utf-8") + return json.dumps( + payload, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + allow_nan=False, + ).encode("utf-8") def sha256_bytes(data: bytes) -> str: @@ -94,7 +100,7 @@ def sha256_file(path: Path) -> str: def compute_zone_manifest_id(manifest: Mapping[str, Any]) -> str: body = {k: v for k, v in manifest.items() if k != "manifest_id"} - raw = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") + raw = canonical_json_bytes(body) return "sha256:" + hashlib.sha256(raw).hexdigest() diff --git a/src/mcproof/repair_loop.py b/src/mcproof/repair_loop.py index 4b51282..b2a6628 100644 --- a/src/mcproof/repair_loop.py +++ b/src/mcproof/repair_loop.py @@ -32,6 +32,7 @@ from typing import Any, Callable, Mapping, Sequence import urllib.request +from .lineage import canonical_json_bytes from .lean_harness import ( BAR_FORBIDDEN_RULES, THEOREM_DECL_RE, @@ -345,7 +346,7 @@ def compute_failure_signature(findings: Sequence[Mapping[str, Any]]) -> str: for f in findings } ) - raw = json.dumps(pairs, separators=(",", ":")).encode("utf-8") + raw = canonical_json_bytes(pairs) return hashlib.sha256(raw).hexdigest()[:24] @@ -779,7 +780,7 @@ def make_llama_server_generator( def _post_json(url: str, payload: Mapping[str, Any]) -> dict[str, Any]: req = urllib.request.Request( url, - data=json.dumps(dict(payload)).encode("utf-8"), + data=canonical_json_bytes(dict(payload)), headers={"Content-Type": "application/json"}, method="POST", ) @@ -1960,7 +1961,7 @@ def run_repair_split( if checkpoint_jsonl is not None: checkpoint_jsonl.parent.mkdir(parents=True, exist_ok=True) with checkpoint_jsonl.open("a", encoding="utf-8", newline="\n") as fh: - fh.write(json.dumps(res, sort_keys=True) + "\n") + fh.write(canonical_json_bytes(res).decode("utf-8") + "\n") n_total = len(results) pass_curve: dict[str, dict[str, Any]] = {} diff --git a/tests/test_pr3_r12_hardening.py b/tests/test_pr3_r12_hardening.py new file mode 100644 index 0000000..670baa4 --- /dev/null +++ b/tests/test_pr3_r12_hardening.py @@ -0,0 +1,741 @@ +#!/usr/bin/env python3 +"""Fail-closed R12 security & provenance regression suite for mcproof PR #3. + +Covers all confirmed P0-1..P0-6 defects, X-1..X-5 blind spots, and T1..T9 +fail-closed kill assertions with zero bare `assert` statements and pure stdlib +`unittest` compatibility across `-I -B`, `-I -O -B`, `-I -B -W error`, and pytest. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import types +import unittest +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parent.parent +SRC_DIR = REPO_ROOT / "src" +if str(SRC_DIR) not in sys.path: + sys.path.insert(0, str(SRC_DIR)) + +from mcproof import domain_protocol, lean_harness, lineage, repair_loop # noqa: E402 + + +def _clean_soko_mod() -> types.SimpleNamespace: + return types.SimpleNamespace( + audit_lean4_source=lambda src, label="", strict_init_only=True: { + "label": label, + "ok": True, + "finding_count": 0, + "findings": [], + } + ) + + +class CanonicalJsonAndLineageTest(unittest.TestCase): + """T1 & T2: Unified canonical JSON encoder and strict allow_nan=False parity.""" + + def test_t1_canonical_json_and_zone_manifest_parity(self) -> None: + payload = {"s": "é", "a": 1, "z": [True, "α"]} + raw = lineage.canonical_json_bytes(payload) + self.assertIn(b"\\u00e9", raw) + expected_id = "sha256:" + hashlib.sha256(raw).hexdigest() + with_id = dict(payload, manifest_id="sha256:" + "0" * 64) + self.assertEqual(lineage.compute_zone_manifest_id(with_id), expected_id) + + # Existing repo zone-manifest.v0.1.json digest remains unchanged. + zone_path = REPO_ROOT / "schemas" / "zone-manifest.v0.1.json" + zone_obj = json.loads(zone_path.read_text(encoding="utf-8")) + self.assertEqual(lineage.compute_zone_manifest_id(zone_obj), lineage.CANONICAL_ZONE_MANIFEST_ID) + + def test_t2_allow_nan_false_and_canonical_rederivation_in_lineage_and_repair_loop(self) -> None: + for bad in (float("nan"), float("inf"), float("-inf")): + with self.subTest(bad=bad): + with self.assertRaises(ValueError): + lineage.canonical_json_bytes({"x": bad}) + with self.assertRaises(ValueError): + lineage.compute_zone_manifest_id({"x": bad}) + + # repair_loop.compute_failure_signature is canonical and order-independent. + sig_a = repair_loop.compute_failure_signature([ + {"rule": "RULE_B", "line": 9}, + {"rule": "RULE_A", "line": 2}, + ]) + sig_b = repair_loop.compute_failure_signature([ + {"rule": "RULE_A", "line": 2}, + {"rule": "RULE_B", "line": 9}, + ]) + self.assertEqual(sig_a, sig_b) + expected_sig = hashlib.sha256( + lineage.canonical_json_bytes([["RULE_A", 2], ["RULE_B", 9]]) + ).hexdigest()[:24] + self.assertEqual(sig_a, expected_sig) + + # repair_loop HTTP payload rejects NaN via canonical_json_bytes. + gen = repair_loop.make_llama_server_generator( + server_url="http://127.0.0.1:1", + lora=[{"id": 0, "scale": float("nan")}], + ) + + class _FakeResp: + def __enter__(self): + return self + + def __exit__(self, *_a): + return False + + def read(self): + return b"{}" + + seen_urls: list[str] = [] + + def _fake_urlopen(req, timeout=300.0): + seen_urls.append(req.full_url) + return _FakeResp() + + with mock.patch("urllib.request.urlopen", side_effect=_fake_urlopen): + with self.assertRaises(ValueError): + gen("prompt", 1) + # Slot-erase POST ({}) succeeded, while the completion POST containing NaN aborted before urlopen. + self.assertEqual(len(seen_urls), 1) + self.assertIn("action=erase", seen_urls[0]) + + # repair_loop JSONL checkpoint lines match canonical_json_bytes(res) + b"\n" byte-for-byte. + with tempfile.TemporaryDirectory(prefix="mcproof_t2_") as td: + ckpt = Path(td) / "ckpt.jsonl" + sample_res = { + "id": "X-1", + "family": "A", + "pass_at_1": True, + "label": "é", + "turns_used": 1, + "oracle_calls": 1, + "total_prompt_tokens": 10, + "total_completion_tokens": 5, + "total_tokens": 15, + "total_retrieved_plane1_tokens": 8, + } + with mock.patch.object(repair_loop, "run_repair_item", return_value=sample_res): + repair_loop.run_repair_split( + [{"id": "X-1", "family": "A"}], + lambda _p, _t: {"text": ""}, + max_turns=1, + checkpoint_jsonl=ckpt, + ) + self.assertEqual(ckpt.read_bytes(), lineage.canonical_json_bytes(sample_res) + b"\n") + + bad_ckpt = Path(td) / "bad_ckpt.jsonl" + bad_res = {"id": "X-2", "family": "A", "pass_at_1": False, "score": math.nan} + with mock.patch.object(repair_loop, "run_repair_item", return_value=bad_res): + with self.assertRaises(ValueError): + repair_loop.run_repair_split( + [{"id": "X-2", "family": "A"}], + lambda _p, _t: {"text": ""}, + max_turns=1, + checkpoint_jsonl=bad_ckpt, + ) + + +class LeanBarRulesAndSokoTest(unittest.TestCase): + """T3 & T5: R12 Lean static rules, compile blocking, comparator blocking, and soko fail-closed.""" + + def test_t3_r12_bar_forbidden_rules_and_positive_controls(self) -> None: + cases = [ + ("theorem t (n : Nat) : n = n := by\n dbg_trace \"hi\"\n rfl\n", "FORBIDDEN_DBG"), + ("def f (n : Nat) : Nat := dbgTraceVal n\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_DBG"), + ("def f : Unit := dbgSleep 1 (fun _ => ())\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_DBG"), + ("def f : Unit := dbgStackTrace (fun _ => ())\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_DBG"), + ("@[export evil_sym]\ndef f (n : Nat) : Nat := n\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_EXPORT_ATTR"), + ("attribute [export evil_sym] f\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_EXPORT_ATTR"), + ("@[init]\ndef evilInit : IO Unit := pure ()\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_INIT_ATTRIBUTE"), + ("@[builtin_init]\ndef evilInit : IO Unit := pure ()\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_INIT_ATTRIBUTE"), + ("attribute [builtin_init] evilInit\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_INIT_ATTRIBUTE"), + ("initialize do pure ()\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_INIT_ATTRIBUTE"), + ("builtin_initialize do pure ()\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_INIT_ATTRIBUTE"), + ("#guard_msgs in\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_EVAL_COMMAND"), + ("#guard 1 + 1 == 2\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_EVAL_COMMAND"), + ("def f (n : Nat) : Nat := panic! \"boom\"\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_PANIC"), + ("def f (n : Nat) : Nat := panicWithDef \"boom\"\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_PANIC"), + ("def f (n : Nat) : Nat := unreachable!\ntheorem t (n : Nat) : n = n := rfl\n", "FORBIDDEN_PANIC"), + ] + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=_clean_soko_mod()): + for src, expected_rule in cases: + with self.subTest(rule=expected_rule, snippet=src.splitlines()[0]): + rep = lean_harness.lint_lean4_source(src, check_vacuous=False, require_theorem=False) + self.assertFalse(rep["passed"]) + rules = {f["rule"] for f in rep["findings"]} + self.assertIn(expected_rule, rules) + + # Positive controls must not trigger false positives. + clean_controls = [ + "export Nat (succ)\ntheorem t (n : Nat) : n + 0 = n := Nat.add_zero n\n", + "theorem init_eq (n : Nat) : n = n := rfl\nattribute [simp] init_eq\n", + "def initialize' : Nat := 1\ndef my_initialize : Nat := initialize'\ntheorem t (n : Nat) : n = n := rfl\n", + 'def msg (n : Nat) : String := s!"#eval dbgTraceVal panic! initialize {n}"\ntheorem t (n : Nat) : n = n := rfl\n', + ] + for src in clean_controls: + with self.subTest(control=src.splitlines()[0]): + rep = lean_harness.lint_lean4_source(src, check_vacuous=False, require_theorem=True) + self.assertTrue(rep["passed"], f"false positive on clean control: {rep['findings']}") + + for rule in ( + "FORBIDDEN_INIT_ATTRIBUTE", + "FORBIDDEN_EXPORT_ATTR", + "FORBIDDEN_DBG", + "FORBIDDEN_PANIC", + "FORBIDDEN_EVAL_COMMAND", + ): + self.assertIn(rule, lean_harness.COMPILE_BLOCKING_LINT_RULES) + + self.assertTrue( + lean_harness.finding_blocks_comparator({"rule": "FORBIDDEN_EVAL_COMMAND", "message": "#guard_msgs"}) + ) + self.assertTrue( + lean_harness.finding_blocks_comparator({"rule": "METAPROGRAM_ESCAPE", "message": "matched '#guard_msgs'"}) + ) + self.assertIn("#guard_msgs", lean_harness._lean_commands_that_may_run("#guard_msgs in\ntheorem t : True := trivial\n")) + + # Char-literal double-quote (`'"'`), raw-string, and guillemet (`«"»`) lexer bypasses: + # Both strip_lean_comments_and_strings(blank_chars=True) and the soko handoff must keep + # code between two `'"'` literals visible so soko-only rules (`import Mathlib`, `ring`, + # `: Float`) and BAR rules (`sorry`, `#eval`, `@[export]`) cannot be swallowed. + char_dquote_cases = [ + ( + "char_dquote_sorry", + "def c : Char := '\"'\ntheorem t : (1 : Nat) = 2 := sorry\ndef d : Char := '\"'\n", + "sorry", + ), + ( + "char_dquote_mathlib", + "def c : Char := '\"'\nimport Mathlib\ntheorem t (n : Nat) : n = n := rfl\ndef d : Char := '\"'\n", + "import Mathlib", + ), + ( + "char_dquote_ring", + "def c : Char := '\"'\ntheorem t (n : Nat) : n + 0 = n := by ring\ndef d : Char := '\"'\n", + "ring", + ), + ( + "char_dquote_float", + "def c : Char := '\"'\ndef bad (x : Float) : Nat := 0\ntheorem t (n : Nat) : n = n := rfl\ndef d : Char := '\"'\n", + "Float", + ), + ( + "char_escapes_and_dquote", + "def a : Char := '\\''\ndef b : Char := '\\\\'\ndef c : Char := '\\\"'\n" + "def q : Char := '\"'\n@[export evil] def f : Nat := 1\ndef r : Char := '\"'\n", + "@[export evil]", + ), + ( + "raw_string_and_guillemet_dquote", + "def s := r#\"\\\"#\ndef «\"» : Nat := 1\nimport Mathlib\ndef «\"2» : Nat := 2\n", + "import Mathlib", + ), + ] + for label, src, needle in char_dquote_cases: + with self.subTest(char_lexer_case=label): + soko_sanitized = lean_harness.strip_lean_comments_and_strings(src, blank_chars=True) + self.assertIn(needle, soko_sanitized) + self.assertEqual(soko_sanitized.count('"') % 2, 0, f"odd quote count in {soko_sanitized!r}") + # Verify lint_lean4_source passes the sanitized text (with balanced quotes) to soko. + captured: list[str] = [] + + def _capture_soko(passed_src: str, label: str = "", strict_init_only: bool = True): + captured.append(passed_src) + return {"label": label, "ok": True, "finding_count": 0, "findings": []} + + fake_soko = types.SimpleNamespace(audit_lean4_source=_capture_soko) + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=fake_soko): + lean_harness.lint_lean4_source(src, label=f"<{label}>", check_vacuous=False) + self.assertEqual(len(captured), 1) + self.assertIn(needle, captured[0]) + self.assertEqual(captured[0].count('"') % 2, 0, f"unbalanced quotes passed to soko: {captured[0]!r}") + + # Interpolated string (`s!"..."`, `f!"..."`, `m!"..."`, custom `!"..."`) + # `{...}` nesting with embedded `'"'`, `'\\"'`, nested `s!"..."`, and comments/strings + # must never desynchronize BAR_FORBIDDEN_RULES, soko handoff, or _lean_commands_that_may_run. + interp_hide_cases = [ + ( + "s_interp_float_line_comment", + 'def x := s!"{\'"\'}"\ntheorem fspec (x : Float) : x = x := rfl\n-- "\n', + "Float", + None, + None, + ), + ( + "f_interp_export_block_comment", + 'def x := f!"{\'"\'}"\n@[export evil_sym]\ndef f (n : Nat) : Nat := n\n/- " -/\n', + "@[export evil_sym]", + "FORBIDDEN_EXPORT_ATTR", + None, + ), + ( + "m_interp_eval_line_comment", + 'def x := m!"{\'"\'}"\n#eval IO.println "pwn"\n-- "\n', + "#eval", + "FORBIDDEN_EVAL_COMMAND", + "#eval", + ), + ( + "custom_interp_dbg_and_escaped_dquote", + 'def x := my!"{\'\\"\'}"\ndef f (n : Nat) : Nat := dbgTraceVal n\n-- "\n', + "dbgTraceVal", + "FORBIDDEN_DBG", + None, + ), + ( + "nested_interp_panic", + 'def x := s!"a {s!"{\'"\'}"} b"\ndef f : Nat := panic! "boom"\n-- "\n', + "panic!", + "FORBIDDEN_PANIC", + None, + ), + ( + "interp_struct_and_comment_braces_init", + 'def x := s!"{ /- " } -/ \'}\' }"\ninitialize do pure ()\n-- "\n', + "initialize", + "FORBIDDEN_INIT_ATTRIBUTE", + None, + ), + ( + "payload_inside_interp_expr", + 'def x := s!"val {dbgTraceVal 1}"\ntheorem t (n : Nat) : n = n := rfl\n', + "dbgTraceVal", + "FORBIDDEN_DBG", + None, + ), + ( + "run_cmd_inside_interp_expr", + 'def x := s!"val {run_cmd pure ()}"\ntheorem t (n : Nat) : n = n := rfl\n', + "run_cmd", + "METAPROGRAM_ESCAPE", + "run_cmd", + ), + ] + for label, src, needle, expected_rule, expected_cmd in interp_hide_cases: + with self.subTest(interp_case=label): + sanitized = lean_harness.strip_lean_comments_and_strings(src, blank_chars=True) + self.assertIn(needle, sanitized) + self.assertEqual(sanitized.count('"') % 2, 0, f"odd quote count in {sanitized!r}") + captured_interp: list[str] = [] + + def _capture_soko_interp(passed_src: str, label: str = "", strict_init_only: bool = True): + captured_interp.append(passed_src) + return {"label": label, "ok": True, "finding_count": 0, "findings": []} + + fake_soko = types.SimpleNamespace(audit_lean4_source=_capture_soko_interp) + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=fake_soko): + rep = lean_harness.lint_lean4_source( + src, label=f"<{label}>", check_vacuous=False, require_theorem=False + ) + self.assertEqual(len(captured_interp), 1) + self.assertIn(needle, captured_interp[0]) + self.assertEqual(captured_interp[0].count('"') % 2, 0) + if expected_rule is not None: + self.assertFalse(rep["passed"]) + self.assertIn(expected_rule, {f["rule"] for f in rep["findings"]}) + if expected_cmd is not None: + self.assertIn(expected_cmd, lean_harness._lean_commands_that_may_run(src)) + + # Literal text inside interpolated strings must NOT trigger command detection. + self.assertEqual( + lean_harness._lean_commands_that_may_run('def x := s!"#eval run_cmd {1}"\n'), + [], + ) + + def test_t5_soko_auditor_fail_closed_and_exec_module_cleanup(self) -> None: + src = "theorem t (n : Nat) : n = n := rfl\n" + bad_reports = [ + {"ok": False, "finding_count": 0, "findings": []}, + {"passed": False, "findings": []}, + {"findings": {}}, + {"ok": True, "finding_count": 1, "findings": []}, + {"passed": True, "findings": [{"code": "UNPROVED_SORRY", "line": 1, "detail": "sorry"}]}, + {"passed": "yes", "findings": []}, + {"ok": False, "findings": ["not-a-dict"]}, + "not-a-mapping", + ] + for bad in bad_reports: + with self.subTest(soko_rep=bad): + fake_mod = types.SimpleNamespace(audit_lean4_source=lambda *_a, **_k: bad) + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=fake_mod): + with self.assertRaises(RuntimeError): + lean_harness.lint_lean4_source(src, check_vacuous=False) + + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=_clean_soko_mod()): + ok_rep = lean_harness.lint_lean4_source(src, check_vacuous=False) + self.assertTrue(ok_rep["passed"]) + + # exec_module failure must clean up sys.modules and raise RuntimeError. + with tempfile.TemporaryDirectory(prefix="mcproof_soko_err_") as td: + bad_soko = Path(td) / "soko_mcp" + bad_soko.mkdir() + (bad_soko / "lean4_auditor.py").write_text("raise ZeroDivisionError('boom')\n", encoding="utf-8") + with mock.patch.object(lean_harness, "dep_repo", return_value=Path(td)): + with self.assertRaises(RuntimeError): + lean_harness._load_soko_lean4_auditor() + self.assertNotIn("soko_lean4_auditor", sys.modules) + + +class EnvScrubAndConfinementTest(unittest.TestCase): + """T4, T6, T7, T9: Env scrubbing, short-name hijack removal, elab_rules confinement, and symlinks.""" + + def test_t4_sandbox_env_and_lean_env_block_caller_pollution(self) -> None: + with tempfile.TemporaryDirectory(prefix="mcproof_elan_") as td: + fake_elan = Path(td) + fake_elan_bin = fake_elan / "bin" + fake_elan_bin.mkdir() + + with mock.patch.object(lean_harness, "elan_bin_dir", return_value=fake_elan_bin.resolve()): + pairs = lean_harness._sandbox_env_pairs({ + "LEAN_PATH": "/evil/olean", + "ELAN_TOOLCHAIN": "evil-toolchain", + "ELAN_HOME": "/evil/elan", + "LD_PRELOAD": "/evil/lib.so", + }) + env_map = dict(pairs) + self.assertNotIn("LEAN_PATH", env_map) + self.assertNotIn("ELAN_TOOLCHAIN", env_map) + self.assertNotIn("LD_PRELOAD", env_map) + expected_elan = lean_harness._toolchain_elan_home() + self.assertEqual(expected_elan, str(fake_elan.resolve())) + self.assertEqual(env_map.get("ELAN_HOME"), expected_elan) + + harness_pairs = lean_harness._sandbox_env_pairs( + {"LEAN_PATH": "/evil/olean"}, + harness_lean_path="/trusted/mod:/trusted/lib", + ) + self.assertEqual(dict(harness_pairs).get("LEAN_PATH"), "/trusted/mod:/trusted/lib") + + polluted = { + "PATH": "/usr/bin:/bin", + "ELAN_HOME": str(fake_elan), + "ELAN_TOOLCHAIN": "evil-tc", + "LEAN_PATH": "/evil/olean", + "LEAN_OPTS": "--evil", + "LEAN_SRC_PATH": "/evil/src", + "LEAN_SYSROOT": "/evil/sysroot", + "LEAN_CC": "/evil/cc", + "LAKE_HOME": "/evil/lake", + "LAKE_PKG_PATH": "/evil/pkg", + "LD_PRELOAD": "/evil/preload.so", + "LD_LIBRARY_PATH": "/evil/lib", + } + with mock.patch.dict(os.environ, polluted, clear=True): + cleaned = lean_harness._lean_env() + for var in lean_harness._LEAN_SCRUB_VARS: + self.assertNotIn(var, cleaned, f"{var} leaked into _lean_env()") + self.assertTrue(cleaned["PATH"].startswith(str(fake_elan_bin.resolve()))) + + # linux_bwrap_functional must not leak MCPROOF_SANDBOX_SENTINEL into parent os.environ + # and must require the probe stdout marker "MCPROOF_PROBE_OK". + saved_cache = lean_harness._BWRAP_FUNCTIONAL + try: + lean_harness._BWRAP_FUNCTIONAL = None + captured_host_env: list[dict[str, str] | None] = [] + + def _fake_spawn(*_a, **kw): + captured_host_env.append(kw.get("host_env")) + self.assertNotIn("MCPROOF_SANDBOX_SENTINEL", os.environ) + return subprocess.CompletedProcess(args=["probe"], returncode=0, stdout="", stderr="") + + with mock.patch.object(lean_harness, "_spawn_confined", side_effect=_fake_spawn), \ + mock.patch("shutil.which", return_value="/usr/bin/tool"), \ + mock.patch.object(sys, "platform", "linux"): + # Empty stdout (missing MCPROOF_PROBE_OK) must fail closed to False. + self.assertFalse(lean_harness.linux_bwrap_functional()) + self.assertTrue(captured_host_env and captured_host_env[0] is not None) + self.assertIn("MCPROOF_SANDBOX_SENTINEL", captured_host_env[0]) + + lean_harness._BWRAP_FUNCTIONAL = None + with mock.patch.object( + lean_harness, + "_spawn_confined", + return_value=subprocess.CompletedProcess(args=["probe"], returncode=0, stdout="MCPROOF_PROBE_OK\n", stderr=""), + ), mock.patch("shutil.which", return_value="/usr/bin/tool"), mock.patch.object(sys, "platform", "linux"): + self.assertTrue(lean_harness.linux_bwrap_functional()) + finally: + lean_harness._BWRAP_FUNCTIONAL = saved_cache + + def test_t6_pspec_driver_disallows_short_name_hijack_fallback(self) -> None: + prompt = "Prove `theorem Foo.target (n : Nat) : n + 0 = n := by sorry`." + candidate = ( + "namespace Foo\n" + "end Foo\n" + "private theorem target : True := trivial\n" + ) + captured_drivers: list[str] = [] + + def _fake_confined(cmd, *, cwd, env=None, timeout_sec=60, readable_dirs=(), harness_lean_path=None): + if str(cmd[-1]).endswith("McproofPromptSpecDriver.lean"): + drv_text = Path(cmd[-1]).read_text(encoding="utf-8") + captured_drivers.append(drv_text) + return subprocess.CompletedProcess( + args=list(cmd), + returncode=0, + stdout="MCPROOF_PSPEC_ERR\tMISSING_PROMPT_THEOREM_NAME\ttarget\n", + stderr="", + ) + return subprocess.CompletedProcess(args=list(cmd), returncode=0, stdout="", stderr="") + + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=_clean_soko_mod()), \ + mock.patch.object(lean_harness, "find_lean_tool", return_value="/usr/bin/lean"), \ + mock.patch.object(lean_harness, "_lean_env", return_value={"PATH": "/usr/bin"}), \ + mock.patch("subprocess.run", return_value=subprocess.CompletedProcess(args=["lean"], returncode=0, stdout="/lib\n", stderr="")), \ + mock.patch.object(lean_harness, "run_confined_command", side_effect=_fake_confined): + findings = lean_harness.verify_lean4_prompt_obligations( + prompt, + candidate, + run_kernel_type_check=True, + lean_project_dir=REPO_ROOT / "lean", + ) + self.assertEqual(len(captured_drivers), 1) + self.assertNotIn("env.find? shortN", captured_drivers[0]) + self.assertIn("env.find? fullN", captured_drivers[0]) + self.assertIn("MISSING_PROMPT_THEOREM_NAME", {f["rule"] for f in findings}) + + def test_t7_elab_rules_confined_across_all_six_comparator_kernels(self) -> None: + self.assertFalse( + lean_harness.finding_blocks_comparator({"rule": "METAPROGRAM_ESCAPE", "message": "matched 'elab_rules'"}) + ) + with tempfile.TemporaryDirectory(prefix="mcproof_t7_") as td: + proj = Path(td) / "proj" + proj.mkdir() + (proj / "lean-toolchain").write_text("leanprover/lean4:v4.35.0\n", encoding="utf-8") + (proj / "lakefile.toml").write_text('name = "demo"\n', encoding="utf-8") + (proj / "comparator.json").write_text( + json.dumps({ + "challenge_module": "Demo.Spec", + "solution_module": "Demo.Proofs", + "theorem_names": ["Demo.Spec.t"], + "permitted_axioms": ["propext", "Classical.choice", "Quot.sound"], + }), + encoding="utf-8", + ) + (proj / "Demo").mkdir() + (proj / "Demo" / "Spec.lean").write_text("theorem Demo.Spec.t (n : Nat) : n = n := sorry\n", encoding="utf-8") + (proj / "Demo" / "Proofs.lean").write_text( + "elab_rules : term | `(0) => pure (.const ``Nat.zero [])\n" + "theorem Demo.Spec.t (n : Nat) : n = n := rfl\n", + encoding="utf-8", + ) + + kernel_lines = ["Exporting #[Demo.Spec.t] from Demo.Proofs"] + for _k, run_line, acc_line in lean_harness.COMPARATOR_ORDERED_KERNELS: + kernel_lines.append(run_line) + kernel_lines.append(acc_line) + kernel_lines.append("Your solution is okay!") + comp_stdout = "\n".join(kernel_lines) + "\n" + + confined_invocations: list[list[str]] = [] + orig_confine = lean_harness._confine_argv + + def _spy_confine(cmd, **kw): + argv = orig_confine(cmd, **kw) + confined_invocations.append(argv) + return argv + + def _fake_subproc_run(argv, **_kw): + if "comparator" in argv: + return subprocess.CompletedProcess(args=argv, returncode=0, stdout=comp_stdout, stderr="") + return subprocess.CompletedProcess(args=argv, returncode=0, stdout="", stderr="") + + fake_elan_bin = Path(td) / "elan" / "bin" + fake_elan_bin.mkdir(parents=True) + + with mock.patch.object(lean_harness, "_load_soko_lean4_auditor", return_value=_clean_soko_mod()), \ + mock.patch.object(lean_harness, "elan_bin_dir", return_value=fake_elan_bin.resolve()), \ + mock.patch.object(lean_harness, "linux_bwrap_functional", return_value=True), \ + mock.patch.object(lean_harness, "find_lean_tool", side_effect=lambda n: f"/usr/bin/{n}"), \ + mock.patch.object(lean_harness, "_lean_env", return_value={"PATH": "/usr/bin"}), \ + mock.patch("shutil.which", side_effect=lambda n: f"/usr/bin/{n}"), \ + mock.patch.object(lean_harness, "_confine_argv", side_effect=_spy_confine), \ + mock.patch("subprocess.run", side_effect=_fake_subproc_run): + res = lean_harness.verify_lean4_project_comparator(proj, allow_unsandboxed=False) + + if lean_harness._nofollow_dir_ops_available(): + # All 4 phases (lake build, axiom driver, lake update, lake comparator --paranoid) ran confined. + self.assertEqual(len(confined_invocations), 4) + for argv in confined_invocations: + self.assertIn("--unshare-net", argv) + self.assertIn("--clearenv", argv) + self.assertIn("-i", argv) + self.assertEqual( + res.paranoid_kernels_run, + tuple(k for k, _, _ in lean_harness.COMPARATOR_ORDERED_KERNELS), + ) + self.assertFalse(res.passed) + self.assertIn("METAPROGRAM_ESCAPE", {f["rule"] for f in res.findings}) + else: + # Non-POSIX hosts without O_NOFOLLOW fail closed before launching any confined phase. + self.assertFalse(res.passed) + self.assertEqual(len(confined_invocations), 0) + self.assertIn("NOFOLLOW_OPEN_UNAVAILABLE", {f["rule"] for f in res.findings}) + sample_argv = orig_confine( + ["lake", "comparator", "--paranoid"], + cwd=proj, + caller_env={"LEAN_PATH": "/evil"}, + readable_dirs=(), + ) + self.assertIn("--unshare-net", sample_argv) + self.assertIn("--clearenv", sample_argv) + self.assertIn("-i", sample_argv) + self.assertFalse(any("LEAN_PATH=/evil" in tok for tok in sample_argv)) + + def test_t9_symlink_root_parent_lake_and_toolchain_toctou_refused(self) -> None: + with tempfile.TemporaryDirectory(prefix="mcproof_t9_") as td: + base = Path(td) + secret = base / "host_secret.txt" + secret.write_text("TOP_SECRET_HOST_DATA\n", encoding="utf-8") + + real_proj = base / "real_proj" + real_proj.mkdir() + (real_proj / "lean-toolchain").write_text("leanprover/lean4:v4.35.0\n", encoding="utf-8") + (real_proj / "comparator.json").write_text("{}", encoding="utf-8") + + # 1. Symlinked project root must be rejected without following .resolve(). + sym_root = base / "sym_root" + sym_root.symlink_to(real_proj, target_is_directory=True) + res_root = lean_harness.verify_lean4_project_comparator(sym_root) + self.assertFalse(res_root.passed) + self.assertIn("UNTRUSTED_PROJECT_SYMLINK", {f["rule"] for f in res_root.findings}) + with self.assertRaises(lean_harness.UntrustedProjectPath): + lean_harness._checked_project_dir(sym_root) + + # 2. Symlink in parent directory must also be rejected. + real_parent = base / "real_parent" + (real_parent / "child_proj").mkdir(parents=True) + sym_parent = base / "sym_parent" + sym_parent.symlink_to(real_parent, target_is_directory=True) + res_parent = lean_harness.verify_lean4_project_comparator(sym_parent / "child_proj") + self.assertFalse(res_parent.passed) + self.assertIn("UNTRUSTED_PROJECT_SYMLINK", {f["rule"] for f in res_parent.findings}) + + # 3. Symlinked .lake + symlinked lean-toolchain must NOT read host secret. + lake_proj = base / "lake_proj" + lake_proj.mkdir() + (lake_proj / "lean-toolchain").symlink_to(secret) + (lake_proj / ".lake").symlink_to(real_proj, target_is_directory=True) + res_lake = lean_harness.verify_lean4_project_comparator(lake_proj) + self.assertFalse(res_lake.passed) + lake_rules = {f["rule"] for f in res_lake.findings} + if lean_harness._nofollow_dir_ops_available(): + self.assertIn("LAKE_CACHE_SYMLINK", lake_rules) + else: + self.assertIn("NOFOLLOW_OPEN_UNAVAILABLE", lake_rules) + self.assertNotIn("TOP_SECRET_HOST_DATA", res_lake.toolchain) + self.assertEqual(lean_harness._read_toolchain_nofollow(lake_proj), "leanprover/lean4:v4.35.0") + + +class RationalDigitCapTest(unittest.TestCase): + """T8: Pre-int() rational digit cap and bounded formatting across all LP outputs.""" + + @staticmethod + def _coprime_59_digit_denominators(count: int) -> list[int]: + """Generate `count` pairwise-coprime 59-digit integers (< 10^60) deterministically.""" + vals: list[int] = [] + cand = 10**58 + 1 + while len(vals) < count: + if all(math.gcd(cand, prev) == 1 for prev in vals): + vals.append(cand) + cand += 2 + return vals + + def test_t8_rational_lp_blocks_oversized_digits_and_formats_huge_rationals_without_false_reject(self) -> None: + huge = "9" * 5000 + old_limit = sys.get_int_max_str_digits() + sys.set_int_max_str_digits(0) + try: + for bad_tok in (huge, f"{huge}/1", f"1/{huge}", f"-{huge}/7"): + with self.subTest(tok_len=len(bad_tok)): + rep = domain_protocol.verify_rational_lp_certificate({ + "mode": "bounds", + "A": [[1]], + "b": [bad_tok], + "c": [1], + "y": [1], + "claimed_lower_bound": 0, + }) + self.assertFalse(rep["passed"]) + self.assertEqual(rep["epistemic_status"], "REJECTED") + self.assertIn("LP_CERT_MALFORMED", {f["rule"] for f in rep["findings"]}) + finally: + sys.set_int_max_str_digits(old_limit) + + # Valid 6-row 59-digit coprime certificate exceeds MAX_DUAL_OBJECTIVE_BITS (~1157 bits > 850), + # yet every input is within MAX_CERT_ABS_INT (10^60) and mathematically valid -> VERIFIED + # with bounded dual_objective summary (never falsely REJECTED). + coprimes6 = self._coprime_59_digit_denominators(6) + rep_valid = domain_protocol.verify_rational_lp_certificate({ + "mode": "bounds", + "A": [[1] for _ in coprimes6], + "b": [f"1/{d}" for d in coprimes6], + "c": [6], + "y": [1 for _ in coprimes6], + "claimed_lower_bound": 0, + }) + self.assertTrue(rep_valid["passed"], f"valid cert falsely rejected: {rep_valid}") + self.assertEqual(rep_valid["epistemic_status"], "VERIFIED") + self.assertEqual(rep_valid["findings"], []) + self.assertTrue(rep_valid["dual_objective"].startswith("")) + self.assertLess(len(rep_valid["dual_objective"]), 64) + + # Invalid 80-row 59-digit coprime certificates produce ~4640-digit denominators (> Python's + # default 4300-digit int_max_str_digits cap). Under the default cap, ALL four finding + # formatting paths must return clean REJECTED reports with ZERO uncaught ValueError. + coprimes80 = self._coprime_59_digit_denominators(80) + self.assertGreater(sys.get_int_max_str_digits(), 0) + + rep_below = domain_protocol.verify_rational_lp_certificate({ + "mode": "bounds", + "A": [[1] for _ in coprimes80], + "b": [f"1/{d}" for d in coprimes80], + "c": [80], + "y": [1 for _ in coprimes80], + "claimed_lower_bound": 1, + }) + self.assertFalse(rep_below["passed"]) + self.assertEqual(rep_below["epistemic_status"], "REJECTED") + self.assertEqual([f["rule"] for f in rep_below["findings"]], ["LP_DUAL_OBJECTIVE_BELOW_CLAIM"]) + self.assertIn("