vinix-ports / tools / release-owners.py
261 lines · 237 sloc · 12.35 KB · 3ffd7b42cd3aa822f3b06bed8f8d5e44c9567a0a
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 suffix = path.removeprefix(prefix)
94 if base == "usr/share/zsh" and old == "5.9" and new == "5.9.2":
95 suffix = {
96 "functions/Completion/Linux/_pmap": "functions/Completion/Unix/_pmap",
97 "functions/Completion/Linux/_chcon": "functions/Completion/Linux/_selinux",
98 }.get(suffix, suffix)
99 return f"{base}/{new}/{suffix}"
100 if origin in ("font-misc-misc", "font-cursor-misc", "font-alias") and path.startswith("usr/share/fonts/misc/"):
101 return "usr/share/fonts/X11/misc/" + path.removeprefix("usr/share/fonts/misc/")
102 if origin == "ncurses" and path.startswith("etc/terminfo/"):
103 return "usr/share/terminfo/" + path.removeprefix("etc/terminfo/")
104 old_target = f"{arch}-alpine-linux-musl"
105 target = f"{arch}-linux-musl"
106 if origin == "binutils" and path.startswith(f"usr/{old_target}/"):
107 return f"usr/{target}/" + path.removeprefix(f"usr/{old_target}/")
108 if origin == "gcc":
109 for directory in ("usr/lib/gcc", "usr/libexec/gcc"):
110 prefix = f"{directory}/{old_target}/"
111 if path.startswith(prefix):
112 return f"{directory}/{target}/" + path.removeprefix(prefix)
113 prefix = f"usr/bin/{old_target}-"
114 if path.startswith(prefix):
115 driver = path.removeprefix(prefix)
116 if driver == "cc":
117 return "usr/bin/cc"
118 if driver and "/" not in driver:
119 return f"usr/bin/{target}-{driver}"
120 return None
121
122
123def replacement(row, path):
124 if row["binary"] == "alpine-keys" and path.endswith(".rsa.pub"):
125 if path.startswith(("etc/apk/keys/", "usr/share/apk/keys/")):
126 return "usr/share/vpac/keyrings/vinix.gpg", "vinix-keyring", "repository trust"
127 if row["binary"] == "alpine-release" and path == "etc/alpine-release":
128 return "etc/os-release", "vinix-release", "operating system identity"
129 if row["binary"] == "apk-tools" and path == "sbin/apk":
130 return "usr/bin/vpac", "vpac", "package management"
131 if row["binary"] == "musl-dev" and path == "usr/include/bits/posix.h":
132 return "usr/include/unistd.h", "musl", "POSIX LP64/OFF64 feature macros"
133 if row["binary"] == "ca-certificates" and path == "etc/apk/protected_paths.d/ca-certificates.list":
134 return "usr/sbin/update-ca-certificates", "ca-certificates", "regeneration of CA bundle and hash links"
135 if row["binary"] == "alpine-baselayout-data" and path == "etc/inittab":
136 return "sbin/init", "vinix-desktop-init", "default desktop startup"
137 return None
138
139
140def rows(path):
141 with path.open() as stream:
142 yield from csv.DictReader(stream, delimiter="\t")
143
144
145def key(row):
146 return row["binary"], row["version"], row["repository"]
147
148
149def owner_requirement(value):
150 path, separator, owner = value.rpartition("=")
151 if not separator or not path.lstrip("/") or not owner:
152 raise argparse.ArgumentTypeError("expected PATH=PACKAGE")
153 return path.removeprefix("/"), owner
154
155
156def action(row, state, names, expected, has_client):
157 if int(row["unavailable"]):
158 return "obtain and compare original source input"
159 if not state:
160 if int(row["different"]):
161 return "review changed published paths and identify their owner"
162 if row["profiles"] == "x11-index-dependency":
163 return "check whether native X11 builds require this index dependency"
164 return "verify as a build or staging input"
165 if not has_client:
166 return "install and audit the target packages"
167 if row["origin"] in ("alpine-keys", "apk-tools"):
168 return "verify the Vinix trust and package-management replacements in the image"
169 if not names.intersection(expected):
170 return "build and install the expected packages"
171 if state["unowned"] or state["other_owner"]:
172 return "resolve missing paths, alternate owners and intentional replacements"
173 return "verify the package behavior in the release image"
174
175
176def compare(args):
177 versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "")
178 for path, expected in args.require_owner:
179 actual = owners.get(path)
180 if actual != expected:
181 raise ValueError(f"{args.arch}: /{path} belongs to {actual or 'no package'}, expected {expected}")
182 names = set(versions)
183 packages = {key(row): row for row in rows(args.comparison / "packages.tsv")}
184 details = defaultdict(Counter)
185 seen = set()
186 moved = []
187 replacements = []
188 args.output.mkdir()
189 if audit:
190 (args.output / "installed-root.log").write_text(audit)
191 if args.require_owner:
192 with (args.output / "required-owners.tsv").open("x") as stream:
193 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
194 writer.writerow(["path", "owner", "version"])
195 writer.writerows((path, owner, versions[owner]) for path, owner in args.require_owner)
196 with (args.output / "paths.tsv").open("x") as stream:
197 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
198 writer.writerow(["binary", "version", "repository", "layer", "published_path",
199 "original_comparison", "candidate_path", "installed_owner", "ownership"])
200 for row in rows(args.comparison / "package-files.tsv"):
201 k = key(row)
202 path = row["published_path"]
203 owner = owners.get(path, "")
204 known = row["comparison"] != "different"
205 expected = providers(packages[k], path)
206 match = ("unmeasured" if not args.client else "unowned" if not owner else
207 "expected_owner" if owner in expected else "other_owner")
208 writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match])
209 observation = k, row["layer"], path
210 if known and observation not in seen:
211 seen.add(observation)
212 details[k][match] += 1
213 if match == "unowned":
214 target = relocated(packages[k], path, args.arch, versions)
215 if target and owners.get(target) in expected:
216 moved.append((*k, row["layer"], path, target, owners[target]))
217 change = replacement(packages[k], path)
218 if change:
219 native, package, function = change
220 replacements.append((*k, row["layer"], path, native, package,
221 owners.get(native, ""), function))
222 with (args.output / "relocations.tsv").open("x") as stream:
223 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
224 writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"])
225 writer.writerows(sorted(moved))
226 with (args.output / "replacements.tsv").open("x") as stream:
227 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
228 writer.writerow(["binary", "version", "repository", "layer", "published_path", "native_path",
229 "expected_owner", "installed_owner", "function"])
230 writer.writerows(sorted(replacements))
231 with (args.output / "packages.tsv").open("x") as stream:
232 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
233 writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages",
234 "installed_expected_packages", "published_matching_paths", "expected_owner",
235 "other_owner", "unowned", "unmeasured", "next_check"])
236 for k, row in packages.items():
237 expected = providers(row)
238 state = details[k]
239 writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected),
240 ",".join(sorted(names.intersection(expected))), sum(state.values()),
241 *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")],
242 action(row, state, names, expected, args.client is not None)])
243 print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, "
244 f"{len(seen)} matching input/layer/path observations")
245
246
247if __name__ == "__main__":
248 parser = argparse.ArgumentParser(description=__doc__)
249 parser.add_argument("arch", choices=("x86_64", "aarch64"))
250 parser.add_argument("comparison", type=Path)
251 parser.add_argument("output", type=Path)
252 parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit")
253 parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v")
254 parser.add_argument("--require-owner", action="append", type=owner_requirement, default=[],
255 metavar="PATH=PACKAGE", help="require an installed owner for a specific path")
256 args = parser.parse_args()
257 if bool(args.client) != bool(args.auditor):
258 parser.error("--client and --auditor must be used together")
259 if args.require_owner and args.client is None:
260 parser.error("--require-owner needs an installed client")
261 compare(args)
262