From 2d15eb4b9805c7c82cebff191e77ce7d9347fd64 Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 10:09:21 +0000 Subject: [PATCH 1/3] Add verified latest-build Web Serial firmware matrix Publish pinned browser runtime and trusted main artifacts through Pages. Link each image to immutable source, actual config, manifest and build attempt. Refuse stale builds, wrong devices and unsupported security states. Assisted-by: Briar --- .github/workflows/offline-tests.yml | 2 + .github/workflows/pages.yml | 23 ++- README.md | 10 + THIRD_PARTY.md | 9 + docs/browser-firmware.md | 77 ++++++++ firmware_site.py | 288 ++++++++++++++++++++++++++++ package.json | 1 + site/firmware-targets.json | 25 +++ site/flasher.js | 123 ++++++++++++ site/index.html | 3 +- site/installer.js | 123 ++++++++++++ site/style.css | 1 + tests/installer.test.mjs | 90 +++++++++ tests/test_browser_site.py | 6 +- tests/test_firmware_site.py | 150 +++++++++++++++ 15 files changed, 924 insertions(+), 7 deletions(-) create mode 100644 docs/browser-firmware.md create mode 100644 firmware_site.py create mode 100644 package.json create mode 100644 site/firmware-targets.json create mode 100644 site/flasher.js create mode 100644 site/installer.js create mode 100644 tests/installer.test.mjs create mode 100644 tests/test_firmware_site.py diff --git a/.github/workflows/offline-tests.yml b/.github/workflows/offline-tests.yml index 30fdb1d..2564d88 100644 --- a/.github/workflows/offline-tests.yml +++ b/.github/workflows/offline-tests.yml @@ -26,3 +26,5 @@ jobs: run: python3 -m compileall -q run.py firmware_test.py transport_test.py certificate_test.py server_test.py browser_test.py websocket_tls.py simulator_test.py ci_runner.py tests - name: Run offline tests run: python3 -m unittest discover -s tests -v + - name: Test browser programming without opening a device + run: node --test tests/installer.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index f7e99d1..2ab3e1e 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -2,8 +2,12 @@ name: Publish browser test hub on: push: branches: [main] - paths: ['site/**', '.github/workflows/pages.yml', 'ci_runner.py'] + paths: ['site/**', 'firmware_site.py', '.github/workflows/pages.yml', 'ci_runner.py'] workflow_dispatch: + workflow_run: + workflows: ['ESP32 test images', 'ESP8266 D1 mini prototype'] + branches: [main] + types: [completed] permissions: contents: read actions: read @@ -12,7 +16,12 @@ concurrency: cancel-in-progress: false jobs: pages: - if: github.repository == 'DynamicDevices/pqc-testing' && github.ref == 'refs/heads/main' && github.actor == 'ajlennon' + if: >- + github.repository == 'DynamicDevices/pqc-testing' && github.ref == 'refs/heads/main' && github.actor == 'ajlennon' && + (github.event_name != 'workflow_run' || + (github.event.workflow_run.head_repository.full_name == github.repository && + github.event.workflow_run.head_branch == 'main' && github.event.workflow_run.actor.login == 'ajlennon' && + (github.event.workflow_run.event == 'push' || github.event.workflow_run.event == 'workflow_dispatch'))) runs-on: [self-hosted, Linux, X64, dd-esl-proxmox] timeout-minutes: 15 permissions: @@ -32,11 +41,17 @@ jobs: GH_TOKEN: ${{ github.token }} run: python3 ci_runner.py pages - name: Check the static public artifact - run: python3 -m unittest discover -s tests -p test_browser_site.py -v + run: | + python3 -m unittest discover -s tests -p 'test_*site.py' -v + node --test tests/installer.test.mjs + - name: Publish latest verified firmware packages and pinned browser runtime + env: + GH_TOKEN: ${{ github.token }} + run: python3 firmware_site.py --output build-site - uses: actions/configure-pages@45bfe0192ca1faeb007ade9deae92b16b8254a0d # v6, Node24 - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5; pinned upload-artifact v7, Node24 with: - path: site + path: build-site - name: Deploy protected-main static files only id: deployment uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1, Node24 diff --git a/README.md b/README.md index 0549c8b..e4457a9 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,16 @@ not implement Zephyr TLS. See [reproduction instructions](docs/reproduce.md) for setup, test order and limitations. +## Program development boards from the browser + +The [GitHub Pages hub](https://dynamicdevices.github.io/pqc-testing/) includes a +per-board/profile **Program latest** matrix using Web Serial. Each available +image links to its exact source revision, compiled configuration, build manifest +and CI run. A failed, pending, stale or unavailable build cannot silently fall +back to an older image. See [installer details](docs/browser-firmware.md), including +supported browsers, development-board/data-loss warnings and the unavailable +D1 mini package. A verified flash is not a hardware or PQC-TLS test pass. + ## Live browser tests and public demo login Open the [GitHub Pages test hub](https://dynamicdevices.github.io/pqc-testing/) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 53759d2..3577777 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -4,6 +4,15 @@ The MIT licence at the repository root covers Dynamic Devices' original code and documentation. It does not relicense dependencies or their source code. Third-party source is fetched separately and excluded from this repository. +The browser installer self-hosts integrity-pinned runtime packages: + +- [esptool-js](https://github.com/espressif/esptool-js), 0.7.1, Apache-2.0. +- [@noble/hashes](https://github.com/paulmillr/noble-hashes), 2.4.0, MIT. + +Their complete upstream `LICENSE` files are published at +`vendor/esptool-js/LICENSE` and `vendor/noble/LICENSE` beside the site. Package +tarball URLs and SHA-512 digests are recorded in `firmware_site.py`. + The experiments use: - [Zephyr](https://github.com/zephyrproject-rtos/zephyr), commit diff --git a/docs/browser-firmware.md b/docs/browser-firmware.md new file mode 100644 index 0000000..787b0a2 --- /dev/null +++ b/docs/browser-firmware.md @@ -0,0 +1,77 @@ +# Browser firmware installer + +The GitHub Pages test hub programs development ESP boards over Web Serial. +Choose **Program latest**, then select the board's USB serial port. A data cable +and an OS-supported USB/serial driver are required. Desktop Chrome or Edge is +recommended. Safari/iOS are unsupported; other browsers need Web Serial support. +HTTPS (or localhost for a preview) is required. The browser permission chooser +cannot be automated away. Close other serial tools before programming. + +## Matrix and source inspection + +ESP32-DevKitC, ESP32-S3-DevKitC and ESP32-C3-DevKitM each have baseline boot and +ML-DSA-44 signature-verification profiles. These are **not TLS firmware** and +have not yet passed physical-board acceptance. A chip-family match cannot prove +the exact board model or pin layout: select the matching physical board. + +Each available image links to its immutable source commit, the actual compiled +`zephyr.config`, its build manifest (including upstream revisions and SHA-256 +digests), and the exact GitHub Actions run attempt. Configuration and notices are +copied from that same verified artifact, never reconstructed from current main. +Notices sit beside the image; see `LICENSE` and `THIRD_PARTY.md` in its directory. + +LOLIN D1 mini hybrid HTTPS remains disabled until its target build, complete +multi-segment flash layout and wolfSSL/SDK binary-distribution and corresponding +source checks are complete. No placeholder binary is offered. + +## What “latest” means + +On a trusted main firmware workflow completion, Pages automatically regenerates +the matrix from that workflow's newest main run. It does not choose an older +successful run when the newest run is pending, failed or unavailable. Publisher +checks bind all required jobs to organisation runner139, group1. PR artifacts +and forks are never offered. The publisher executes no downloaded artifact code. + +At a user's click, the browser fetches the catalogue without its cache, queries +GitHub for the newest main run/attempt, and checks for relevant source changes +since that build. It downloads one versioned snapshot and verifies every image's +SHA-256 before opening the serial port. After chip/security/flash-capacity checks, +it repeats the freshness checks immediately before writing. A newer build or +source revision stops programming until a fresh successful build is published. +GitHub API errors, offline operation, an incomplete source comparison and rate +limits fail closed. Anonymous GitHub API limits may require waiting before retry. + +Latest is defined at the final pre-write check. A build arriving during the +write does not replace segments mid-write or trigger another flash. There is no +automatic background programming. Source comparisons accept unrelated newer main +changes (such as documentation) but refuse changed build inputs. + +## Flashing and verification + +The installer refuses unsupported secure-boot/encrypted boards and never changes +security settings, burns fuses or requests full-chip erase. It overwrites the +selected image sectors, which can destroy existing firmware/data in those sectors; +this is not a backup tool. Flash size/frequency/mode headers are kept unchanged. +SHA-256 verifies the published download; stub MD5 readback verifies transfer, not +publisher authenticity. Trust rests on the HTTPS site, repository and build +controls, not MD5. Runtime packages are pinned by SHA-512 and self-hosted with +their licences: esptool-js0.7.1 (Apache-2.0), @noble/hashes2.4.0 (MIT). + +After programming, open **Serial console · 115200 baud** to inspect firmware +results. The bounded log lives only in this tab, with no storage or upload. Do not +print secrets. A verified flash is not a boot, signature-test or PQC-TLS pass. + +## Reproduction without hardware + +```sh +python3 -m unittest discover -s tests -v +node --test tests/installer.test.mjs +python3 firmware_site.py --offline --output /tmp/pqc-site-preview +python3 -m http.server 8000 --directory /tmp/pqc-site-preview +``` + +The offline preview downloads only integrity-pinned browser dependencies, offers +no firmware, and never opens a device. Production publication runs on the admitted +DD runner via `.github/workflows/pages.yml`; no local firmware compilation occurs. + +Assisted-by: Briar diff --git a/firmware_site.py b/firmware_site.py new file mode 100644 index 0000000..55a9ab1 --- /dev/null +++ b/firmware_site.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Publish verified latest-main firmware with the static site, never compile it. + +Artifacts are data: no extracted script is executed. Failed/pending/newer builds +produce unavailable entries, not silent last-good fallback. Assisted-by: Briar. +""" +import argparse +import base64 +from datetime import datetime, timezone +import hashlib +import io +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import tarfile +import urllib.error +import urllib.parse +import urllib.request +import zipfile + +ROOT = Path(__file__).resolve().parent +REPO = "DynamicDevices/pqc-testing" +PACKAGES = { + "esptool-js": ("https://registry.npmjs.org/esptool-js/-/esptool-js-0.7.1.tgz", + "vw1isT5ROHgpRmMG3y6B81dceeZ7O1WhF1x05qFbAlH8N0N/pOQqODzJLA+36lCbOXCw06iA4CWctyrQQ7VeSA=="), + "noble": ("https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", + "X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="), +} + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def safe_path(name): + path = PurePosixPath(name) + if path.is_absolute() or ".." in path.parts or "\\" in name or not path.parts: + raise ValueError("Unsafe archive path") + return path + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +class GitHub: + def __init__(self, token): + self.token = token + + def request(self, path): + request = urllib.request.Request("https://api.github.com/repos/" + REPO + "/" + path, + headers={"Authorization": "Bearer " + self.token, + "Accept": "application/vnd.github+json"}) + return urllib.request.urlopen(request, timeout=30) + + def json(self, path): + with self.request(path) as response: + return json.load(response) + + def archive(self, artifact): + # Never forward a GitHub token to a redirected object-storage host. + request = urllib.request.Request( + f"https://api.github.com/repos/{REPO}/actions/artifacts/{artifact['id']}/zip", + headers={"Authorization": "Bearer " + self.token}) + try: + with urllib.request.build_opener(NoRedirect()).open(request, timeout=30) as response: + data = response.read() + except urllib.error.HTTPError as error: + if error.code != 302: + raise + url = error.headers["Location"] + parsed = urllib.parse.urlparse(url) + if parsed.scheme != "https" or not parsed.hostname or not parsed.hostname.endswith( + (".blob.core.windows.net", ".actions.githubusercontent.com", ".githubusercontent.com")): + raise ValueError("Unexpected artifact storage redirect") from None + with urllib.request.urlopen(url, timeout=60) as response: + data = response.read() + expected = artifact.get("digest", "") + if expected != "sha256:" + sha256(data): + raise ValueError("Missing/mismatched GitHub artifact digest") + return data + + +def validate_run(run, workflow_id): + if (run.get("workflow_id") != workflow_id or run.get("head_branch") != "main" or + run.get("head_repository", {}).get("full_name") != REPO or + run.get("actor", {}).get("login") != "ajlennon" or + run.get("event") not in ("push", "workflow_dispatch") or + not re.fullmatch(r"[a-f0-9]{40}", run.get("head_sha", ""))): + raise ValueError("Untrusted workflow/source identity") + if run.get("status") != "completed" or run.get("conclusion") != "success": + raise ValueError("Latest main build is " + run.get("status", "unknown") + "/" + str(run.get("conclusion"))) + + +def check_fresh(compare, inputs): + if compare.get("status") not in ("identical", "ahead"): + raise ValueError("Build source is not an ancestor of current main") + files = compare.get("files") + # GitHub compare exposes at most 300 files. A saturated result is incomplete + # evidence, not permission to assume omitted firmware inputs are unchanged. + if not isinstance(files, list) or len(files) >= 300: + raise ValueError("Cannot establish complete source freshness") + for file in files: + names = [file.get("filename", ""), file.get("previous_filename", "")] + if any(name.startswith(prefix) for name in names for prefix in inputs): + raise ValueError("Newer firmware source exists; await its successful main build") + + +def latest(api, channel): + workflow = api.json("actions/workflows/" + channel["workflow"]) + runs = api.json(f"actions/workflows/{workflow['id']}/runs?branch=main&per_page=1")["workflow_runs"] + if not runs: + raise ValueError("No main firmware build exists") + run = runs[0] + validate_run(run, workflow["id"]) + compare = api.json("compare/" + run["head_sha"] + "...main") + check_fresh(compare, channel["inputs"]) + jobs = api.json(f"actions/runs/{run['id']}/jobs?filter=latest&per_page=100")["jobs"] + for name in channel["jobs"]: + matches = [job for job in jobs if job.get("name") == name] + if len(matches) != 1 or any(matches[0].get(k) != v for k, v in { + "status": "completed", "conclusion": "success", "runner_id": 139, + "runner_name": "dd-esl-proxmox", "runner_group_id": 1}.items()): + raise ValueError("Missing or untrusted successful runner job: " + name) + return run + + +def image_from_archive(data, target, head): + with zipfile.ZipFile(io.BytesIO(data)) as archive: + names = archive.namelist() + if len(set(names)) != len(names): + raise ValueError("Duplicate artifact member") + for item in archive.infolist(): + safe_path(item.filename) + if (item.external_attr >> 16) & 0o170000 == 0o120000: + raise ValueError("Artifact symlinks are forbidden") + candidates = [name for name in names if name == target["profile"] + "/manifest.json" or + name.endswith("/" + target["profile"] + "/manifest.json")] + if len(candidates) != 1: + raise ValueError("Missing/ambiguous profile manifest") + prefix = candidates[0][:-len("manifest.json")] + manifest = json.loads(archive.read(candidates[0])) + for key, value in (("source_head", head), ("board", target["board"]), + ("profile", target["profile"]), ("chip", target["artifact_board"])): + if manifest.get(key) != value: + raise ValueError("Artifact identity mismatch: " + key) + if (manifest.get("boot_method") != "ESP_SIMPLE_BOOT; unsigned development image" or + int(manifest.get("flash_offset", "-1"), 0) != target["offset"]): + raise ValueError("Unsupported flash layout") + config = archive.read(prefix + "zephyr.config").decode() + flash = re.search(r"^CONFIG_FLASH_SIZE=(\d+)$", config, re.M) + if not flash or "CONFIG_ESP_SPIRAM=y" in config or "CONFIG_SPIRAM=y" in config: + raise ValueError("Unknown flash/PSRAM board configuration") + flash_bytes = int(flash[1]) * 1024 + image = archive.read(prefix + "zephyr.bin") + hashes = manifest.get("sha256", {}) + if sha256(archive.read(prefix + "zephyr.config")) != hashes.get("zephyr.config") or "CONFIG_ESP_SIMPLE_BOOT=y" not in config.splitlines(): + raise ValueError("Unverified/unsupported boot configuration") + if (sha256(image) != hashes.get("zephyr.bin") or len(image) != manifest.get("image_bytes") or + target["offset"] + len(image) > flash_bytes): + raise ValueError("Firmware checksum/size/bounds mismatch") + files = {"firmware.bin": image, "build-manifest.json": archive.read(candidates[0]), + "zephyr.config": archive.read(prefix + "zephyr.config")} + for name in names: + leaf = name[len(prefix):] if name.startswith(prefix) else "" + if leaf and "/" not in leaf and ("LICENSE" in leaf or "NOTICE" in leaf or leaf == "THIRD_PARTY.md"): + content = archive.read(name) + if sha256(content) != hashes.get(leaf): + raise ValueError("Licence notice checksum mismatch") + files[leaf] = content + if "LICENSE" not in files or "THIRD_PARTY.md" not in files: + raise ValueError("Missing distribution notices") + for dependency in ("ZEPHYR-", "HAL-ESPRESSIF-", "HAL-XTENSA-") + (("DILITHIUM-",) if target["profile"] == "mldsa44" else ()): + if not any(name.startswith(dependency) and "LICENSE" in name for name in files): + raise ValueError("Missing upstream licence: " + dependency) + return files, flash_bytes + + +def vendor(output, cache): + destination = output / "vendor" + destination.mkdir() + for name, (url, integrity) in PACKAGES.items(): + path = cache / (name + "-" + hashlib.sha256(integrity.encode()).hexdigest() + ".tgz") + if not path.exists(): + with urllib.request.urlopen(url, timeout=30) as response: + path.write_bytes(response.read()) + raw = path.read_bytes() + if base64.b64encode(hashlib.sha512(raw).digest()).decode() != integrity: + raise ValueError("Pinned JavaScript package integrity mismatch: " + name) + with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive: + for item in archive.getmembers(): + parts = safe_path(item.name).parts + if not item.isfile() or not parts or parts[0] != "package": + continue + relative = PurePosixPath(*parts[1:]) + if name == "esptool-js": + if str(relative) not in ("bundle.js", "LICENSE", "LICENSE.md", "README.md"): + continue + elif not (str(relative).endswith(".js") or "LICENSE" in str(relative)): + continue + dest = destination / name / str(relative) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(archive.extractfile(item).read()) + if not (destination / "esptool-js/bundle.js").is_file() or not (destination / "noble/legacy.js").is_file(): + raise ValueError("Pinned browser runtime files missing") + + +def catalogue(api, policy, output): + result = {"schema": 1, "repository": REPO, + "generated_at": datetime.now(timezone.utc).isoformat(), "builds": []} + channels, archives = {}, {} + for target in policy["targets"]: + entry = dict(target, available=False) + try: + if target.get("blocked"): + raise ValueError(target["blocked"]) + channel = target["channel"] + if channel not in channels: + try: + run = latest(api, policy["channels"][channel]) + artifacts = api.json(f"actions/runs/{run['id']}/artifacts?per_page=100")["artifacts"] + channels[channel] = (run, artifacts) + except Exception as error: + channels[channel] = error + if isinstance(channels[channel], Exception): + raise channels[channel] + run, artifacts = channels[channel] + name = "pqc-" + target["artifact_board"] + "-" + run["head_sha"] + matches = [a for a in artifacts if a["name"] == name and not a.get("expired")] + if len(matches) != 1: + raise ValueError("Missing/expired/ambiguous successful build artifact") + artifact = matches[0] + if artifact["id"] not in archives: + archives[artifact["id"]] = api.archive(artifact) + files, flash_bytes = image_from_archive(archives[artifact["id"]], target, run["head_sha"]) + relative = PurePosixPath("firmware", str(run["id"]), target["id"]) + dest = output / str(relative) + dest.mkdir(parents=True) + for leaf, content in files.items(): + (dest / leaf).write_bytes(content) + entry.update(available=True, run_id=run["id"], run_attempt=run["run_attempt"], run_url=run["html_url"], + source_head=run["head_sha"], workflow_id=run["workflow_id"], + flash_bytes=flash_bytes, hardware_tested=False, pqc_tls=False, + manifest=str(relative / "build-manifest.json"), + config=str(relative / "zephyr.config"), + parts=[{"path": str(relative / "firmware.bin"), "offset": target["offset"], + "size": len(files["firmware.bin"]), "sha256": sha256(files["firmware.bin"])}]) + except Exception as error: + # Do not expose signed storage URLs, tokens or raw infrastructure logs. + entry["reason"] = str(error) if isinstance(error, ValueError) else "Build metadata unavailable; no stale fallback" + result["builds"].append(entry) + (output / "firmware").mkdir(exist_ok=True) + (output / "firmware/catalog.json").write_text(json.dumps(result, indent=2) + "\n") + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=ROOT / "build-site") + parser.add_argument("--offline", action="store_true", help="Preview unavailable builds without GitHub credentials") + args = parser.parse_args() + if args.output.exists(): + raise SystemExit("Output already exists; use a fresh isolated output directory") + if not args.offline: + import ci_runner + ci_runner.main("pages") + shutil.copytree(ROOT / "site", args.output) + parent = Path(os.environ.get("RUNNER_WORKSPACE", ROOT / "build-cache")) + cache = parent.parent / ".pqc-web-installer-cache" if "RUNNER_WORKSPACE" in os.environ else parent + cache.mkdir(mode=0o700, exist_ok=True) + if cache.is_symlink() or cache.stat().st_uid != os.getuid() or cache.stat().st_mode & 0o022: + raise SystemExit("Untrusted JavaScript cache directory") + vendor(args.output, cache) + class Offline: + def json(self, path): + raise ValueError("Offline preview: no firmware build provenance") + api = Offline() if args.offline else GitHub(os.environ["GH_TOKEN"]) + result = catalogue(api, json.loads((ROOT / "site/firmware-targets.json").read_text()), args.output) + print(json.dumps({"output": str(args.output), "available": sum(b["available"] for b in result["builds"]), + "targets": len(result["builds"])})) + + +if __name__ == "__main__": + main() diff --git a/package.json b/package.json new file mode 100644 index 0000000..f3f161c --- /dev/null +++ b/package.json @@ -0,0 +1 @@ +{"private":true,"type":"module","scripts":{"test":"node --test tests/installer.test.mjs"}} diff --git a/site/firmware-targets.json b/site/firmware-targets.json new file mode 100644 index 0000000..c6f73b8 --- /dev/null +++ b/site/firmware-targets.json @@ -0,0 +1,25 @@ +{ + "schema": 1, + "repository": "DynamicDevices/pqc-testing", + "channels": { + "esp32": { + "workflow": "esp32-images.yml", + "jobs": ["runner-preflight", "images-esp32", "images-esp32s3", "images-esp32c3"], + "inputs": ["src/", "host/", "ci/", "vendor/", ".gitmodules", "LICENSE", "THIRD_PARTY.md", "prj.conf", "crypto.cmake", "CMakeLists.txt", "west.yml", ".github/workflows/esp32-images.yml"] + }, + "esp8266": { + "workflow": "esp8266-images.yml", + "jobs": ["d1mini-build"], + "inputs": ["firmware/esp8266/", "ci/esp8266", ".github/workflows/esp8266-images.yml"] + } + }, + "targets": [ + {"id":"esp32-baseline","channel":"esp32","family":"ESP32","board":"esp32_devkitc/esp32/procpu","artifact_board":"esp32","profile":"baseline","offset":4096,"label":"ESP32-DevKitC · boot baseline"}, + {"id":"esp32-mldsa44","channel":"esp32","family":"ESP32","board":"esp32_devkitc/esp32/procpu","artifact_board":"esp32","profile":"mldsa44","offset":4096,"label":"ESP32-DevKitC · ML-DSA-44 verification"}, + {"id":"esp32s3-baseline","channel":"esp32","family":"ESP32-S3","board":"esp32s3_devkitc/esp32s3/procpu","artifact_board":"esp32s3","profile":"baseline","offset":0,"label":"ESP32-S3-DevKitC · boot baseline"}, + {"id":"esp32s3-mldsa44","channel":"esp32","family":"ESP32-S3","board":"esp32s3_devkitc/esp32s3/procpu","artifact_board":"esp32s3","profile":"mldsa44","offset":0,"label":"ESP32-S3-DevKitC · ML-DSA-44 verification"}, + {"id":"esp32c3-baseline","channel":"esp32","family":"ESP32-C3","board":"esp32c3_devkitm/esp32c3","artifact_board":"esp32c3","profile":"baseline","offset":0,"label":"ESP32-C3-DevKitM · boot baseline"}, + {"id":"esp32c3-mldsa44","channel":"esp32","family":"ESP32-C3","board":"esp32c3_devkitm/esp32c3","artifact_board":"esp32c3","profile":"mldsa44","offset":0,"label":"ESP32-C3-DevKitM · ML-DSA-44 verification"}, + {"id":"d1mini-hybrid-https","channel":"esp8266","family":"ESP8266","board":"lolin-d1-mini-4mb","profile":"hybrid-https","label":"LOLIN D1 mini · hybrid HTTPS","blocked":"No distribution-eligible firmware yet: target build, complete flash layout and wolfSSL/SDK licence/source-package checks are required."} + ] +} diff --git a/site/flasher.js b/site/flasher.js new file mode 100644 index 0000000..22ca51b --- /dev/null +++ b/site/flasher.js @@ -0,0 +1,123 @@ +/* SPDX-License-Identifier: MIT. Assisted-by: Briar. */ +import {program, inspectionLinks} from './installer.js'; + +const $ = id => document.getElementById(id); +const base = new URL('./', import.meta.url); +const repo = 'DynamicDevices/pqc-testing'; +let policy, busy = false, rememberedPort, consoleReader; +const supported = Boolean(window.isSecureContext && navigator.serial); +const log = message => { $('firmware-log').textContent = ($('firmware-log').textContent + message + '\n').slice(-16000); }; + +async function fetchChecked(url) { + const response = await fetch(url, {cache: 'no-store', credentials: 'omit', redirect: 'error', signal: AbortSignal.timeout(30000)}); + if (!response.ok) throw Error(`Metadata/download unavailable (HTTP ${response.status}); no stale fallback`); + return response; +} +function local(path) { + const url = new URL(path, base); + if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname) || url.search || url.hash) + throw Error('Invalid site artifact path'); + return url; +} +const json = async path => (await fetchChecked(local(path))).json(); +const api = async path => (await fetchChecked(`https://api.github.com/repos/${repo}/${path}`)).json(); +const catalogue = async id => (await json('firmware/catalog.json')).builds.find(b => b.id === id); +function setBusy(value) { + busy = value; + for (const button of document.querySelectorAll('[data-program]')) button.disabled = value || !supported || button.dataset.available !== 'true'; + $('firmware-refresh').disabled = value; + $('serial-start').disabled = value || !supported; +} + +async function runtime(port) { + const [{ESPLoader, Transport}, {md5}, {bytesToHex}] = await Promise.all([ + import('./vendor/esptool-js/bundle.js'), import('./vendor/noble/legacy.js'), import('./vendor/noble/utils.js')]); + const transport = new Transport(port); + return {transport, md5: data => bytesToHex(md5(data)), + loader: new ESPLoader({transport, baudrate: 115200, terminal: {clean() {}, write: log, writeLine: log}})}; +} + +async function install(entry) { + if (busy) return; + // Keep the chooser directly in the user gesture, before any network await. + const port = navigator.serial.requestPort(); + setBusy(true); + $('firmware-progress').value = 0; + $('firmware-state').textContent = 'Checking latest build and downloaded image…'; + try { + const result = await program(entry, {port, policy, api, catalogue, runtime, log, + bytes: async path => new Uint8Array(await (await fetchChecked(local(path))).arrayBuffer()), + progress: value => { $('firmware-progress').value = value; }}); + rememberedPort = result.port; + $('firmware-state').textContent = `Programmed and transfer-verified: ${result.source_head.slice(0, 12)}. Hardware test not yet confirmed.`; + } catch (error) { + $('firmware-state').textContent = error.message; + log(error.message); + } finally { setBusy(false); } +} + +async function refresh() { + if (busy) return; + setBusy(true); + try { + const [rules, catalog] = await Promise.all([json('firmware-targets.json'), json('firmware/catalog.json')]); + if (rules.repository !== repo || catalog.repository !== repo || rules.schema !== 1 || catalog.schema !== 1) + throw Error('Unsupported firmware catalogue'); + policy = rules; + $('firmware-matrix').replaceChildren(); + for (const target of rules.targets) { + const entry = catalog.builds.find(b => b.id === target.id); + const row = document.createElement('article'); + const title = document.createElement('h3'); title.textContent = target.label; + const detail = document.createElement('p'); + detail.textContent = entry?.available ? `main ${entry.source_head.slice(0, 12)} · run ${entry.run_id} · not hardware tested` : (entry?.reason || 'No verified firmware package'); + const button = document.createElement('button'); button.type = 'button'; + button.textContent = 'Program latest'; button.dataset.program = target.id; + button.dataset.available = String(Boolean(entry?.available && !target.blocked)); + button.addEventListener('click', () => install(entry)); + row.append(title, detail); + if (entry?.available) { + const links = document.createElement('p'); + for (const [label, url] of inspectionLinks(entry)) { + const link = document.createElement('a'); link.textContent = label; + link.href = url.startsWith('https://github.com/') ? url : local(url); + if (links.childNodes.length) links.append(' · '); + links.append(link); + } + row.append(links); + } + row.append(button); $('firmware-matrix').append(row); + } + $('firmware-state').textContent = supported ? 'Latest build is rechecked on GitHub immediately before writing. No older-build fallback.' : 'Web Serial unavailable. Open this HTTPS page in a supported desktop browser.'; + } catch (error) { + $('firmware-matrix').replaceChildren(); + $('firmware-state').textContent = error.message; + } finally { setBusy(false); } +} + +$('firmware-refresh').addEventListener('click', refresh); +$('serial-stop').addEventListener('click', () => consoleReader?.cancel()); +$('serial-start').addEventListener('click', async () => { + if (busy) return; + const selected = rememberedPort ? Promise.resolve(rememberedPort) : navigator.serial.requestPort(); + setBusy(true); + let port; + try { + port = await selected; + await port.open({baudRate: 115200}); + rememberedPort = port; + consoleReader = port.readable.getReader(); $('serial-stop').disabled = false; + const decoder = new TextDecoder(); + while (true) { + const {value, done} = await consoleReader.read(); + if (done) break; + log(decoder.decode(value, {stream: true})); + } + } catch (error) { log(error.message); } + finally { + consoleReader?.releaseLock(); consoleReader = undefined; + if (port?.readable) await port.close().catch(error => log(error.message)); + $('serial-stop').disabled = true; setBusy(false); + } +}); +refresh(); diff --git a/site/index.html b/site/index.html index 123f4f5..d911ec5 100644 --- a/site/index.html +++ b/site/index.html @@ -1,8 +1,9 @@ -Dynamic Devices | PQC browser tests +Dynamic Devices | PQC browser tests
Dynamic Devices

Post-quantum cryptography testing

Test a real browser connection

PQC lab: TLS 1.3. These endpoints require hybrid X25519MLKEM768 key exchange and use a publicly trusted, classical ECDSA certificate. The separate strict lab on ports 8090, 8890 and 8891 also requires ML-DSA-65 authentication.

+

Program latest firmware over USB

Development boards only. Connect with a data USB cable, choose the matching board and build, then select its port. Use a desktop browser with Web Serial (Chrome or Edge recommended). The browser always asks permission.

Programming overwrites the image sectors, but does not erase the whole chip. Existing data in those sectors will be lost. Secure-boot/encrypted boards are refused. ESP32 builds below test boot or signature verification, not PQC TLS. A successful flash is not a hardware test pass.

Loading build metadata…

Serial output stays in this tab only; do not print secrets.

HTTPS / Ajax · 8091

Fetch a small JSON response over the browser's verified HTTPS connection.

Not run

MQTT over WebSockets · 8892

Connect directly to Mosquitto, authenticate, subscribe, publish and check the returned message. No proxy or bridge. This browser test uses MQTT 3.1.1 and QoS 0; the Python runner separately tests MQTT 5 and QoS 1.

Public demo account: anyone can read or inject messages in its test topics. Do not send personal data, secrets or production traffic. The shared password is intentional; it does not identify a trusted user.

diff --git a/site/installer.js b/site/installer.js new file mode 100644 index 0000000..9c01d3f --- /dev/null +++ b/site/installer.js @@ -0,0 +1,123 @@ +/* SPDX-License-Identifier: MIT. Assisted-by: Briar. No stored credentials. */ +const REPO = 'DynamicDevices/pqc-testing'; +const hex = bytes => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join(''); + +export function inspectionLinks(entry) { + if (!/^[a-f0-9]{40}$/.test(entry.source_head || '') || !Number.isSafeInteger(entry.run_id) || entry.run_id <= 0 || + !Number.isSafeInteger(entry.run_attempt) || entry.run_attempt <= 0 || !/^[a-z0-9-]+$/.test(entry.id || '')) + throw Error('Invalid source/build reference'); + const directory = `firmware/${entry.run_id}/${entry.id}/`; + return [ + ['Source revision', `https://github.com/${REPO}/tree/${entry.source_head}`], + ['Compiled configuration', directory + 'zephyr.config'], + ['Build manifest', directory + 'build-manifest.json'], + ['Build run', `https://github.com/${REPO}/actions/runs/${entry.run_id}/attempts/${entry.run_attempt}`], + ['Licence', directory + 'LICENSE'], ['Third-party notices', directory + 'THIRD_PARTY.md'], + ]; +} + +export function validateFresh(compare, inputs) { + if (!['identical', 'ahead'].includes(compare.status) || !Array.isArray(compare.files) || compare.files.length >= 300) + throw Error('Cannot establish complete current-main firmware freshness'); + if (compare.files.some(f => [f.filename || '', f.previous_filename || ''].some(name => inputs.some(p => name.startsWith(p))))) + throw Error('Newer firmware source exists; wait for its successful main build'); +} + +export function validateRun(run, workflowId) { + if (run.workflow_id !== workflowId || run.head_branch !== 'main' || run.head_repository?.full_name !== REPO || + run.actor?.login !== 'ajlennon' || !['push', 'workflow_dispatch'].includes(run.event) || !/^[a-f0-9]{40}$/.test(run.head_sha || '')) + throw Error('Untrusted firmware workflow/source'); + if (run.status !== 'completed' || run.conclusion !== 'success') + throw Error(`Latest firmware build is ${run.status}/${run.conclusion || 'pending'}; no older-build fallback`); +} + +export async function freshBuild(entry, policy, api) { + const channel = policy.channels[entry.channel]; + if (!channel || !entry.available || entry.blocked) throw Error(entry.reason || entry.blocked || 'Build unavailable'); + const workflow = await api(`actions/workflows/${channel.workflow}`); + const runs = await api(`actions/workflows/${workflow.id}/runs?branch=main&per_page=1`); + const run = runs.workflow_runs?.[0]; + if (!run) throw Error('No current-main firmware build'); + validateRun(run, workflow.id); + if (run.id !== entry.run_id || run.run_attempt !== entry.run_attempt || run.head_sha !== entry.source_head || workflow.id !== entry.workflow_id) + throw Error('A different/newer build exists; refresh the matrix before programming'); + validateFresh(await api(`compare/${run.head_sha}...main`), channel.inputs); + return run; +} + +export async function verifiedParts(entry, bytes, subtle = crypto.subtle) { + if (!Array.isArray(entry.parts) || !entry.parts.length || !Number.isSafeInteger(entry.flash_bytes) || entry.flash_bytes <= 0) + throw Error('Missing complete flash layout'); + const selected = []; + for (const part of entry.parts) { + const prefix = `firmware/${entry.run_id}/${entry.id}/`; + if (typeof part.path !== 'string' || !part.path.startsWith(prefix) || part.path.slice(prefix.length) !== 'firmware.bin' || + !/^[a-f0-9]{64}$/.test(part.sha256 || '') || !Number.isSafeInteger(part.offset) || part.offset < 0 || + !Number.isSafeInteger(part.size) || part.size <= 0 || part.offset + part.size > entry.flash_bytes) + throw Error('Invalid segment path, digest or flash bounds'); + const data = await bytes(part.path); + if (data.length !== part.size || hex(new Uint8Array(await subtle.digest('SHA-256', data))) !== part.sha256) + throw Error('Firmware download checksum/length mismatch; no write performed'); + selected.push({data, address: part.offset}); + } + const sorted = [...selected].sort((a, b) => a.address - b.address); + for (let i = 1; i < sorted.length; i++) + if (sorted[i - 1].address + sorted[i - 1].data.length > sorted[i].address) throw Error('Overlapping flash segments'); + return selected; +} + +export async function checkDevice(loader, entry) { + const family = loader.chip?.CHIP_NAME; + if (family !== entry.family) throw Error(`Wrong chip: selected ${entry.family}, detected ${family || 'unknown'}`); + if (loader.secureDownloadMode || !loader.IS_STUB) throw Error('Verified stub unavailable or secure download mode; unsupported, no bypass'); + if (family === 'ESP32') { + // Read-only checks matching Espressif esptool/targets/esp32.py: + // BLK0 word6 ABS_DONE[0:1], word0 FLASH_CRYPT_CNT[26:20]. + if (typeof loader.chip.readEfuse !== 'function') throw Error('Cannot check ESP32 security state'); + const absDone = await loader.chip.readEfuse(loader, 6); + const crypt = await loader.chip.readEfuse(loader, 0); + if (![absDone, crypt].every(n => Number.isInteger(n) && n >= 0 && n <= 0xffffffff)) throw Error('Unknown ESP32 security state'); + if ((absDone & 0x30) || (crypt & 0x07f00000)) throw Error('Security-provisioned ESP32 refused; development images only'); + } else if (family !== 'ESP8266') { + const security = await loader.getSecurityInfo(); + if (security.parsedFlags?.SECURE_BOOT_EN !== false || security.parsedFlags?.SECURE_DOWNLOAD_ENABLE !== false || + !Number.isInteger(security.flashCryptCnt) || security.flashCryptCnt !== 0) + throw Error('Secure-boot/encryption state unsupported; no security settings changed'); + } + const detected = await loader.detectFlashSize(); + const match = /^(\d+)(KB|MB)$/.exec(detected || ''); + const size = match ? Number(match[1]) * (match[2] === 'MB' ? 1048576 : 1024) : 0; + if (size < entry.flash_bytes) throw Error('Unknown or insufficient physical flash for this board configuration'); +} + +export async function program(entry, services) { + // Port selection does not open/reset it. Download/hash checks precede opening. + const port = await services.port; + const current = await services.catalogue(entry.id); + const target = services.policy.targets.find(t => t.id === entry.id); + if (!target || target.blocked || !current || ['id', 'board', 'family', 'profile', 'channel', 'offset'].some(k => current[k] !== target[k]) || + current.parts?.length !== 1 || current.parts[0].offset !== target.offset) + throw Error('Selected board/profile changed; refresh the matrix'); + await freshBuild(current, services.policy, services.api); + const files = await verifiedParts(current, services.bytes, services.subtle); + let transport; + try { + const runtime = await services.runtime(port); + transport = runtime.transport; + if (typeof runtime.md5 !== 'function') throw Error('Readback verification unavailable'); + await runtime.loader.main(); + await checkDevice(runtime.loader, current); + // Revalidate after slow device detection, immediately before the first write. + // Keep this immutable snapshot for all segments, even if a build changes. + await freshBuild(current, services.policy, services.api); + services.log(`Programming ${current.label}; main ${current.source_head}; run ${current.run_id}. No full-chip erase.`); + await runtime.loader.writeFlash({fileArray: files, flashSize: 'keep', flashMode: 'keep', flashFreq: 'keep', + eraseAll: false, compress: true, calculateMD5Hash: runtime.md5, + reportProgress: (_i, written, total) => services.progress(Math.round(100 * written / total))}); + await runtime.loader.after('hard_reset'); + services.log('Programming and transfer verification complete. This is not a PQC test pass. Use Serial console to inspect firmware results.'); + return {port, source_head: current.source_head}; + } finally { + if (transport) await transport.disconnect().catch(() => services.log('Port close failed; unplug and reconnect before retrying.')); + } +} diff --git a/site/style.css b/site/style.css index 5a519e3..0c44270 100644 --- a/site/style.css +++ b/site/style.css @@ -1 +1,2 @@ :root{font:18px/1.6 system-ui,sans-serif;color:#0b1c2c;background:#f4f6f7}body{margin:0}header,footer{background:#0b1c2c;color:white;padding:1.5rem max(1.5rem,calc((100vw - 960px)/2))}header img{width:260px;max-width:90%;background:white;padding:.6rem}header p{margin-bottom:0}main{max-width:960px;margin:2rem auto;padding:0 1.5rem}h1{line-height:1.2;font-size:2.1rem}h2{font-size:1.3rem}section{background:white;border-left:5px solid #6db33f;padding:1.2rem 1.5rem;margin:1.5rem 0;border-radius:4px}button{background:#0b1c2c;color:white;border:0;border-bottom:4px solid #e88a3c;border-radius:4px;font:inherit;padding:.6rem 1rem;cursor:pointer}button:disabled{opacity:.6;cursor:wait}label{display:block;margin:.7rem 0}input{display:block;box-sizing:border-box;font:inherit;padding:.4rem;width:min(100%,400px);border:1px solid #667580;border-radius:3px}output{display:block;margin:1rem 0 0;padding:.6rem;background:#edf1f3;border-radius:3px;white-space:pre-wrap;overflow-wrap:anywhere}.pass{background:#e8f5dd;color:#214900}.error{background:#fff1df;color:#714000}a{color:#145886}footer{font-size:.85rem} +#firmware-matrix{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,290px),1fr));gap:1rem;margin:1rem 0}#firmware-matrix article{border:1px solid #ccd5dc;border-radius:4px;padding:1rem;overflow-wrap:anywhere}#firmware-matrix h3{margin:0;font-size:1.05rem}#firmware-matrix p{font-size:.85rem}#firmware-progress{width:100%;height:1.5rem}#firmware-log{max-height:20rem;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere;background:#0b1c2c;color:#f4f6f7;padding:1rem;font-size:.8rem}#serial-stop{margin-left:.5rem} diff --git a/tests/installer.test.mjs b/tests/installer.test.mjs new file mode 100644 index 0000000..38fae06 --- /dev/null +++ b/tests/installer.test.mjs @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: MIT. Assisted-by: Briar. Fake serial only. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {createHash, webcrypto} from 'node:crypto'; +import {readFileSync} from 'node:fs'; +import {program, validateFresh, validateRun, verifiedParts, checkDevice, inspectionLinks} from '../site/installer.js'; + +const policy = JSON.parse(readFileSync(new URL('../site/firmware-targets.json', import.meta.url))); +const data = new Uint8Array([0xe9, 1, 2, 3]); +const digest = createHash('sha256').update(data).digest('hex'); +function fixture() { + const entry = {...policy.targets[0], available: true, run_id: 7, run_attempt: 1, workflow_id: 8, + source_head: 'a'.repeat(40), flash_bytes: 4194304, + parts: [{path: 'firmware/7/esp32-baseline/firmware.bin', offset: 4096, size: 4, sha256: digest}]}; + const run = {id: 7, run_attempt: 1, workflow_id: 8, head_sha: entry.source_head, head_branch: 'main', + head_repository: {full_name: policy.repository}, actor: {login: 'ajlennon'}, event: 'push', status: 'completed', conclusion: 'success'}; + const calls = []; + const loader = {chip: {CHIP_NAME: 'ESP32', readEfuse: async () => 0}, IS_STUB: true, + main: async () => calls.push('open'), detectFlashSize: async () => '4MB', + writeFlash: async opts => { calls.push('write'); assert.equal(opts.eraseAll, false); + assert.equal(opts.flashSize, 'keep'); assert.equal(opts.flashMode, 'keep'); assert.equal(opts.flashFreq, 'keep'); + assert.equal(typeof opts.calculateMD5Hash, 'function'); assert.deepEqual(opts.fileArray, [{data, address: 4096}]); }, + after: async () => calls.push('reset')}; + const services = {policy, port: Promise.resolve({}), catalogue: async () => entry, + api: async path => path.includes('/runs?') ? {workflow_runs: [run]} : path.startsWith('compare/') ? {status: 'identical', files: []} : {id: 8}, + bytes: async () => data, subtle: webcrypto.subtle, log() {}, progress() {}, + runtime: async () => ({loader, md5() {}, transport: {disconnect: async () => calls.push('close')}})}; + return {entry, run, calls, loader, services}; +} +test('one verified snapshot; no full erase; reset and release port', async () => { + const f = fixture(); await program(f.entry, f.services); + assert.deepEqual(f.calls, ['open', 'write', 'reset', 'close']); +}); +test('inspection links bind source, actual config and run attempt to each offered image', () => { + const f = fixture(); + const links = Object.fromEntries(inspectionLinks(f.entry)); + assert.equal(links['Source revision'], `https://github.com/${policy.repository}/tree/${f.entry.source_head}`); + assert.equal(links['Compiled configuration'], 'firmware/7/esp32-baseline/zephyr.config'); + assert.equal(links['Build manifest'], 'firmware/7/esp32-baseline/build-manifest.json'); + assert.equal(links['Build run'], `https://github.com/${policy.repository}/actions/runs/7/attempts/1`); + f.entry.source_head = 'main'; assert.throws(() => inspectionLinks(f.entry)); +}); +for (const [name, change] of [ + ['wrong chip', f => { f.loader.chip.CHIP_NAME = 'ESP32-S3'; }], + ['encrypted classic board', f => { f.loader.chip.readEfuse = async () => 0xffffffff; }], + ['insufficient flash', f => { f.loader.detectFlashSize = async () => '2MB'; }], + ['missing stub', f => { f.loader.IS_STUB = false; }], + ['secure download', f => { f.loader.secureDownloadMode = true; }], + ['missing verification', f => { f.services.runtime = async () => ({loader: f.loader, transport: {disconnect: async () => f.calls.push('close')}}); }], + ['digest mismatch', f => { f.entry.parts[0].sha256 = '0'.repeat(64); }], + ['wrong target offset', f => { f.entry.parts[0].offset = 0; }], + ['changed source', f => { f.services.api = async path => path.startsWith('compare/') ? {status: 'ahead', files: [{filename: 'src/main.c'}]} : path.includes('/runs?') ? {workflow_runs: [f.run]} : {id: 8}; }], + ['latest failed', f => { f.run.conclusion = 'failure'; }], + ['latest queued', f => { f.run.status = 'queued'; }], + ['new attempt', f => { f.run.run_attempt++; }], + ['different run', f => { f.run.id++; }], +]) test(`${name}: no write or reset`, async () => { + const f = fixture(); change(f); + await assert.rejects(program(f.entry, f.services)); + assert.ok(!f.calls.includes('write')); assert.ok(!f.calls.includes('reset')); + if (name === 'digest mismatch') assert.ok(!f.calls.includes('open')); +}); +test('new build during device detection stops before writing', async () => { + const f = fixture(); f.loader.main = async () => { f.run.id++; }; + await assert.rejects(program(f.entry, f.services), /newer build/); + assert.deepEqual(f.calls, ['close']); +}); +test('unsafe file paths and overlapping segments refused', async () => { + const f = fixture(); f.entry.parts[0].path = 'https://other.invalid/image'; + await assert.rejects(verifiedParts(f.entry, f.services.bytes), /path/); + f.entry.parts[0].path = 'firmware/7/esp32-baseline/firmware.bin'; f.entry.parts.push({...f.entry.parts[0]}); + await assert.rejects(verifiedParts(f.entry, f.services.bytes), /Overlapping/); +}); +test('freshness refuses incomplete diff, renamed inputs and divergent source', () => { + for (const compare of [{status: 'diverged', files: []}, {status: 'ahead', files: Array(300).fill({})}, + {status: 'ahead', files: [{filename: 'new', previous_filename: 'src/main.c'}]}]) + assert.throws(() => validateFresh(compare, ['src/'])); + validateFresh({status: 'ahead', files: [{filename: 'README.md'}]}, ['src/']); +}); +test('untrusted run identity refused', () => { + const f = fixture(); f.run.head_repository.full_name = 'someone/fork'; + assert.throws(() => validateRun(f.run, 8)); +}); +test('modern chips fail closed on missing security flags', async () => { + const f = fixture(); f.entry.family = f.loader.chip.CHIP_NAME = 'ESP32-C3'; + f.loader.getSecurityInfo = async () => ({parsedFlags: {}, flashCryptCnt: 0}); + await assert.rejects(checkDevice(f.loader, f.entry), /security settings/); + f.loader.getSecurityInfo = async () => ({parsedFlags: {SECURE_BOOT_EN: false, SECURE_DOWNLOAD_ENABLE: false}, flashCryptCnt: 0}); + await checkDevice(f.loader, f.entry); +}); diff --git a/tests/test_browser_site.py b/tests/test_browser_site.py index 3625460..d49d9d3 100644 --- a/tests/test_browser_site.py +++ b/tests/test_browser_site.py @@ -19,7 +19,8 @@ def handle_starttag(self, tag, attrs): class BrowserSiteTests(unittest.TestCase): def test_artifact_contains_only_intended_static_files(self): self.assertEqual({p.name for p in (ROOT / 'site').iterdir()}, - {'index.html', 'style.css', 'tests.js', 'dynamic-devices.svg'}) + {'index.html', 'style.css', 'tests.js', 'dynamic-devices.svg', + 'firmware-targets.json', 'installer.js', 'flasher.js'}) self.assertFalse(any(p.is_symlink() for p in (ROOT / 'site').iterdir())) def test_assets_are_first_party_and_present(self): @@ -30,8 +31,9 @@ def test_assets_are_first_party_and_present(self): self.assertNotIn(':', path) self.assertTrue((ROOT / 'site' / path).is_file()) scripts = [a for t, a in tags if t == 'script'] - self.assertEqual(len(scripts), 1) + self.assertEqual(len(scripts), 2) self.assertEqual(scripts[0]['src'], 'tests.js') + self.assertEqual(scripts[1], {'type': 'module', 'src': 'flasher.js'}) def test_only_intentionally_public_credentials_are_prefilled(self): html = (ROOT / 'site/index.html').read_text() diff --git a/tests/test_firmware_site.py b/tests/test_firmware_site.py new file mode 100644 index 0000000..5ffb375 --- /dev/null +++ b/tests/test_firmware_site.py @@ -0,0 +1,150 @@ +"""Installer publisher tests: synthetic archives only, no firmware builds.""" +import copy +import io +import json +from pathlib import Path +import tempfile +import unittest +import zipfile + +import firmware_site as site + +POLICY = json.loads((site.ROOT / 'site/firmware-targets.json').read_text()) +HEAD = 'a' * 40 + + +def archive(target, mutate=None): + files = {'zephyr.bin': b'\xe9\x01\x02\x03', 'zephyr.config': b'CONFIG_FLASH_SIZE=4096\nCONFIG_ESP_SIMPLE_BOOT=y\n', + 'LICENSE': b'MIT', 'THIRD_PARTY.md': b'notices'} + for label in ('ZEPHYR', 'HAL-ESPRESSIF', 'HAL-XTENSA', 'DILITHIUM'): + files[label + '-LICENSE'] = b'upstream licence fixture' + manifest = dict(board=target['board'], chip=target['artifact_board'], profile=target['profile'], + source_head=HEAD, boot_method='ESP_SIMPLE_BOOT; unsigned development image', + flash_offset=hex(target['offset']), image_bytes=4, + sha256={k: site.sha256(v) for k, v in files.items()}) + if mutate: + mutate(manifest, files) + stream = io.BytesIO() + with zipfile.ZipFile(stream, 'w') as z: + prefix = target['profile'] + '/' + for name, value in files.items(): + z.writestr(prefix + name, value) + z.writestr(prefix + 'manifest.json', json.dumps(manifest)) + return stream.getvalue() + + +class API: + def __init__(self): + self.run = dict(id=7, run_attempt=1, workflow_id=8, head_sha=HEAD, head_branch='main', + head_repository={'full_name': site.REPO}, actor={'login': 'ajlennon'}, + event='push', status='completed', conclusion='success', html_url='https://github.com/build') + self.compare = {'status': 'identical', 'files': []} + self.jobs = [dict(name=name, status='completed', conclusion='success', runner_id=139, + runner_name='dd-esl-proxmox', runner_group_id=1) for name in POLICY['channels']['esp32']['jobs']] + + def json(self, path): + if '/runs?' in path: + return {'workflow_runs': [self.run]} + if path.startswith('compare/'): + return self.compare + if '/jobs?' in path: + return {'jobs': self.jobs} + return {'id': 8} + + +class FirmwareSiteTests(unittest.TestCase): + def test_six_images_published_from_three_verified_artifacts(self): + class Complete(API): + def __init__(self): + super().__init__() + self.downloads = [] + + def json(self, path): + if '/artifacts?' in path: + return {'artifacts': [dict(id=i, name='pqc-' + board + '-' + HEAD) + for i, board in enumerate(('esp32', 'esp32s3', 'esp32c3'))]} + return super().json(path) + + def archive(self, artifact): + self.downloads.append(artifact['id']) + board = ('esp32', 'esp32s3', 'esp32c3')[artifact['id']] + output = io.BytesIO() + with zipfile.ZipFile(output, 'w') as destination: + for target in POLICY['targets'][:6]: + if target['artifact_board'] == board: + with zipfile.ZipFile(io.BytesIO(archive(target))) as source: + for name in source.namelist(): + destination.writestr(name, source.read(name)) + return output.getvalue() + + api = Complete() + with tempfile.TemporaryDirectory() as temp: + result = site.catalogue(api, POLICY, Path(temp)) + self.assertEqual(len([b for b in result['builds'] if b['available']]), 6) + self.assertEqual(len(api.downloads), 3) + for entry in result['builds'][:6]: + self.assertEqual(entry['run_attempt'], 1) + manifest = json.loads((Path(temp) / entry['manifest']).read_text()) + self.assertEqual(manifest['source_head'], entry['source_head']) + self.assertEqual(site.sha256((Path(temp) / entry['config']).read_bytes()), manifest['sha256']['zephyr.config']) + self.assertEqual(site.sha256((Path(temp) / entry['parts'][0]['path']).read_bytes()), entry['parts'][0]['sha256']) + + def test_latest_validated_and_no_older_success_fallback(self): + api = API() + self.assertEqual(site.latest(api, POLICY['channels']['esp32'])['id'], 7) + for key, value in [('status', 'queued'), ('conclusion', 'failure'), ('head_branch', 'other')]: + changed = API() + changed.run[key] = value + with self.assertRaises(ValueError): + site.latest(changed, POLICY['channels']['esp32']) + + def test_wrong_runner_or_missing_job(self): + for key, value in [('runner_id', 140), ('runner_group_id', 2), ('conclusion', 'skipped')]: + api = API() + api.jobs[0][key] = value + with self.assertRaises(ValueError): + site.latest(api, POLICY['channels']['esp32']) + api = API() + api.jobs.pop() + with self.assertRaises(ValueError): + site.latest(api, POLICY['channels']['esp32']) + + def test_complete_source_freshness(self): + for diff in [{'status': 'behind', 'files': []}, {'status': 'ahead', 'files': [{}] * 300}, + {'status': 'ahead', 'files': [{'filename': 'new', 'previous_filename': 'src/main.c'}]}]: + with self.assertRaises(ValueError): + site.check_fresh(diff, ['src/']) + site.check_fresh({'status': 'ahead', 'files': [{'filename': 'README.md'}]}, ['src/']) + + def test_valid_matrix_archives_include_exact_configuration_and_manifest(self): + for target in POLICY['targets'][:6]: + with self.subTest(target=target['id']): + files, size = site.image_from_archive(archive(target), target, HEAD) + self.assertEqual(size, 4194304) + self.assertEqual(site.sha256(files['zephyr.config']), json.loads(files['build-manifest.json'])['sha256']['zephyr.config']) + + def test_invalid_archive_identity_hash_boot_bounds_notices(self): + target = POLICY['targets'][0] + changes = [lambda m, f: m.update(board='wrong'), lambda m, f: m.update(source_head='b'*40), + lambda m, f: m.update(flash_offset='0x0'), lambda m, f: f.update({'zephyr.bin': b'bad'}), + lambda m, f: f.update({'zephyr.config': b'CONFIG_FLASH_SIZE=1\n'}), + lambda m, f: f.update({'../unsafe': b'x'}), lambda m, f: f.pop('LICENSE'), + lambda m, f: m['sha256'].update({'LICENSE': '0'*64})] + for change in changes: + with self.assertRaises((ValueError, KeyError)): + site.image_from_archive(archive(target, change), target, HEAD) + + def test_unavailable_catalogue_is_explicit_and_never_publishes_binary(self): + class Offline: + def json(self, path): + raise ValueError('Pending build') + with tempfile.TemporaryDirectory() as temp: + result = site.catalogue(Offline(), POLICY, Path(temp)) + self.assertEqual(len(result['builds']), 7) + self.assertFalse(any(b['available'] for b in result['builds'])) + self.assertFalse(list(Path(temp).rglob('*.bin'))) + self.assertIn('distribution', result['builds'][-1]['reason']) + + +if __name__ == '__main__': + unittest.main() From 4aa201705bb0476c62d59177a467be7239493d35 Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 10:12:30 +0000 Subject: [PATCH 2/3] Retain licences for bundled browser dependencies Pin pako and atob-lite notice packages and require runtime licence files before publication. Assisted-by: Briar --- THIRD_PARTY.md | 5 ++++- firmware_site.py | 12 +++++++++++- tests/test_firmware_site.py | 3 ++- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 3577777..d28871d 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -8,9 +8,12 @@ The browser installer self-hosts integrity-pinned runtime packages: - [esptool-js](https://github.com/espressif/esptool-js), 0.7.1, Apache-2.0. - [@noble/hashes](https://github.com/paulmillr/noble-hashes), 2.4.0, MIT. +- esptool-js embeds [pako](https://github.com/nodeca/pako), 2.1.0, MIT/Zlib, + and [atob-lite](https://github.com/hughsk/atob-lite), 2.0.0, MIT. Their complete upstream `LICENSE` files are published at -`vendor/esptool-js/LICENSE` and `vendor/noble/LICENSE` beside the site. Package +`vendor/esptool-js/LICENSE`, `vendor/noble/LICENSE`, `vendor/pako/LICENSE` and +`vendor/atob-lite/LICENSE.md` beside the site. Package tarball URLs and SHA-512 digests are recorded in `firmware_site.py`. The experiments use: diff --git a/firmware_site.py b/firmware_site.py index 55a9ab1..39a9b7f 100644 --- a/firmware_site.py +++ b/firmware_site.py @@ -28,6 +28,11 @@ "vw1isT5ROHgpRmMG3y6B81dceeZ7O1WhF1x05qFbAlH8N0N/pOQqODzJLA+36lCbOXCw06iA4CWctyrQQ7VeSA=="), "noble": ("https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", "X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA=="), + # esptool's bundle embeds these packages; retain their complete licences too. + "pako": ("https://registry.npmjs.org/pako/-/pako-2.1.0.tgz", + "w+eufiZ1WuJYgPXbV/PO3NCMEc3xqylkKHzp8bxp1uW4qaSNQUkwmLLEc3kKsfz8lpV1F8Ht3U1Cm+9Srog2ug=="), + "atob-lite": ("https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz", + "LEeSAWeh2Gfa2FtlQE1shxQ8zi5F9GHarrGKz08TMdODD5T4eH6BMsvtnhbWZ+XQn+Gb6om/917ucvRu7l7ukw=="), } @@ -200,13 +205,18 @@ def vendor(output, cache): if name == "esptool-js": if str(relative) not in ("bundle.js", "LICENSE", "LICENSE.md", "README.md"): continue - elif not (str(relative).endswith(".js") or "LICENSE" in str(relative)): + elif name == "noble" and not (str(relative).endswith(".js") or "LICENSE" in str(relative)): + continue + elif name in ("pako", "atob-lite") and not relative.name.upper().startswith(("LICENSE", "NOTICE", "COPYING")): continue dest = destination / name / str(relative) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_bytes(archive.extractfile(item).read()) if not (destination / "esptool-js/bundle.js").is_file() or not (destination / "noble/legacy.js").is_file(): raise ValueError("Pinned browser runtime files missing") + for package in PACKAGES: + if not any(path.name.upper().startswith("LICENSE") for path in (destination / package).rglob('*') if path.is_file()): + raise ValueError("Missing pinned runtime licence: " + package) def catalogue(api, policy, output): diff --git a/tests/test_firmware_site.py b/tests/test_firmware_site.py index 5ffb375..e97ea95 100644 --- a/tests/test_firmware_site.py +++ b/tests/test_firmware_site.py @@ -1,5 +1,4 @@ """Installer publisher tests: synthetic archives only, no firmware builds.""" -import copy import io import json from pathlib import Path @@ -53,6 +52,8 @@ def json(self, path): class FirmwareSiteTests(unittest.TestCase): + def test_pinned_runtime_includes_bundled_dependency_notices(self): + self.assertEqual(set(site.PACKAGES), {'esptool-js', 'noble', 'pako', 'atob-lite'}) def test_six_images_published_from_three_verified_artifacts(self): class Complete(API): def __init__(self): From 80e885263d27aa2e64bea41c1faeb56f148f0e95 Mon Sep 17 00:00:00 2001 From: Alex J Lennon Date: Fri, 4 Dec 2026 10:13:50 +0000 Subject: [PATCH 3/3] Set up Node24 in installer CI and Pages jobs Correct admitted-runner failure: Node was not on PATH. Use a pinned official action and disable package-manager caching. Assisted-by: Briar --- .github/workflows/offline-tests.yml | 5 +++++ .github/workflows/pages.yml | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/offline-tests.yml b/.github/workflows/offline-tests.yml index 2564d88..c452abd 100644 --- a/.github/workflows/offline-tests.yml +++ b/.github/workflows/offline-tests.yml @@ -26,5 +26,10 @@ jobs: run: python3 -m compileall -q run.py firmware_test.py transport_test.py certificate_test.py server_test.py browser_test.py websocket_tls.py simulator_test.py ci_runner.py tests - name: Run offline tests run: python3 -m unittest discover -s tests -v + - name: Set up job-local JavaScript test runtime + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6, Node24 + with: + node-version: '24' + package-manager-cache: false - name: Test browser programming without opening a device run: node --test tests/installer.test.mjs diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 2ab3e1e..74f6a83 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -40,6 +40,11 @@ jobs: env: GH_TOKEN: ${{ github.token }} run: python3 ci_runner.py pages + - name: Set up job-local JavaScript test runtime + uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6, Node24 + with: + node-version: '24' + package-manager-cache: false - name: Check the static public artifact run: | python3 -m unittest discover -s tests -p 'test_*site.py' -v