stdlib: add one pinned Bundle resolver and explicit pack input

Add tools/stdlib/bundle.py + bundle-pin.json as the single source-side
Bundle identity (name, version, source commit, tree/alias digests) and
require tools/pack-stdlib.py --stdlib-dir instead of reading the
checkout implicitly. Missing input, missing manifest, digest/alias
mismatch, pin mismatch and symlinks fail closed; two packs are
byte-identical. Tests: tools/ci/test_stdlib_bundle_tools.py.
This commit is contained in:
cflmy committed 2026-11-26 15:00:26 +08:00
1 parent b9c72e1d2a
commit 1b9d9c4c26
4 files changed
+700 -64

No files matched your search

+316
View File
@@ -0,0 +1,316 @@
"""Explicit stdlib Bundle input tests (ADR-0070 / issue #11 Phase A).
Covers the shared resolver (`tools/stdlib/bundle.py`) and the deterministic
package entry point (`tools/pack-stdlib.py`). The digest helpers here are
independent re-implementations so a bug in the shared helper cannot make the
test agree with itself.
"""
from __future__ import annotations
import contextlib
import hashlib
import importlib.util
import io
import json
import os
import tarfile
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def load_module(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
def independent_tree_digest(root: Path) -> str:
digest = hashlib.sha256()
paths = sorted(
(path.relative_to(root).as_posix(), path)
for path in root.rglob("*.mq.md")
if path.is_file()
)
for relative, path in paths:
digest.update(relative.encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def independent_aliases_digest(aliases: list[dict]) -> str:
digest = hashlib.sha256()
for alias in sorted(aliases, key=lambda item: (item["target_module"], item["target_function"])):
digest.update(alias["target_module"].encode())
digest.update(b"\0")
digest.update(alias["target_function"].encode())
digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
ALIASES = [
{
"public_names": ["print", "打印"],
"target_module": "io.mq.md",
"target_function": "写值",
"expected_signature": "params(值)",
"effects": ["write"],
}
]
def make_bundle(root: Path, *, version: str = "9.9.9", name: str = "marqdo-stdlib") -> dict:
"""Create a minimal Bundle with independently computed digests."""
root.mkdir(parents=True)
(root / "README.md").write_text("# test bundle\n")
(root / "io.mq.md").write_text("## @knowledge io\n")
(root / "io").mkdir()
(root / "io" / "console.mq.md").write_text("## @knowledge console\n")
manifest = {
"schema": "marqdo.stdlib-bundle",
"schema_version": 1,
"name": name,
"version": version,
"digest": independent_tree_digest(root),
"aliases_digest": independent_aliases_digest(ALIASES),
"public_aliases": ALIASES,
}
(root / "stdlib.json").write_text(json.dumps(manifest, indent=2) + "\n")
return manifest
def write_pin(path: Path, manifest: dict, source_path: str, commit: str = "a" * 40) -> dict:
pin = {
"schema": "marqdo.stdlib-bundle-pin",
"schema_version": 1,
"name": manifest["name"],
"version": manifest["version"],
"source": {"kind": "test", "repository": "test/test", "commit": commit, "path": source_path},
"tree_digest": manifest["digest"],
"aliases_digest": manifest["aliases_digest"],
}
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(pin, indent=2) + "\n")
return pin
class BundleResolverTest(unittest.TestCase):
def setUp(self) -> None:
self.bundle = load_module("stdlib_bundle", ROOT / "tools/stdlib/bundle.py")
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def test_repository_bundle_matches_the_pin(self) -> None:
root, record, pin = self.bundle.resolve()
self.assertEqual(root, (ROOT / "stdlib").resolve())
self.assertEqual(record["tree_digest"], pin["tree_digest"])
self.assertEqual(record["aliases_digest"], pin["aliases_digest"])
self.assertEqual(record["name"], "marqdo-stdlib")
self.assertIn("io.mq.md", record["files"])
def test_explicit_valid_bundle_still_has_to_match_the_pin(self) -> None:
other = self.dir / "other-bundle"
matching = make_bundle(other)
pin_path = self.dir / "pin.json"
write_pin(pin_path, matching, str(other))
root, record, _ = self.bundle.resolve(other, pin_path)
self.assertEqual(root, other.resolve())
self.assertEqual(record["name"], "marqdo-stdlib")
pinned = load_module("stdlib_bundle_pin_check", ROOT / "tools/stdlib/bundle.py")
self.assertRaisesRegex(
pinned.BundleError,
"does not match the pin",
pinned.verify_pin,
{"name": "marqdo-stdlib", "version": "0.1.0",
"tree_digest": "sha256:" + "0" * 64, "aliases_digest": "sha256:" + "0" * 64},
pinned.load_pin(ROOT / "tools/stdlib/bundle-pin.json"),
)
def test_bad_explicit_input_fails_even_when_the_default_is_valid(self) -> None:
with self.assertRaisesRegex(self.bundle.BundleError, "does not exist"):
self.bundle.resolve(self.dir / "missing")
def test_missing_manifest_fails(self) -> None:
bare = self.dir / "bare"
bare.mkdir()
(bare / "io.mq.md").write_text("## @knowledge io\n")
with self.assertRaisesRegex(self.bundle.BundleError, "has no manifest"):
self.bundle.verify(bare)
def test_tree_digest_mismatch_fails(self) -> None:
bundle = self.dir / "tampered"
make_bundle(bundle)
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
with self.assertRaisesRegex(self.bundle.BundleError, "tree digest mismatch"):
self.bundle.verify(bundle)
def test_alias_digest_mismatch_fails(self) -> None:
bundle = self.dir / "alias-tampered"
manifest = make_bundle(bundle)
manifest["aliases_digest"] = "sha256:" + "0" * 64
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "alias digest mismatch"):
self.bundle.verify(bundle)
def test_public_aliases_without_a_digest_fail(self) -> None:
bundle = self.dir / "no-alias-digest"
manifest = make_bundle(bundle)
del manifest["aliases_digest"]
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "without aliases_digest"):
self.bundle.verify(bundle)
def test_symlink_inside_the_bundle_is_rejected(self) -> None:
bundle = self.dir / "linked"
make_bundle(bundle)
try:
(bundle / "escape.mq.md").symlink_to("/etc/hostname")
except (OSError, NotImplementedError):
self.skipTest("symbolic links are unavailable on this host")
with self.assertRaisesRegex(self.bundle.BundleError, "symbolic link"):
self.bundle.verify(bundle)
def test_bad_pin_schema_is_rejected(self) -> None:
pin_path = self.dir / "bad-pin.json"
pin_path.write_text(json.dumps({"schema": "other", "schema_version": 1}) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "schema_version"):
self.bundle.load_pin(pin_path)
def test_cli_prints_the_resolved_path(self) -> None:
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
self.assertEqual(self.bundle.main(["--print-path"]), 0)
self.assertEqual(Path(stdout.getvalue().strip()), (ROOT / "stdlib").resolve())
def test_cli_fails_for_an_invalid_explicit_input(self) -> None:
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
self.assertEqual(self.bundle.main(["--stdlib-dir", str(self.dir / "missing")]), 1)
self.assertIn("does not exist", stderr.getvalue())
class PackStdlibTest(unittest.TestCase):
def setUp(self) -> None:
self.pack = load_module("pack_stdlib", ROOT / "tools/pack-stdlib.py")
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def run_pack(self, *args: str) -> int:
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
return self.pack.main(list(args))
def test_stdlib_dir_is_required(self) -> None:
with self.assertRaises(SystemExit) as raised, contextlib.redirect_stderr(io.StringIO()):
self.pack.main([])
self.assertEqual(raised.exception.code, 2)
def test_missing_input_fails(self) -> None:
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(self.dir / "missing"), "--out-dir", str(self.dir))
self.assertIn("does not exist", str(raised.exception.code))
def test_missing_manifest_fails(self) -> None:
bare = self.dir / "bare"
bare.mkdir()
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(bare), "--out-dir", str(self.dir))
self.assertIn("has no manifest", str(raised.exception.code))
def test_tampered_tree_fails(self) -> None:
bundle = self.dir / "bundle"
make_bundle(bundle)
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(bundle), "--out-dir", str(self.dir))
self.assertIn("tree digest mismatch", str(raised.exception.code))
def test_pin_mismatch_fails(self) -> None:
bundle = self.dir / "bundle"
manifest = make_bundle(bundle)
pin_path = self.dir / "pin.json"
pin = write_pin(pin_path, manifest, str(bundle))
pin["tree_digest"] = "sha256:" + "0" * 64
pin_path.write_text(json.dumps(pin) + "\n")
with self.assertRaises(SystemExit) as raised:
self.run_pack(
"--stdlib-dir", str(bundle), "--out-dir", str(self.dir), "--bundle-pin", str(pin_path)
)
self.assertIn("does not match the pin", str(raised.exception.code))
def test_pack_is_deterministic_and_records_the_bundle_identity(self) -> None:
bundle = self.dir / "bundle"
manifest = make_bundle(bundle)
pin_path = self.dir / "pin.json"
write_pin(pin_path, manifest, str(bundle))
first = self.dir / "first"
second = self.dir / "second"
for out in (first, second):
self.assertEqual(
self.run_pack(
"--stdlib-dir", str(bundle), "--out-dir", str(out),
"--bundle-pin", str(pin_path),
),
0,
)
archive_name = "marqdo-stdlib-9.9.9.tar.gz"
first_bytes = (first / archive_name).read_bytes()
self.assertEqual(first_bytes, (second / archive_name).read_bytes())
self.assertEqual(
(first / f"{archive_name}.sha256").read_bytes(),
(second / f"{archive_name}.sha256").read_bytes(),
)
descriptor = json.loads((first / "marqdo-stdlib-9.9.9.json").read_text())
self.assertEqual(descriptor["schema"], "marqdo.stdlib-package")
self.assertEqual(descriptor["schema_version"], 1)
self.assertEqual(descriptor["name"], manifest["name"])
self.assertEqual(descriptor["version"], manifest["version"])
self.assertEqual(descriptor["tree_digest"], independent_tree_digest(bundle))
self.assertEqual(descriptor["aliases_digest"], independent_aliases_digest(ALIASES))
self.assertEqual(
descriptor["archive_sha256"], "sha256:" + hashlib.sha256(first_bytes).hexdigest()
)
self.assertEqual(descriptor["files"], sorted(descriptor["files"]))
with tarfile.open(first / archive_name, mode="r:gz") as archive:
members = archive.getmembers()
self.assertEqual([m.name for m in members], descriptor["files"])
for member in members:
self.assertEqual(member.mtime, 0)
self.assertIn(member.uid, (0,))
self.assertEqual(member.gid, 0)
self.assertEqual(member.mode, 0o644)
self.assertEqual(
archive.extractfile("io.mq.md").read(), (bundle / "io.mq.md").read_bytes()
)
def test_repository_bundle_packs_against_the_committed_pin(self) -> None:
out = self.dir / "out"
self.assertEqual(
self.run_pack(
"--stdlib-dir", str(ROOT / "stdlib"), "--out-dir", str(out),
"--bundle-pin", str(ROOT / "tools/stdlib/bundle-pin.json"),
),
0,
)
descriptor = json.loads((out / "marqdo-stdlib-0.1.0.json").read_text())
manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text())
self.assertEqual(descriptor["tree_digest"], manifest["digest"])
self.assertEqual(descriptor["aliases_digest"], manifest["aliases_digest"])
if __name__ == "__main__":
unittest.main()
+61 -64
View File
@@ -1,74 +1,79 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Build a deterministic offline marqdo-stdlib package. """Build a deterministic offline marqdo-stdlib package from an explicit Bundle.
The archive is intended for the separate external stdlib repository/release The input is one unpacked Bundle root (a directory that contains
workflow, not for the CLI's in-repo development fallback. It contains the `stdlib.json`), passed with the required `--stdlib-dir`. This script does not
Markdown stdlib tree, stdlib.json and README.md, with stable mtimes/ownership. read the checkout's `stdlib/` implicitly: the CLI release and the separate
stdlib release workflow both name the Bundle they package (ADR-0070).
The archive contains the Markdown stdlib tree, `stdlib.json` and every other
file in the Bundle, with stable mtimes/ownership. An optional `--bundle-pin`
also requires the input to match the pinned name/version/commit/digests.
Usage:
python3 tools/pack-stdlib.py --stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json
""" """
from __future__ import annotations
import argparse
import hashlib import hashlib
import io import io
import json import json
import os import sys
import tarfile import tarfile
from pathlib import Path from pathlib import Path
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
STDLIB = ROOT / "stdlib"
DIST = ROOT / "dist" DIST = ROOT / "dist"
sys.path.insert(0, str(Path(__file__).resolve().parent / "stdlib"))
def aliases_digest(manifest: dict) -> str: import bundle as stdlib_bundle # noqa: E402
digest = hashlib.sha256()
for alias in sorted(
manifest.get("public_aliases", []),
key=lambda a: (a["target_module"], a["target_function"]),
):
digest.update(alias["target_module"].encode())
digest.update(b"\0")
digest.update(alias["target_function"].encode())
digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode())
digest.update(b"\0")
return f"sha256:{digest.hexdigest()}"
def tree_digest() -> str: def gzip_open(raw):
digest = hashlib.sha256() import gzip
for path in sorted(
STDLIB.rglob("*.mq.md"), key=lambda p: p.relative_to(STDLIB).as_posix() return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
):
relative = path.relative_to(STDLIB).as_posix()
digest.update(relative.encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
def main() -> int: def verify_input(root: Path, pin_path: Path | None) -> dict:
manifest = json.loads((STDLIB / "stdlib.json").read_text()) try:
version = manifest["version"] record = stdlib_bundle.verify(root)
digest = tree_digest() stdlib_bundle.require_files(record, ("stdlib.json",))
if manifest["digest"] != f"sha256:{digest}": if record["aliases_digest"] is None:
raise SystemExit("stdlib.json digest does not match the tree") raise stdlib_bundle.BundleError(
alias_digest = aliases_digest(manifest) f"{root / 'stdlib.json'} declares no aliases_digest"
if manifest.get("aliases_digest") != alias_digest: )
raise SystemExit("stdlib.json aliases_digest does not match public_aliases") if pin_path is not None:
pin = stdlib_bundle.load_pin(pin_path)
stdlib_bundle.verify_pin(record, pin)
except stdlib_bundle.BundleError as error:
raise SystemExit(f"pack-stdlib: error: {error}") from error
return record
files = sorted(
[p for p in STDLIB.rglob("*") if p.is_file() and p.name != "stdlib.json"] def main(argv: list[str]) -> int:
+ [STDLIB / "stdlib.json"], parser = argparse.ArgumentParser(description=__doc__)
key=lambda p: p.relative_to(STDLIB).as_posix(), parser.add_argument("--stdlib-dir", required=True)
) parser.add_argument("--out-dir", default=str(DIST))
DIST.mkdir(exist_ok=True) parser.add_argument("--bundle-pin", default=None)
archive = DIST / f"marqdo-stdlib-{version}.tar.gz" args = parser.parse_args(argv)
root = Path(args.stdlib_dir)
record = verify_input(root, Path(args.bundle_pin) if args.bundle_pin else None)
version = record["version"]
files = [root / name for name in record["files"]]
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
archive = out_dir / f"marqdo-stdlib-{version}.tar.gz"
with archive.open("wb") as raw: with archive.open("wb") as raw:
with gzip_open(raw) as gz: with gzip_open(raw) as gz:
with tarfile.open(fileobj=gz, mode="w") as tar: with tarfile.open(fileobj=gz, mode="w") as tar:
for path in files: for path in files:
relative = path.relative_to(STDLIB).as_posix() relative = path.relative_to(root).as_posix()
info = tarfile.TarInfo(name=relative) info = tarfile.TarInfo(name=relative)
data = path.read_bytes() data = path.read_bytes()
info.size = len(data) info.size = len(data)
@@ -81,28 +86,20 @@ def main() -> int:
descriptor = { descriptor = {
"schema": "marqdo.stdlib-package", "schema": "marqdo.stdlib-package",
"schema_version": 1, "schema_version": 1,
"name": manifest["name"], "name": record["name"],
"version": version, "version": version,
"tree_digest": f"sha256:{digest}", "tree_digest": record["tree_digest"],
"aliases_digest": alias_digest, "aliases_digest": record["aliases_digest"],
"archive": archive.name, "archive": archive.name,
"archive_sha256": f"sha256:{archive_sha}", "archive_sha256": f"sha256:{archive_sha}",
"files": [p.relative_to(STDLIB).as_posix() for p in files], "files": record["files"],
} }
descriptor_path = DIST / f"marqdo-stdlib-{version}.json" descriptor_path = out_dir / f"marqdo-stdlib-{version}.json"
descriptor_path.write_text(json.dumps(descriptor, indent=2) + "\n") descriptor_path.write_text(json.dumps(descriptor, indent=2) + "\n")
(DIST / f"{archive.name}.sha256").write_text( (out_dir / f"{archive.name}.sha256").write_text(f"{archive_sha} {archive.name}\n")
f"{archive_sha} {archive.name}\n"
)
print(json.dumps(descriptor, indent=2)) print(json.dumps(descriptor, indent=2))
return 0 return 0
def gzip_open(raw):
import gzip
return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
if __name__ == "__main__": if __name__ == "__main__":
raise SystemExit(main()) raise SystemExit(main(sys.argv[1:]))
+15
View File
@@ -0,0 +1,15 @@
{
"schema": "marqdo.stdlib-bundle-pin",
"schema_version": 1,
"name": "marqdo-stdlib",
"version": "0.1.0",
"source": {
"kind": "in-repo",
"repository": "cflmy/marqdo-cli",
"commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8",
"path": "stdlib",
"note": "Phase A (ADR-0070): the pinned Bundle is the checkout tree at this commit. Phase B replaces this record with the accepted ecosystem Bundle commit and digest; do not change it in the same commit as test fixtures."
},
"tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb"
}
+308
View File
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""One resolver and verifier for a stdlib Bundle (ADR-0070).
Every source-side consumer that needs the official Bundle — packaging tools,
product tests, the performance runner and release CI — resolves it through
this module instead of concatenating a checkout path. The identity comes from
`tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest,
alias digest); an explicit input may change the location but must still match
the pinned digests.
The digest algorithms are byte-identical to `marqdo_cli::stdlib` and to
`tools/release/smoke.py` (which stays an independent verifier of the shipped
archive). Nothing here is used by the running CLI.
Usage:
python3 tools/stdlib/bundle.py [--stdlib-dir PATH] [--pin PATH] [--print-path]
Exit status is 1 for an invalid Bundle and 2 for a bad command line.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PIN_PATH = ROOT / "tools" / "stdlib" / "bundle-pin.json"
PIN_SCHEMA = "marqdo.stdlib-bundle-pin"
PIN_SCHEMA_VERSION = 1
REQUIRED_MANIFEST_FIELDS = ("name", "version", "digest")
class BundleError(Exception):
"""An input is not a verifiable stdlib Bundle."""
def _sha256_bytes(*chunks: bytes) -> str:
digest = hashlib.sha256()
for chunk in chunks:
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def _walk_files(root: Path) -> list[Path]:
"""Every regular file under `root`, sorted, rejecting symlinks.
Deterministic packaging must not follow a link outside the Bundle root or
archive a link whose target differs by platform.
"""
files: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
dirnames.sort()
base = Path(dirpath)
for name in dirnames:
if (base / name).is_symlink():
raise BundleError(
f"stdlib Bundle contains a symbolic link directory: "
f"{(base / name).relative_to(root).as_posix()}"
)
for name in sorted(filenames):
path = base / name
if path.is_symlink():
raise BundleError(
f"stdlib Bundle contains a symbolic link: "
f"{path.relative_to(root).as_posix()}"
)
if path.is_file():
files.append(path)
files.sort(key=lambda path: path.relative_to(root).as_posix())
return files
def load_manifest(root: Path) -> dict:
manifest_path = root / "stdlib.json"
if not root.is_dir():
raise BundleError(f"stdlib Bundle directory does not exist: {root}")
if not manifest_path.is_file():
raise BundleError(f"stdlib Bundle has no manifest: {manifest_path}")
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"cannot read valid JSON from {manifest_path}: {error}") from error
if not isinstance(manifest, dict):
raise BundleError(f"{manifest_path} must contain a JSON object")
for field in REQUIRED_MANIFEST_FIELDS:
value = manifest.get(field)
if not isinstance(value, str) or not value:
raise BundleError(f"{manifest_path} has no non-empty `{field}`")
return manifest
def tree_digest(root: Path) -> str:
"""`relative POSIX path + NUL + bytes + NUL` over every `*.mq.md` file."""
root = Path(root)
chunks: list[bytes] = []
for path in _walk_files(root):
if not path.name.endswith(".mq.md"):
continue
chunks.append(path.relative_to(root).as_posix().encode())
chunks.append(b"\0")
chunks.append(path.read_bytes())
chunks.append(b"\0")
return _sha256_bytes(*chunks)
def aliases_digest(manifest: dict) -> str:
"""Canonical digest over `public_aliases`, byte-identical to the loader."""
chunks: list[bytes] = []
aliases = sorted(
manifest.get("public_aliases", []),
key=lambda alias: (alias["target_module"], alias["target_function"]),
)
for alias in aliases:
chunks.append(alias["target_module"].encode())
chunks.append(b"\0")
chunks.append(alias["target_function"].encode())
chunks.append(b"\0")
for name in sorted(alias["public_names"]):
chunks.append(name.encode())
chunks.append(b"\0")
return _sha256_bytes(*chunks)
def _verify_aliases(manifest: dict, manifest_path: Path) -> list[dict]:
raw = manifest.get("public_aliases", [])
if not isinstance(raw, list):
raise BundleError(f"{manifest_path} public_aliases must be an array")
seen: set[str] = set()
aliases: list[dict] = []
for entry in raw:
if not isinstance(entry, dict):
raise BundleError(f"{manifest_path} public alias must be an object")
names = entry.get("public_names")
if not isinstance(names, list) or not names:
raise BundleError(f"{manifest_path} public alias declares no names")
for name in names:
if not isinstance(name, str) or not name:
raise BundleError(f"{manifest_path} public alias name must be a non-empty string")
if name in seen:
raise BundleError(f"{manifest_path} public alias name `{name}` is declared twice")
seen.add(name)
module = entry.get("target_module")
if not isinstance(module, str) or not module:
raise BundleError(f"{manifest_path} public alias has no target_module")
relative = Path(module)
if relative.is_absolute() or ".." in relative.parts:
raise BundleError(
f"{manifest_path} public alias target_module `{module}` must stay inside the Bundle"
)
function = entry.get("target_function")
if not isinstance(function, str) or not function:
raise BundleError(f"{manifest_path} public alias has no target_function")
aliases.append(entry)
aliases.sort(key=lambda alias: (alias["target_module"], alias["target_function"]))
return aliases
def verify(root: Path) -> dict:
"""Validate one unpacked Bundle root and return its identity record."""
root = Path(root)
manifest = load_manifest(root)
manifest_path = root / "stdlib.json"
tree = tree_digest(root)
declared_tree = manifest["digest"]
if declared_tree != tree:
raise BundleError(
f"stdlib tree digest mismatch: stdlib.json declares {declared_tree}, "
f"the files are {tree}"
)
aliases = _verify_aliases(manifest, manifest_path)
declared_aliases = manifest.get("aliases_digest")
actual_aliases = aliases_digest(manifest)
if declared_aliases is None and aliases:
raise BundleError(f"{manifest_path} declares public_aliases without aliases_digest")
if declared_aliases is not None and declared_aliases != actual_aliases:
raise BundleError(
f"stdlib public-alias digest mismatch: stdlib.json declares {declared_aliases}, "
f"the alias table is {actual_aliases}"
)
files = sorted(path.relative_to(root).as_posix() for path in _walk_files(root))
modules = [name for name in files if name.endswith(".mq.md")]
if not modules:
raise BundleError(f"stdlib Bundle {root} contains no .mq.md module")
return {
"name": manifest["name"],
"version": manifest["version"],
"tree_digest": tree,
"aliases_digest": actual_aliases if declared_aliases is not None else None,
"file_count": len(files),
"files": files,
}
def require_files(record: dict, required: tuple[str, ...]) -> None:
missing = [name for name in required if name not in record["files"]]
if missing:
raise BundleError(
"stdlib Bundle is missing required file(s): " + ", ".join(missing)
)
def load_pin(path: Path = PIN_PATH) -> dict:
path = Path(path)
try:
pin = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"cannot read Bundle pin {path}: {error}") from error
if not isinstance(pin, dict):
raise BundleError(f"Bundle pin {path} must contain a JSON object")
if pin.get("schema") != PIN_SCHEMA or pin.get("schema_version") != PIN_SCHEMA_VERSION:
raise BundleError(
f"Bundle pin {path} must be {PIN_SCHEMA} schema_version {PIN_SCHEMA_VERSION}"
)
source = pin.get("source")
if not isinstance(source, dict) or not isinstance(source.get("path"), str):
raise BundleError(f"Bundle pin {path} has no source.path")
for field in ("name", "version", "tree_digest", "aliases_digest"):
if not isinstance(pin.get(field), str) or not pin[field]:
raise BundleError(f"Bundle pin {path} has no non-empty `{field}`")
return pin
def verify_pin(record: dict, pin: dict) -> None:
"""Require a verified Bundle record to match the pinned identity."""
for field in ("name", "version", "tree_digest", "aliases_digest"):
if record.get(field) != pin.get(field):
raise BundleError(
f"stdlib Bundle does not match the pin: {field} is "
f"{record.get(field)!r}, the pin records {pin.get(field)!r}"
)
def resolve(
explicit: str | Path | None = None,
pin_path: Path = PIN_PATH,
*,
require_pin: bool = True,
) -> tuple[Path, dict, dict]:
"""Resolve and verify the Bundle, returning `(root, record, pin)`.
`explicit` overrides the pinned location but never the pinned identity
unless `require_pin` is false. A bad explicit input fails even when the
default location is valid; there is no fallback.
"""
pin = load_pin(pin_path)
if explicit is None:
root = ROOT / pin["source"]["path"]
else:
root = Path(explicit)
record = verify(root)
if require_pin:
verify_pin(record, pin)
require_files(
record,
(
"stdlib.json",
"io.mq.md",
"io/console.mq.md",
),
)
return root.resolve(), record, pin
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(
description="Resolve and verify the pinned stdlib Bundle (ADR-0070)."
)
parser.add_argument("--stdlib-dir", default=None)
parser.add_argument("--pin", default=str(PIN_PATH))
parser.add_argument("--print-path", action="store_true")
parser.add_argument("--dump-pin", action="store_true")
args = parser.parse_args(argv)
try:
root, record, pin = resolve(args.stdlib_dir, Path(args.pin))
except BundleError as error:
print(f"bundle: error: {error}", file=sys.stderr)
return 1
if args.print_path:
print(root)
return 0
if args.dump_pin:
print(json.dumps(pin, indent=2, sort_keys=True))
return 0
print(
json.dumps(
{
"root": str(root),
"name": record["name"],
"version": record["version"],
"tree_digest": record["tree_digest"],
"aliases_digest": record["aliases_digest"],
"source_commit": pin["source"].get("commit"),
"file_count": record["file_count"],
},
indent=2,
sort_keys=True,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))