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