vinix-ports / tools / release-owners.py
270 lines · 246 sloc · 12.85 KB · 2355e147dd040383b4166d8221c51b2594b171e5
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}
40LIBRARY_RELOCATIONS = {
41 ("llvm17", "usr/lib/libLLVM-17.0.6.so"): "usr/lib/libLLVM-17.so",
42 ("pcre2", "usr/lib/libpcre2-8.so.0.12.0"): "usr/lib/libpcre2-8.so.0",
43 ("pcre2", "usr/lib/libpcre2-posix.so.3.0.5"): "usr/lib/libpcre2-posix.so.3",
44 ("zlib", "usr/lib/libz.so.1.3.2"): "usr/lib/libz.so.1",
45}
46
47
48def providers(row, path=None):
49 if row["binary"] == "ca-certificates":
50 if path is None:
51 return ("ca-certificates", "ca-certificates-bundle")
52 if Path(path).parent == Path("usr/share/ca-certificates/mozilla") and path.endswith(".crt"):
53 return ("ca-certificates-bundle",)
54 if row["origin"] == "alpine-baselayout":
55 if path is None:
56 return (*SOURCE_OWNERS["alpine-baselayout"], "vinix-release")
57 if path == "etc/motd":
58 return ("vinix-release",)
59 if row["origin"] == "mesa" and row["repository"] == "v3.20/main":
60 return ("mesa-glx-legacy",)
61 return BINARY_OWNERS.get(row["binary"], SOURCE_OWNERS.get(row["origin"], (row["origin"],)))
62
63
64def field(body, name):
65 for group in body.strip().split("\n\n"):
66 marker, _, value = group.partition("\n")
67 if marker == "%" + name + "%":
68 return value.splitlines()
69 return []
70
71
72def installed(client, arch, auditor):
73 result = subprocess.check_output([auditor, arch, client], text=True)
74 versions = {}
75 owners = {}
76 for description in sorted((client / "db/local").glob("*/desc")):
77 record = description.read_text()
78 name, = field(record, "NAME")
79 version, = field(record, "VERSION")
80 versions[name] = version
81 for path in field(description.with_name("files").read_text(), "FILES"):
82 if not path.endswith("/"):
83 if path in owners:
84 raise ValueError(f"multiple owners for {path}")
85 owners[path] = name
86 return versions, owners, result
87
88
89def relocated(row, path, arch, versions):
90 origin = row["origin"]
91 if origin == "zsh" and origin in versions:
92 old = row["version"].rsplit("-r", 1)[0]
93 new = versions[origin].rsplit("-", 1)[0]
94 if path == f"bin/zsh-{old}":
95 return f"bin/zsh-{new}"
96 for base in ("usr/share/zsh", "usr/lib/zsh"):
97 prefix = f"{base}/{old}/"
98 if path.startswith(prefix):
99 suffix = path.removeprefix(prefix)
100 if base == "usr/share/zsh" and old == "5.9" and new == "5.9.2":
101 suffix = {
102 "functions/Completion/Linux/_pmap": "functions/Completion/Unix/_pmap",
103 "functions/Completion/Linux/_chcon": "functions/Completion/Linux/_selinux",
104 }.get(suffix, suffix)
105 return f"{base}/{new}/{suffix}"
106 if origin in ("font-misc-misc", "font-cursor-misc", "font-alias") and path.startswith("usr/share/fonts/misc/"):
107 return "usr/share/fonts/X11/misc/" + path.removeprefix("usr/share/fonts/misc/")
108 if origin == "ncurses" and path.startswith("etc/terminfo/"):
109 return "usr/share/terminfo/" + path.removeprefix("etc/terminfo/")
110 old_target = f"{arch}-alpine-linux-musl"
111 target = f"{arch}-linux-musl"
112 if origin == "binutils" and path.startswith(f"usr/{old_target}/"):
113 return f"usr/{target}/" + path.removeprefix(f"usr/{old_target}/")
114 if origin == "gcc":
115 upstream = row["version"].rsplit("-r", 1)[0]
116 if path == f"usr/lib/gcc/{old_target}/{upstream}/libgomp.spec":
117 return "usr/lib/libgomp.spec"
118 for directory in ("usr/lib/gcc", "usr/libexec/gcc"):
119 prefix = f"{directory}/{old_target}/"
120 if path.startswith(prefix):
121 return f"{directory}/{target}/" + path.removeprefix(prefix)
122 prefix = f"usr/bin/{old_target}-"
123 if path.startswith(prefix):
124 driver = path.removeprefix(prefix)
125 if driver == "cc":
126 return "usr/bin/cc"
127 if driver and "/" not in driver:
128 return f"usr/bin/{target}-{driver}"
129 return LIBRARY_RELOCATIONS.get((origin, path))
130
131
132def replacement(row, path):
133 if row["binary"] == "alpine-keys" and path.endswith(".rsa.pub"):
134 if path.startswith(("etc/apk/keys/", "usr/share/apk/keys/")):
135 return "usr/share/vpac/keyrings/vinix.gpg", "vinix-keyring", "repository trust"
136 if row["binary"] == "alpine-release" and path == "etc/alpine-release":
137 return "etc/os-release", "vinix-release", "operating system identity"
138 if row["binary"] == "apk-tools" and path == "sbin/apk":
139 return "usr/bin/vpac", "vpac", "package management"
140 if row["binary"] == "musl-dev" and path == "usr/include/bits/posix.h":
141 return "usr/include/unistd.h", "musl", "POSIX LP64/OFF64 feature macros"
142 if row["binary"] == "ca-certificates" and path == "etc/apk/protected_paths.d/ca-certificates.list":
143 return "usr/sbin/update-ca-certificates", "ca-certificates", "regeneration of CA bundle and hash links"
144 if row["binary"] == "alpine-baselayout-data" and path == "etc/inittab":
145 return "sbin/init", "vinix-desktop-init", "default desktop startup"
146 return None
147
148
149def rows(path):
150 with path.open() as stream:
151 yield from csv.DictReader(stream, delimiter="\t")
152
153
154def key(row):
155 return row["binary"], row["version"], row["repository"]
156
157
158def owner_requirement(value):
159 path, separator, owner = value.rpartition("=")
160 if not separator or not path.lstrip("/") or not owner:
161 raise argparse.ArgumentTypeError("expected PATH=PACKAGE")
162 return path.removeprefix("/"), owner
163
164
165def action(row, state, names, expected, has_client):
166 if int(row["unavailable"]):
167 return "obtain and compare original source input"
168 if not state:
169 if int(row["different"]):
170 return "review changed published paths and identify their owner"
171 if row["profiles"] == "x11-index-dependency":
172 return "check whether native X11 builds require this index dependency"
173 return "verify as a build or staging input"
174 if not has_client:
175 return "install and audit the target packages"
176 if row["origin"] in ("alpine-keys", "apk-tools"):
177 return "verify the Vinix trust and package-management replacements in the image"
178 if not names.intersection(expected):
179 return "build and install the expected packages"
180 if state["unowned"] or state["other_owner"]:
181 return "resolve missing paths, alternate owners and intentional replacements"
182 return "verify the package behavior in the release image"
183
184
185def compare(args):
186 versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "")
187 for path, expected in args.require_owner:
188 actual = owners.get(path)
189 if actual != expected:
190 raise ValueError(f"{args.arch}: /{path} belongs to {actual or 'no package'}, expected {expected}")
191 names = set(versions)
192 packages = {key(row): row for row in rows(args.comparison / "packages.tsv")}
193 details = defaultdict(Counter)
194 seen = set()
195 moved = []
196 replacements = []
197 args.output.mkdir()
198 if audit:
199 (args.output / "installed-root.log").write_text(audit)
200 if args.require_owner:
201 with (args.output / "required-owners.tsv").open("x") as stream:
202 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
203 writer.writerow(["path", "owner", "version"])
204 writer.writerows((path, owner, versions[owner]) for path, owner in args.require_owner)
205 with (args.output / "paths.tsv").open("x") as stream:
206 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
207 writer.writerow(["binary", "version", "repository", "layer", "published_path",
208 "original_comparison", "candidate_path", "installed_owner", "ownership"])
209 for row in rows(args.comparison / "package-files.tsv"):
210 k = key(row)
211 path = row["published_path"]
212 owner = owners.get(path, "")
213 known = row["comparison"] != "different"
214 expected = providers(packages[k], path)
215 match = ("unmeasured" if not args.client else "unowned" if not owner else
216 "expected_owner" if owner in expected else "other_owner")
217 writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match])
218 observation = k, row["layer"], path
219 if known and observation not in seen:
220 seen.add(observation)
221 details[k][match] += 1
222 if match == "unowned":
223 target = relocated(packages[k], path, args.arch, versions)
224 if target and owners.get(target) in expected:
225 moved.append((*k, row["layer"], path, target, owners[target]))
226 change = replacement(packages[k], path)
227 if change:
228 native, package, function = change
229 replacements.append((*k, row["layer"], path, native, package,
230 owners.get(native, ""), function))
231 with (args.output / "relocations.tsv").open("x") as stream:
232 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
233 writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"])
234 writer.writerows(sorted(moved))
235 with (args.output / "replacements.tsv").open("x") as stream:
236 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
237 writer.writerow(["binary", "version", "repository", "layer", "published_path", "native_path",
238 "expected_owner", "installed_owner", "function"])
239 writer.writerows(sorted(replacements))
240 with (args.output / "packages.tsv").open("x") as stream:
241 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
242 writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages",
243 "installed_expected_packages", "published_matching_paths", "expected_owner",
244 "other_owner", "unowned", "unmeasured", "next_check"])
245 for k, row in packages.items():
246 expected = providers(row)
247 state = details[k]
248 writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected),
249 ",".join(sorted(names.intersection(expected))), sum(state.values()),
250 *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")],
251 action(row, state, names, expected, args.client is not None)])
252 print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, "
253 f"{len(seen)} matching input/layer/path observations")
254
255
256if __name__ == "__main__":
257 parser = argparse.ArgumentParser(description=__doc__)
258 parser.add_argument("arch", choices=("x86_64", "aarch64"))
259 parser.add_argument("comparison", type=Path)
260 parser.add_argument("output", type=Path)
261 parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit")
262 parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v")
263 parser.add_argument("--require-owner", action="append", type=owner_requirement, default=[],
264 metavar="PATH=PACKAGE", help="require an installed owner for a specific path")
265 args = parser.parse_args()
266 if bool(args.client) != bool(args.auditor):
267 parser.error("--client and --auditor must be used together")
268 if args.require_owner and args.client is None:
269 parser.error("--require-owner needs an installed client")
270 compare(args)
271