| author | |
| committer | |
| log | 3f653a2992f3c98b9b144cb41d673c86bbfc49d6 |
| tree | 4ad7a37dcbcb5af46aa11f2e08a175aafcbae364 |
| parent | aef167536486f4539104b503ed9986cd979a3ebc |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Adds the ota service (token-authenticated PUT /builds, unguessable install
pages and manifests) and tools/ota.py, which checks the IPA's profile covers
the device and uploads it.
Assisted-by: claude-sonnet-5.55 files changed, 295 insertions(+), 0 deletions(-)
service/ota/build/Dockerfile created+3| ... | @@ -0,0 +1,3 @@ | ||
| 1 | FROM docker.io/library/python:3.13-slim@sha256:37134a49d21d2120e4c4d73bb76f8a4ab9aef31f096f7ec2ead48c2feead4332 | ||
| 2 | COPY ota.py /app/ota.py | ||
| 3 | CMD ["python3", "-u", "/app/ota.py"] | ||
service/ota/build/ota.py created+110| ... | @@ -0,0 +1,110 @@ | ||
| 1 | #!/usr/bin/env python3 | ||
| 2 | import hmac | ||
| 3 | import html | ||
| 4 | from http import HTTPStatus | ||
| 5 | import http.server | ||
| 6 | import os | ||
| 7 | from pathlib import Path | ||
| 8 | import plistlib | ||
| 9 | import re | ||
| 10 | import shutil | ||
| 11 | import tempfile | ||
| 12 | import zipfile | ||
| 13 | |||
| 14 | ROOT = Path(os.environ["OTA_ROOT"]) | ||
| 15 | ORIGIN = os.environ["OTA_ORIGIN"] | ||
| 16 | TOKEN = os.environ["OTA_UPLOAD_TOKEN"].encode() | ||
| 17 | KEEP = 20 | ||
| 18 | MAX_IPA = 2 * 1024**3 | ||
| 19 | BUILD = re.compile(r"/([0-9a-f]{32})(/manifest\.plist|/app\.ipa)?\Z") | ||
| 20 | APP_PLIST = re.compile(r"Payload/[^/]+\.app/Info\.plist\Z") | ||
| 21 | |||
| 22 | |||
| 23 | def app_info(ipa): | ||
| 24 | with zipfile.ZipFile(ipa) as archive: | ||
| 25 | return plistlib.loads(archive.read(next(name for name in archive.namelist() if APP_PLIST.fullmatch(name)))) | ||
| 26 | |||
| 27 | |||
| 28 | def title(info): | ||
| 29 | return info.get("CFBundleDisplayName") or info["CFBundleName"] | ||
| 30 | |||
| 31 | |||
| 32 | def version(info): | ||
| 33 | return info["CFBundleShortVersionString"] | ||
| 34 | |||
| 35 | |||
| 36 | class Handler(http.server.BaseHTTPRequestHandler): | ||
| 37 | protocol_version = "HTTP/1.1" | ||
| 38 | |||
| 39 | def send(self, status, content_type, body): | ||
| 40 | self.send_response(status) | ||
| 41 | self.send_header("Content-Type", content_type) | ||
| 42 | self.send_header("Content-Length", str(len(body))) | ||
| 43 | self.end_headers() | ||
| 44 | self.wfile.write(body) | ||
| 45 | |||
| 46 | def do_GET(self): | ||
| 47 | if self.path == "/health": | ||
| 48 | return self.send(HTTPStatus.OK, "text/plain", b"ok") | ||
| 49 | match = BUILD.fullmatch(self.path) | ||
| 50 | ipa = ROOT / match[1] / "app.ipa" if match else None | ||
| 51 | if not ipa or not ipa.is_file(): | ||
| 52 | return self.send(HTTPStatus.NOT_FOUND, "text/plain", b"not found") | ||
| 53 | if match[2] == "/app.ipa": | ||
| 54 | self.send_response(HTTPStatus.OK) | ||
| 55 | self.send_header("Content-Type", "application/octet-stream") | ||
| 56 | self.send_header("Content-Length", str(ipa.stat().st_size)) | ||
| 57 | self.end_headers() | ||
| 58 | with ipa.open("rb") as source: | ||
| 59 | shutil.copyfileobj(source, self.wfile, 1 << 20) | ||
| 60 | return | ||
| 61 | info = app_info(ipa) | ||
| 62 | base = f"{ORIGIN}/{match[1]}" | ||
| 63 | if match[2]: | ||
| 64 | return self.send(HTTPStatus.OK, "text/xml", plistlib.dumps({"items": [{ | ||
| 65 | "assets": [{"kind": "software-package", "url": f"{base}/app.ipa"}], | ||
| 66 | "metadata": {"bundle-identifier": info["CFBundleIdentifier"], "bundle-version": version(info), "kind": "software", "title": title(info)}, | ||
| 67 | }]})) | ||
| 68 | install = html.escape(f"itms-services://?action=download-manifest&url={base}/manifest.plist") | ||
| 69 | self.send(HTTPStatus.OK, "text/html; charset=utf-8", f"""<!doctype html> | ||
| 70 | <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | ||
| 71 | <title>{html.escape(title(info))}</title> | ||
| 72 | <style>body{{font:18px system-ui;max-width:24em;margin:20vh auto;padding:0 1em;text-align:center}}a{{display:inline-block;margin-top:1em;padding:.7em 2em;border-radius:2em;background:#07f;color:#fff;text-decoration:none}}</style> | ||
| 73 | <h1>{html.escape(title(info))}</h1><p>{html.escape(version(info))}</p><a href="{install}">Install</a> | ||
| 74 | """.encode()) | ||
| 75 | |||
| 76 | def do_PUT(self): | ||
| 77 | if self.path != "/builds" or not hmac.compare_digest(self.headers.get("Authorization", "").encode(), b"Bearer " + TOKEN): | ||
| 78 | self.close_connection = True | ||
| 79 | return self.send(HTTPStatus.UNAUTHORIZED, "text/plain", b"unauthorized") | ||
| 80 | size = int(self.headers.get("Content-Length", -1)) | ||
| 81 | if not 0 < size <= MAX_IPA: | ||
| 82 | self.close_connection = True | ||
| 83 | return self.send(HTTPStatus.LENGTH_REQUIRED, "text/plain", b"a Content-Length up to 2 GiB is required") | ||
| 84 | ROOT.mkdir(exist_ok=True) | ||
| 85 | with tempfile.NamedTemporaryFile(dir=ROOT, prefix=".upload-", delete=False) as upload: | ||
| 86 | try: | ||
| 87 | remaining = size | ||
| 88 | while remaining: | ||
| 89 | chunk = self.rfile.read(min(1 << 20, remaining)) | ||
| 90 | if not chunk: | ||
| 91 | raise ConnectionError("upload ended early") | ||
| 92 | upload.write(chunk) | ||
| 93 | remaining -= len(chunk) | ||
| 94 | upload.flush() | ||
| 95 | app_info(upload.name) | ||
| 96 | except (ConnectionError, zipfile.BadZipFile, StopIteration, KeyError, plistlib.InvalidFileException): | ||
| 97 | os.unlink(upload.name) | ||
| 98 | self.close_connection = True | ||
| 99 | return self.send(HTTPStatus.BAD_REQUEST, "text/plain", b"not an IPA with an app Info.plist") | ||
| 100 | build = os.urandom(16).hex() | ||
| 101 | (ROOT / build).mkdir() | ||
| 102 | os.chmod(upload.name, 0o644) | ||
| 103 | os.replace(upload.name, ROOT / build / "app.ipa") | ||
| 104 | for old in sorted((path for path in ROOT.glob("*/") if BUILD.fullmatch("/" + path.name)), key=lambda path: path.stat().st_mtime)[:-KEEP]: | ||
| 105 | shutil.rmtree(old) | ||
| 106 | self.send(HTTPStatus.CREATED, "text/plain", f"{ORIGIN}/{build}\n".encode()) | ||
| 107 | |||
| 108 | |||
| 109 | if __name__ == "__main__": | ||
| 110 | http.server.ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever() | ||
service/ota/service.pkl created+33| ... | @@ -0,0 +1,33 @@ | ||
| 1 | amends "../../config/Service.pkl" | ||
| 2 | |||
| 3 | import "../../config/site.pkl" as site | ||
| 4 | |||
| 5 | local host = module.container.http.hostname | ||
| 6 | |||
| 7 | name = "OTA" | ||
| 8 | tagline = "Over-the-air installs for signed iOS builds" | ||
| 9 | launcher = false | ||
| 10 | stageIsolation = "fresh" | ||
| 11 | |||
| 12 | secrets { ["upload_token"] {} } | ||
| 13 | |||
| 14 | container { | ||
| 15 | build = "build" | ||
| 16 | readOnlyRoot = true | ||
| 17 | cpu = 100 | ||
| 18 | memory = 256 | ||
| 19 | |||
| 20 | http { | ||
| 21 | containerPort = 8080 | ||
| 22 | subdomain = "ota" | ||
| 23 | checkPath = "/health" | ||
| 24 | } | ||
| 25 | |||
| 26 | volumes { ["/data"] {} } | ||
| 27 | |||
| 28 | env { | ||
| 29 | ["OTA_ROOT"] = "/data" | ||
| 30 | ["OTA_ORIGIN"] = "https://\(host)" | ||
| 31 | ["OTA_UPLOAD_TOKEN"] = "${secret.own.upload_token}" | ||
| 32 | } | ||
| 33 | } | ||
tools/ota-test.py created+102| ... | @@ -0,0 +1,102 @@ | ||
| 1 | #!/usr/bin/env python3 | ||
| 2 | import importlib.util | ||
| 3 | import io | ||
| 4 | import os | ||
| 5 | from pathlib import Path | ||
| 6 | import plistlib | ||
| 7 | import shutil | ||
| 8 | import tempfile | ||
| 9 | import threading | ||
| 10 | import unittest | ||
| 11 | import urllib.error | ||
| 12 | import urllib.request | ||
| 13 | import zipfile | ||
| 14 | |||
| 15 | REPO = Path(__file__).resolve().parents[1] | ||
| 16 | root = tempfile.TemporaryDirectory() | ||
| 17 | os.environ.update(OTA_ROOT=root.name, OTA_ORIGIN="https://ota.example", OTA_UPLOAD_TOKEN="secret") | ||
| 18 | |||
| 19 | |||
| 20 | def load(name, path): | ||
| 21 | spec = importlib.util.spec_from_file_location(name, path) | ||
| 22 | module = importlib.util.module_from_spec(spec) | ||
| 23 | spec.loader.exec_module(module) | ||
| 24 | return module | ||
| 25 | |||
| 26 | |||
| 27 | service = load("ota_service", REPO / "service/ota/build/ota.py") | ||
| 28 | client = load("ota_client", REPO / "tools/ota.py") | ||
| 29 | |||
| 30 | |||
| 31 | def ipa(devices=None): | ||
| 32 | buffer = io.BytesIO() | ||
| 33 | with zipfile.ZipFile(buffer, "w") as archive: | ||
| 34 | archive.writestr("Payload/App.app/Info.plist", plistlib.dumps({ | ||
| 35 | "CFBundleIdentifier": "net.example.app", "CFBundleName": "App", "CFBundleDisplayName": "Fancy <App>", "CFBundleShortVersionString": "1.2", | ||
| 36 | })) | ||
| 37 | if devices is not None: | ||
| 38 | archive.writestr("Payload/App.app/embedded.mobileprovision", b"\x30\x82cms" + plistlib.dumps({"ProvisionedDevices": devices}) + b"\x00sig") | ||
| 39 | return buffer.getvalue() | ||
| 40 | |||
| 41 | |||
| 42 | class Service(unittest.TestCase): | ||
| 43 | @classmethod | ||
| 44 | def setUpClass(cls): | ||
| 45 | cls.server = service.http.server.ThreadingHTTPServer(("127.0.0.1", 0), service.Handler) | ||
| 46 | threading.Thread(target=cls.server.serve_forever, daemon=True).start() | ||
| 47 | cls.base = f"http://127.0.0.1:{cls.server.server_port}" | ||
| 48 | |||
| 49 | @classmethod | ||
| 50 | def tearDownClass(cls): | ||
| 51 | cls.server.shutdown() | ||
| 52 | |||
| 53 | def setUp(self): | ||
| 54 | for path in Path(root.name).iterdir(): | ||
| 55 | shutil.rmtree(path) | ||
| 56 | |||
| 57 | def request(self, path, data=None, token="secret", method=None): | ||
| 58 | request = urllib.request.Request(self.base + path, data=data, method=method or ("PUT" if data is not None else "GET")) | ||
| 59 | if token: | ||
| 60 | request.add_header("Authorization", f"Bearer {token}") | ||
| 61 | return urllib.request.urlopen(request) | ||
| 62 | |||
| 63 | def test_upload_is_authenticated_and_validated(self): | ||
| 64 | for token, body, status in ((None, ipa(), 401), ("wrong", ipa(), 401), ("secret", b"not a zip", 400)): | ||
| 65 | with self.subTest(token=token, status=status), self.assertRaises(urllib.error.HTTPError) as error: | ||
| 66 | self.request("/builds", body, token) | ||
| 67 | self.assertEqual(error.exception.code, status) | ||
| 68 | self.assertEqual([path for path in Path(root.name).iterdir()], []) | ||
| 69 | |||
| 70 | def test_install_link_serves_page_manifest_and_ipa_then_prunes(self): | ||
| 71 | body = ipa() | ||
| 72 | link = self.request("/builds", body).read().decode().strip() | ||
| 73 | build = link.rsplit("/", 1)[1] | ||
| 74 | page = self.request(f"/{build}").read().decode() | ||
| 75 | self.assertIn("Fancy &lt;App&gt;", page) | ||
| 76 | self.assertIn(f"itms-services://?action=download-manifest&amp;url=https://ota.example/{build}/manifest.plist", page) | ||
| 77 | manifest = plistlib.loads(self.request(f"/{build}/manifest.plist").read())["items"][0] | ||
| 78 | self.assertEqual(manifest["assets"][0]["url"], f"https://ota.example/{build}/app.ipa") | ||
| 79 | self.assertEqual(manifest["metadata"]["bundle-identifier"], "net.example.app") | ||
| 80 | self.assertEqual(self.request(f"/{build}/app.ipa").read(), body) | ||
| 81 | for _ in range(service.KEEP): | ||
| 82 | self.request("/builds", body) | ||
| 83 | with self.assertRaises(urllib.error.HTTPError) as error: | ||
| 84 | self.request(f"/{build}") | ||
| 85 | self.assertEqual(error.exception.code, 404) | ||
| 86 | self.assertEqual(len(list(Path(root.name).iterdir())), service.KEEP) | ||
| 87 | |||
| 88 | |||
| 89 | class Profile(unittest.TestCase): | ||
| 90 | def read(self, data): | ||
| 91 | with tempfile.NamedTemporaryFile(suffix=".ipa") as file: | ||
| 92 | file.write(data) | ||
| 93 | file.flush() | ||
| 94 | return client.provisioned(file.name) | ||
| 95 | |||
| 96 | def test_reads_devices_from_the_signed_profile_and_reports_none_when_unsigned(self): | ||
| 97 | self.assertEqual(self.read(ipa(["00008110-001234567890401E"]))["ProvisionedDevices"], ["00008110-001234567890401E"]) | ||
| 98 | self.assertIsNone(self.read(ipa())) | ||
| 99 | |||
| 100 | |||
| 101 | if __name__ == "__main__": | ||
| 102 | unittest.main() | ||
tools/ota.py created+47| ... | @@ -0,0 +1,47 @@ | ||
| 1 | #!/usr/bin/env python3 | ||
| 2 | """Upload a signed IPA for one device to the OTA service and print its install link.""" | ||
| 3 | import argparse | ||
| 4 | import plistlib | ||
| 5 | import re | ||
| 6 | import subprocess | ||
| 7 | import sys | ||
| 8 | import zipfile | ||
| 9 | |||
| 10 | from deploy import ssh | ||
| 11 | |||
| 12 | SERVER = "https://ota.paperclover.net" | ||
| 13 | PROFILE = re.compile(r"Payload/[^/]+\.app/embedded\.mobileprovision\Z") | ||
| 14 | |||
| 15 | |||
| 16 | def provisioned(ipa): | ||
| 17 | with zipfile.ZipFile(ipa) as archive: | ||
| 18 | name = next((name for name in archive.namelist() if PROFILE.fullmatch(name)), None) | ||
| 19 | if name is None: | ||
| 20 | return None | ||
| 21 | signed = archive.read(name) | ||
| 22 | return plistlib.loads(signed[signed.index(b"<?xml"):signed.rindex(b"</plist>") + 8]) | ||
| 23 | |||
| 24 | |||
| 25 | def main(): | ||
| 26 | parser = argparse.ArgumentParser(description=__doc__) | ||
| 27 | parser.add_argument("ipa") | ||
| 28 | parser.add_argument("udid") | ||
| 29 | parser.add_argument("--server", default=SERVER) | ||
| 30 | args = parser.parse_args() | ||
| 31 | |||
| 32 | profile = provisioned(args.ipa) | ||
| 33 | if profile is None: | ||
| 34 | sys.exit(f"{args.ipa} has no embedded.mobileprovision; sign it with a profile that includes the device") | ||
| 35 | udid = args.udid.replace("-", "").upper() | ||
| 36 | if not profile.get("ProvisionsAllDevices") and udid not in {device.replace("-", "").upper() for device in profile.get("ProvisionedDevices", [])}: | ||
| 37 | sys.exit(f"the profile in {args.ipa} does not include {args.udid}; register the device and re-sign") | ||
| 38 | |||
| 39 | token = ssh("NOMAD_TOKEN=$(cat /var/lib/snowglobe/nomad.token) nomad var get -item=upload_token nomad/jobs/ota", capture=True).stdout.strip() | ||
| 40 | subprocess.run( | ||
| 41 | ["curl", "--fail-with-body", "--progress-bar", "--config", "-", "--upload-file", args.ipa, f"{args.server}/builds"], | ||
| 42 | input=f'header = "Authorization: Bearer {token}"\n', text=True, check=True, | ||
| 43 | ) | ||
| 44 | |||
| 45 | |||
| 46 | if __name__ == "__main__": | ||
| 47 | main() | ||