Add ARM signed updates and native release automation
This commit is contained in:
@@ -4,6 +4,7 @@ from datetime import datetime, timezone
|
||||
from hashlib import file_digest
|
||||
from importlib import metadata
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import re
|
||||
@@ -16,7 +17,7 @@ from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from arm.version import NAME, VERSION
|
||||
from arm.version import NAME, VERSION, version_key
|
||||
from arm.branding import (
|
||||
APPLICATION_ICON, APPLICATION_IMAGE, APPLICATION_LOGO, APP_MODEL_ID, BUNDLED_ASSETS,
|
||||
COPYRIGHT, DESCRIPTION, INSTALL_ID, PUBLISHER, SUPPORT_URL, WEBSITE,
|
||||
@@ -87,16 +88,25 @@ def build_info():
|
||||
data[key] = bool(value) if key == "source_modified" else value
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
if "BUILD_NUMBER" in os.environ and "JENKINS_URL" in os.environ:
|
||||
number = os.environ["BUILD_NUMBER"]
|
||||
if not number.isdecimal() or int(number) < 1 or data.get("source_modified") is not False:
|
||||
raise RuntimeError("Jenkins requires a clean, numbered source checkout")
|
||||
revision = data.get("source_revision")
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", revision or "") or revision != os.environ.get("ARM_SOURCE_COMMIT"):
|
||||
raise RuntimeError("Jenkins source commit does not match the build")
|
||||
data["jenkins_build"] = int(number)
|
||||
return data
|
||||
|
||||
|
||||
def build(compiler, output):
|
||||
if platform.system() != "Windows" or struct.calcsize("P") != 8 or platform.machine().lower() not in ("amd64", "x86_64"):
|
||||
raise RuntimeError("Use native x64 Windows Python")
|
||||
match = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)\.(\d+)_([a-z]+)", VERSION)
|
||||
if not match:
|
||||
raise ValueError("Unexpected ARM version format")
|
||||
numbers = tuple(int(value) for value in match.groups()[:4])
|
||||
numbers = version_key(VERSION)[:4]
|
||||
changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8")
|
||||
if not re.search(rf"^## {re.escape(VERSION)}\s", changelog, re.M):
|
||||
raise RuntimeError("CHANGELOG.md does not contain the authoritative version")
|
||||
identity = build_info()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
with TemporaryDirectory(prefix="arm-release-") as temporary:
|
||||
temporary = Path(temporary)
|
||||
@@ -108,6 +118,15 @@ def build(compiler, output):
|
||||
encoding="utf-8",
|
||||
)
|
||||
assets = [part for asset in BUNDLED_ASSETS for part in ("--add-data", f"{ROOT / asset};branding")]
|
||||
update_data = [part for name in ("VERSION.md", "update-source.json") for part in ("--add-data", f"{ROOT / name};.")]
|
||||
worker_name = "AdaptiveResourceMonitorMaintenance"
|
||||
run([
|
||||
sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed", "--onefile",
|
||||
"--name", worker_name, "--paths", str(ROOT), "--workpath", str(temporary / "work"),
|
||||
"--distpath", str(temporary / "maintenance"), "--specpath", str(temporary),
|
||||
"--version-file", str(version_file), "--manifest", str(ROOT / "packaging" / "windows.manifest"),
|
||||
"--icon", str(ICON), "--exclude-module", "PySide6", *update_data, str(ROOT / "tools" / "maintenance.py"),
|
||||
])
|
||||
run([
|
||||
sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed",
|
||||
"--name", "AdaptiveResourceMonitor", "--paths", str(ROOT),
|
||||
@@ -116,14 +135,16 @@ def build(compiler, output):
|
||||
"--manifest", str(ROOT / "packaging" / "windows.manifest"),
|
||||
"--icon", str(ICON),
|
||||
*assets,
|
||||
*update_data,
|
||||
"--add-data", f"{ROOT / 'arm' / 'providers' / 'linux_probe.sh'};arm/providers",
|
||||
"--hidden-import", "pynvml", "--exclude-module", "tkinter",
|
||||
str(ROOT / "monitor.pyw"),
|
||||
])
|
||||
payload = temporary / "dist" / "AdaptiveResourceMonitor"
|
||||
shutil.copyfile(temporary / "maintenance" / f"{worker_name}.exe", payload / f"{worker_name}.exe")
|
||||
(payload / "VERSION.txt").write_text(VERSION + "\n", encoding="utf-8")
|
||||
(payload / "BUILD.json").write_text(json.dumps(build_info(), indent=2) + "\n", encoding="utf-8")
|
||||
for name in ("README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md"):
|
||||
(payload / "BUILD.json").write_text(json.dumps(identity, indent=2) + "\n", encoding="utf-8")
|
||||
for name in ("README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md", "VERSION.md"):
|
||||
shutil.copyfile(ROOT / name, payload / name)
|
||||
if (ROOT / "LICENSE.md").is_file():
|
||||
shutil.copyfile(ROOT / "LICENSE.md", payload / "LICENSE.md")
|
||||
|
||||
243
tools/ci_release.py
Normal file
243
tools/ci_release.py
Normal file
@@ -0,0 +1,243 @@
|
||||
"""Sign an archived Jenkins candidate and publish an explicitly pinned build."""
|
||||
import argparse
|
||||
from base64 import b64decode, b64encode
|
||||
from hashlib import file_digest
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from tempfile import TemporaryDirectory
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import quote
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from arm.branding import APP_MODEL_ID
|
||||
from arm.update_client import ReleaseClient
|
||||
from arm.update_release import (
|
||||
ARCHITECTURE, KINDS, MANIFEST, UpdateError, artifact_name, canonical, sha256, source_config,
|
||||
verify_file, verify_manifest,
|
||||
)
|
||||
from arm.update_worker import unpack_portable, verify_executable
|
||||
from arm.version import VERSION, version_key
|
||||
|
||||
CHECKSUMS = "SHA256SUMS.txt"
|
||||
NOTES = "RELEASE_NOTES.md"
|
||||
KEY = "arm-ed25519.pub"
|
||||
RECEIPT = "release-build.json"
|
||||
|
||||
|
||||
def git(*args):
|
||||
return subprocess.check_output(("git", *args), cwd=ROOT, text=True, encoding="utf-8").strip()
|
||||
|
||||
|
||||
def head_version(commit, version):
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", commit):
|
||||
raise UpdateError("Expected a 40-character Git commit")
|
||||
version_key(version)
|
||||
if git("show", f"{commit}:VERSION.md") != version:
|
||||
raise UpdateError("Pinned commit and authoritative version disagree")
|
||||
|
||||
|
||||
def notes_at(commit, version):
|
||||
text = git("show", f"{commit}:CHANGELOG.md")
|
||||
section = re.search(rf"^## {re.escape(version)}\s[^\n]*\n(.*?)(?=^## |\Z)", text, re.M | re.S)
|
||||
if not section or not section[1].strip():
|
||||
raise UpdateError("Pinned version has no changelog entry")
|
||||
return section[1].strip()
|
||||
|
||||
|
||||
def expected_receipt(release):
|
||||
return {
|
||||
"application": APP_MODEL_ID, "architecture": ARCHITECTURE, "version": release.version,
|
||||
"source_commit": release.commit, "jenkins_build": release.build,
|
||||
"packages": {kind: {"name": p.name, "size": p.size, "sha256": p.sha256}
|
||||
for kind, p in release.packages.items()},
|
||||
}
|
||||
|
||||
|
||||
def checksums(release):
|
||||
return "".join(f"{package.sha256} {package.name}\n" for _, package in sorted(release.packages.items()))
|
||||
|
||||
|
||||
def files_for(release):
|
||||
return {*(p.name for p in release.packages.values()), MANIFEST, CHECKSUMS, NOTES, KEY, RECEIPT}
|
||||
|
||||
|
||||
def verify(folder, version, commit, number):
|
||||
head_version(commit, version)
|
||||
source = source_config()
|
||||
release = verify_manifest((folder / MANIFEST).read_bytes(), source["public_key"], version)
|
||||
if (release.commit, release.build, release.notes) != (commit, number, notes_at(commit, version)):
|
||||
raise UpdateError("Signed manifest does not match the pinned Jenkins build or changelog")
|
||||
if {path.name for path in folder.iterdir()} != files_for(release):
|
||||
raise UpdateError("Release folder contains missing or unexpected files")
|
||||
if (json.loads((folder / RECEIPT).read_bytes()) != expected_receipt(release)
|
||||
or (folder / KEY).read_text(encoding="ascii").strip() != source["public_key"]
|
||||
or (folder / NOTES).read_text(encoding="utf-8").strip() != release.notes
|
||||
or (folder / CHECKSUMS).read_text(encoding="ascii") != checksums(release)):
|
||||
raise UpdateError("Artifact receipt, notes, key or checksums disagree with the signed manifest")
|
||||
for package in release.packages.values():
|
||||
verify_file(folder / package.name, package)
|
||||
print(f"{package.name} | {package.size:,} bytes | SHA-256 {package.sha256}")
|
||||
verify_executable(folder / release.packages["installed"].name, version)
|
||||
with TemporaryDirectory(prefix="arm-release-verify-") as temporary:
|
||||
payload = Path(temporary)
|
||||
unpack_portable(folder / release.packages["portable"].name, payload, version)
|
||||
build = json.loads((payload / "BUILD.json").read_bytes())
|
||||
if (build.get("source_revision"), build.get("jenkins_build"), build.get("source_modified")) != (commit, number, False):
|
||||
raise UpdateError("Portable package is inconsistent with the selected Jenkins build")
|
||||
if json.loads((payload / "_internal" / "update-source.json").read_bytes()) != source:
|
||||
raise UpdateError("Packaged update repository or trust key is inconsistent")
|
||||
print(f"Verified Ed25519 signature, Windows x64 packages and build identity | {version} | {commit} | Jenkins #{number}")
|
||||
return release
|
||||
|
||||
|
||||
def sign(folder, commit, number):
|
||||
head_version(commit, VERSION)
|
||||
source = source_config()
|
||||
key = Ed25519PrivateKey.from_private_bytes(b64decode(os.environ.pop("ARM_ED25519_SIGNING_KEY"), validate=True))
|
||||
if b64encode(key.public_key().public_bytes_raw()).decode() != source["public_key"]:
|
||||
raise UpdateError("Jenkins signing identity does not match the application's public key")
|
||||
archives = {}
|
||||
for kind in KINDS:
|
||||
name = artifact_name(VERSION, kind)
|
||||
path = folder / name
|
||||
archives[kind] = {"name": name, "size": path.stat().st_size, "sha256": sha256(path)}
|
||||
notes = notes_at(commit, VERSION)
|
||||
manifest = {"protocol": 1, "application": APP_MODEL_ID, "architecture": ARCHITECTURE, "version": VERSION,
|
||||
"commit": commit, "build": number, "notes": notes, "packages": archives}
|
||||
raw = canonical({"manifest": manifest, "signature": b64encode(key.sign(canonical(manifest))).decode()})
|
||||
release = verify_manifest(raw, source["public_key"], VERSION)
|
||||
(folder / MANIFEST).write_bytes(raw)
|
||||
(folder / RECEIPT).write_bytes(canonical(expected_receipt(release)) + b"\n")
|
||||
(folder / CHECKSUMS).write_bytes(checksums(release).encode("ascii"))
|
||||
(folder / NOTES).write_bytes((notes + "\n").encode("utf-8"))
|
||||
(folder / KEY).write_bytes((source["public_key"] + "\n").encode("ascii"))
|
||||
print(f"Signed {VERSION} with the ARM-specific Ed25519 Jenkins credential")
|
||||
|
||||
|
||||
class Publication:
|
||||
def __init__(self, client, token):
|
||||
self.client = client
|
||||
self.auth = {"Authorization": f"token {token}", "Accept": "application/json"}
|
||||
|
||||
def request(self, path, data=None, method=None, optional=False, headers=None):
|
||||
if isinstance(data, dict):
|
||||
data = canonical(data)
|
||||
request = Request(self.client.api + path, data, method=method, headers={
|
||||
**self.auth, "Content-Type": "application/json", **(headers or {})
|
||||
})
|
||||
try:
|
||||
with self.client.opener.open(request, timeout=120) as response:
|
||||
return json.load(response)
|
||||
except HTTPError as exc:
|
||||
if optional and exc.code == 404:
|
||||
return None
|
||||
raise UpdateError(f"Gitea {method or 'GET'} {path} failed HTTP {exc.code}") from None
|
||||
|
||||
def upload(self, release_id, path):
|
||||
boundary = uuid4().hex
|
||||
start = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"attachment\";"
|
||||
f" filename=\"{path.name}\"\r\nContent-Type: application/octet-stream\r\n\r\n").encode("ascii")
|
||||
body = start + path.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii")
|
||||
row = self.request(f"/releases/{release_id}/assets?name={quote(path.name)}", body, "POST", headers={
|
||||
"Content-Type": f"multipart/form-data; boundary={boundary}"
|
||||
})
|
||||
if (row.get("name"), row.get("size")) != (path.name, path.stat().st_size):
|
||||
raise UpdateError(f"Gitea returned unexpected attachment details for {path.name}")
|
||||
print(f"Uploaded draft attachment {path.name}")
|
||||
|
||||
def verify_downloads(self, folder, row, signed, anonymous):
|
||||
matches = row["assets"]
|
||||
if len(matches) != len(files_for(signed)) or {entry["name"] for entry in matches} != files_for(signed):
|
||||
raise UpdateError("Release contains unexpected or missing attachments")
|
||||
version = signed.version
|
||||
if (row["tag_name"], row["body"], row["prerelease"]) != (version, signed.notes, not version.endswith("_stable")):
|
||||
raise UpdateError("Release title, body or classification disagrees with the signed metadata")
|
||||
for entry in matches:
|
||||
file = folder / entry["name"]
|
||||
url = self.client.attachment(row, version, file.name, file.stat().st_size)
|
||||
headers = {} if anonymous else self.auth
|
||||
with self.client.open(url, headers) as response:
|
||||
if response.headers.get("Content-Length") not in (None, str(file.stat().st_size)):
|
||||
raise UpdateError(f"Release download size mismatch for {file.name}")
|
||||
if file.name == MANIFEST:
|
||||
remote = response.read(file.stat().st_size + 1)
|
||||
if remote != signed.envelope:
|
||||
raise UpdateError("Downloaded signed release manifest differs from the archived candidate")
|
||||
verify_manifest(remote, self.client.source["public_key"], version)
|
||||
elif file_digest(response, "sha256").hexdigest() != sha256(file):
|
||||
raise UpdateError(f"Downloaded SHA-256 mismatch for {file.name}")
|
||||
print(f"{'Anonymous' if anonymous else 'Draft'} readback verified {file.name}")
|
||||
|
||||
|
||||
def publish(folder, version, commit, number):
|
||||
if subprocess.run(("git", "merge-base", "--is-ancestor", commit, "origin/main"), cwd=ROOT).returncode:
|
||||
raise UpdateError("Selected commit is not reachable from main")
|
||||
release = verify(folder, version, commit, number)
|
||||
api = Publication(ReleaseClient(), os.environ.pop("ARM_GITEA_PUBLISH_TOKEN"))
|
||||
tag = quote(version)
|
||||
repository = api.request("")
|
||||
if repository["private"] is not False:
|
||||
raise UpdateError("The release repository must pass anonymous access validation before publication")
|
||||
row = api.request(f"/releases/tags/{tag}", optional=True)
|
||||
original_tag = api.request(f"/tags/{tag}", optional=True)
|
||||
if original_tag and original_tag["commit"]["sha"] != commit:
|
||||
raise UpdateError("An existing version tag points at a different commit")
|
||||
if row and not row["draft"]:
|
||||
api.verify_downloads(folder, row, release, True)
|
||||
print(f"Version {version} is already public with the exact selected bytes")
|
||||
return
|
||||
if row is None:
|
||||
row = api.request("/releases", {"tag_name": version, "target_commitish": commit, "name": f"Adaptive Resource Monitor {version}",
|
||||
"body": release.notes, "draft": True, "prerelease": not version.endswith("_stable")}, "POST")
|
||||
address = f"/releases/{row['id']}"
|
||||
if (row["body"], row["target_commitish"]) != (release.notes, commit):
|
||||
raise UpdateError("Existing draft does not match the selected build")
|
||||
existing = {item["name"] for item in row["assets"]}
|
||||
if existing - files_for(release):
|
||||
raise UpdateError("Draft contains unrecognized attachments")
|
||||
for name in sorted(files_for(release) - existing):
|
||||
api.upload(row["id"], folder / name)
|
||||
api.verify_downloads(folder, api.request(address), release, False)
|
||||
api.request(address, {"draft": False}, "PATCH")
|
||||
try:
|
||||
opened = json.loads(api.client.read(api.client.api + f"/releases/tags/{tag}", 2 * 1024**2))
|
||||
tag_info = json.loads(api.client.read(api.client.api + f"/tags/{tag}", 64 * 1024))
|
||||
if opened["draft"] or tag_info["commit"]["sha"] != commit:
|
||||
raise UpdateError("Published release or Git tag did not match the pinned build")
|
||||
api.verify_downloads(folder, opened, release, True)
|
||||
except Exception:
|
||||
api.request(address, {"draft": True}, "PATCH")
|
||||
raise
|
||||
print(f"Published and anonymously verified {api.client.base}/{api.client.repository}/releases/tag/{tag}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("sign", "verify", "publish"))
|
||||
parser.add_argument("folder", type=Path)
|
||||
parser.add_argument("commit")
|
||||
parser.add_argument("build", type=int)
|
||||
parser.add_argument("--version", default=VERSION)
|
||||
args = parser.parse_args()
|
||||
if args.build < 1:
|
||||
parser.error("Use a positive Jenkins build number")
|
||||
if args.action == "sign":
|
||||
sign(args.folder, args.commit, args.build)
|
||||
elif args.action == "publish":
|
||||
publish(args.folder, args.version, args.commit, args.build)
|
||||
else:
|
||||
verify(args.folder, args.version, args.commit, args.build)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
15
tools/install_ci_compiler.py
Normal file
15
tools/install_ci_compiler.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""Extract the signed Inno compiler through its native portable installer."""
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from windows_gui import start_isolated
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
installer, destination = (Path(value).resolve() for value in sys.argv[1:])
|
||||
raise SystemExit(start_isolated(
|
||||
[str(installer), "/PORTABLE=1", "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", f"/DIR={destination}"],
|
||||
f"ARM_Compiler_{uuid4().hex[:10]}", timeout=90,
|
||||
))
|
||||
5
tools/maintenance.py
Normal file
5
tools/maintenance.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from arm.update_worker import main
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
19
tools/prepare_windows_compiler.ps1
Normal file
19
tools/prepare_windows_compiler.ps1
Normal file
@@ -0,0 +1,19 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$scratch = Join-Path $PWD '.ci'
|
||||
$compiler = Join-Path $scratch 'inno'
|
||||
$download = Join-Path $scratch 'innosetup-7.1.1-x64.exe'
|
||||
$origin = 'https://github.com/jrsoftware/issrc/releases/download/is-7_1_1/innosetup-7.1.1-x64.exe'
|
||||
$expected = '8a5a6711c3766a6e5fb74f280ba0e3551e719ce94538d901fdbd1f8f9920b3f0'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $origin -OutFile $download
|
||||
if ((Get-FileHash -LiteralPath $download -Algorithm SHA256).Hash -ine $expected) {
|
||||
throw 'Inno Setup download SHA-256 mismatch'
|
||||
}
|
||||
$signature = Get-AuthenticodeSignature -LiteralPath $download
|
||||
if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'CN=Pyrsys B\.V\.') {
|
||||
throw 'Inno Setup publisher verification failed'
|
||||
}
|
||||
& '.ci\python\Scripts\python.exe' tools\install_ci_compiler.py $download $compiler
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath (Join-Path $compiler 'ISCC.exe'))) {
|
||||
throw 'Portable Inno Setup staging failed'
|
||||
}
|
||||
Write-Host 'Inno Setup 7.1.1 x64 hash, publisher and portable staging verified.'
|
||||
Reference in New Issue
Block a user