vinix-ports / tools / release-owners.py
193 lines · 173 sloc · 8.58 KB · 58e9dd86ba35e1113283c5b33407f8a7c7614e44
Raw
1"""Compare published release inputs with package owners in an audited vpac root."""
2import argparse
3import csv
4import subprocess
5from collections import Counter, defaultdict
6from pathlib import Path
7
8
9# Most Alpine split packages are combined under their source name in Vinix.
10# These are expected owners. Actual ownership comes from the installed database.
11SOURCE_OWNERS = {
12 "alpine-base": ("vinix-release",),
13 "alpine-baselayout": ("vinix-filesystem", "vinix-accounts", "netbase"),
14 "alpine-keys": ("vinix-keyring",),
15 "apk-tools": ("vpac",),
16 "hwdata": ("hwdata-pci",),
17 "llvm17": ("llvm17-libs",),
18 "llvm19": ("llvm19-libs",),
19 "mpc1": ("mpc",),
20 "mpfr4": ("mpfr",),
21 "openssh": ("openssh-client",),
22 "pax-utils": ("scanelf",),
23}
24BINARY_OWNERS = {
25 "ca-certificates-bundle": ("ca-certificates-bundle",),
26 "glu-dev": ("glu-headers",),
27 "libatomic": ("gcc-libs",),
28 "libelf": ("libelf",),
29 "libgcc": ("gcc-libs",),
30 "libgomp": ("gcc-libs",),
31 "libstdc++": ("gcc-libs",),
32 "libuuid": ("libuuid",),
33 "musl-utils": ("musl-utils",),
34 "ssl_client": ("ssl-client",),
35 "mesa-dev": ("mesa", "mesa-platform-headers", "mesa-gallium-sdk"),
36 "mesa-dri-gallium": ("mesa",),
37 "mesa-osmesa": ("mesa-gallium-sdk",),
38 "mesa-xatracker": ("mesa-gallium-sdk",),
39}
40
41
42def providers(row, path=None):
43 if row["binary"] == "ca-certificates":
44 if path is None:
45 return ("ca-certificates", "ca-certificates-bundle")
46 if Path(path).parent == Path("usr/share/ca-certificates/mozilla") and path.endswith(".crt"):
47 return ("ca-certificates-bundle",)
48 if row["origin"] == "alpine-baselayout":
49 if path is None:
50 return (*SOURCE_OWNERS["alpine-baselayout"], "vinix-release")
51 if path == "etc/motd":
52 return ("vinix-release",)
53 if row["origin"] == "mesa" and row["repository"] == "v3.20/main":
54 return ("mesa-glx-legacy",)
55 return BINARY_OWNERS.get(row["binary"], SOURCE_OWNERS.get(row["origin"], (row["origin"],)))
56
57
58def field(body, name):
59 for group in body.strip().split("\n\n"):
60 marker, _, value = group.partition("\n")
61 if marker == "%" + name + "%":
62 return value.splitlines()
63 return []
64
65
66def installed(client, arch, auditor):
67 result = subprocess.check_output([auditor, arch, client], text=True)
68 versions = {}
69 owners = {}
70 for description in sorted((client / "db/local").glob("*/desc")):
71 record = description.read_text()
72 name, = field(record, "NAME")
73 version, = field(record, "VERSION")
74 versions[name] = version
75 for path in field(description.with_name("files").read_text(), "FILES"):
76 if not path.endswith("/"):
77 if path in owners:
78 raise ValueError(f"multiple owners for {path}")
79 owners[path] = name
80 return versions, owners, result
81
82
83def relocated(row, path, arch, versions):
84 origin = row["origin"]
85 if origin == "zsh" and origin in versions:
86 old = row["version"].rsplit("-r", 1)[0]
87 new = versions[origin].rsplit("-", 1)[0]
88 if path == f"bin/zsh-{old}":
89 return f"bin/zsh-{new}"
90 for base in ("usr/share/zsh", "usr/lib/zsh"):
91 prefix = f"{base}/{old}/"
92 if path.startswith(prefix):
93 return f"{base}/{new}/" + path.removeprefix(prefix)
94 if origin in ("font-misc-misc", "font-cursor-misc", "font-alias") and path.startswith("usr/share/fonts/misc/"):
95 return "usr/share/fonts/X11/misc/" + path.removeprefix("usr/share/fonts/misc/")
96 if origin == "ncurses" and path.startswith("etc/terminfo/"):
97 return "usr/share/terminfo/" + path.removeprefix("etc/terminfo/")
98 if origin == "binutils" and path.startswith(f"usr/{arch}-alpine-linux-musl/"):
99 return f"usr/{arch}-linux-musl/" + path.removeprefix(f"usr/{arch}-alpine-linux-musl/")
100 return None
101
102
103def rows(path):
104 with path.open() as stream:
105 yield from csv.DictReader(stream, delimiter="\t")
106
107
108def key(row):
109 return row["binary"], row["version"], row["repository"]
110
111
112def action(row, state, names, expected, has_client):
113 if int(row["unavailable"]):
114 return "obtain and compare original source input"
115 if not state:
116 if int(row["different"]):
117 return "review changed published paths and identify their owner"
118 if row["profiles"] == "x11-index-dependency":
119 return "check whether native X11 builds require this index dependency"
120 return "verify as a build or staging input"
121 if not has_client:
122 return "install and audit the target packages"
123 if row["origin"] in ("alpine-keys", "apk-tools"):
124 return "verify the Vinix trust and package-management replacements in the image"
125 if not names.intersection(expected):
126 return "build and install the expected packages"
127 if state["unowned"] or state["other_owner"]:
128 return "resolve missing paths, alternate owners and intentional replacements"
129 return "verify the package behavior in the release image"
130
131
132def compare(args):
133 versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "")
134 names = set(versions)
135 packages = {key(row): row for row in rows(args.comparison / "packages.tsv")}
136 details = defaultdict(Counter)
137 seen = set()
138 moved = []
139 args.output.mkdir()
140 if audit:
141 (args.output / "installed-root.log").write_text(audit)
142 with (args.output / "paths.tsv").open("x") as stream:
143 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
144 writer.writerow(["binary", "version", "repository", "layer", "published_path",
145 "original_comparison", "candidate_path", "installed_owner", "ownership"])
146 for row in rows(args.comparison / "package-files.tsv"):
147 k = key(row)
148 path = row["published_path"]
149 owner = owners.get(path, "")
150 known = row["comparison"] != "different"
151 expected = providers(packages[k], path)
152 match = ("unmeasured" if not args.client else "unowned" if not owner else
153 "expected_owner" if owner in expected else "other_owner")
154 writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match])
155 observation = k, row["layer"], path
156 if known and observation not in seen:
157 seen.add(observation)
158 details[k][match] += 1
159 if match == "unowned":
160 target = relocated(packages[k], path, args.arch, versions)
161 if target and owners.get(target) in expected:
162 moved.append((*k, row["layer"], path, target, owners[target]))
163 with (args.output / "relocations.tsv").open("x") as stream:
164 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
165 writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"])
166 writer.writerows(sorted(moved))
167 with (args.output / "packages.tsv").open("x") as stream:
168 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
169 writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages",
170 "installed_expected_packages", "published_matching_paths", "expected_owner",
171 "other_owner", "unowned", "unmeasured", "next_check"])
172 for k, row in packages.items():
173 expected = providers(row)
174 state = details[k]
175 writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected),
176 ",".join(sorted(names.intersection(expected))), sum(state.values()),
177 *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")],
178 action(row, state, names, expected, args.client is not None)])
179 print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, "
180 f"{len(seen)} matching input/layer/path observations")
181
182
183if __name__ == "__main__":
184 parser = argparse.ArgumentParser(description=__doc__)
185 parser.add_argument("arch", choices=("x86_64", "aarch64"))
186 parser.add_argument("comparison", type=Path)
187 parser.add_argument("output", type=Path)
188 parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit")
189 parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v")
190 args = parser.parse_args()
191 if bool(args.client) != bool(args.auditor):
192 parser.error("--client and --auditor must be used together")
193 compare(args)
194