vinix-ports / tools / release-owners.py
191 lines · 171 sloc · 8.54 KB · c6895517c2081e0adf4663c1802c0a38b43311cd
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 "libatomic": ("gcc-libs",),
27 "libgcc": ("gcc-libs",),
28 "libgomp": ("gcc-libs",),
29 "libstdc++": ("gcc-libs",),
30 "libuuid": ("libuuid",),
31 "musl-utils": ("musl-utils",),
32 "ssl_client": ("ssl-client",),
33 "mesa-dev": ("mesa", "mesa-platform-headers", "mesa-gallium-sdk"),
34 "mesa-dri-gallium": ("mesa-gallium-sdk",),
35 "mesa-osmesa": ("mesa-gallium-sdk",),
36 "mesa-xatracker": ("mesa-gallium-sdk",),
37}
38
39
40def providers(row, path=None):
41 if row["binary"] == "ca-certificates":
42 if path is None:
43 return ("ca-certificates", "ca-certificates-bundle")
44 if Path(path).parent == Path("usr/share/ca-certificates/mozilla") and path.endswith(".crt"):
45 return ("ca-certificates-bundle",)
46 if row["origin"] == "alpine-baselayout":
47 if path is None:
48 return (*SOURCE_OWNERS["alpine-baselayout"], "vinix-release")
49 if path == "etc/motd":
50 return ("vinix-release",)
51 if row["origin"] == "mesa" and row["repository"] == "v3.20/main":
52 return ("mesa-glx-legacy",)
53 return BINARY_OWNERS.get(row["binary"], SOURCE_OWNERS.get(row["origin"], (row["origin"],)))
54
55
56def field(body, name):
57 for group in body.strip().split("\n\n"):
58 marker, _, value = group.partition("\n")
59 if marker == "%" + name + "%":
60 return value.splitlines()
61 return []
62
63
64def installed(client, arch, auditor):
65 result = subprocess.check_output([auditor, arch, client], text=True)
66 versions = {}
67 owners = {}
68 for description in sorted((client / "db/local").glob("*/desc")):
69 record = description.read_text()
70 name, = field(record, "NAME")
71 version, = field(record, "VERSION")
72 versions[name] = version
73 for path in field(description.with_name("files").read_text(), "FILES"):
74 if not path.endswith("/"):
75 if path in owners:
76 raise ValueError(f"multiple owners for {path}")
77 owners[path] = name
78 return versions, owners, result
79
80
81def relocated(row, path, arch, versions):
82 origin = row["origin"]
83 if origin == "zsh" and origin in versions:
84 old = row["version"].rsplit("-r", 1)[0]
85 new = versions[origin].rsplit("-", 1)[0]
86 if path == f"bin/zsh-{old}":
87 return f"bin/zsh-{new}"
88 for base in ("usr/share/zsh", "usr/lib/zsh"):
89 prefix = f"{base}/{old}/"
90 if path.startswith(prefix):
91 return f"{base}/{new}/" + path.removeprefix(prefix)
92 if origin in ("font-misc-misc", "font-cursor-misc", "font-alias") and path.startswith("usr/share/fonts/misc/"):
93 return "usr/share/fonts/X11/misc/" + path.removeprefix("usr/share/fonts/misc/")
94 if origin == "ncurses" and path.startswith("etc/terminfo/"):
95 return "usr/share/terminfo/" + path.removeprefix("etc/terminfo/")
96 if origin == "binutils" and path.startswith(f"usr/{arch}-alpine-linux-musl/"):
97 return f"usr/{arch}-linux-musl/" + path.removeprefix(f"usr/{arch}-alpine-linux-musl/")
98 return None
99
100
101def rows(path):
102 with path.open() as stream:
103 yield from csv.DictReader(stream, delimiter="\t")
104
105
106def key(row):
107 return row["binary"], row["version"], row["repository"]
108
109
110def action(row, state, names, expected, has_client):
111 if int(row["unavailable"]):
112 return "obtain and compare original source input"
113 if not state:
114 if int(row["different"]):
115 return "review changed published paths and identify their owner"
116 if row["profiles"] == "x11-index-dependency":
117 return "check whether native X11 builds require this index dependency"
118 return "verify as a build or staging input"
119 if not has_client:
120 return "install and audit the target packages"
121 if row["origin"] in ("alpine-keys", "apk-tools"):
122 return "verify the Vinix trust and package-management replacements in the image"
123 if not names.intersection(expected):
124 return "build and install the expected packages"
125 if state["unowned"] or state["other_owner"]:
126 return "resolve missing paths, alternate owners and intentional replacements"
127 return "verify the package behavior in the release image"
128
129
130def compare(args):
131 versions, owners, audit = installed(args.client, args.arch, args.auditor) if args.client else ({}, {}, "")
132 names = set(versions)
133 packages = {key(row): row for row in rows(args.comparison / "packages.tsv")}
134 details = defaultdict(Counter)
135 seen = set()
136 moved = []
137 args.output.mkdir()
138 if audit:
139 (args.output / "installed-root.log").write_text(audit)
140 with (args.output / "paths.tsv").open("x") as stream:
141 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
142 writer.writerow(["binary", "version", "repository", "layer", "published_path",
143 "original_comparison", "candidate_path", "installed_owner", "ownership"])
144 for row in rows(args.comparison / "package-files.tsv"):
145 k = key(row)
146 path = row["published_path"]
147 owner = owners.get(path, "")
148 known = row["comparison"] != "different"
149 expected = providers(packages[k], path)
150 match = ("unmeasured" if not args.client else "unowned" if not owner else
151 "expected_owner" if owner in expected else "other_owner")
152 writer.writerow([*k, row["layer"], path, row["comparison"], row["candidate_path"], owner, match])
153 observation = k, row["layer"], path
154 if known and observation not in seen:
155 seen.add(observation)
156 details[k][match] += 1
157 if match == "unowned":
158 target = relocated(packages[k], path, args.arch, versions)
159 if target and owners.get(target) in expected:
160 moved.append((*k, row["layer"], path, target, owners[target]))
161 with (args.output / "relocations.tsv").open("x") as stream:
162 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
163 writer.writerow(["binary", "version", "repository", "layer", "published_path", "installed_path", "owner"])
164 writer.writerows(sorted(moved))
165 with (args.output / "packages.tsv").open("x") as stream:
166 writer = csv.writer(stream, delimiter="\t", lineterminator="\n")
167 writer.writerow(["binary", "version", "repository", "origin", "profiles", "expected_packages",
168 "installed_expected_packages", "published_matching_paths", "expected_owner",
169 "other_owner", "unowned", "unmeasured", "next_check"])
170 for k, row in packages.items():
171 expected = providers(row)
172 state = details[k]
173 writer.writerow([*k, row["origin"], row["profiles"], ",".join(expected),
174 ",".join(sorted(names.intersection(expected))), sum(state.values()),
175 *[state[s] for s in ("expected_owner", "other_owner", "unowned", "unmeasured")],
176 action(row, state, names, expected, args.client is not None)])
177 print(f"{args.arch}: {len(packages)} release input rows, {len(names)} installed packages, "
178 f"{len(seen)} matching input/layer/path observations")
179
180
181if __name__ == "__main__":
182 parser = argparse.ArgumentParser(description=__doc__)
183 parser.add_argument("arch", choices=("x86_64", "aarch64"))
184 parser.add_argument("comparison", type=Path)
185 parser.add_argument("output", type=Path)
186 parser.add_argument("--client", type=Path, help="fresh signed vpac client to audit")
187 parser.add_argument("--auditor", type=Path, help="compiled tests/installed-root.v")
188 args = parser.parse_args()
189 if bool(args.client) != bool(args.auditor):
190 parser.error("--client and --auditor must be used together")
191 compare(args)
192