vinix-ports / tests / feed-rejection.py
86 lines · 80 sloc · 4.15 KB · 91e3d5f628b876db94da2ae2346c753513255a9d
Raw
1"""Verify rejection and rollback in disposable copies of a signed vpac test feed."""
2import argparse
3import base64
4import csv
5import io
6import re
7import shutil
8import subprocess
9import tarfile
10from pathlib import Path
11
12
13def replace_package_signature(db, package, signature):
14 result = io.BytesIO()
15 changed = 0
16 with tarfile.open(db, "r:gz") as old, tarfile.open(fileobj=result, mode="w:gz") as new:
17 for entry in old:
18 if not entry.isfile():
19 new.addfile(entry)
20 continue
21 body = old.extractfile(entry).read()
22 if entry.name.endswith("/desc") and b"%NAME%\n" + package.encode() + b"\n" in body:
23 body, count = re.subn(b"(%PGPSIG%\n)[^\n]+", lambda m: m.group(1) + base64.b64encode(signature), body)
24 changed += count
25 entry.size = len(body)
26 new.addfile(entry, io.BytesIO(body))
27 if changed != 1:
28 raise ValueError("expected exactly one embedded package signature")
29 db.write_bytes(result.getvalue())
30
31
32def run(args):
33 args.work.mkdir()
34 with (args.repo / "packages.tsv").open() as index:
35 packages = {row["name"]: row["archive"] for row in csv.DictReader(index, delimiter="\t")}
36 archive = packages[args.package]
37 donor = next(filename for name, filename in packages.items() if name != args.package)
38 for case in ["control", "database-signature", "package-bytes", "package-signature"]:
39 repo = args.work / case
40 # Materialize index aliases so every mutation stays in this copy.
41 shutil.copytree(args.repo, repo)
42 directory = repo / args.arch
43 db = directory / "vinix.db"
44 db_sig = directory / "vinix.db.sig"
45 if case == "database-signature":
46 db_sig.write_bytes((directory / "vinix.files.sig").read_bytes())
47 elif case == "package-bytes":
48 with (directory / archive).open("r+b") as stream:
49 stream.seek(-1, 2)
50 last = stream.read(1)[0]
51 stream.seek(-1, 2)
52 stream.write(bytes([last ^ 1]))
53 elif case == "package-signature":
54 signature = (directory / (donor + ".sig")).read_bytes()
55 (directory / (archive + ".sig")).write_bytes(signature)
56 replace_package_signature(db, args.package, signature)
57 signer = (args.keys / "signer.fingerprint").read_text().strip()
58 signed = subprocess.check_output(["gpg", "--homedir", args.keys / "signing", "--batch",
59 "--local-user", signer, "--output", "-", "--detach-sign", db])
60 db_sig.write_bytes(signed)
61 subprocess.run(["gpg", "--homedir", args.keys / "verify", "--batch", "--verify", db_sig, db],
62 check=True, capture_output=True)
63 client = args.work / (case + "-client")
64 result = subprocess.run(["feed", "install", args.keys, repo, args.arch, client,
65 "--fakeroot", args.package], capture_output=True, text=True)
66 log = result.stdout + result.stderr
67 (args.work / (case + ".log")).write_text(log)
68 records = [item for item in (client / "db/local").iterdir() if item.is_dir()]
69 if case == "control":
70 if result.returncode or not records:
71 raise RuntimeError("pristine feed failed; see control.log")
72 else:
73 if result.returncode == 0 or records or any((client / "root").iterdir()):
74 raise RuntimeError(f"{case} transaction did not reject cleanly")
75 if not re.search(r"(invalid|corrupt|checksum mismatch|missing signature|bad signature)", log, flags=re.I):
76 raise RuntimeError(f"{case} failed without an integrity diagnostic; see its log")
77 print(case, "passed", flush=True)
78
79
80if __name__ == "__main__":
81 parser = argparse.ArgumentParser(description=__doc__)
82 for item in ["keys", "repo", "work"]:
83 parser.add_argument(item, type=lambda path: Path(path).resolve())
84 parser.add_argument("arch", choices=["x86_64", "aarch64"])
85 parser.add_argument("package", help="package with no dependencies from a feed that also contains a second package")
86 run(parser.parse_args())
87