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.
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.
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..e97ea95
--- /dev/null
+++ b/tests/test_firmware_site.py
@@ -0,0 +1,151 @@
+"""Installer publisher tests: synthetic archives only, no firmware builds."""
+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_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):
+ 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()