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(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