diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..4069539 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Unified-diff context prefixes precede empty lines and upstream tab indentation. +ci/patches/*.patch whitespace=-blank-at-eol,-space-before-tab diff --git a/.github/workflows/esp32-images.yml b/.github/workflows/esp32-images.yml index 22cadd3..5ee9399 100644 --- a/.github/workflows/esp32-images.yml +++ b/.github/workflows/esp32-images.yml @@ -3,7 +3,7 @@ on: workflow_dispatch: push: branches: [main] - paths: ['src/**', 'host/**', 'ci/**', 'firmware_inventory.py', 'examples/andysc/review/schema-sources.json', 'prj.conf', 'crypto.cmake', 'CMakeLists.txt', 'west.yml', '.github/workflows/esp32-images.yml'] + paths: ['src/**', 'host/**', 'ci/**', 'docs/s2mini-pqc.md', 'firmware_inventory.py', 'examples/andysc/review/schema-sources.json', 'prj.conf', 'crypto.cmake', 'CMakeLists.txt', 'west.yml', '.github/workflows/esp32-images.yml'] # Applying this label is an explicit dispatch of a locally reviewed candidate. # Synchronizing a labelled PR does not automatically approve the new revision. pull_request: @@ -40,7 +40,7 @@ jobs: fail-fast: false max-parallel: 1 matrix: - board: [esp32, esp32s3, esp32c3] + board: [esp32s2mini, esp32, esp32s3, esp32c3] runs-on: [self-hosted, Linux, X64, dd-esl-proxmox] timeout-minutes: 45 steps: diff --git a/README.md b/README.md index 7960a99..841bcea 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ certification**. A build, flash or signature test is not a PQC network test. | Build Mac SSH tools | [SSH page and v9 download](https://dynamicdevices.github.io/pqc-testing/ssh/) · [instructions](examples/oqs-ssh/README.md) | Separate tools; one-time profile enables `ssh pqc-lab` and `scp file.txt pqc-lab:./`. Build generates no keys or connections. | | Try Zephyr application code | [Native simulator setup](docs/zephyr-simulator.md) | Ten live HTTPS/MQTTS controls using host OpenSSL, **not embedded Zephyr TLS**. | | Flash an ESP32 test image | [Builds and flashing](docs/esp32-images.md) · [browser installer](docs/browser-firmware.md) | Boot/resource and ML-DSA-44 signature-verification images, **not PQC network clients**. | +| Test an ESP32-S2 Mini | [S2 Mini bring-up](docs/s2mini-pqc.md) | Native USB baseline and ML-DSA-44 verifier; XTVTX hardware/PSRAM unverified; no TLS or KC heater control. | | Explore ESP8266 feasibility | [D1 mini experiment](docs/esp8266-d1mini.md) | A limited hybrid-HTTPS prototype; no proved ML-DSA certificate authentication or complete PQC acceptance. | | Review evidence and inventories | [Dated results](docs/testing-results.md) · [SBOM/CBOM guide](docs/inventories.md) | Which artifact was tested or inventoried, and the limits of each claim. | diff --git a/ci/esp32_images.py b/ci/esp32_images.py index 5d83eeb..9691d41 100644 --- a/ci/esp32_images.py +++ b/ci/esp32_images.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Build six public test images ONLY on the admitted DD organisation runner. +"""Build public ESP32-family test images ONLY on the admitted DD runner. No flashing, Wi-Fi secrets, broker credentials, host installs or local fallback. Assisted-by: Briar @@ -18,7 +18,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) import firmware_inventory -ZEPHYR = "dccb09599635bdff17633fa7e9dab014b91dce90" +ZEPHYR = "41d10b59730406bbab4ca9f1fbbe9e96aafb4966" # Zephyr v4.5.0 +HAL_ESPRESSIF = "cc81db00233af6020f2fea9fbb0d0098fb3d0d86" DILITHIUM = "d35ba3fe5449bee3e6d43e1f296c3ca818bd36be" IMAGE = "ghcr.io/zephyrproject-rtos/ci@sha256:37e841452087905085ffcd82ed44a223f3e7eb86bf9316443a313ae07e09cfe0" IMAGE_COMPRESSED_BYTES = 6692490107 @@ -27,9 +28,19 @@ "esp32": ("esp32_devkitc/esp32/procpu", "esp32", 0x1000), "esp32s3": ("esp32s3_devkitc/esp32s3/procpu", "esp32s3", 0), "esp32c3": ("esp32c3_devkitm/esp32c3", "esp32c3", 0), + "esp32s2mini": ("esp32s2_lolin_mini/esp32s2", "esp32s2", 0x1000), } +def board_build_args(board): + args = ["-DEXTRA_CONF_FILE=" + str(ROOT / "ci/esp32.conf")] + if board == "esp32s2mini": + args = ["-DEXTRA_CONF_FILE=" + str(ROOT / "ci/esp32.conf") + ";" + + str(ROOT / "ci/s2mini.conf"), "-DSNIPPET=cdc-acm-console", + "-DDTC_OVERLAY_FILE=" + str(ROOT / "ci/s2mini.overlay")] + return args + + def command(args, **kwargs): return subprocess.run(args, check=True, **kwargs) @@ -109,6 +120,12 @@ def docker(work, arguments, *, network="none", seconds=1800): subprocess.run(["docker", "stop", "--time", "15", name], capture_output=True, timeout=30) +def ensure_image(): + # An existing exact-digest image is already the requested immutable input. + if subprocess.run(["docker", "image", "inspect", IMAGE], capture_output=True, timeout=20).returncode: + command(["docker", "pull", IMAGE], timeout=900) + + def build(board): guard_environment() run, attempt = os.environ.get("GITHUB_RUN_ID", ""), os.environ.get("GITHUB_RUN_ATTEMPT", "") @@ -132,8 +149,9 @@ def build(board): raise RuntimeError("Source export failed") head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True, timeout=15).strip() (work / "source-head.txt").write_text(head + "\n") - command(["docker", "pull", IMAGE], timeout=900) - docker(work, ["python3", "/work/pqc-testing/ci/esp32_images.py", "prepare-container"], network="bridge") + ensure_image() + docker(work, ["python3", "/work/pqc-testing/ci/esp32_images.py", "prepare-container", + "--board", board], network="bridge") docker(work, ["/work/.venv/bin/python", "/work/pqc-testing/ci/esp32_images.py", "build-container", "--board", board]) destination = ROOT / "build-esp32-artifacts" / board shutil.copytree(work / "artifacts" / board, destination) @@ -156,7 +174,7 @@ def update_imported_modules(west): # Last matching filter wins. Exclude everything except these pinned projects. command(west + ["config", "--", "manifest.project-filter", "-.*,+zephyr,+hal_espressif,+hal_xtensa"], timeout=30) # Named project updates cannot resolve imported manifest entries in west1.5. - command(west + ["update", "--narrow"], timeout=600) + command(west + ["update", "--narrow", "--fetch-opt=--depth=1"], timeout=600) def install_zephyr_requirements(python): @@ -167,17 +185,36 @@ def install_zephyr_requirements(python): command([python, "-c", "import jsonschema, elftools, yaml, pykwalify, west"], timeout=30) -def prepare_container(): +def s2mini_patch_specs(): + return ((Path("/work/zephyr"), ZEPHYR, "s2mini-zephyr-cache.patch"), + (Path("/work/modules/hal/espressif"), HAL_ESPRESSIF, "s2mini-hal-usb.patch")) + + +def apply_board_patches(board): + if board != "esp32s2mini": + return + for repo, revision, name in s2mini_patch_specs(): + observed = subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], + text=True, timeout=15).strip() + if observed != revision: + raise RuntimeError("Wrong source revision for S2 USB backport") + patch = str(ROOT / "ci/patches" / name) + command(["git", "-C", str(repo), "apply", "--check", patch], timeout=15) + command(["git", "-C", str(repo), "apply", patch], timeout=15) + + +def prepare_container(board): container_guard() command(["python3", "-m", "venv", "--system-site-packages", "/work/.venv"], timeout=60) python = "/work/.venv/bin/python" install_build_tools(python) west = [python, "-m", "west"] command(west + ["init", "-l", "pqc-testing"], timeout=60) - command(west + ["update", "--narrow", "zephyr"], timeout=600) + command(west + ["update", "--narrow", "--fetch-opt=--depth=1", "zephyr"], timeout=600) update_imported_modules(west) if subprocess.check_output(["git", "-C", "zephyr", "rev-parse", "HEAD"], text=True).strip() != ZEPHYR: raise RuntimeError("Wrong Zephyr source") + apply_board_patches(board) install_zephyr_requirements(python) command([python, str(ROOT / "firmware_inventory.py"), "--schema-dir", "/work/inventory-schemas", "--fetch-schemas"], timeout=90) @@ -194,19 +231,56 @@ def read_config(path): return dict(line.split("=", 1) for line in path.read_text().splitlines() if line.startswith("CONFIG_") and "=" in line) +def compiled_flash_bytes(dts): + # Zephyr 4.5 derives Espressif flash size from chosen DT, not CONFIG_FLASH_SIZE. + sys.path.insert(0, "/work/zephyr/scripts/dts/python-devicetree/src") + from devicetree.dtlib import DT + flash = DT(str(dts)).get_node("/chosen").props["zephyr,flash"].to_path() + cells = flash.props["reg"].to_nums() + if len(cells) != 2 or cells[0] != 0: + raise RuntimeError("Unexpected flash address/size encoding") + return cells[1] + + +def check_s2mini_policy(config, flash_bytes): + observed = dict(flash_bytes=flash_bytes, + usb_cdc=config.get("CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT") == "y", + psram=config.get("CONFIG_ESP_SPIRAM") == "y", + stack_sentinel=config.get("CONFIG_STACK_SENTINEL") == "y") + expected = dict(flash_bytes=4 * 1024 * 1024, usb_cdc=True, psram=False, stack_sentinel=True) + if observed != expected: + raise RuntimeError("S2 Mini requires 4MB flash, USB CDC, stack sentinel and PSRAM disabled: " + + json.dumps(observed, sort_keys=True)) + + def package(board, profile, build_dir, output, head): zephyr = build_dir / "zephyr" config = read_config(zephyr / ".config") target, chip, offset = BOARDS[board] if config.get("CONFIG_ESP_SIMPLE_BOOT") != "y" or config.get("CONFIG_SOC", "").strip('"') != chip: raise RuntimeError("Unexpected boot layout/SoC; do not publish flash instructions") + flash_bytes = compiled_flash_bytes(zephyr / "zephyr.dts") + if type(flash_bytes) is not int or flash_bytes <= offset or offset + (zephyr / "zephyr.bin").stat().st_size > flash_bytes: + raise RuntimeError("Image exceeds compiled flash layout") + if board == "esp32s2mini": + check_s2mini_policy(config, flash_bytes) destination = output / board / profile destination.mkdir(parents=True) for name in ("zephyr.bin", "zephyr.elf", "zephyr.map"): shutil.copyfile(zephyr / name, destination / name) shutil.copyfile(zephyr / ".config", destination / "zephyr.config") + shutil.copyfile(zephyr / "zephyr.dts", destination / "zephyr.dts") shutil.copyfile(ROOT / "LICENSE", destination / "LICENSE") shutil.copyfile(ROOT / "THIRD_PARTY.md", destination / "THIRD_PARTY.md") + if board == "esp32s2mini": + shutil.copyfile(ROOT / "docs/s2mini-pqc.md", destination / "S2MINI-TEST.md") + for _, _, name in s2mini_patch_specs(): + shutil.copyfile(ROOT / "ci/patches" / name, destination / name) + reports = sorted(build_dir.rglob("*.su")) + if profile == "mldsa44" and not reports: + raise RuntimeError("Missing compiler stack-usage reports") + (destination / "stack-usage.txt").write_text("".join( + f"# {p.relative_to(build_dir)}\n{p.read_text()}\n" for p in reports)) for label, upstream in (("ZEPHYR", Path("/work/zephyr")), ("HAL-ESPRESSIF", Path("/work/modules/hal/espressif")), ("HAL-XTENSA", Path("/work/modules/hal/xtensa"))): @@ -233,12 +307,18 @@ def package(board, profile, build_dir, output, head): for name, path in (("hal_espressif", "modules/hal/espressif"), ("hal_xtensa", "modules/hal/xtensa"))}, "boot_method": "ESP_SIMPLE_BOOT; unsigned development image", "flash_offset": hex(offset), "serial_baud": 115200, - "image_bytes": (destination / "zephyr.bin").stat().st_size, + "image_bytes": (destination / "zephyr.bin").stat().st_size, "flash_bytes": flash_bytes, "static_writable_section_bytes": writable, "main_stack_bytes": int(config["CONFIG_MAIN_STACK_SIZE"], 0), "hardware_tested": False, "pqc_tls": False, "expectation": "RESULT: PASS; signature acceptance/rejection checks" if profile == "mldsa44" else "RESULT: PASS; baseline boot only", "sha256": hashes} + if board == "esp32s2mini": + manifest.update(flash_bytes=4 * 1024 * 1024, console="USB CDC ACM; DTR wait up to 30s", + psram_enabled=False, advertised_psram_bytes=2 * 1024 * 1024, + clone_compatibility="XTVTX S2 Mini V1.0.0: unverified on hardware", + source_patches={name: {"base_revision": revision, "sha256": hashes[name]} + for _, revision, name in s2mini_patch_specs()}) inventories = firmware_inventory.make_documents(manifest) for name, content in inventories.items(): (destination / name).write_bytes(content) @@ -280,12 +360,15 @@ def build_container(board): env = dict(os.environ, ZEPHYR_BASE="/work/zephyr", PATH="/work/.venv/bin:" + os.environ["PATH"]) command(["cmake", "-S", str(ROOT / "host"), "-B", "/work/build-host", "-G", "Ninja"], env=env, timeout=60) command(["cmake", "--build", "/work/build-host", "--target", "fixture", "-j", "2"], env=env, timeout=180) + # Profiles share board/Kconfig/toolchain. Snapshot baseline first, then + # reconfigure application sources only; Ninja retains unchanged Zephyr objects. + # Each board/job still gets its own fresh disposable workspace. + directory = Path("/work") / f"build-{board}" for profile in ("baseline", "mldsa44"): - directory = Path("/work") / f"build-{board}-{profile}" command(["cmake", "-S", str(ROOT), "-B", str(directory), "-G", "Ninja", "-DBOARD=" + BOARDS[board][0], "-DPQC_ENABLED=" + ("ON" if profile == "mldsa44" else "OFF"), "-DFIXTURE_DIR=/work/build-host", "-DPython3_EXECUTABLE=" + sys.executable, - "-DEXTRA_CONF_FILE=" + str(ROOT / "ci/esp32.conf")], env=env, timeout=180) + *board_build_args(board)], env=env, timeout=180) command(["cmake", "--build", str(directory), "-j", "2"], env=env, timeout=600) package(board, profile, directory, Path("/work/artifacts"), head) @@ -299,7 +382,7 @@ def main(argv=None): try: if args.phase == "preflight": preflight(args.job_name) elif args.phase == "verify-runner": verify_runner(args.job_name) - elif args.phase == "prepare-container": prepare_container() + elif args.phase == "prepare-container" and args.board: prepare_container(args.board) elif args.phase == "build" and args.board: build(args.board) elif args.phase == "cleanup" and args.board: cleanup(args.board) elif args.phase == "build-container" and args.board: build_container(args.board) diff --git a/ci/patches/README.md b/ci/patches/README.md new file mode 100644 index 0000000..369ed92 --- /dev/null +++ b/ci/patches/README.md @@ -0,0 +1,18 @@ +# S2 Mini USB backport + +Only `esp32s2mini` applies these patches in its disposable CI dependency checkouts. +The base Zephyr v4.5.0 and hal_espressif revisions stay pinned; the other board +builds remain unmodified. Patch applicability and exact HEAD checks fail closed. + +- `s2mini-hal-usb.patch`: missing S2 USB HAL includes and wrapper compilation, + adapted from [hal_espressif #694](https://github.com/zephyrproject-rtos/hal_espressif/pull/694). +- `s2mini-zephyr-cache.patch`: zero-length cache-range handling from + [Zephyr #125458](https://github.com/zephyrproject-rtos/zephyr/pull/125458). +- The associated USB devicetree node is in `../s2mini.overlay`, loaded before + the CDC-console snippet. `../s2mini.conf` sets the matching DWC2 stack size. + +Upstream code is Apache-2.0; the existing artifact licence bundle includes the +Zephyr and HAL notices. Original patch adaptation assistance: Briar. +Artifacts include both patches and their SHA256/base-revision metadata. Hardware +enumeration and clone compatibility are still unverified. Retire this backport +when adopting a stable release that contains the complete S2 USB fixes. diff --git a/ci/patches/s2mini-hal-usb.patch b/ci/patches/s2mini-hal-usb.patch new file mode 100644 index 0000000..d6d3975 --- /dev/null +++ b/ci/patches/s2mini-hal-usb.patch @@ -0,0 +1,25 @@ +diff --git a/zephyr/esp32s2/CMakeLists.txt b/zephyr/esp32s2/CMakeLists.txt +--- a/zephyr/esp32s2/CMakeLists.txt ++++ b/zephyr/esp32s2/CMakeLists.txt +@@ -78,4 +78,6 @@ + ../../components/esp_hal_uart/include + ../../components/esp_hal_uart/${CONFIG_SOC_SERIES}/include ++ ../../components/esp_hal_usb/include ++ ../../components/esp_hal_usb/${CONFIG_SOC_SERIES}/include + ../../components/esp_hal_wdt/include + ../../components/esp_hal_wdt/${CONFIG_SOC_SERIES}/include +@@ -249,9 +251,14 @@ + zephyr_sources_ifdef(CONFIG_I2S_ESP32 + ../../components/esp_hal_i2s/i2s_hal.c + ../../components/hal/hal_utils.c + ) + ++ if (CONFIG_UDC_DWC2 OR CONFIG_UHC_DWC2) ++ zephyr_include_directories(../../components/usb/include) ++ zephyr_sources(../../components/esp_hal_usb/usb_wrap_hal.c) ++ endif() ++ + zephyr_sources_ifdef(CONFIG_UART_ESP32 + ../../components/esp_hal_uart/uart_hal.c + ../../components/esp_hal_uart/uart_hal_iram.c + ) diff --git a/ci/patches/s2mini-zephyr-cache.patch b/ci/patches/s2mini-zephyr-cache.patch new file mode 100644 index 0000000..9202a8d --- /dev/null +++ b/ci/patches/s2mini-zephyr-cache.patch @@ -0,0 +1,36 @@ +diff --git a/drivers/cache/cache_esp32.c b/drivers/cache/cache_esp32.c +--- a/drivers/cache/cache_esp32.c ++++ b/drivers/cache/cache_esp32.c +@@ -44,6 +44,10 @@ + int cache_data_flush_range(void *addr, size_t size) + { + esp_err_t ret; + ++ if (size == 0U) { ++ return 0; ++ } ++ + ret = esp_cache_msync(addr, size, + ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_UNALIGNED); +@@ -58,6 +62,10 @@ + uintptr_t aligned_addr = (uintptr_t)addr & ~(line - 1); + size_t aligned_size = (((uintptr_t)addr + size + line - 1) & ~(line - 1)) - aligned_addr; + ++ if (size == 0U) { ++ return 0; ++ } ++ + ret = esp_cache_msync((void *)aligned_addr, aligned_size, ESP_CACHE_MSYNC_FLAG_DIR_M2C); + + return (ret == ESP_OK || ret == ESP_ERR_NOT_SUPPORTED) ? 0 : -EIO; +@@ -67,6 +75,10 @@ + int cache_data_flush_and_invd_range(void *addr, size_t size) + { + esp_err_t ret; + ++ if (size == 0U) { ++ return 0; ++ } ++ + ret = esp_cache_msync(addr, size, + ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_INVALIDATE | diff --git a/ci/s2mini.conf b/ci/s2mini.conf new file mode 100644 index 0000000..1f51014 --- /dev/null +++ b/ci/s2mini.conf @@ -0,0 +1,5 @@ +# First bring-up uses internal SRAM only; the clone's advertised PSRAM is untested. +CONFIG_ESP_SPIRAM=n +CONFIG_STACK_SENTINEL=y +# Match the upstream S2 DWC2 support fix, rather than the generic 512-byte default. +CONFIG_UDC_DWC2_STACK_SIZE=1024 diff --git a/ci/s2mini.overlay b/ci/s2mini.overlay new file mode 100644 index 0000000..4de51d8 --- /dev/null +++ b/ci/s2mini.overlay @@ -0,0 +1,25 @@ +/* + * S2 USB node adapted from upstream Zephyr PR #125458 for v4.5.0. + * SPDX-License-Identifier: Apache-2.0 + */ +/* Loaded before the CDC snippet so its zephyr_udc0 reference is resolvable. */ +&{/soc} { + zephyr_udc0: usb_otg: usb_otg@60080000 { + compatible = "espressif,esp32-usb-otg-fs", "snps,dwc2"; + reg = <0x60080000 DT_SIZE_K(256)>; + interrupts = ; + interrupt-parent = <&intc>; + clocks = <&clock ESP32_USB_MODULE>; + num-out-eps = <7>; + num-in-eps = <5>; + ghwcfg1 = <0x00000000>; + ghwcfg2 = <0x224dd930>; + ghwcfg4 = <0xd3f0a030>; + g-rx-fifo-size = <64>; + g-np-tx-fifo-size = <16>; + g-tx-fifo-size = <32 32 32 24>; + phy-dp-pin = <20>; + phy-dm-pin = <19>; + status = "okay"; + }; +}; diff --git a/docs/esp32-images.md b/docs/esp32-images.md index a46c317..ce251c3 100644 --- a/docs/esp32-images.md +++ b/docs/esp32-images.md @@ -10,6 +10,10 @@ producing a binary. | ESP32-DevKitC, primary CPU | `esp32_devkitc/esp32/procpu` | baseline; ML-DSA-44 verification | | ESP32-S3-DevKitC, primary CPU | `esp32s3_devkitc/esp32s3/procpu` | baseline; ML-DSA-44 verification | | ESP32-C3-DevKitM | `esp32c3_devkitm/esp32c3` | baseline; ML-DSA-44 verification | +| ESP32-S2 Lolin Mini reference / XTVTX candidate | `esp32s2_lolin_mini/esp32s2` | baseline; ML-DSA-44 verification; USB CDC console | + +For the S2 Mini, use the [specific download, native USB and test instructions](s2mini-pqc.md). +XTVTX compatibility and advertised PSRAM have not been verified on hardware. Other modules/flash layouts need their own validated board configuration. Do not flash these binaries to an ESP8266, an ESP32 secondary CPU, or an arbitrary @@ -39,11 +43,15 @@ The strict server policy must not be weakened to make a demonstration connect. ## Build and artifact provenance The source revisions are the repository's exact candidate, Zephyr -`dccb09599635bdff17633fa7e9dab014b91dce90`, and Dilithium reference +`41d10b59730406bbab4ca9f1fbbe9e96aafb4966` (v4.5.0), and Dilithium reference `d35ba3fe5449bee3e6d43e1f296c3ca818bd36be`. The official Zephyr CI image is digest-pinned to its Linux/amd64 manifest and supplies SDK1.0.1. Preparation creates its Python environment only inside the disposable job workspace. +Only the S2 Mini applies the documented [USB backport](s2mini-pqc.md#zephyr-version-and-usb-backport). +Its source patch files and hashes are included in each S2 artifact and manifest. +Other boards use unmodified release sources. The full matrix rebuilds after a pin update. + Each board produces an artifact named `pqc--`, containing `baseline/` and `mldsa44/`. Each profile has: diff --git a/docs/s2mini-pqc.md b/docs/s2mini-pqc.md new file mode 100644 index 0000000..aac0a12 --- /dev/null +++ b/docs/s2mini-pqc.md @@ -0,0 +1,139 @@ +# ESP32-S2 Mini: first Zephyr PQC test + +This target is for an **ESP32-S2 Mini V1.0.0, 4 MB flash, advertised 2 MB PSRAM**, +using Zephyr's `esp32s2_lolin_mini/esp32s2` reference board. The requested XTVTX +board is a third-party variant: its wiring, flash and USB operation have not yet +been verified on hardware. Check the actual board/chip before programming it. + +Use a standalone development board powered by USB, disconnected from KC heater, +relay, sensor and mains circuitry. This is not KettleCompanion application firmware. +It does not drive an application GPIO or contain Wi-Fi credentials. + +## What the two images do + +Both profiles appear alongside the other boards in the +[USB programming matrix](https://dynamicdevices.github.io/pqc-testing/#firmware-title). +Choose the **LOLIN / XTVTX S2 Mini** row and **Program latest** in desktop Chrome +or Edge. The publisher waits for the current trusted main build; programming +rechecks freshness and checksums, rejects the wrong chip or provisioned security +state, and writes the Simple Boot image at **0x1000**. There is no older-build +fallback. Each row links to the exact source, compiled config, S2 config/overlay, +build run and downloadable evidence. An unmerged PR artifact is not a main release. + +All four Zephyr board targets (ESP32, S3, C3 and S2 Mini) use the shared **4.5.0** +pin. Only S2 Mini applies the documented USB backport. The ESP8266 and ESP-IDF +CheerLightsQ builds use their own frameworks; they are not Zephyr targets. + +1. **baseline:** boot Zephyr and print a stack watermark and `RESULT: PASS`. +2. **mldsa44:** verify a synthetic ML-DSA-44 signature five times, then reject + tampered signature/message, wrong key/context, truncated, oversized and empty + signatures. Print verdicts, elapsed time, stack watermark and `RESULT: PASS`. + +This uses the project's pinned PQ-Crystals implementation and public test fixture, +not wolfSSL or host TLS offload. It is an algorithm feasibility test, not a FIPS +validation, verified boot, OTA security, PQC HTTPS client or production image. +An image building successfully does not prove any of these tests passed on a board. + +**PSRAM is deliberately disabled for this first test.** Both profiles use internal +SRAM so a clone's unknown PSRAM wiring cannot mask initial bring-up failures. +The chip has 320 KB SRAM in total; that is not available application heap. +The manifest records advertised PSRAM separately from enabled/verified memory. +Do not treat this build as evidence that the extra 2 MB works. + +## Zephyr version and USB backport + +The base is **Zephyr v4.5.0**, pinned to +`41d10b59730406bbab4ca9f1fbbe9e96aafb4966`, with its declared hal_espressif +`cc81db00233af6020f2fea9fbb0d0098fb3d0d86`. This release does not yet expose +the S2 USB controller, despite the chip having USB hardware. + +The S2 build adapts the upstream fixes in +[Zephyr PR #125458](https://github.com/zephyrproject-rtos/zephyr/pull/125458) and +[hal_espressif PR #694](https://github.com/zephyrproject-rtos/hal_espressif/pull/694): + +- The board overlay supplies the S2 DWC2 node, PHY pins, FIFO layout and endpoint + counts; it loads before the generic CDC-console snippet. +- The HAL patch supplies the missing USB includes and wrapper source. +- The Zephyr cache patch handles empty USB cache-sync ranges without calling + the HAL with a null buffer. The DWC2 worker stack is set to the upstream S2 size. + +These are narrow S2-only backports, not a claim that the release supports S2 USB +without changes. Preparation checks exact dependency commits and patch applicability +and fails closed on drift. Patch files/hashes and base revisions are shipped with +the artifacts. The non-S2 builds remain unpatched. Hardware USB enumeration is +still unverified on this XTVTX board. + +The packaging guard reads flash capacity from the compiled devicetree's chosen +flash node, matching Zephyr 4.5's Espressif image builder. It does not depend on +the old `CONFIG_FLASH_SIZE` symbol. USB, stack-sentinel and disabled-PSRAM checks +still use the effective configuration and report their observed values on failure. + +## Obtain the exact build + +Use a successful **ESP32 test images** run with an `images-esp32s2mini` job. +Download `pqc-esp32s2mini-SOURCE_SHA` from that run, not an ESP32/S3/C3 image. +Record the run URL and full source SHA. GitHub artifacts expire after 14 days. + +```sh +gh run download RUN_ID --repo DynamicDevices/pqc-testing --name pqc-esp32s2mini-SOURCE_SHA +cd baseline +sha256sum -c SHA256SUMS +``` + +Read `manifest.json`: it must name `esp32s2_lolin_mini/esp32s2`, `esp32s2`, +the intended profile, `flash_offset: 0x1000`, 4 MB flash, USB CDC console and +`psram_enabled: false`. `hardware_tested` and `pqc_tls` are false. +The package includes the effective `.config`, devicetree, linker map, licences, +inventories and compiler stack-usage report. Static reports are not whole-thread +worst-case bounds or runtime headroom measurements. + +## Flash baseline first + +Use esptool 5.2.0 in an isolated environment. Verify the chip and flash capacity +before writing. Use the actual detected port, not this placeholder: + +```sh +esptool --chip esp32s2 --port /dev/ttyACM0 flash-id +esptool --chip esp32s2 --port /dev/ttyACM0 write-flash --flash-mode dio --flash-size 4MB 0x1000 zephyr.bin +``` + +If needed, enter the ROM downloader by holding BOOT, pressing/releasing RESET, +then releasing BOOT. Some boards require unplug/replug with BOOT held. Use a +data-capable USB cable. Never use `--force`, burn fuses, disable security or run +a whole-chip erase to work around an unidentified failure. Do not write to a +production, encrypted or secure-boot-enabled device with this unsigned image. + +## Read the native USB console + +These images explicitly select Zephyr's **USB CDC ACM** console because the Mini +normally connects its USB port directly to the ESP32-S2, rather than a UART bridge. +Firmware USB and ROM-download USB can enumerate as different ports. After reset, +find the new CDC port and open a serial terminal at 115200 baud with DTR asserted. +The application waits up to 30 seconds for DTR, then runs the tests once regardless. +No periodic tests, background monitoring or flash-persisted counters are added. + +If the terminal misses the output, reset/reconnect and open it again promptly. +No output is an incomplete test, not a pass. If USB never enumerates, preserve +the image identity and error, recover to the ROM downloader and investigate the +clone/USB support rather than repeatedly reflashing the same failed image. + +Baseline must print `RESULT: PASS`. Then verify checksums and flash the `mldsa44/` +image in the same way. All acceptance and rejection lines must say PASS, followed +by `RESULT: PASS`. Preserve any exception, watchdog reset or stack-sentinel fault; +those are failures, not acceptable results. + +## Return these results + +- Board marking/revision, detected chip/flash, run URL, source SHA and image SHA256. +- Baseline console result and the complete ML-DSA acceptance/rejection results. +- Elapsed time and `main_stack_unused_bytes`; the main stack is configured to + 49152 bytes. Measure spare stack on the full exercised test, not just at boot. +- Resets, USB problems or exceptions. Do not include private credentials. + +Hardware results apply only to that exact image and board. A working baseline +and verifier are the first gate; PSRAM validation and real Zephyr networking with +hybrid TLS and certificate verification remain separate follow-on work. + +See [general image provenance and limitations](esp32-images.md). + +Assisted-by: Briar. diff --git a/docs/zephyr-simulator.md b/docs/zephyr-simulator.md index af0a2ce..5641a2e 100644 --- a/docs/zephyr-simulator.md +++ b/docs/zephyr-simulator.md @@ -1,6 +1,7 @@ # Run Zephyr application tests against the PQC lab -This builds a real **Zephyr 4.4.2 native simulator** application on 64-bit Linux. +This targets a real **Zephyr 4.5.0 native simulator** application on 64-bit Linux. +The recorded live results below used 4.4.2; they are not a 4.5.0 test pass. Its C application fetches the HTTPS page and speaks MQTT5. A small, explicitly host-only backend uses Linux sockets and OpenSSL for TLS. No root privileges, TAP devices, host firewall changes, emulated network setup or hardware are needed. @@ -52,7 +53,7 @@ export PQC_ZEPHYR_WORKSPACE="$PWD" cd pqc-testing ``` -`west.yml` pins Zephyr to `dccb09599635bdff17633fa7e9dab014b91dce90`. +`west.yml` pins Zephyr to `41d10b59730406bbab4ca9f1fbbe9e96aafb4966` (v4.5.0). The runner refuses another revision. An existing workspace at that pin is also usable: set `PQC_ZEPHYR_WORKSPACE` to its parent directory and activate a Python environment with Zephyr's build dependencies installed. Set `PQC_GIT` to a Git @@ -201,8 +202,8 @@ selection switch for this application. Primary source anchors, pinned to the tested Zephyr revision: -- [ESP32 boards](https://github.com/zephyrproject-rtos/zephyr/tree/dccb09599635bdff17633fa7e9dab014b91dce90/boards/espressif) -- [ESP8266 modem shields](https://github.com/zephyrproject-rtos/zephyr/tree/dccb09599635bdff17633fa7e9dab014b91dce90/boards/shields/esp_8266) -- [Mbed TLS / PSA Kconfig](https://github.com/zephyrproject-rtos/zephyr/blob/dccb09599635bdff17633fa7e9dab014b91dce90/modules/mbedtls/Kconfig.tf-psa-crypto) +- [ESP32 boards](https://github.com/zephyrproject-rtos/zephyr/tree/41d10b59730406bbab4ca9f1fbbe9e96aafb4966/boards/espressif) +- [ESP8266 modem shields](https://github.com/zephyrproject-rtos/zephyr/tree/41d10b59730406bbab4ca9f1fbbe9e96aafb4966/boards/shields/esp_8266) +- [Mbed TLS / PSA Kconfig](https://github.com/zephyrproject-rtos/zephyr/blob/41d10b59730406bbab4ca9f1fbbe9e96aafb4966/modules/mbedtls/Kconfig.tf-psa-crypto) Assisted-by: Briar diff --git a/firmware_site.py b/firmware_site.py index 1b6c257..ac95c52 100644 --- a/firmware_site.py +++ b/firmware_site.py @@ -156,7 +156,7 @@ def image_from_archive(data, target, head): 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"])): + ("profile", target["profile"]), ("chip", target.get("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 @@ -164,11 +164,33 @@ def image_from_archive(data, target, head): 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: + s2mini = target["artifact_board"] == "esp32s2mini" + dt_flash = manifest.get("flash_bytes") + if ((not flash and (type(dt_flash) is not int or dt_flash <= 0)) or + "CONFIG_ESP_SPIRAM=y" in config or "CONFIG_SPIRAM=y" in config): raise ValueError("Unknown flash/PSRAM board configuration") - # This pinned Zephyr revision emits CONFIG_FLASH_SIZE in bytes (the - # ESP32 4 MiB artifact records 4194304), not legacy KiB units. - flash_bytes = int(flash[1]) + # C3 retains Kconfig FLASH_SIZE in KiB; older ESP32 packages used bytes. + # The builder-validated devicetree size is authoritative when present; + # accept only these exact unit conversions, never inconsistent capacity. + if dt_flash is not None and (type(dt_flash) is not int or dt_flash <= 0 or + (flash and int(flash[1]) != dt_flash and int(flash[1]) * 1024 != dt_flash)): + raise ValueError("Contradictory flash configuration") + if s2mini: + # The pinned builder checks chosen flash in compiled devicetree; + # Zephyr 4.5 S2 no longer emits CONFIG_FLASH_SIZE. Keep its exact + # image-bound manifest, config and DTS in the evidence bundle. + required = {"CONFIG_SOC=\"esp32s2\"", "CONFIG_USB_DEVICE_STACK_NEXT=y", + "CONFIG_USBD_CDC_ACM_CLASS=y", "CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=y", + "CONFIG_STACK_SENTINEL=y", + "CONFIG_MAIN_STACK_SIZE=49152"} + if (type(manifest.get("flash_bytes")) is not int or manifest["flash_bytes"] != 4194304 or + manifest.get("psram_enabled") is not False or + not required.issubset(config.splitlines()) or + (flash and int(flash[1]) != manifest["flash_bytes"] and int(flash[1]) * 1024 != manifest["flash_bytes"])): + raise ValueError("Unsupported S2 Mini flash/USB/stack configuration") + # Retain earlier image-bound CONFIG_FLASH_SIZE values in bytes; + # 4.5 packages carry the builder-validated chosen-devicetree size. + flash_bytes = dt_flash if dt_flash is not None else int(flash[1]) image = archive.read(prefix + "zephyr.bin") hashes = manifest.get("sha256", {}) inventory_files = {} @@ -182,6 +204,8 @@ def image_from_archive(data, target, head): if any(name not in inventory_files for name in firmware_inventory.INVENTORIES): raise ValueError("Missing build-bound SBOM/CBOM evidence; rebuild firmware") firmware_inventory.validate_documents(inventory_files, manifest) + if dt_flash is not None and "zephyr.dts" not in inventory_files: + raise ValueError("Missing compiled devicetree evidence") 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 diff --git a/simulator_test.py b/simulator_test.py index 8b1598f..0d0572b 100644 --- a/simulator_test.py +++ b/simulator_test.py @@ -14,7 +14,7 @@ import sys ROOT = Path(__file__).resolve().parent -PIN = "dccb09599635bdff17633fa7e9dab014b91dce90" +PIN = "41d10b59730406bbab4ca9f1fbbe9e96aafb4966" # Zephyr v4.5.0 CASES = {"https-pqc-transfer", "mqtt-pqc-round-trip", "mqtt-bad-password", "mqtt-forbidden-publish"} | { f"{service}-{case}" for service in ("https", "mqtt") diff --git a/site/firmware-targets.json b/site/firmware-targets.json index 7615b79..f6258e3 100644 --- a/site/firmware-targets.json +++ b/site/firmware-targets.json @@ -9,7 +9,7 @@ }, "esp32": { "workflow": "esp32-images.yml", - "jobs": ["runner-preflight", "images-esp32", "images-esp32s3", "images-esp32c3"], + "jobs": ["runner-preflight", "images-esp32", "images-esp32s3", "images-esp32c3", "images-esp32s2mini"], "inputs": ["src/", "host/", "ci/", "vendor/", "firmware_inventory.py", "examples/andysc/review/schema-sources.json", ".gitmodules", "LICENSE", "THIRD_PARTY.md", "prj.conf", "crypto.cmake", "CMakeLists.txt", "west.yml", ".github/workflows/esp32-images.yml"] }, "esp8266": { @@ -25,6 +25,8 @@ {"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":"esp32s2mini-baseline","channel":"esp32","family":"ESP32-S2","board":"esp32s2_lolin_mini/esp32s2","artifact_board":"esp32s2mini","chip":"esp32s2","profile":"baseline","offset":4096,"label":"LOLIN / XTVTX S2 Mini · boot baseline (PSRAM off; hardware untested)"}, + {"id":"esp32s2mini-mldsa44","channel":"esp32","family":"ESP32-S2","board":"esp32s2_lolin_mini/esp32s2","artifact_board":"esp32s2mini","chip":"esp32s2","profile":"mldsa44","offset":4096,"label":"LOLIN / XTVTX S2 Mini · ML-DSA-44 verification (offline; PSRAM off)"}, {"id":"esp32-cheerlightsq","channel":"cheerlightsq","family":"ESP32","board":"esp32-wroom-32","artifact_board":"esp32","profile":"cheerlightsq","offset":4096,"flash_layout":"esp-idf-esp32-v1","label":"ESP32-WROOM-32 · experimental CheerLightsQ colour client"}, {"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/installer.js b/site/installer.js index 9bd993b..5265e2b 100644 --- a/site/installer.js +++ b/site/installer.js @@ -15,6 +15,11 @@ export function inspectionLinks(entry) { return [ ['Source revision', `https://github.com/${REPO}/tree/${entry.source_head}`], ['Compiled configuration', directory + (entry.flash_layout === 'esp-idf-esp32-v1' ? 'sdkconfig' : 'zephyr.config')], + ...(entry.artifact_board === 'esp32s2mini' ? [ + ['S2 Mini flashing and USB serial guide', `https://github.com/${REPO}/blob/${entry.source_head}/docs/s2mini-pqc.md`], + ['S2 Mini build configuration', `https://github.com/${REPO}/blob/${entry.source_head}/ci/s2mini.conf`], + ['S2 Mini USB overlay', `https://github.com/${REPO}/blob/${entry.source_head}/ci/s2mini.overlay`], + ] : []), ['Build manifest', directory + 'build-manifest.json'], ['SPDX SBOM', directory + 'sbom.spdx.json'], ['CycloneDX CBOM', directory + 'cbom.cdx.json'], diff --git a/src/main.c b/src/main.c index 9fb70bc..2770762 100644 --- a/src/main.c +++ b/src/main.c @@ -2,6 +2,26 @@ #include #include #include +#ifdef CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT +#include +#include +static int wait_for_console(void) +{ + const struct device *console = DEVICE_DT_GET(DT_CHOSEN(zephyr_console)); + if (!device_is_ready(console)) { + return -1; + } + /* A finite attach window, not a forever wait or periodic background test. */ + for (int i = 0; i < 300; ++i) { + uint32_t dtr = 0; + if (uart_line_ctrl_get(console, UART_LINE_CTRL_DTR, &dtr) == 0 && dtr) { + return 0; + } + k_msleep(100); + } + return 0; /* Tests still run without an attached terminal; no result is inferred. */ +} +#endif #if PQC_ENABLED #include "sign.h" #include "fixture.h" @@ -19,6 +39,11 @@ static int verify(const uint8_t *sig, size_t n, const uint8_t *msg, int main(void) { +#ifdef CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT + if (wait_for_console() != 0) { + return 1; + } +#endif int failures = 0; printk("PQC feasibility: %s\n", PQC_ENABLED ? "ML-DSA-44 reference" : "baseline"); #if PQC_ENABLED diff --git a/tests/installer.test.mjs b/tests/installer.test.mjs index f4374ea..ec5667e 100644 --- a/tests/installer.test.mjs +++ b/tests/installer.test.mjs @@ -8,6 +8,36 @@ import {program, validateFresh, validateRun, verifiedParts, checkDevice, inspect 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'); +test('S2 Mini profiles retain exact build/config links and ESP32-S2 layout', () => { + const targets = policy.targets.filter(t => t.artifact_board === 'esp32s2mini'); + assert.equal(targets.length, 2); + assert.ok(policy.channels.esp32.jobs.includes('images-esp32s2mini')); + for (const target of targets) { + assert.equal(target.family, 'ESP32-S2'); + assert.equal(target.offset, 0x1000); + const entry = {...fixture().entry, ...target}; + const links = Object.fromEntries(inspectionLinks(entry)); + assert.equal(links['S2 Mini build configuration'], `https://github.com/${policy.repository}/blob/${entry.source_head}/ci/s2mini.conf`); + assert.equal(links['S2 Mini USB overlay'], `https://github.com/${policy.repository}/blob/${entry.source_head}/ci/s2mini.overlay`); + assert.match(links['S2 Mini flashing and USB serial guide'], /docs\/s2mini-pqc\.md$/); + } +}); + +test('both S2 Mini profiles program only a matching non-provisioned ESP32-S2', async () => { + for (const target of policy.targets.filter(t => t.artifact_board === 'esp32s2mini')) { + const f = fixture(); + Object.assign(f.entry, target); + f.entry.parts[0].path = `firmware/7/attempt-1/${target.id}/${'b'.repeat(64)}/firmware.bin`; + f.loader.chip.CHIP_NAME = 'ESP32-S2'; + f.loader.getSecurityInfo = async () => ({parsedFlags: {SECURE_BOOT_EN: false, SECURE_DOWNLOAD_ENABLE: false}, flashCryptCnt: 0}); + await program(f.entry, f.services); + assert.deepEqual(f.calls, ['open', 'write', 'reset', 'close']); + f.calls.length = 0; + f.loader.chip.CHIP_NAME = 'ESP32-S3'; + await assert.rejects(program(f.entry, f.services), /Wrong chip/); + assert.ok(!f.calls.includes('write')); + } +}); 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, evidence_sha256: 'b'.repeat(64), diff --git a/tests/test_esp32_images.py b/tests/test_esp32_images.py index 57e540c..8fb2b1c 100644 --- a/tests/test_esp32_images.py +++ b/tests/test_esp32_images.py @@ -4,8 +4,9 @@ import os from pathlib import Path import tempfile +import types import unittest -from unittest.mock import patch +from unittest.mock import Mock, patch PATH = Path(__file__).resolve().parents[1] / "ci/esp32_images.py" spec = importlib.util.spec_from_file_location("esp32_images", PATH) @@ -14,6 +15,39 @@ class ImageBuilderTests(unittest.TestCase): + def test_exact_digest_image_is_pulled_only_when_missing(self): + for returncode in (0, 1): + with self.subTest(returncode=returncode), \ + patch.object(builder.subprocess, "run", return_value=types.SimpleNamespace(returncode=returncode)) as inspect, \ + patch.object(builder, "command") as run: + builder.ensure_image() + inspect.assert_called_once_with(["docker", "image", "inspect", builder.IMAGE], capture_output=True, timeout=20) + if returncode: + run.assert_called_once_with(["docker", "pull", builder.IMAGE], timeout=900) + else: + run.assert_not_called() + + def test_profiles_share_build_tree_but_package_baseline_before_reconfiguration(self): + for board in builder.BOARDS: + events = [] + with self.subTest(board=board), patch.object(builder, "container_guard"), \ + patch.object(Path, "read_text", side_effect=['a' * 40, '1.0.1']), \ + patch.dict(os.environ, {'ZEPHYR_SDK_INSTALL_DIR': '/sdk'}), \ + patch.object(builder, "command", side_effect=lambda args, **kw: events.append(args)), \ + patch.object(builder, "package", side_effect=lambda b, p, d, out, h: events.append(('package', b, p, d, h))): + builder.build_container(board) + configured = [e for e in events if isinstance(e, list) and + any(flag in e for flag in ('-DPQC_ENABLED=OFF', '-DPQC_ENABLED=ON'))] + self.assertEqual(len(configured), 2) + self.assertEqual(configured[0][configured[0].index('-B') + 1], '/work/build-' + board) + self.assertEqual(configured[0][configured[0].index('-B') + 1], configured[1][configured[1].index('-B') + 1]) + baseline = next(e for e in events if isinstance(e, tuple) and e[2] == 'baseline') + signature = next(e for e in events if isinstance(e, tuple) and e[2] == 'mldsa44') + self.assertLess(events.index(baseline), events.index(configured[1])) + self.assertLess(events.index(configured[1]), events.index(signature)) + self.assertEqual(baseline[3], signature[3]) + self.assertEqual(baseline[4], 'a' * 40) + def test_complete_zephyr_requirements_installed_in_build_interpreter(self): with patch.object(builder, "command") as run: builder.install_zephyr_requirements("/work/.venv/bin/python") @@ -29,7 +63,7 @@ def test_imported_modules_use_filtered_full_update(self): builder.update_imported_modules(west) self.assertEqual(run.call_args_list[0].args[0], west + [ "config", "--", "manifest.project-filter", "-.*,+zephyr,+hal_espressif,+hal_xtensa"]) - self.assertEqual(run.call_args_list[1].args[0], west + ["update", "--narrow"]) + self.assertEqual(run.call_args_list[1].args[0], west + ["update", "--narrow", "--fetch-opt=--depth=1"]) def test_build_tools_installed_for_the_exact_build_interpreter(self): with patch.object(builder, "command") as run: @@ -61,10 +95,87 @@ def test_no_local_or_hosted_fallback(self): builder.guard_environment() def test_matrix_has_no_esp8266_or_native_sim(self): - self.assertEqual(set(builder.BOARDS), {"esp32", "esp32s3", "esp32c3"}) + self.assertEqual(set(builder.BOARDS), {"esp32", "esp32s3", "esp32c3", "esp32s2mini"}) self.assertEqual(builder.BOARDS["esp32"][2], 0x1000) self.assertEqual(builder.BOARDS["esp32s3"][2], 0) + def test_s2mini_target_layout_and_native_usb(self): + self.assertEqual(builder.BOARDS["esp32s2mini"], + ("esp32s2_lolin_mini/esp32s2", "esp32s2", 0x1000)) + args = builder.board_build_args("esp32s2mini") + self.assertIn("-DSNIPPET=cdc-acm-console", args) + self.assertIn("s2mini.conf", args[0]) + self.assertIn("s2mini.overlay", args[2]) + self.assertTrue(args[2].startswith("-DDTC_OVERLAY_FILE=")) + for board in ("esp32", "esp32c3", "esp32s3"): + self.assertEqual(builder.board_build_args(board), + ["-DEXTRA_CONF_FILE=" + str(builder.ROOT / "ci/esp32.conf")]) + + def test_release_pins_are_consistent(self): + import simulator_test + self.assertEqual(builder.ZEPHYR, "41d10b59730406bbab4ca9f1fbbe9e96aafb4966") + self.assertEqual(simulator_test.PIN, builder.ZEPHYR) + self.assertIn("revision: " + builder.ZEPHYR, (builder.ROOT / "west.yml").read_text()) + + def test_usb_backport_only_applied_to_s2_at_exact_bases(self): + with patch.object(builder, "command") as run, patch.object(builder.subprocess, "check_output") as read: + builder.apply_board_patches("esp32s3") + run.assert_not_called() + read.assert_not_called() + read.side_effect = [revision + "\n" for _, revision, _ in builder.s2mini_patch_specs()] + builder.apply_board_patches("esp32s2mini") + self.assertEqual(run.call_count, 4) + for check, apply in zip(run.call_args_list[::2], run.call_args_list[1::2]): + self.assertIn("--check", check.args[0]) + self.assertNotIn("--check", apply.args[0]) + with patch.object(builder, "command") as run, \ + patch.object(builder.subprocess, "check_output", return_value="wrong\n"): + with self.assertRaisesRegex(RuntimeError, "Wrong source revision"): + builder.apply_board_patches("esp32s2mini") + run.assert_not_called() + + def test_patch_check_failure_stops_before_mutation(self): + with patch.object(builder.subprocess, "check_output", return_value=builder.ZEPHYR + "\n"), \ + patch.object(builder, "command", side_effect=builder.subprocess.CalledProcessError(1, "git apply")) as run: + with self.assertRaises(builder.subprocess.CalledProcessError): + builder.apply_board_patches("esp32s2mini") + self.assertEqual(run.call_count, 1) + self.assertIn("--check", run.call_args.args[0]) + + def test_s2mini_rejects_wrong_flash_console_psram_or_stack_policy(self): + good = dict(CONFIG_ESP_SIMPLE_BOOT="y", CONFIG_SOC='"esp32s2"', + CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT="y", + CONFIG_STACK_SENTINEL="y") + # A modern configuration without legacy CONFIG_FLASH_SIZE must be accepted. + builder.check_s2mini_policy(good, 4 * 1024 * 1024) + with self.assertRaisesRegex(RuntimeError, "S2 Mini requires"): + builder.check_s2mini_policy(good, 8 * 1024 * 1024) + for key, value in (("CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT", "n"), + ("CONFIG_ESP_SPIRAM", "y"), ("CONFIG_STACK_SENTINEL", "n")): + with self.subTest(key=key): + with self.assertRaisesRegex(RuntimeError, "S2 Mini requires"): + builder.check_s2mini_policy(dict(good, **{key: value}), 4 * 1024 * 1024) + + def test_compiled_flash_size_uses_chosen_node_and_rejects_bad_reg(self): + reg = Mock() + flash = types.SimpleNamespace(props={"reg": reg}) + chosen = types.SimpleNamespace(props={"zephyr,flash": Mock()}) + chosen.props["zephyr,flash"].to_path.return_value = flash + tree = Mock() + tree.get_node.return_value = chosen + module = types.ModuleType("devicetree.dtlib") + module.DT = Mock(return_value=tree) + with patch.dict(builder.sys.modules, {"devicetree": types.ModuleType("devicetree"), + "devicetree.dtlib": module}), \ + patch.object(builder.sys, "path", list(builder.sys.path)): + reg.to_nums.return_value = [0, 4 * 1024 * 1024] + self.assertEqual(builder.compiled_flash_bytes(Path("effective.dts")), 4 * 1024 * 1024) + tree.get_node.assert_called_with("/chosen") + for cells in ([4 * 1024 * 1024], [1, 4 * 1024 * 1024], [0, 0, 4 * 1024 * 1024]): + reg.to_nums.return_value = cells + with self.assertRaisesRegex(RuntimeError, "Unexpected flash"): + builder.compiled_flash_bytes(Path("effective.dts")) + def test_container_is_nonroot_confined_and_has_independent_timeout(self): with patch.object(builder, "command") as run, patch.object(builder.subprocess, "run") as stop, \ patch.object(builder.os, "getuid", return_value=1000), patch.object(builder.os, "getgid", return_value=1000): diff --git a/tests/test_firmware_site.py b/tests/test_firmware_site.py index b95a172..cdad955 100644 --- a/tests/test_firmware_site.py +++ b/tests/test_firmware_site.py @@ -13,18 +13,32 @@ HEAD = 'a' * 40 -def archive(target, mutate=None): +def archive(target, mutate=None, modern=False, flash_kib=False): files = {'zephyr.bin': b'\xe9\x01\x02\x03', 'zephyr.elf': b'ELF fixture', 'zephyr.map': b'map fixture', 'zephyr.config': b'CONFIG_FLASH_SIZE=4194304\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'], + s2mini = target['artifact_board'] == 'esp32s2mini' + if modern: + files['zephyr.config'] = b'CONFIG_ESP_SIMPLE_BOOT=y\n' + if flash_kib: + files['zephyr.config'] += b'CONFIG_FLASH_SIZE=4096\n' + files['zephyr.dts'] = b'compiled DTS fixture; validated by pinned builder' + if s2mini: + files['zephyr.config'] = (b'CONFIG_ESP_SIMPLE_BOOT=y\nCONFIG_SOC="esp32s2"\n' + b'CONFIG_USB_DEVICE_STACK_NEXT=y\nCONFIG_USBD_CDC_ACM_CLASS=y\n' + b'CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=y\n' + b'CONFIG_STACK_SENTINEL=y\nCONFIG_MAIN_STACK_SIZE=49152\n') + files['zephyr.dts'] = b'compiled DTS fixture; validated by pinned builder' + manifest = dict(board=target['board'], chip=target.get('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, zephyr_revision='b'*40, reference_revision='c'*40 if target['profile']=='mldsa44' else None, modules={'hal_espressif':'d'*40,'hal_xtensa':'e'*40}, sdk_version='1.0.1', build_image='sha256:'+'f'*64, sha256={k: site.sha256(v) for k, v in files.items()}) + if s2mini or modern: + manifest.update(flash_bytes=4194304, psram_enabled=False) docs = inventory.make_documents(manifest) files.update(docs) manifest['sha256'].update({k:site.sha256(v) for k,v in docs.items()}) @@ -61,7 +75,7 @@ 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): + def test_eight_images_published_from_four_verified_artifacts(self): class Complete(API): def __init__(self): super().__init__() @@ -70,15 +84,15 @@ def __init__(self): 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'))]} + for i, board in enumerate(('esp32', 'esp32s3', 'esp32c3', 'esp32s2mini'))]} return super().json(path) def archive(self, artifact): self.downloads.append(artifact['id']) - board = ('esp32', 'esp32s3', 'esp32c3')[artifact['id']] + board = ('esp32', 'esp32s3', 'esp32c3', 'esp32s2mini')[artifact['id']] output = io.BytesIO() with zipfile.ZipFile(output, 'w') as destination: - for target in POLICY['targets'][:6]: + for target in POLICY['targets'][:8]: if target['artifact_board'] == board: with zipfile.ZipFile(io.BytesIO(archive(target))) as source: for name in source.namelist(): @@ -88,9 +102,9 @@ def archive(self, artifact): 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(len([b for b in result['builds'] if b['available']]), 8) + self.assertEqual(len(api.downloads), 4) + for entry in result['builds'][:8]: self.assertEqual(entry['run_attempt'], 1) manifest = json.loads((Path(temp) / entry['manifest']).read_text()) self.assertEqual(manifest['source_head'], entry['source_head']) @@ -134,12 +148,58 @@ def test_complete_source_freshness(self): 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]: + for target in POLICY['targets'][:8]: 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_s2mini_flash_usb_stack_psram_and_dts_guards(self): + target = next(t for t in POLICY['targets'] if t['id'] == 'esp32s2mini-mldsa44') + for change in (lambda m, f: m.update(chip='esp32s2mini'), + lambda m, f: m.update(flash_bytes=8388608), + lambda m, f: m.update(flash_bytes=True), + lambda m, f: m.update(psram_enabled=True), + lambda m, f: f.pop('zephyr.dts'), + lambda m, f: f.update({'zephyr.dts': b'tampered'})): + with self.subTest(change=change), self.assertRaises((ValueError, KeyError)): + site.image_from_archive(archive(target, change), target, HEAD) + for line in (b'CONFIG_USBD_CDC_ACM_CLASS=y', b'CONFIG_USB_DEVICE_STACK_NEXT=y', + b'CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=y', + b'CONFIG_STACK_SENTINEL=y', b'CONFIG_MAIN_STACK_SIZE=49152'): + def remove_required(m, f): + f['zephyr.config'] = f['zephyr.config'].replace(line, b'') + m['sha256']['zephyr.config'] = site.sha256(f['zephyr.config']) + with self.subTest(line=line), self.assertRaises(ValueError): + site.image_from_archive(archive(target, remove_required), target, HEAD) + + def test_zephyr_45_devicetree_flash_for_every_matrix_target(self): + for target in POLICY['targets'][:8]: + with self.subTest(target=target['id']): + files, size = site.image_from_archive(archive(target, modern=True), target, HEAD) + self.assertEqual(size, 4194304) + with zipfile.ZipFile(io.BytesIO(files['evidence.zip'])) as bundle: + self.assertIn('zephyr.dts', bundle.namelist()) + for change in (lambda m, f: m.pop('flash_bytes'), + lambda m, f: m.update(flash_bytes=True), + lambda m, f: m.update(flash_bytes=-1), + lambda m, f: f.pop('zephyr.dts'), + lambda m, f: f.update({'zephyr.dts': b'tampered'})): + with self.assertRaises((ValueError, KeyError)): + site.image_from_archive(archive(target, change, modern=True), target, HEAD) + + def test_c3_kconfig_kib_matches_devicetree_bytes_without_relaxing_capacity(self): + for target in POLICY['targets']: + if target.get('artifact_board') != 'esp32c3': + continue + files, size = site.image_from_archive(archive(target, modern=True, flash_kib=True), target, HEAD) + self.assertEqual(size, 4194304) + self.assertIn(b'CONFIG_FLASH_SIZE=4096', files['zephyr.config']) + for capacity in (2097152, 8388608): + with self.assertRaisesRegex(ValueError, 'Contradictory flash'): + site.image_from_archive(archive(target, lambda m, f: m.update(flash_bytes=capacity), + modern=True, flash_kib=True), target, HEAD) + 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), diff --git a/west.yml b/west.yml index 631d386..7905ecb 100644 --- a/west.yml +++ b/west.yml @@ -3,7 +3,7 @@ manifest: projects: - name: zephyr url: https://github.com/zephyrproject-rtos/zephyr - revision: dccb09599635bdff17633fa7e9dab014b91dce90 + revision: 41d10b59730406bbab4ca9f1fbbe9e96aafb4966 import: true self: path: pqc-testing