From 88f0a7528c60330e68b77fa18d65a13e707fecab Mon Sep 17 00:00:00 2001 From: shahid arifuddin Date: Wed, 25 Nov 2026 02:31:45 -0600 Subject: [PATCH] Harden bar/check.py trust sections, srcDir validation, and [[trusted]] spec_hash Close three trust-boundary escapes in bar/check.py and harden bar.toml validation: 1. Empty/whitespace page sections (check_page): fail closed when 'What you must trust', 'Re-check', or 'What is not proved' is present with an empty or whitespace-only body instead of skipping trust/recheck checks. 2. lakefile.toml srcDir overrides (lakefile_problems): enforce an exact root allowlist ('.' or './') with no backslash normalization so neither .lake/, .git/, subdirectories, nor literal Linux '.\' directories can hide Lean sources from lean_files()/check_source() or desync statement_dependencies(); also reject non-list lean_lib/lean_exe/require tables. 3. [[trusted]] allowlist pinning & bar.toml framing (validate_bar, spec_hash, check_spec): deterministically fold [[trusted]] entries into spec_hash (preserving exact hashes when [[trusted]] is absent), validate spec.code (no whitespace/control chars), hashed path fields (no control chars), and [[trusted]] schema (required non-empty control-free string file/feature/reason, no extra keys, no default=str) on both local bar, direct spec_hash calls, and remote 'then' (skipping malformed older reviews) so neither post-approval [[trusted]] edits nor spec.code newline injection can reuse an old review. 4. Document the [[trusted]] hash pinning and root-srcDir rules in playbook/verified-bar.md and bar/template/bar.toml. Signed-off-by: shahid arifuddin --- bar/check.py | 122 +++++--- bar/template/bar.toml | 4 +- bar/tests/test_bar_hardening.py | 499 ++++++++++++++++++++++++++++++++ playbook/verified-bar.md | 4 +- 4 files changed, 593 insertions(+), 36 deletions(-) create mode 100644 bar/tests/test_bar_hardening.py diff --git a/bar/check.py b/bar/check.py index a775610..e5bb82f 100644 --- a/bar/check.py +++ b/bar/check.py @@ -126,14 +126,15 @@ def read_text(path): return path.read_bytes().replace(b"\r\n", b"\n").decode("utf-8") -def load_bar(root): - path = root / "bar.toml" - if not path.is_file(): - raise ProjectError("no bar.toml at the project root") - try: - bar = tomllib.loads(read_text(path)) - except (tomllib.TOMLDecodeError, UnicodeDecodeError) as e: - raise ProjectError(f"bar.toml does not parse: {e}") +_CTRL_RE = re.compile(r"[\x00-\x1f\x7f]") +_CODE_ENTRY_RE = re.compile(r"[^\s\x00-\x1f\x7f]+") +_TRUSTED_KEYS = {"file", "feature", "reason"} + + +def validate_bar(bar): + """Validate bar.toml structure and reject unsafe control/whitespace framing.""" + if not isinstance(bar, dict): + raise ProjectError("bar.toml must be a table") shape = [ ("project", dict), ("spec", dict), ("tests", dict), ("project.spec_authors", list), ("project.entry_points", list), ("spec.files", list), @@ -146,17 +147,49 @@ def load_bar(root): node = node.get(part) if isinstance(node, dict) else None if node is not None and not isinstance(node, kind): raise ProjectError(f"bar.toml: {key} must be a {'table' if kind is dict else 'list'}") - for key in ("spec.approval", "trusted"): - parent, child = key.split(".") if "." in key else (None, key) - entries = (bar.get(parent, {}) if parent else bar).get(child, []) - if any(not isinstance(e, dict) for e in entries): - raise ProjectError(f"bar.toml: each [[{key}]] entry must be a table") + page = bar.get("project", {}).get("page") + if page is not None and (not isinstance(page, str) or not page or _CTRL_RE.search(page)): + raise ProjectError("bar.toml: project.page must be a non-empty string without control characters") + for key in ("spec.files", "project.entry_points", "tests.files"): + parent, child = key.split(".") + for item in bar.get(parent, {}).get(child, []): + if not isinstance(item, str) or not item or _CTRL_RE.search(item): + raise ProjectError(f"bar.toml: each {key} entry must be a non-empty string without control characters") + for item in bar.get("spec", {}).get("code", []): + if not isinstance(item, str) or not _CODE_ENTRY_RE.fullmatch(item): + raise ProjectError("bar.toml: each spec.code entry must be a string without whitespace or control characters") + for entry in bar.get("spec", {}).get("approval", []): + if not isinstance(entry, dict): + raise ProjectError("bar.toml: each [[spec.approval]] entry must be a table") + for entry in bar.get("trusted", []): + if not isinstance(entry, dict): + raise ProjectError("bar.toml: each [[trusted]] entry must be a table") + extra = set(entry) - _TRUSTED_KEYS + if extra: + raise ProjectError(f"bar.toml: [[trusted]] has unsupported key(s): {', '.join(sorted(extra))}") + for req in ("file", "feature", "reason"): + val = entry.get(req) + if not isinstance(val, str) or not val.strip() or _CTRL_RE.search(val): + raise ProjectError( + f"bar.toml: [[trusted]] {req} must be a non-empty string without control characters" + ) status = bar.get("project", {}).get("status") if status not in ("in-progress", "verified"): raise ProjectError('bar.toml: [project] status must be "in-progress" or "verified"') return bar +def load_bar(root): + path = root / "bar.toml" + if not path.is_file(): + raise ProjectError("no bar.toml at the project root") + try: + bar = tomllib.loads(read_text(path)) + except (tomllib.TOMLDecodeError, UnicodeDecodeError) as e: + raise ProjectError(f"bar.toml does not parse: {e}") + return validate_bar(bar) + + def load_comparator(root): path = root / "comparator.json" if not path.is_file(): @@ -220,9 +253,10 @@ def reviewed_files(bar): def spec_hash(root, bar, read=None): """The hash a reviewer approves: the spec files, comparator.json, the entry points people run, the test files, the whole public page (a - claim anywhere on it is a public claim), and the list of code under - proof. `read` maps a path in the project to its text; by default it - reads the working tree.""" + claim anywhere on it is a public claim), the list of code under + proof, and any trusted source-rule exceptions. `read` maps a path in + the project to its text; by default it reads the working tree.""" + validate_bar(bar) read = read or (lambda rel: read_text(root / rel)) h = hashlib.sha256() covered = [] @@ -230,9 +264,17 @@ def spec_hash(root, bar, read=None): data = read(rel).replace("\r\n", "\n").encode("utf-8") h.update(f"file {rel}\n{hashlib.sha256(data).hexdigest()}\n".encode()) covered.append(rel) - code = sorted(str(c) for c in bar.get("spec", {}).get("code", [])) + code = sorted(bar.get("spec", {}).get("code", [])) h.update(("code " + " ".join(code) + "\n").encode()) covered.append("bar.toml: [spec] code = " + ", ".join(code)) + trusted_raw = bar.get("trusted", []) + if trusted_raw: + canon = lambda t: json.dumps(t, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + entries = sorted(trusted_raw, key=canon) + payload = json.dumps([canon(t) for t in entries], separators=(",", ":"), ensure_ascii=True) + h.update(f"trusted {payload}\n".encode()) + summary = ", ".join(f"{t['file']}:{t['feature']}" for t in entries) + covered.append("bar.toml: [[trusted]] = " + summary) return h.hexdigest(), covered @@ -317,16 +359,22 @@ def keys(table, kind, where): if key == "leanOptions" and isinstance(value, dict): problems.extend(f"{where} sets the option `{o}`" for o in value if RISKY_OPTION.match(o) and ("lakefile.toml", o) not in trusted) - if key == "srcDir" and isinstance(value, str): - p = Path(value) - if p.is_absolute() or ".." in p.parts: - problems.append(f"{where} has a srcDir outside the project: {value}") + if key == "srcDir" and value not in (".", "./"): + problems.append( + f"{where} sets `srcDir` to {value!r}; sources must live at the project root" + ) keys(cfg, "package", "lakefile.toml") for kind in ("lean_lib", "lean_exe", "require"): - for i, table in enumerate(cfg.get(kind, [])): + tables = cfg.get(kind, []) + if not isinstance(tables, list): + problems.append(f"lakefile.toml `{kind}` must be an array of tables") + continue + for i, table in enumerate(tables): if isinstance(table, dict): keys(table, kind, f"lakefile.toml [[{kind}]] {table.get('name', i)}") + else: + problems.append(f"lakefile.toml [[{kind}]] entry {i} must be a table") return problems @@ -611,10 +659,13 @@ def check_spec(root, bar, rep, offline, github): commit = r.get("commit_id") if not commit: continue - at = spec_hash(root, bar, lambda rel: github.read(owner, repo, commit, prefix + rel))[0] # The reviewed pull request must be the one that records this # approval, so the review is of the spec, not of something else. - then = tomllib.loads(github.read(owner, repo, commit, prefix + "bar.toml")) + try: + then = validate_bar(tomllib.loads(github.read(owner, repo, commit, prefix + "bar.toml"))) + except (ProjectError, tomllib.TOMLDecodeError): + continue + at = spec_hash(root, then, lambda rel: github.read(owner, repo, commit, prefix + rel))[0] recorded = any(x.get("sha256") == current and str(x.get("reviewer", "")).lower() == reviewer.lower() for x in then.get("spec", {}).get("approval", []) if isinstance(x, dict)) if at == current and recorded: @@ -834,10 +885,14 @@ def check_page(root, page_secs, page, bar, rep, page_text=None): return problems = [] for title in SECTIONS: - if find_section(page_secs, title) is None: + sec = find_section(page_secs, title) + if sec is None: problems.append(f"no '{title}' section") - trust = (find_section(page_secs, TRUST) or "").lower() - if trust: + elif not sec.strip(): + problems.append(f"'{title}' section is empty") + trust_sec = find_section(page_secs, TRUST) + if trust_sec is not None: + trust = trust_sec.lower() absent = [w for w in TRUST_WORDS if w not in trust] if absent: problems.append(f"'{TRUST}' does not mention: {', '.join(absent)}") @@ -856,12 +911,13 @@ def check_page(root, page_secs, page, bar, rep, page_text=None): problems.append(f"the page's status line does not say in progress: '{line.group(1).strip()}'") elif status == "verified" and ("verified" not in said or "not" in said): problems.append(f"the page's status line does not say verified: '{line.group(1).strip()}'") - recheck = find_section(page_secs, RECHECK) or "" - if recheck and RECHECK_COMMAND not in recheck: - problems.append(f"'{RECHECK}' does not give `{RECHECK_COMMAND}`") - test_cmd = bar.get("tests", {}).get("command") - if recheck and test_cmd and test_cmd not in recheck: - problems.append(f"'{RECHECK}' does not give the test command `{test_cmd}`") + recheck_sec = find_section(page_secs, RECHECK) + if recheck_sec is not None: + if RECHECK_COMMAND not in recheck_sec: + problems.append(f"'{RECHECK}' does not give `{RECHECK_COMMAND}`") + test_cmd = bar.get("tests", {}).get("command") + if test_cmd and test_cmd not in recheck_sec: + problems.append(f"'{RECHECK}' does not give the test command `{test_cmd}`") if problems: rep.unmet(6, "; ".join(problems)) else: diff --git a/bar/template/bar.toml b/bar/template/bar.toml index 2cd33a5..c36aebd 100644 --- a/bar/template/bar.toml +++ b/bar/template/bar.toml @@ -40,7 +40,9 @@ command = "python3 tests/run_tests.py" files = ["tests/run_tests.py"] # Exceptions to the source rule, one entry per file and feature. Each -# file must also be named under "What you must trust" on the page. +# entry is pinned by `--spec-hash` (adding or editing one voids prior +# approvals), and each file must also be named under "What you must trust" +# on the page. # # [[trusted]] # file = "Clamp/Ffi.lean" diff --git a/bar/tests/test_bar_hardening.py b/bar/tests/test_bar_hardening.py new file mode 100644 index 0000000..6c5af34 --- /dev/null +++ b/bar/tests/test_bar_hardening.py @@ -0,0 +1,499 @@ +#!/usr/bin/env python3 +"""Regression tests for bar/check.py trust-boundary hardening: +1. Empty/whitespace page sections (trust, re-check, not-proved) fail closed. +2. lakefile.toml srcDir overrides (including .lake/.git/sub/non-string) are rejected. +3. [[trusted]] entries are folded into spec_hash and verified against the reviewed bar.toml. +""" + +import json +import os +import sys +import unittest +from pathlib import Path +from unittest import mock + +TESTS_DIR = Path(__file__).resolve().parent +BAR_DIR = TESTS_DIR.parent +for path in (BAR_DIR, TESTS_DIR): + if str(path) not in sys.path: + sys.path.insert(0, str(path)) + +import check # noqa: E402 +from test_check import FakeGitHub, Project, approved_by # noqa: E402 + + +class EmptySectionHardeningTest(unittest.TestCase): + def setUp(self): + self.p = Project() + self.saved_env = os.environ.get("GITHUB_REPOSITORY") + os.environ.pop("GITHUB_REPOSITORY", None) + + def tearDown(self): + if self.saved_env is None: + os.environ.pop("GITHUB_REPOSITORY", None) + else: + os.environ["GITHUB_REPOSITORY"] = self.saved_env + self.p.close() + + def _write_readme(self, trust_body, recheck_body, not_proved_body="- Parsing in Main.lean."): + (self.p.root / "README.md").write_text( + "# Clamp\n\n" + "Status: in progress. The specification has not been approved by a reviewer, so this is not verified.\n\n" + "## What is proved\n\n" + "- `Clamp.Spec.clamp_in_range`\n" + "- `Clamp.Spec.clamp_of_mem`\n\n" + f"## What is not proved\n\n{not_proved_body}\n\n" + f"## What you must trust\n\n{trust_body}\n\n" + f"## Re-check it\n\n{recheck_body}\n", + encoding="utf-8", + ) + + def test_empty_trust_section_fails_closed(self): + self._write_readme( + trust_body="", + recheck_body="Run `lake comparator --paranoid` and `python3 tests/run_tests.py`.", + ) + got = self.p.run() + self.assertEqual(got[6][0], "OPEN") + self.assertIn("'What you must trust' section is empty", got[6][1]) + for word in check.TRUST_WORDS: + self.assertIn(word, got[6][1]) + + self.p.edit("bar.toml", 'status = "in-progress"', 'status = "verified"') + self.p.edit( + "README.md", + "Status: in progress. The specification has not been approved by a reviewer, so this is not verified.", + "Status: verified.", + ) + got_verified = self.p.run() + self.assertEqual(got_verified[6][0], "FAIL") + self.assertIn("'What you must trust' section is empty", got_verified[6][1]) + + def test_whitespace_trust_section_checks_trusted_files_and_dependencies(self): + self.p.append( + "bar.toml", + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\nreason = "ffi"\n', + ) + (self.p.root / "lake-manifest.json").write_text( + '{"version": "1.3.0", "packagesDir": ".lake/packages", "name": "clamp", "lakeDir": ".lake",' + ' "packages": [{"name": "mathlib", "type": "git"}]}', + encoding="utf-8", + ) + self._write_readme( + trust_body=" \n\t \n", + recheck_body="Run `lake comparator --paranoid` and `python3 tests/run_tests.py`.", + ) + got = self.p.run() + self.assertEqual(got[6][0], "OPEN") + self.assertIn("'What you must trust' section is empty", got[6][1]) + self.assertIn("trusted file Clamp.lean", got[6][1]) + self.assertIn("dependency mathlib", got[6][1]) + + def test_empty_recheck_section_fails_closed(self): + self._write_readme( + trust_body="- Lean kernel, compiler, runtime, and hardware.", + recheck_body=" \n", + ) + got = self.p.run() + self.assertEqual(got[6][0], "OPEN") + self.assertIn("'Re-check' section is empty", got[6][1]) + self.assertIn(check.RECHECK_COMMAND, got[6][1]) + self.assertIn("python3 tests/run_tests.py", got[6][1]) + + self.p.edit("bar.toml", 'status = "in-progress"', 'status = "verified"') + self.p.edit( + "README.md", + "Status: in progress. The specification has not been approved by a reviewer, so this is not verified.", + "Status: verified.", + ) + self.assertEqual(self.p.run()[6][0], "FAIL") + + def test_empty_not_proved_section_fails_closed(self): + self._write_readme( + trust_body="- Lean kernel, compiler, runtime, and hardware.", + recheck_body="Run `lake comparator --paranoid` and `python3 tests/run_tests.py`.", + not_proved_body=" ", + ) + got = self.p.run() + self.assertEqual(got[6][0], "OPEN") + self.assertIn("'What is not proved' section is empty", got[6][1]) + + def test_non_empty_valid_sections_pass(self): + self._write_readme( + trust_body="- Lean kernel, compiler, runtime, and hardware.", + recheck_body="Run `lake comparator --paranoid` and `python3 tests/run_tests.py`.", + ) + self.assertEqual(self.p.run()[6][0], "PASS") + + +class SrcDirHardeningTest(unittest.TestCase): + def setUp(self): + self.p = Project() + + def tearDown(self): + self.p.close() + + def test_dot_lake_srcdir_cannot_hide_forbidden_lean_code(self): + hidden = self.p.root / ".lake" / "hidden" + hidden.mkdir(parents=True) + (hidden / "Clamp.lean").write_text( + 'axiom cheat : False\n@[extern "evil"] opaque f : Unit -> Unit\n', + encoding="utf-8", + ) + self.p.edit( + "lakefile.toml", + '[[lean_lib]]\nname = "Clamp"', + '[[lean_lib]]\nname = "Clamp"\nsrcDir = ".lake/hidden"', + ) + status, detail = self.p.run()[4] + self.assertEqual(status, "FAIL") + self.assertIn("srcDir", detail) + self.assertIn(".lake/hidden", detail) + + def test_non_root_and_malformed_srcdir_variants_rejected(self): + bad_values = [ + '".lake"', + '".lake/hidden"', + '"a/.lake/b"', + '".git/hidden"', + '"sub"', + '"src/lean"', + '"../elsewhere"', + r'"..\\elsewhere"', + r'".\\"', + r'"./\\"', + r'".\\."', + r'"\\"', + '"/tmp/evil"', + r'"C:\\evil"', + '""', + '" "', + "123", + '["."]', + ] + for raw in bad_values: + with self.subTest(srcDir=raw): + p = Project() + try: + p.edit( + "lakefile.toml", + '[[lean_lib]]\nname = "Clamp"', + f'[[lean_lib]]\nname = "Clamp"\nsrcDir = {raw}', + ) + status, detail = p.run()[4] + self.assertEqual(status, "FAIL") + self.assertIn("srcDir", detail) + finally: + p.close() + + def test_package_srcdir_rejected_even_when_listed_in_trusted(self): + self.p.append( + "bar.toml", + '\n[[trusted]]\nfile = "lakefile.toml"\nfeature = "srcDir"\nreason = "bypass attempt"\n', + ) + self.p.edit("lakefile.toml", "defaultTargets", 'srcDir = ".lake/hidden"\ndefaultTargets') + status, detail = self.p.run()[4] + self.assertEqual(status, "FAIL") + self.assertIn("srcDir", detail) + + def test_lean_exe_srcdir_rejected(self): + self.p.edit( + "lakefile.toml", + '[[lean_exe]]\nname = "clamp"\nroot = "Main"', + '[[lean_exe]]\nname = "clamp"\nroot = "Main"\nsrcDir = ".git/hooks"', + ) + status, detail = self.p.run()[4] + self.assertEqual(status, "FAIL") + self.assertIn("srcDir", detail) + + def test_explicit_root_dot_srcdir_allowed(self): + self.p.edit( + "lakefile.toml", + '[[lean_lib]]\nname = "Clamp"', + '[[lean_lib]]\nname = "Clamp"\nsrcDir = "."', + ) + self.p.edit( + "lakefile.toml", + '[[lean_exe]]\nname = "clamp"\nroot = "Main"', + '[[lean_exe]]\nname = "clamp"\nroot = "Main"\nsrcDir = "./"', + ) + self.assertEqual(self.p.run()[4][0], "PASS") + + def test_non_list_lean_lib_table_rejected(self): + (self.p.root / "lakefile.toml").write_text( + 'name = "clamp"\nversion = "0.1.0"\nlicense = "Apache-2.0"\n' + 'defaultTargets = ["Clamp"]\n\n' + '[lean_lib]\nname = "Clamp"\nsrcDir = ".lake/hidden"\n', + encoding="utf-8", + ) + status, detail = self.p.run()[4] + self.assertEqual(status, "FAIL") + self.assertIn("lean_lib", detail) + + +class TrustedSpecHashHardeningTest(unittest.TestCase): + def setUp(self): + self.p = Project() + env = mock.patch.dict(os.environ) + env.start() + self.addCleanup(env.stop) + os.environ.pop("GITHUB_REPOSITORY", None) + reviewers = Path(self.p.tmp.name) / "reviewers.toml" + reviewers.write_text( + '[[reviewer]]\nlogin = "reviewer-b"\n[[reviewer]]\nlogin = "example-author"\n', + encoding="utf-8", + ) + os.environ["BAR_REVIEWERS"] = str(reviewers) + + def tearDown(self): + self.p.close() + + def test_spec_hash_sensitive_to_trusted_entries_and_order_independent(self): + bar0 = check.load_bar(self.p.root) + h0, cov0 = check.spec_hash(self.p.root, bar0) + self.assertFalse(any("[[trusted]]" in item for item in cov0)) + + bar1 = dict(bar0) + bar1["trusted"] = [{"file": "Clamp.lean", "feature": "extern", "reason": "ffi"}] + h1, cov1 = check.spec_hash(self.p.root, bar1) + self.assertNotEqual(h0, h1) + self.assertTrue(any("[[trusted]]" in item and "Clamp.lean:extern" in item for item in cov1)) + + # Editing file, feature, or reason each changes the hash. + for field, mutated in ( + ("file", "Main.lean"), + ("feature", "unsafe"), + ("reason", "different reason"), + ): + bar_mut = dict(bar0) + entry = dict(bar1["trusted"][0]) + entry[field] = mutated + bar_mut["trusted"] = [entry] + h_mut, _ = check.spec_hash(self.p.root, bar_mut) + self.assertNotEqual(h1, h_mut, f"changing {field} must change spec_hash") + + # Duplicate entry produces distinct hash. + bar_dup = dict(bar0) + bar_dup["trusted"] = [dict(bar1["trusted"][0]), dict(bar1["trusted"][0])] + h_dup, _ = check.spec_hash(self.p.root, bar_dup) + self.assertNotEqual(h1, h_dup) + + # Reordering entries yields the exact same canonical hash. + e_a = {"file": "Clamp.lean", "feature": "extern", "reason": "a"} + e_b = {"file": "Main.lean", "feature": "unsafe", "reason": "b"} + bar_ab = dict(bar0) + bar_ab["trusted"] = [e_a, e_b] + bar_ba = dict(bar0) + bar_ba["trusted"] = [e_b, e_a] + self.assertEqual(check.spec_hash(self.p.root, bar_ab)[0], check.spec_hash(self.p.root, bar_ba)[0]) + + def test_post_approval_trusted_addition_invalidates_review(self): + os.environ["GITHUB_REPOSITORY"] = "Proven-Commons/clamp" + self.p.approve() + github = approved_by(self.p) + self.assertEqual(self.p.run(offline=False, github=github)[1][0], "PASS") + + # Post-approval attacker adds a [[trusted]] exception for lakefile.toml without re-review. + self.p.append( + "bar.toml", + '\n[[trusted]]\nfile = "lakefile.toml"\nfeature = "moreLinkArgs"\nreason = "unreviewed"\n', + ) + self.p.append("lakefile.toml", 'moreLinkArgs = ["-lm"]\n') + got = self.p.run(offline=False, github=github) + self.assertEqual(got[1][0], "OPEN") + self.assertIn("the spec changed after the last approval", got[1][1]) + + self.p.edit("bar.toml", 'status = "in-progress"', 'status = "verified"') + self.assertEqual(self.p.run(offline=False, github=github)[1][0], "FAIL") + + def test_prerecorded_future_hash_cannot_smuggle_post_approval_trusted(self): + os.environ["GITHUB_REPOSITORY"] = "Proven-Commons/clamp" + # Compute the future spec_hash WITH a [[trusted]] entry not yet in bar.toml at review time. + bar_with_trusted = check.load_bar(self.p.root) + bar_with_trusted["trusted"] = [ + {"file": "lakefile.toml", "feature": "moreLinkArgs", "reason": "smuggled"} + ] + future_hash, _ = check.spec_hash(self.p.root, bar_with_trusted) + + # Record future_hash in bar.toml WITHOUT the [[trusted]] entry at commit C, then simulate GitHub review. + self.p.append( + "bar.toml", + f'\n[[spec.approval]]\nreviewer = "reviewer-b"\ndate = "2026-11-02"\n' + f'sha256 = "{future_hash}"\nrecord = "https://github.com/Proven-Commons/clamp/pull/7"\n', + ) + github = FakeGitHub("reviewer-b", self.p.snapshot()) + + # After review, add [[trusted]] to working-tree bar.toml so current spec_hash == future_hash. + self.p.append( + "bar.toml", + '\n[[trusted]]\nfile = "lakefile.toml"\nfeature = "moreLinkArgs"\nreason = "smuggled"\n', + ) + got = self.p.run(offline=False, github=github) + self.assertEqual(got[1][0], "OPEN") + self.assertIn("is not the text this hash covers", got[1][1]) + + def test_trusted_entry_approved_at_review_time_passes(self): + os.environ["GITHUB_REPOSITORY"] = "Proven-Commons/clamp" + self.p.edit( + "Clamp.lean", + "end Clamp", + '@[extern "lean_clamp"] def ext (n : Nat) : Nat := n\n\nend Clamp', + ) + self.p.append( + "bar.toml", + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\nreason = "reviewed ffi"\n', + ) + self.p.edit( + "README.md", + "- The hardware it runs on.", + "- The hardware it runs on.\n- `Clamp.lean`, which calls C.", + ) + self.p.approve() + github = approved_by(self.p) + got = self.p.run(offline=False, github=github) + self.assertEqual(got[1][0], "PASS", got[1][1]) + self.assertEqual(got[4][0], "PASS", got[4][1]) + self.assertEqual(got[6][0], "PASS", got[6][1]) + + def test_spec_code_newline_cannot_forge_trusted_line_in_spec_hash(self): + os.environ["GITHUB_REPOSITORY"] = "Proven-Commons/clamp" + forged_trusted = json.dumps( + [json.dumps({"feature": "sorry", "file": "Clamp.lean", "reason": "forged"}, sort_keys=True, separators=(",", ":"))], + separators=(",", ":"), + ) + # Local bar.toml with newline/whitespace in spec.code must fail validation. + self.p.edit("bar.toml", 'code = ["Clamp.clamp"]', f'code = ["Clamp.clamp\\ntrusted {forged_trusted.replace(chr(34), chr(92) + chr(34))}"]') + with self.assertRaises(check.ProjectError): + check.load_bar(self.p.root) + + # Space-containing spec.code entry must also fail validation (prevents ["A B"] == ["A", "B"]). + p_sp = Project() + try: + p_sp.edit("bar.toml", 'code = ["Clamp.clamp"]', 'code = ["Clamp.a Clamp.b"]') + with self.assertRaises(check.ProjectError): + check.load_bar(p_sp.root) + finally: + p_sp.close() + + # Remote reviewed commit with forged newline in spec.code must fail closed (never PASS). + p_rem = Project() + try: + p_rem.append( + "bar.toml", + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "sorry"\nreason = "forged"\n', + ) + p_rem.approve() + current_hash, _ = check.spec_hash(p_rem.root, check.load_bar(p_rem.root)) + snap = p_rem.snapshot() + clean_bar = ( + p_rem.root.joinpath("bar.toml").read_text(encoding="utf-8") + .split('\n[[trusted]]\n')[0] + .replace( + 'code = ["Clamp.clamp"]', + f'code = ["Clamp.clamp\\ntrusted {forged_trusted.replace(chr(34), chr(92) + chr(34))}"]', + ) + + f'\n[[spec.approval]]\nreviewer = "reviewer-b"\ndate = "2026-10-24"\n' + + f'sha256 = "{current_hash}"\nrecord = "https://github.com/Proven-Commons/clamp/pull/7"\n' + ) + snap["bar.toml"] = clean_bar + github = FakeGitHub("reviewer-b", snap) + got = p_rem.run(offline=False, github=github) + self.assertEqual(got[1][0], "OPEN") + self.assertIn("is not the text this hash covers", got[1][1]) + finally: + p_rem.close() + + def test_trusted_schema_validation_rejects_non_string_and_unknown_keys(self): + bad_snippets = [ + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = 1979-05-27\nreason = "bad"\n', + '\n[[trusted]]\nfile = ["Clamp.lean"]\nfeature = "extern"\nreason = "bad"\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nreason = "missing feature"\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\n', + '\n[[trusted]]\nfile = " "\nfeature = "extern"\nreason = "blank file"\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = " "\nreason = "blank feature"\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\nreason = " "\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\nreason = "ok"\nextra = "nope"\n', + '\n[[trusted]]\nfile = "Clamp.lean"\nfeature = "extern"\nreason = 42\n', + ] + for snippet in bad_snippets: + with self.subTest(snippet=snippet.strip()): + p = Project() + try: + p.append("bar.toml", snippet) + with self.assertRaises(check.ProjectError): + check.load_bar(p.root) + finally: + p.close() + + def test_control_chars_in_hashed_paths_and_direct_spec_hash_rejected(self): + path_cases = [ + ("spec.files", 'files = ["SPEC.md", "Clamp/Spec.lean"]', 'files = ["SPEC.md", "Clamp/Spec.lean\\nfile evil"]'), + ("project.page", 'page = "README.md"', 'page = "README.md\\nfile evil"'), + ("project.entry_points", 'entry_points = ["Main.lean"]', 'entry_points = ["Main.lean\\tbad"]'), + ("tests.files", 'files = ["tests/run_tests.py"]', 'files = ["tests/run_tests.py\\rbad"]'), + ] + for label, old, new in path_cases: + with self.subTest(field=label): + p = Project() + try: + p.edit("bar.toml", old, new) + with self.assertRaises(check.ProjectError): + check.load_bar(p.root) + finally: + p.close() + + # Direct spec_hash call on an unvalidated dict must also reject forged control chars and bad trusted schema. + base_bar = check.load_bar(self.p.root) + bad_code = {**base_bar, "spec": {**base_bar["spec"], "code": ["Clamp.clamp\ntrusted []"]}} + with self.assertRaises(check.ProjectError): + check.spec_hash(self.p.root, bad_code) + bad_path = {**base_bar, "project": {**base_bar["project"], "page": "README.md\nforged"}} + with self.assertRaises(check.ProjectError): + check.spec_hash(self.p.root, bad_path) + bad_trusted = {**base_bar, "trusted": [{"file": "Clamp.lean", "feature": "extern"}]} + with self.assertRaises(check.ProjectError): + check.spec_hash(self.p.root, bad_trusted) + + def test_malformed_older_review_is_skipped_when_valid_review_exists(self): + os.environ["GITHUB_REPOSITORY"] = "Proven-Commons/clamp" + self.p.approve() + good_snap = self.p.snapshot() + bad_snap = dict(good_snap) + bad_snap["bar.toml"] = 'not = [valid toml\n' + + class TwoReviewGitHub(FakeGitHub): + def __init__(self, login, good_files, bad_files): + super().__init__(login, good_files) + self.good_sha = self.review["commit_id"] + self.bad_sha = "0000000000000000000000000000000000000000" + self.files_by_commit = {self.bad_sha: bad_files, self.good_sha: good_files} + + def reviews(self, owner, repo, number): + return [ + { + "state": "APPROVED", + "user": {"login": "reviewer-b"}, + "commit_id": self.bad_sha, + "submitted_at": "2026-10-23T00:00:00Z", + "id": 1, + }, + { + "state": "APPROVED", + "user": {"login": "reviewer-b"}, + "commit_id": self.good_sha, + "submitted_at": "2026-10-24T00:00:00Z", + "id": 2, + }, + ] + + def read(self, owner, repo, commit, path): + return self.files_by_commit[commit][path] + + github = TwoReviewGitHub("reviewer-b", good_snap, bad_snap) + got = self.p.run(offline=False, github=github) + self.assertEqual(got[1][0], "PASS", got[1][1]) + self.assertIn(github.good_sha[:12], got[1][1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/playbook/verified-bar.md b/playbook/verified-bar.md index f60ff77..58e3d2c 100644 --- a/playbook/verified-bar.md +++ b/playbook/verified-bar.md @@ -12,7 +12,7 @@ A project may use the word verified in public only when every item below holds. 3. **The proofs prove the approved statements, and one command re-checks them.** `comparator.json` names every theorem in the challenge file. `lake comparator --paranoid` builds the challenge and the proofs in a sandbox and checks that each named theorem proves exactly the statement in the challenge file, uses no axiom but `propext`, `Classical.choice`, and `Quot.sound`, and is accepted by Lean's kernel and by every other kernel shipped with Lean. It does not build the program people run; item 4 covers that. Each statement depends only on the spec files, on the code under proof named in `bar.toml`, and on code from outside the project. A definition or instance anywhere else in the project could change what a statement means without changing its text, and the approval would not notice. `lean-toolchain` pins an exact Lean release. -4. **The code that runs is the code that was proved.** Kernels check the logical definitions, not the compiled program, and some Lean features let the two differ, skip the kernel, or change what a statement means. Project code does not use `implemented_by`, `extern`, `unsafe`, native evaluation (`native_decide`, `decide +native`), `debug.skipKernelTC`, or `axiom`, and has no `sorry` or `admit` outside the challenge file. It does no metaprogramming: no `import Lean`, and no `macro`, `syntax`, `elab`, `notation`, or `run_cmd`. The build is a `lakefile.toml` that sets no compiler or linker arguments and no plugins. Each exception is listed in `bar.toml` with its reason and named under What you must trust. The programs people run, whether a command-line tool or the library's entry points, call the proved functions, not copies of them. +4. **The code that runs is the code that was proved.** Kernels check the logical definitions, not the compiled program, and some Lean features let the two differ, skip the kernel, or change what a statement means. Project code does not use `implemented_by`, `extern`, `unsafe`, native evaluation (`native_decide`, `decide +native`), `debug.skipKernelTC`, or `axiom`, and has no `sorry` or `admit` outside the challenge file. It does no metaprogramming: no `import Lean`, and no `macro`, `syntax`, `elab`, `notation`, or `run_cmd`. The build is a `lakefile.toml` that keeps Lean sources at the project root (no non-root `srcDir` overrides) and sets no compiler or linker arguments and no plugins. Each exception is listed in `bar.toml` (`[[trusted]]`) with its reason, pinned in the spec approval hash, and named under What you must trust. The programs people run, whether a command-line tool or the library's entry points, call the proved functions, not copies of them. 5. **Differential tests ran against the original, and the record is in the repo.** The inputs are random, from a recorded seed, and mutated from those samples where the input has a structure to mutate. The committed `tests/TEST-RESULTS.md` records the oracle and its version, the seed, the number of inputs, and the failures, and a fresh run gives the same seed, count, and failures. There are no failures. A case where the original is wrong is left out of the comparison by the test script, with a link to its bug report, and listed under What is not proved. @@ -41,7 +41,7 @@ A run exits 1 when an item fails, or when `bar.toml` says `verified` and any ite | 6 | The status line matches `bar.toml`. The four sections exist, the trust section names what it must, and Re-check it gives both commands. | Whether the text is true and complete. | | 7 | A workflow at the top of the repo calls the verified-bar workflow, and the default branch requires the `bar / bar` check. | That releases are tagged only from the default branch. | -The person checks happen once, at approval, and the hash pins everything that person judged. That is why any change to the page, the entry points, or the tests voids the approval: a claim cannot grow after review, wherever it is written. Keep numbers that change often, such as test counts, in `tests/TEST-RESULTS.md` rather than on the page. +The person checks happen once, at approval, and the hash pins everything that person judged. That is why any change to the page, the entry points, the tests, or `[[trusted]]` exceptions voids the approval: a claim cannot grow and a source-rule exemption cannot be added after review, wherever it is written. Keep numbers that change often, such as test counts, in `tests/TEST-RESULTS.md` rather than on the page. ## What a library repo contains