vinix-ports / tools / release-owners.py
227 lines · 205 sloc · 10.69 KB
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 action(row, state, names, expected, has_client):
136 if int(row["unavailable"]):
137 return "obtain and compare original source input"
138 if not state:
139 if int(row["different"]):
140 return "review changed published paths and identify their owner"
141 if row["profiles"] == "x11-index-dependency":
142 return "check whether native X11 builds require this index dependency"
143 return "verify as a build or staging input"
144 if not has_client:
145 return "install and audit the target packages"
146 if row["origin"] in ("alpine-keys", "apk-tools"):
147 return "verify the Vinix trust and package-management replacements in the image"
148 if not names.intersection(expected):
149 return "build and install the expected packages"
150 if state["unowned"] or state["other_owner"]:
151 return "resolve missing paths, alternate owners and intentional replacements"
152 return "verify the package behavior in the release image"
153
154
155def compare(args):
156 versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "")
157 names = set(versions)
158 packages = {key(row): row for row in rows(args.comparison / "packages.tsv")}
159 details = defaultdict(Counter)
160 seen = set()
161 moved = []
162 replacements = []
163 args.output.mkdir()
164 if audit:
165 (args.output / "installed-root.log").write_text(audit)
166 with (args.output / "paths.tsv").open("x") as stream:
167 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
168 writer.writerow(["binary", "version", "repository", "layer", "published_path",
169 "original_comparison", "candidate_path", "installed_owner", "ownership"])
170 for row in rows(args.comparison / "package-files.tsv"):
171 k = key(row)
172 path = row["published_path"]
173 owner = owners.get(path, "")
174 known = row["comparison"] != "different"
175 expected = providers(packages[k], path)
176 match = ("unmeasured" if not args.client else "unowned" if not owner else
177 "expected_owner" if owner in expected else "other_owner")
178 writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match])
179 observation = k, row["layer"], path
180 if known and observation not in seen:
181 seen.add(observation)
182 details[k][match] += 1
183 if match == "unowned":
184 target = relocated(packages[k], path, args.arch, versions)
185 if target and owners.get(target) in expected:
186 moved.append((*k, row["layer"], path, target, owners[target]))
187 change = replacement(packages[k], path)
188 if change:
189 native, package, function = change
190 replacements.append((*k, row["layer"], path, native, package,
191 owners.get(native, ""), function))
192 with (args.output / "relocations.tsv").open("x") as stream:
193 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
194 writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"])
195 writer.writerows(sorted(moved))
196 with (args.output / "replacements.tsv").open("x") as stream:
197 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
198 writer.writerow(["binary", "version", "repository", "layer", "published_path", "native_path",
199 "expected_owner", "installed_owner", "function"])
200 writer.writerows(sorted(replacements))
201 with (args.output / "packages.tsv").open("x") as stream:
202 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
203 writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages",
204 "installed_expected_packages", "published_matching_paths", "expected_owner",
205 "other_owner", "unowned", "unmeasured", "next_check"])
206 for k, row in packages.items():
207 expected = providers(row)
208 state = details[k]
209 writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected),
210 ",".join(sorted(names.intersection(expected))), sum(state.values()),
211 *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")],
212 action(row, state, names, expected, args.client is not None)])
213 print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, "
214 f"{len(seen)} matching input/layer/path observations")
215
216
217if __name__ == "__main__":
218 parser = argparse.ArgumentParser(description=__doc__)
219 parser.add_argument("arch", choices=("x86_64", "aarch64"))
220 parser.add_argument("comparison", type=Path)
221 parser.add_argument("output", type=Path)
222 parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit")
223 parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v")
224 args = parser.parse_args()
225 if bool(args.client) != bool(args.auditor):
226 parser.error("--client and --auditor must be used together")
227 compare(args)
228