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