diff --git a/service/ota/build/Dockerfile b/service/ota/build/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3bf81fc2c77a48d0373298ed9ad8240b5188a076 --- /dev/null +++ b/service/ota/build/Dockerfile @@ -0,0 +1,3 @@ +FROM docker.io/library/python:3.13-slim@sha256:37134a49d21d2120e4c4d73bb76f8a4ab9aef31f096f7ec2ead48c2feead4332 +COPY ota.py /app/ota.py +CMD ["python3", "-u", "/app/ota.py"] diff --git a/service/ota/build/ota.py b/service/ota/build/ota.py new file mode 100644 index 0000000000000000000000000000000000000000..fb3f3a8f5a783f540ee68ed40cc09bb910c09601 --- /dev/null +++ b/service/ota/build/ota.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +import hmac +import html +from http import HTTPStatus +import http.server +import os +from pathlib import Path +import plistlib +import re +import shutil +import tempfile +import zipfile + +ROOT = Path(os.environ["OTA_ROOT"]) +ORIGIN = os.environ["OTA_ORIGIN"] +TOKEN = os.environ["OTA_UPLOAD_TOKEN"].encode() +KEEP = 20 +MAX_IPA = 2 * 1024**3 +BUILD = re.compile(r"/([0-9a-f]{32})(/manifest\.plist|/app\.ipa)?\Z") +APP_PLIST = re.compile(r"Payload/[^/]+\.app/Info\.plist\Z") + + +def app_info(ipa): + with zipfile.ZipFile(ipa) as archive: + return plistlib.loads(archive.read(next(name for name in archive.namelist() if APP_PLIST.fullmatch(name)))) + + +def title(info): + return info.get("CFBundleDisplayName") or info["CFBundleName"] + + +def version(info): + return info["CFBundleShortVersionString"] + + +class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def send(self, status, content_type, body): + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + if self.path == "/health": + return self.send(HTTPStatus.OK, "text/plain", b"ok") + match = BUILD.fullmatch(self.path) + ipa = ROOT / match[1] / "app.ipa" if match else None + if not ipa or not ipa.is_file(): + return self.send(HTTPStatus.NOT_FOUND, "text/plain", b"not found") + if match[2] == "/app.ipa": + self.send_response(HTTPStatus.OK) + self.send_header("Content-Type", "application/octet-stream") + self.send_header("Content-Length", str(ipa.stat().st_size)) + self.end_headers() + with ipa.open("rb") as source: + shutil.copyfileobj(source, self.wfile, 1 << 20) + return + info = app_info(ipa) + base = f"{ORIGIN}/{match[1]}" + if match[2]: + return self.send(HTTPStatus.OK, "text/xml", plistlib.dumps({"items": [{ + "assets": [{"kind": "software-package", "url": f"{base}/app.ipa"}], + "metadata": {"bundle-identifier": info["CFBundleIdentifier"], "bundle-version": version(info), "kind": "software", "title": title(info)}, + }]})) + install = html.escape(f"itms-services://?action=download-manifest&url={base}/manifest.plist") + self.send(HTTPStatus.OK, "text/html; charset=utf-8", f""" + +{html.escape(title(info))} + +

{html.escape(title(info))}

{html.escape(version(info))}

Install +""".encode()) + + def do_PUT(self): + if self.path != "/builds" or not hmac.compare_digest(self.headers.get("Authorization", "").encode(), b"Bearer " + TOKEN): + self.close_connection = True + return self.send(HTTPStatus.UNAUTHORIZED, "text/plain", b"unauthorized") + size = int(self.headers.get("Content-Length", -1)) + if not 0 < size <= MAX_IPA: + self.close_connection = True + return self.send(HTTPStatus.LENGTH_REQUIRED, "text/plain", b"a Content-Length up to 2 GiB is required") + ROOT.mkdir(exist_ok=True) + with tempfile.NamedTemporaryFile(dir=ROOT, prefix=".upload-", delete=False) as upload: + try: + remaining = size + while remaining: + chunk = self.rfile.read(min(1 << 20, remaining)) + if not chunk: + raise ConnectionError("upload ended early") + upload.write(chunk) + remaining -= len(chunk) + upload.flush() + app_info(upload.name) + except (ConnectionError, zipfile.BadZipFile, StopIteration, KeyError, plistlib.InvalidFileException): + os.unlink(upload.name) + self.close_connection = True + return self.send(HTTPStatus.BAD_REQUEST, "text/plain", b"not an IPA with an app Info.plist") + build = os.urandom(16).hex() + (ROOT / build).mkdir() + os.chmod(upload.name, 0o644) + os.replace(upload.name, ROOT / build / "app.ipa") + for old in sorted((path for path in ROOT.glob("*/") if BUILD.fullmatch("/" + path.name)), key=lambda path: path.stat().st_mtime)[:-KEEP]: + shutil.rmtree(old) + self.send(HTTPStatus.CREATED, "text/plain", f"{ORIGIN}/{build}\n".encode()) + + +if __name__ == "__main__": + http.server.ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever() diff --git a/service/ota/service.pkl b/service/ota/service.pkl new file mode 100644 index 0000000000000000000000000000000000000000..c81a14ea69550839b5f195056768bc5c3b673e58 --- /dev/null +++ b/service/ota/service.pkl @@ -0,0 +1,33 @@ +amends "../../config/Service.pkl" + +import "../../config/site.pkl" as site + +local host = module.container.http.hostname + +name = "OTA" +tagline = "Over-the-air installs for signed iOS builds" +launcher = false +stageIsolation = "fresh" + +secrets { ["upload_token"] {} } + +container { + build = "build" + readOnlyRoot = true + cpu = 100 + memory = 256 + + http { + containerPort = 8080 + subdomain = "ota" + checkPath = "/health" + } + + volumes { ["/data"] {} } + + env { + ["OTA_ROOT"] = "/data" + ["OTA_ORIGIN"] = "https://\(host)" + ["OTA_UPLOAD_TOKEN"] = "${secret.own.upload_token}" + } +} diff --git a/tools/ota-test.py b/tools/ota-test.py new file mode 100644 index 0000000000000000000000000000000000000000..9e430537266004a59b68f4573c12657b17846e2a --- /dev/null +++ b/tools/ota-test.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +import importlib.util +import io +import os +from pathlib import Path +import plistlib +import shutil +import tempfile +import threading +import unittest +import urllib.error +import urllib.request +import zipfile + +REPO = Path(__file__).resolve().parents[1] +root = tempfile.TemporaryDirectory() +os.environ.update(OTA_ROOT=root.name, OTA_ORIGIN="https://ota.example", OTA_UPLOAD_TOKEN="secret") + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +service = load("ota_service", REPO / "service/ota/build/ota.py") +client = load("ota_client", REPO / "tools/ota.py") + + +def ipa(devices=None): + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as archive: + archive.writestr("Payload/App.app/Info.plist", plistlib.dumps({ + "CFBundleIdentifier": "net.example.app", "CFBundleName": "App", "CFBundleDisplayName": "Fancy ", "CFBundleShortVersionString": "1.2", + })) + if devices is not None: + archive.writestr("Payload/App.app/embedded.mobileprovision", b"\x30\x82cms" + plistlib.dumps({"ProvisionedDevices": devices}) + b"\x00sig") + return buffer.getvalue() + + +class Service(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.server = service.http.server.ThreadingHTTPServer(("127.0.0.1", 0), service.Handler) + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + cls.base = f"http://127.0.0.1:{cls.server.server_port}" + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + + def setUp(self): + for path in Path(root.name).iterdir(): + shutil.rmtree(path) + + def request(self, path, data=None, token="secret", method=None): + request = urllib.request.Request(self.base + path, data=data, method=method or ("PUT" if data is not None else "GET")) + if token: + request.add_header("Authorization", f"Bearer {token}") + return urllib.request.urlopen(request) + + def test_upload_is_authenticated_and_validated(self): + for token, body, status in ((None, ipa(), 401), ("wrong", ipa(), 401), ("secret", b"not a zip", 400)): + with self.subTest(token=token, status=status), self.assertRaises(urllib.error.HTTPError) as error: + self.request("/builds", body, token) + self.assertEqual(error.exception.code, status) + self.assertEqual([path for path in Path(root.name).iterdir()], []) + + def test_install_link_serves_page_manifest_and_ipa_then_prunes(self): + body = ipa() + link = self.request("/builds", body).read().decode().strip() + build = link.rsplit("/", 1)[1] + page = self.request(f"/{build}").read().decode() + self.assertIn("Fancy <App>", page) + self.assertIn(f"itms-services://?action=download-manifest&url=https://ota.example/{build}/manifest.plist", page) + manifest = plistlib.loads(self.request(f"/{build}/manifest.plist").read())["items"][0] + self.assertEqual(manifest["assets"][0]["url"], f"https://ota.example/{build}/app.ipa") + self.assertEqual(manifest["metadata"]["bundle-identifier"], "net.example.app") + self.assertEqual(self.request(f"/{build}/app.ipa").read(), body) + for _ in range(service.KEEP): + self.request("/builds", body) + with self.assertRaises(urllib.error.HTTPError) as error: + self.request(f"/{build}") + self.assertEqual(error.exception.code, 404) + self.assertEqual(len(list(Path(root.name).iterdir())), service.KEEP) + + +class Profile(unittest.TestCase): + def read(self, data): + with tempfile.NamedTemporaryFile(suffix=".ipa") as file: + file.write(data) + file.flush() + return client.provisioned(file.name) + + def test_reads_devices_from_the_signed_profile_and_reports_none_when_unsigned(self): + self.assertEqual(self.read(ipa(["00008110-001234567890401E"]))["ProvisionedDevices"], ["00008110-001234567890401E"]) + self.assertIsNone(self.read(ipa())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ota.py b/tools/ota.py new file mode 100755 index 0000000000000000000000000000000000000000..2bc6af74d87d5246d24582febaee18e9684cd7eb --- /dev/null +++ b/tools/ota.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Upload a signed IPA for one device to the OTA service and print its install link.""" +import argparse +import plistlib +import re +import subprocess +import sys +import zipfile + +from deploy import ssh + +SERVER = "https://ota.paperclover.net" +PROFILE = re.compile(r"Payload/[^/]+\.app/embedded\.mobileprovision\Z") + + +def provisioned(ipa): + with zipfile.ZipFile(ipa) as archive: + name = next((name for name in archive.namelist() if PROFILE.fullmatch(name)), None) + if name is None: + return None + signed = archive.read(name) + return plistlib.loads(signed[signed.index(b"") + 8]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("ipa") + parser.add_argument("udid") + parser.add_argument("--server", default=SERVER) + args = parser.parse_args() + + profile = provisioned(args.ipa) + if profile is None: + sys.exit(f"{args.ipa} has no embedded.mobileprovision; sign it with a profile that includes the device") + udid = args.udid.replace("-", "").upper() + if not profile.get("ProvisionsAllDevices") and udid not in {device.replace("-", "").upper() for device in profile.get("ProvisionedDevices", [])}: + sys.exit(f"the profile in {args.ipa} does not include {args.udid}; register the device and re-sign") + + token = ssh("NOMAD_TOKEN=$(cat /var/lib/snowglobe/nomad.token) nomad var get -item=upload_token nomad/jobs/ota", capture=True).stdout.strip() + subprocess.run( + ["curl", "--fail-with-body", "--progress-bar", "--config", "-", "--upload-file", args.ipa, f"{args.server}/builds"], + input=f'header = "Authorization: Bearer {token}"\n', text=True, check=True, + ) + + +if __name__ == "__main__": + main()