From d3da3a1882999a80db34089153f9684fd8d7bbee Mon Sep 17 00:00:00 2001 From: aur-build Date: Sat, 21 Nov 2026 09:38:33 +0000 Subject: tools: key items by (module, name), and prove the surface by compiling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The auditor's two counterexamples were both detector bugs, and they were the same class of bug as the ones before: the instrument was reading the source in a way that flattered the number. - Rows are keyed by `(module, name)`. Keyed by bare name, `pipeline::dispatch::Pool::shutdown` merged into the `db::Writer::shutdown` row, which is gated, so an ungated item was reported `already-gated`. - The production-mention index is built from lines with comments and string literals removed. Searching raw text made `review::approve::withdraw` look production-used because the *string* "withdraw" appears in an HTTP route pattern and an audit action; every real caller named `withdraw_package` or `withdraw_release_in`, which are different items. - A `pub` declaration inside a private module is not a public declaration. Without that, the inner-module narrowing made the detector report an `http::new` nobody could name. - For a name declared in several modules — `new`, `open`, `record`, `parse` — a bare mention elsewhere cannot be resolved, so the row is kept and flagged `ambiguous` rather than silently dropped, and `tools/test-surface-ambiguous.json` holds the human verdict. An ambiguous row with no verdict fails the architecture test; "the tool could not tell" is not a disposition. - The count rule was duplicated between `--json` and `--write-budget` and the two drifted the moment a rule was added to one. `tally()` is now the one place. `tools/release-surface-probe.py` replaces inference with compilation for the final claim. It writes a throwaway crate depending on `aur-build` twice, with and without `test-support`, and tries to name every dispositioned item from outside. A path that compiles with the feature proves the path is real; every such path must fail without it. Current result: 28 real external paths, 27 closed in a release build, and the one that stays open is `db::Writer`, which is public because `Db` has a `pub writer: Writer` field and Rust will not type a public field with a private type. That is recorded as `interface` in `tools/test-surface-interface.json` — a disposition that admits reachability and names the signature that forces it — and the probe fails if the file claims an item that is not in fact reachable, so it cannot quietly rot. The tool's own docstring and the generated table claimed "Rust has no test-conditional visibility". That was false and is gone, replaced with the two shapes that do it. --- tools/release-surface-probe.py | 149 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 tools/release-surface-probe.py (limited to 'tools/release-surface-probe.py') diff --git a/tools/release-surface-probe.py b/tools/release-surface-probe.py new file mode 100644 index 0000000..2f6830b --- /dev/null +++ b/tools/release-surface-probe.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""Prove what the release build actually exports, by compiling against it. + +`tools/test-surface.py` reads the source and *infers* which `pub` items exist +only for tests. Inference can be wrong — it already was, twice: a detector that +matched names inside string literals called `review::approve::withdraw` +production-used, and a detector keyed by bare name merged +`pipeline::dispatch::Pool::shutdown` into the gated `db::Writer::shutdown` row. + +This tool does not infer. It writes a throwaway crate that depends on +`aur-build` twice over — once without `test-support`, once with — and tries to +name every dispositioned item from outside. An item is honest only if: + + * at least one candidate path compiles **with** the feature, which proves the + path is real and the item is genuinely reachable to the test tier, and + * every path that compiles with the feature fails **without** it, which proves + a release build does not export it. + +A path that compiles in both builds is a leak and this tool exits non-zero. + +An item with no nameable path at all is not a pass and not a failure: a method +(`Config::store_dir`) or a const inside a private submodule cannot be named by a +`use` line whatever its visibility. Those are reported separately with the +source line that states their visibility, for a human to read. + +Usage: + python3 tools/release-surface-probe.py # report + python3 tools/release-surface-probe.py --quiet # exit code only +""" +import argparse +import json +import os +import re +import shutil +import subprocess +import sys + +ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.." +CACHE = os.path.join(ROOT, "target", "release-surface-probe") + + +def table(): + out = subprocess.run([sys.executable, os.path.join(ROOT, "tools", "test-surface.py"), + "--json"], capture_output=True, text=True, cwd=ROOT) + if out.returncode != 0: + sys.exit("tools/test-surface.py failed: " + out.stderr) + return json.loads(out.stdout)["rows"] + + +def candidates(row): + """Paths an outside crate could try for this item. + + The declaring file's module path, and the top-level module the census groups + it under, because most items are re-exported up to the module door. Neither + reaches a method or an item inside a nested private module; those are + reported as not nameable rather than guessed at. + """ + f = row["where"].rsplit(":", 1)[0] + mod = f[len("src/"):-len(".rs")] + if mod.endswith("/mod"): + mod = mod[: -len("/mod")] + top = mod.split("/")[0] + paths = {"aur_build::%s::%s" % (mod.replace("/", "::"), row["name"]), + "aur_build::%s::%s" % (top, row["name"])} + return sorted(paths) + + +def build(feature): + """Compile one probe binary per candidate path; return the set that failed.""" + d = os.path.join(CACHE, "with" if feature else "no") + shutil.rmtree(d, ignore_errors=True) + os.makedirs(os.path.join(d, "src", "bin")) + with open(os.path.join(d, "Cargo.toml"), "w") as h: + h.write('[package]\nname="surface-probe"\nversion="0.0.0"\nedition="2021"\n\n' + '[dependencies]\naur-build = { path = "%s"%s }\n' + % (os.path.abspath(os.path.join(ROOT, ".")), + ', features = ["test-support"]' if feature else "")) + with open(os.path.join(d, "src", "main.rs"), "w") as h: + h.write("fn main() {}\n") + + units = {} + rows = table() + for i, row in enumerate(rows): + for j, path in enumerate(candidates(row)): + name = "x%02d_%d" % (i, j) + units[name] = (row["module"], row["name"], path, row["disp"]) + with open(os.path.join(d, "src", "bin", name + ".rs"), "w") as h: + h.write("#![allow(unused_imports, dead_code)]\nuse %s;\nfn main() {}\n" % path) + + r = subprocess.run(["cargo", "build", "--bins", "--keep-going", "--message-format=short", + "--target-dir", os.path.join(CACHE, "tgt-" + ("with" if feature else "no"))], + cwd=d, capture_output=True, text=True) + if "error: could not compile `surface-probe`" not in r.stdout + r.stderr and not units: + sys.exit("probe build produced no output; cargo is not working") + failed = set(re.findall(r"\b(x\d+_\d+)\.rs", r.stdout + r.stderr)) + return units, failed + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--quiet", action="store_true", help="print nothing unless something leaked") + args = ap.parse_args() + + units_with, failed_with = build(True) + _, failed_without = build(False) + + real = set(units_with) - failed_with # paths that really exist + # An `interface` item is reachable in a release build on purpose: a public + # signature requires it and no test asked for it. The probe's job is to + # confirm the reachability is the declared kind, not to pretend it is gone. + declared = {u for u in real if units_with[u][3] == "interface"} + leaked = sorted(real - failed_without - declared) # ...and a release build still exports + unexpected = sorted(declared - real) # declared public, but not reachable + nameable = {} + for u in real: + mod, name, path, disp = units_with[u] + nameable.setdefault((mod, name), []).append(path) + silent = sorted({(units_with[u][0], units_with[u][1]) for u in failed_with} - set(nameable)) + + if not args.quiet: + print("candidate paths probed: %d" % len(units_with)) + print("real external paths: %d (compile with test-support)" % len(real)) + print("of those, unreachable in a release build: %d" % len([u for u in real if u in failed_without])) + print("declared public interface (reachable on purpose): %d" % len(declared)) + print("items with a nameable path: %d" % len(nameable)) + print("items no `use` line can name (methods, private submodules): %d" % len(silent)) + for mod, name in silent: + print(" %s.%s" % (mod, name)) + print() + + if unexpected: + print("DECLARED PUBLIC BUT NOT REACHABLE — the interface file is stale:") + for u in unexpected: + print(" %s.%s %s" % (units_with[u][0], units_with[u][1], units_with[u][2])) + return 1 + + if leaked: + print("LEAKED INTO THE RELEASE BUILD — these paths compile with and without the feature:") + for u in leaked: + mod, name, path, disp = units_with[u] + print(" %-14s %-22s %s (disposition: %s)" % (mod, name, path, disp)) + return 1 + if not args.quiet: + print("nothing leaked: every path that reaches the test tier is closed in a release build") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) -- cgit v1.2.3