mirror of
https://github.com/agessaman/MeshCore.git
synced 2026-12-04 11:54:12 +00:00
Merge branch 'feat/observer-stability-reduced-tls' into test/observer-stability-integration
This commit is contained in:
commit
48dfdbed5a
9 files changed
+570
-65
No files matched your search
@@ -41,6 +41,7 @@ Build all kiss radio firmwares
|
||||
$ sh build.sh build-kiss-radio-firmwares
|
||||
|
||||
Environment Variables:
|
||||
MESHCORE_REDUCED_TLS=0: Disables reduced TLS for observer release builds (default: auto).
|
||||
DISABLE_DEBUG=1: Disables all debug logging flags (MESH_DEBUG, MESH_PACKET_LOGGING, etc.)
|
||||
If not set, debug flags from variant platformio.ini files are used.
|
||||
|
||||
@@ -219,6 +220,15 @@ build_firmware() {
|
||||
# disable debug flags if requested
|
||||
disable_debug_flags
|
||||
|
||||
# Scope the observer default to this target, including the merged binary.
|
||||
case "$1" in
|
||||
*observer*)
|
||||
scripts/fetch_mbedtls_4k.sh --all
|
||||
local MESHCORE_REDUCED_TLS="${MESHCORE_REDUCED_TLS-auto}"
|
||||
export MESHCORE_REDUCED_TLS
|
||||
;;
|
||||
esac
|
||||
|
||||
# build firmware target
|
||||
pio run -e $1
|
||||
|
||||
|
||||
@@ -140,19 +140,40 @@ from the first archive that satisfies an undefined symbol.
|
||||
|
||||
They are not committed: ~6 MB per architecture, and they have to be rebuilt for every
|
||||
`platformio/espressif32` bump, so committing them would grow history permanently and go
|
||||
stale silently. Instead they are published as a release asset and fetched on demand:
|
||||
stale silently. Instead they are published as release assets and fetched on demand:
|
||||
|
||||
```
|
||||
scripts/fetch_mbedtls_4k.sh esp32s3 # download + verify against the manifest
|
||||
MESHCORE_REDUCED_TLS=1 pio run -e Heltec_v3_repeater_observer_mqtt
|
||||
```sh
|
||||
scripts/fetch_mbedtls_4k.sh --all # fetch every architecture in the manifest
|
||||
MESHCORE_REDUCED_TLS=auto pio run -e Heltec_v3_repeater_observer_mqtt
|
||||
```
|
||||
|
||||
- `scripts/mbedtls_4k_manifest.txt` — per-arch sha256 of each archive. **Update it on every
|
||||
platform bump**, together with the published asset.
|
||||
- `scripts/fetch_mbedtls_4k.sh` — downloads into `.mbedtls-4k/<arch>/` (gitignored) and
|
||||
verifies. `MBEDTLS_4K_LOCAL=<dir>` copies from a local build tree instead of downloading.
|
||||
- `scripts/mbedtls_4k.py` — wired into `esp32_base.extra_scripts`, but a **no-op unless
|
||||
`MESHCORE_REDUCED_TLS=1`**, so ordinary builds need no artifact and behave as before.
|
||||
- `scripts/mbedtls_4k_manifest.txt` pins the release tag, per-architecture archive hashes,
|
||||
and stock framework fingerprints. The current tag is `mbedtls-4k`. Every platform bump
|
||||
gets a new tag named after the platform version, with rebuilt archives and updated
|
||||
fingerprints. Never delete old tags: old commits must keep building with their pinned assets.
|
||||
- `scripts/fetch_mbedtls_4k.sh` downloads into `.mbedtls-4k/<arch>/` (gitignored) and
|
||||
verifies. Valid existing archives are a no-op, including offline use. Downloads retry on
|
||||
transient failures. Pass an architecture instead of `--all` to fetch only that one.
|
||||
`MBEDTLS_4K_LOCAL=<dir>` copies from a local build tree instead of downloading;
|
||||
`MBEDTLS_4K_BASE_URL` overrides the release download URL.
|
||||
- `scripts/mbedtls_4k.py` is wired into `esp32_base.extra_scripts`. With the variable unset,
|
||||
ordinary `pio run` needs no archives and uses the framework unchanged. `0` or an empty
|
||||
value disables the hook. `1` forces it for the selected environment and fails on any
|
||||
missing or incompatible archives.
|
||||
- `auto` selects environments whose resolved project and board flags define
|
||||
`WITH_MQTT_BRIDGE` without `BOARD_HAS_PSRAM`. A qualifying MCU absent from the manifest
|
||||
builds stock with a visible summary (currently classic `esp32`). Once its archive entries
|
||||
are added, all verification becomes mandatory, including the linker-map check.
|
||||
Each build with the variable set prints one summary; `active` appears only after the
|
||||
map check passes, including when the existing link is reused.
|
||||
|
||||
`build.sh build-firmware <env>` fetches all manifest architectures before each observer
|
||||
build and defaults to `MESHCORE_REDUCED_TLS=auto`. Both observer release workflows call
|
||||
this path. A fetch failure stops the build. Existing verified archives avoid repeated
|
||||
network access within a shard. Caller values are preserved, so
|
||||
`MESHCORE_REDUCED_TLS=0 FIRMWARE_VERSION=v0.0.0-test bash build.sh build-firmware <env>`
|
||||
is the escape hatch (the fetch still verifies or stages the archives). Non-observer
|
||||
builds neither fetch archives nor set the variable.
|
||||
|
||||
The opt-in path is deliberately loud, because both ways this can go wrong produce a
|
||||
firmware that looks correct and silently lacks the change:
|
||||
@@ -168,6 +189,17 @@ build flag reaching the compiler proves nothing about what got linked.
|
||||
|
||||
## How to verify it worked
|
||||
|
||||
An active build reports `reduced-TLS: <env>: active` after verifying all four linked
|
||||
archive paths. `strings .pio/build/<env>/firmware.bin | grep 'TLS outbound record'`
|
||||
finds the boot-log format, which prints `TLS outbound record: 4096 bytes (reduced)`.
|
||||
A plain build with the variable unset prints no reduced-TLS summary and its map names
|
||||
the framework's own archives.
|
||||
|
||||
Measured on a Heltec V3 with two WSS slots on November 10, 2026: boot free heap rose
|
||||
from 70.3 K to 94.9 K and the largest free block from 52.2 K to 75.8 K. After four slot
|
||||
reconfigures, the reduced build's largest block was 73.7 K; the stock build had fallen
|
||||
to 37.9 K after two. These are hardware observations from that comparison, not a fleet soak.
|
||||
|
||||
1. `strings`/`grep` the new `sdkconfig.h` for the four settings.
|
||||
2. Build and check the RAM figure; static usage should be unchanged (these are heap buffers).
|
||||
3. On hardware, `get mqtt.stats` at boot with two slots connected: the largest free block
|
||||
|
||||
+54
-41
@@ -1,75 +1,88 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fetch the reduced-TLS mbedTLS archives into .mbedtls-4k/<arch>/.
|
||||
#
|
||||
# These archives are built from the shipped sdkconfig plus three lines
|
||||
# (CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y, IN_CONTENT_LEN 16384,
|
||||
# OUT_CONTENT_LEN 4096) and save ~12 KiB of internal DRAM per TLS connection.
|
||||
# See docs/mbedtls-tls-footprint.md for the rationale and the build recipe.
|
||||
#
|
||||
# They are not committed: ~6 MB per architecture, and they must be rebuilt for
|
||||
# every platform bump, so they are published as a release asset keyed on the
|
||||
# espressif32 platform version instead.
|
||||
#
|
||||
# scripts/fetch_mbedtls_4k.sh [arch] # default: esp32s3
|
||||
#
|
||||
# Set MBEDTLS_4K_LOCAL to skip the download and copy from a local build tree:
|
||||
# MBEDTLS_4K_LOCAL=~/mbedtls-4k-esp32s3/staged scripts/fetch_mbedtls_4k.sh
|
||||
# Fetch and verify reduced-TLS archives; valid local copies need no download.
|
||||
# Usage: scripts/fetch_mbedtls_4k.sh [arch|--all] (default: esp32s3).
|
||||
# MBEDTLS_4K_LOCAL copies a local archive tree instead of downloading.
|
||||
set -euo pipefail
|
||||
|
||||
ARCH="${1:-esp32s3}"
|
||||
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
DEST="$REPO_ROOT/.mbedtls-4k/$ARCH"
|
||||
MANIFEST="$REPO_ROOT/scripts/mbedtls_4k_manifest.txt"
|
||||
BASE_URL="${MBEDTLS_4K_BASE_URL:-https://github.com/agessaman/MeshCore/releases/download/mbedtls-4k}"
|
||||
|
||||
if [ ! -f "$MANIFEST" ]; then
|
||||
echo "error: missing $MANIFEST" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Manifest lines: <arch> <sha256> <filename>. Blank lines and # comments ignored.
|
||||
# The "platform" and "stock:<arch>" lines bind the archives to a framework version;
|
||||
# they are the build check's business, not ours, and are not architectures.
|
||||
expected="$(awk -v a="$ARCH" '$1 == a && $0 !~ /^#/ {print $2" "$3}' "$MANIFEST")"
|
||||
arches="$(awk 'NF == 3 && $1 !~ /^(#|stock:)/ {print $1}' "$MANIFEST" | sort -u)"
|
||||
if [ "$ARCH" = "--all" ]; then
|
||||
if [ -z "$arches" ]; then
|
||||
echo "error: no architectures in $MANIFEST" >&2
|
||||
exit 1
|
||||
fi
|
||||
for arch in $arches; do
|
||||
bash "$REPO_ROOT/scripts/fetch_mbedtls_4k.sh" "$arch"
|
||||
done
|
||||
exit 0
|
||||
fi
|
||||
|
||||
release="$(awk '$1 == "release" && NF == 2 {print $2}' "$MANIFEST")"
|
||||
if [ -z "$release" ]; then
|
||||
echo "error: no release tag in $MANIFEST" >&2
|
||||
exit 1
|
||||
fi
|
||||
BASE_URL="${MBEDTLS_4K_BASE_URL:-https://github.com/agessaman/MeshCore/releases/download/$release}"
|
||||
DEST="$REPO_ROOT/.mbedtls-4k/$ARCH"
|
||||
expected="$(awk -v a="$ARCH" '$1 == a && NF == 3 {print $2" "$3}' "$MANIFEST")"
|
||||
if [ -z "$expected" ]; then
|
||||
echo "error: no manifest entries for arch '$ARCH'" >&2
|
||||
echo "known arches: $(awk '$0 !~ /^#/ && NF && $1 != "platform" && $1 !~ /^stock:/ {print $1}' \
|
||||
"$MANIFEST" | sort -u | tr '\n' ' ')" >&2
|
||||
echo "known arches: $arches" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$DEST"
|
||||
verify_archives() {
|
||||
(
|
||||
cd "$1"
|
||||
if command -v shasum >/dev/null 2>&1; then
|
||||
echo "$expected" | shasum -a 256 -c -
|
||||
else
|
||||
echo "$expected" | sha256sum -c -
|
||||
fi
|
||||
)
|
||||
}
|
||||
|
||||
if [ -d "$DEST" ] && verify_archives "$DEST" >/dev/null 2>&1; then
|
||||
echo "ok: $ARCH archives already verified in $DEST (no download)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
mkdir -p "$tmp/staged"
|
||||
if [ -n "${MBEDTLS_4K_LOCAL:-}" ]; then
|
||||
echo "copying from $MBEDTLS_4K_LOCAL"
|
||||
while read -r _sha name; do
|
||||
cp "$MBEDTLS_4K_LOCAL/$name" "$DEST/$name"
|
||||
cp "$MBEDTLS_4K_LOCAL/$name" "$tmp/staged/$name"
|
||||
done <<< "$expected"
|
||||
else
|
||||
TARBALL="mbedtls-4k-$ARCH.tar.gz"
|
||||
echo "downloading $BASE_URL/$TARBALL"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
curl -fsSL "$BASE_URL/$TARBALL" -o "$tmp/$TARBALL"
|
||||
tar -xzf "$tmp/$TARBALL" -C "$tmp"
|
||||
curl -fsSL --retry 3 --retry-delay 2 --retry-connrefused "$BASE_URL/$TARBALL" -o "$tmp/$TARBALL"
|
||||
mkdir -p "$tmp/unpacked"
|
||||
tar -xzf "$tmp/$TARBALL" -C "$tmp/unpacked"
|
||||
while read -r _sha name; do
|
||||
# Accept the archive whether or not the tarball has a leading directory.
|
||||
found="$(find "$tmp" -name "$name" -type f | head -1)"
|
||||
# Accept tarballs with or without a leading directory.
|
||||
found="$(find "$tmp/unpacked" -name "$name" -type f | head -1)"
|
||||
if [ -z "$found" ]; then
|
||||
echo "error: $name missing from $TARBALL" >&2
|
||||
exit 1
|
||||
fi
|
||||
cp "$found" "$DEST/$name"
|
||||
cp "$found" "$tmp/staged/$name"
|
||||
done <<< "$expected"
|
||||
fi
|
||||
|
||||
# Verify every archive against the manifest. A wrong or truncated archive would
|
||||
# otherwise link silently and produce a firmware without the reduced buffers.
|
||||
cd "$DEST"
|
||||
if command -v shasum >/dev/null 2>&1; then
|
||||
echo "$expected" | shasum -a 256 -c -
|
||||
else
|
||||
echo "$expected" | sha256sum -c -
|
||||
fi
|
||||
|
||||
verify_archives "$tmp/staged"
|
||||
mkdir -p "$DEST"
|
||||
while read -r _sha name; do
|
||||
cp "$tmp/staged/$name" "$DEST/$name"
|
||||
done <<< "$expected"
|
||||
echo "ok: $ARCH archives verified in $DEST"
|
||||
+64
-11
@@ -1,7 +1,7 @@
|
||||
"""Link the reduced-TLS mbedTLS archives, and prove they were actually linked.
|
||||
|
||||
Opt in per build with MESHCORE_REDUCED_TLS=1. Off by default, so an ordinary build
|
||||
needs no 6 MB artifact and behaves exactly as before.
|
||||
Use MESHCORE_REDUCED_TLS=auto for non-PSRAM MQTT observers, or 1 to force it.
|
||||
Off by default, so an ordinary build needs no artifact and behaves as before.
|
||||
|
||||
MESHCORE_REDUCED_TLS=1 pio run -e Heltec_v3_repeater_observer_mqtt
|
||||
|
||||
@@ -28,6 +28,7 @@ from our directory.
|
||||
"""
|
||||
Import("env")
|
||||
|
||||
import atexit
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
@@ -35,7 +36,18 @@ import sys
|
||||
REQUIRED = ("libmbedcrypto.a", "libmbedtls_2.a", "libmbedtls.a", "libmbedx509.a")
|
||||
|
||||
|
||||
_summary_printed = False
|
||||
|
||||
|
||||
def _summary(status):
|
||||
global _summary_printed
|
||||
if not _summary_printed:
|
||||
print("reduced-TLS: %s: %s" % (env.subst("$PIOENV"), status))
|
||||
_summary_printed = True
|
||||
|
||||
|
||||
def _fail(msg):
|
||||
_summary("not applied (validation failed)")
|
||||
print("\n*** reduced-TLS build failed ***", file=sys.stderr)
|
||||
print(msg, file=sys.stderr)
|
||||
print(
|
||||
@@ -99,22 +111,43 @@ def _framework_lib_dir(platform, arch):
|
||||
return None
|
||||
|
||||
|
||||
if os.environ.get("MESHCORE_REDUCED_TLS", "") not in ("1", "true", "yes"):
|
||||
mode = os.environ.get("MESHCORE_REDUCED_TLS")
|
||||
if mode is None:
|
||||
Return()
|
||||
atexit.register(_summary, "not applied (linker map check did not run)")
|
||||
if mode not in ("auto", "1", "true", "yes"):
|
||||
_summary("not applied (disabled)")
|
||||
Return()
|
||||
|
||||
if mode == "auto":
|
||||
# Pre scripts run before ProcessProgramDeps populates CPPDEFINES.
|
||||
flags = [env.BoardConfig().get("build.extra_flags", []),
|
||||
env.GetProjectOption("build_flags", [])]
|
||||
parsed = env.ParseFlags(flags).get("CPPDEFINES", [])
|
||||
defines = {item[0] if isinstance(item, (tuple, list)) else item for item in parsed}
|
||||
if "WITH_MQTT_BRIDGE" not in defines:
|
||||
_summary("not applied (not an observer)")
|
||||
Return()
|
||||
if "BOARD_HAS_PSRAM" in defines:
|
||||
_summary("not applied (PSRAM)")
|
||||
Return()
|
||||
|
||||
project_dir = env.subst("$PROJECT_DIR")
|
||||
arch = env.BoardConfig().get("build.mcu", "")
|
||||
if not arch:
|
||||
_fail("could not determine board MCU, so cannot pick an archive set")
|
||||
|
||||
wanted, stock, manifest_platform = _manifest(project_dir, arch)
|
||||
if not wanted:
|
||||
if mode == "auto":
|
||||
_summary("not applied (no archives for %s)" % arch)
|
||||
Return()
|
||||
_fail("manifest has no entries for arch '%s'" % arch)
|
||||
|
||||
staged = os.path.join(project_dir, ".mbedtls-4k", arch)
|
||||
if not os.path.isdir(staged):
|
||||
_fail("no archives for %s at %s" % (arch, staged))
|
||||
|
||||
wanted, stock, manifest_platform = _manifest(project_dir, arch)
|
||||
if not wanted:
|
||||
_fail("manifest has no entries for arch '%s'" % arch)
|
||||
|
||||
for name in REQUIRED:
|
||||
archive = os.path.join(staged, name)
|
||||
if not os.path.isfile(archive):
|
||||
@@ -167,13 +200,14 @@ for name in REQUIRED:
|
||||
if manifest_platform and manifest_platform != platform_id:
|
||||
# Hashes are the check; the version string is orientation. Identical archives
|
||||
# under a renamed platform are not a compatibility problem.
|
||||
print("reduced-TLS: manifest says %s, installed is %s — archives match, so this is "
|
||||
print("mbedTLS: manifest says %s, installed is %s — archives match, so this is "
|
||||
"only a stale label" % (manifest_platform, platform_id))
|
||||
|
||||
# Prepend so these satisfy mbedTLS symbols ahead of the framework's own copies:
|
||||
# the linker takes each archive member from the first archive that resolves it.
|
||||
env.Prepend(LIBPATH=[staged])
|
||||
print("reduced-TLS: linking mbedTLS from %s (verified)" % staged)
|
||||
env.AppendUnique(CPPDEFINES=[("MQTT_TLS_OUT_RECORD_LEN", 4096)])
|
||||
_map_verified = False
|
||||
|
||||
|
||||
def _verify_map(source, target, env):
|
||||
@@ -186,6 +220,9 @@ def _verify_map(source, target, env):
|
||||
"""
|
||||
# Derive the map name from PROGNAME rather than hardcoding firmware.map, so a
|
||||
# renamed program cannot leave us inspecting a stale or absent file.
|
||||
global _map_verified
|
||||
if _map_verified:
|
||||
return
|
||||
map_path = os.path.join(env.subst("$BUILD_DIR"),
|
||||
env.subst("${PROGNAME}") + ".map")
|
||||
if not os.path.isfile(map_path):
|
||||
@@ -197,6 +234,7 @@ def _verify_map(source, target, env):
|
||||
print("Cannot prove the reduced-TLS archives were linked. Ensure the env "
|
||||
"emits a map (-Wl,-Map), or unset MESHCORE_REDUCED_TLS.",
|
||||
file=sys.stderr)
|
||||
_summary("not applied (linker map verification failed)")
|
||||
env.Exit(1)
|
||||
return
|
||||
# The map records whatever the linker was given, which for a -L hit is a path
|
||||
@@ -223,6 +261,7 @@ def _verify_map(source, target, env):
|
||||
file=sys.stderr)
|
||||
for path in sorted(stray):
|
||||
print(" " + path, file=sys.stderr)
|
||||
_summary("not applied (linker map verification failed)")
|
||||
env.Exit(1)
|
||||
return
|
||||
# Every required archive must appear. Seeing only some of them means the rest
|
||||
@@ -235,10 +274,24 @@ def _verify_map(source, target, env):
|
||||
print(" missing: " + ", ".join(missing), file=sys.stderr)
|
||||
print("Either the map format changed or mbedTLS was resolved elsewhere; "
|
||||
"the reduced buffers cannot be assumed.", file=sys.stderr)
|
||||
_summary("not applied (linker map verification failed)")
|
||||
env.Exit(1)
|
||||
return
|
||||
print("reduced-TLS: confirmed all %d archives linked from %s"
|
||||
_map_verified = True
|
||||
print("mbedTLS: confirmed all %d archives linked from %s"
|
||||
% (len(REQUIRED), staged))
|
||||
_summary("active")
|
||||
|
||||
|
||||
env.AddPostAction("$BUILD_DIR/${PROGNAME}.elf", _verify_map)
|
||||
# ESP32's builder renames the default program after pre scripts run.
|
||||
program_name = env.subst("${PROGNAME}")
|
||||
if program_name == "program":
|
||||
program_name = "firmware"
|
||||
program_path = os.path.join(env.subst("$BUILD_DIR"), program_name)
|
||||
env.AddPostAction(program_path + ".elf", _verify_map)
|
||||
|
||||
# Check cached links too, before producing or reusing the binary.
|
||||
verify = env.Alias("verify_reduced_tls", program_path + ".elf", _verify_map)
|
||||
env.AlwaysBuild(verify)
|
||||
env.Depends(program_path + ".bin", verify)
|
||||
env.Default(verify)
|
||||
@@ -1,11 +1,13 @@
|
||||
# Reduced-TLS mbedTLS archives (OUT_CONTENT_LEN 4096, IN_CONTENT_LEN 16384).
|
||||
# Format: <arch> <sha256> <filename>
|
||||
#
|
||||
# Rebuild these for every espressif32 platform bump — the archives must match the
|
||||
# rest of the framework they link against. Built as of platformio/espressif32@6.11.0
|
||||
# Each platform bump gets a new release tag named after the platform version.
|
||||
# Never delete old tags: old commits must keep building with their pinned assets.
|
||||
# Rebuild both archive sets together. Built as of platformio/espressif32@6.11.0
|
||||
# from the recipe in docs/mbedtls-tls-footprint.md.
|
||||
#
|
||||
# Fetch with: scripts/fetch_mbedtls_4k.sh esp32s3
|
||||
# Fetch with: scripts/fetch_mbedtls_4k.sh --all
|
||||
release mbedtls-4k
|
||||
esp32s3 01629f635b33ffa2c1fdfcd8ac52327cd3a92e8d4e7c9a32d92974e0cfdfe398 libmbedcrypto.a
|
||||
esp32s3 07e7a09847589fefc35bc8d2f739d556535d535acd7185a9824b2af8edd5b05a libmbedtls_2.a
|
||||
esp32s3 e12bcc8d76a368e819987f266e73c265178d6b6675f05d0e29014bb543c402af libmbedtls.a
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Check observer defaults, caller overrides, and fetch failures in build.sh."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
BUILD = Path(__file__).resolve().parents[2] / "build.sh"
|
||||
|
||||
|
||||
class ReleaseBuildTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / "scripts").mkdir()
|
||||
(self.root / "bin").mkdir()
|
||||
shutil.copy(BUILD, self.root / "build.sh")
|
||||
for path, source in {
|
||||
"bin/git": '#!/usr/bin/env bash\necho abcdef0\n',
|
||||
"bin/pio": '''#!/usr/bin/env bash
|
||||
if [ "$1" = project ]; then
|
||||
echo '[]'
|
||||
exit 0
|
||||
fi
|
||||
printf '%s TLS=%s\\n' "$*" "${MESHCORE_REDUCED_TLS-unset}" >> "$BUILD_TEST_LOG"
|
||||
''',
|
||||
"scripts/fetch_mbedtls_4k.sh": '''#!/usr/bin/env bash
|
||||
printf 'fetch %s\\n' "$*" >> "$BUILD_TEST_LOG"
|
||||
exit "${BUILD_TEST_FETCH_EXIT:-0}"
|
||||
''',
|
||||
}.items():
|
||||
script = self.root / path
|
||||
script.write_text(source)
|
||||
script.chmod(0o755)
|
||||
self.variables = {key: value for key, value in os.environ.items()
|
||||
if key not in ("MESHCORE_REDUCED_TLS", "PLATFORMIO_BUILD_FLAGS")}
|
||||
self.variables.update(PATH=str(self.root / "bin") + os.pathsep + os.environ["PATH"],
|
||||
BUILD_TEST_LOG=str(self.root / "build.log"), FIRMWARE_VERSION="v0.0.0-test")
|
||||
|
||||
def build(self, *envs, **variables):
|
||||
return subprocess.run(["bash", "build.sh", "build-firmware", *envs], cwd=self.root,
|
||||
env={**self.variables, **variables}, text=True, capture_output=True)
|
||||
|
||||
def test_observer_default_does_not_leak_to_next_target(self):
|
||||
result = self.build("observer_fixture", "repeater_fixture")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.root / "build.log").read_text().splitlines(), [
|
||||
"fetch --all", "run -e observer_fixture TLS=auto",
|
||||
"run -t mergebin -e observer_fixture TLS=auto", "run -e repeater_fixture TLS=unset",
|
||||
"run -t mergebin -e repeater_fixture TLS=unset"])
|
||||
|
||||
def test_caller_values_survive_for_both_build_steps(self):
|
||||
for mode in ("0", "", "1", "auto"):
|
||||
with self.subTest(mode=mode):
|
||||
result = self.build("observer_fixture", MESHCORE_REDUCED_TLS=mode)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
lines = (self.root / "build.log").read_text().splitlines()[-3:]
|
||||
self.assertEqual(lines, ["fetch --all", f"run -e observer_fixture TLS={mode}",
|
||||
f"run -t mergebin -e observer_fixture TLS={mode}"])
|
||||
|
||||
def test_fetch_failure_prevents_build(self):
|
||||
result = self.build("observer_fixture", BUILD_TEST_FETCH_EXIT="23")
|
||||
self.assertEqual(result.returncode, 23)
|
||||
self.assertEqual((self.root / "build.log").read_text(), "fetch --all\n")
|
||||
|
||||
def test_non_observer_does_not_fetch_or_set_mode(self):
|
||||
result = self.build("repeater_fixture", BUILD_TEST_FETCH_EXIT="23")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.root / "build.log").read_text().splitlines(), [
|
||||
"run -e repeater_fixture TLS=unset", "run -t mergebin -e repeater_fixture TLS=unset"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Check fetching without network access, including future manifest architectures."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "fetch_mbedtls_4k.sh"
|
||||
ARCHIVES = ("libmbedcrypto.a", "libmbedtls_2.a", "libmbedtls.a", "libmbedx509.a")
|
||||
|
||||
|
||||
class FetchTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / "scripts").mkdir()
|
||||
(self.root / "bin").mkdir()
|
||||
shutil.copy(SCRIPT, self.root / "scripts/fetch_mbedtls_4k.sh")
|
||||
lines = ["release platform-6.11.0", "platform espressif32@6.11.0"]
|
||||
for arch in ("esp32s3", "esp32"):
|
||||
source = self.root / arch
|
||||
source.mkdir()
|
||||
with tarfile.open(self.root / f"mbedtls-4k-{arch}.tar.gz", "w:gz") as tar:
|
||||
for name in ARCHIVES:
|
||||
content = (arch + name).encode()
|
||||
(source / name).write_bytes(content)
|
||||
tar.add(source / name, arcname=f"staged/{name}")
|
||||
lines.append(f"{arch} {hashlib.sha256(content).hexdigest()} {name}")
|
||||
lines.append(f"stock:{arch} unused {name}")
|
||||
(self.root / "scripts/mbedtls_4k_manifest.txt").write_text("\n".join(lines))
|
||||
curl = self.root / "bin/curl"
|
||||
curl.write_text(f"#!{sys.executable}\n" + '''import os, pathlib, shutil, sys
|
||||
with open(os.environ["FETCH_CURL_LOG"], "a") as log:
|
||||
log.write(" ".join(sys.argv[1:]) + "\\n")
|
||||
if os.environ.get("FETCH_CURL_FAIL"):
|
||||
sys.exit(1)
|
||||
shutil.copyfile(pathlib.Path(os.environ["FETCH_ASSETS"]) / sys.argv[-3].rsplit("/", 1)[-1], sys.argv[-1])
|
||||
''')
|
||||
curl.chmod(0o755)
|
||||
self.variables = {key: value for key, value in os.environ.items()
|
||||
if not key.startswith("MBEDTLS_4K_")}
|
||||
self.variables.update(PATH=str(self.root / "bin") + os.pathsep + os.environ["PATH"],
|
||||
FETCH_CURL_LOG=str(self.root / "curl.log"), FETCH_ASSETS=str(self.root))
|
||||
|
||||
def fetch(self, arch, **variables):
|
||||
return subprocess.run(["bash", "scripts/fetch_mbedtls_4k.sh", arch], cwd=self.root,
|
||||
env={**self.variables, **variables}, text=True, capture_output=True)
|
||||
|
||||
def test_all_uses_release_tag_retries_and_skips_verified_archives(self):
|
||||
first = self.fetch("--all")
|
||||
self.assertEqual(first.returncode, 0, first.stderr)
|
||||
calls = (self.root / "curl.log").read_text().splitlines()
|
||||
self.assertEqual(len(calls), 2)
|
||||
for arch, call in zip(("esp32", "esp32s3"), calls):
|
||||
self.assertIn(f"/platform-6.11.0/mbedtls-4k-{arch}.tar.gz", call)
|
||||
self.assertIn("--retry 3", call)
|
||||
for name in ARCHIVES:
|
||||
self.assertEqual((self.root / f".mbedtls-4k/{arch}/{name}").read_bytes(),
|
||||
(self.root / arch / name).read_bytes())
|
||||
second = self.fetch("--all", FETCH_CURL_FAIL="1")
|
||||
self.assertEqual(second.returncode, 0, second.stderr)
|
||||
self.assertEqual(second.stdout.count("no download"), 2)
|
||||
self.assertEqual((self.root / "curl.log").read_text().splitlines(), calls)
|
||||
|
||||
def test_url_override_and_corrupt_archive_repair(self):
|
||||
first = self.fetch("esp32s3", MBEDTLS_4K_BASE_URL="https://override.invalid/assets")
|
||||
self.assertEqual(first.returncode, 0, first.stderr)
|
||||
self.assertIn("https://override.invalid/assets/mbedtls-4k-esp32s3.tar.gz",
|
||||
(self.root / "curl.log").read_text())
|
||||
damaged = self.root / ".mbedtls-4k/esp32s3/libmbedtls.a"
|
||||
damaged.write_bytes(b"wrong")
|
||||
repaired = self.fetch("esp32s3", MBEDTLS_4K_LOCAL=str(self.root / "esp32s3"))
|
||||
self.assertEqual(repaired.returncode, 0, repaired.stderr)
|
||||
self.assertEqual(damaged.read_bytes(), (self.root / "esp32s3/libmbedtls.a").read_bytes())
|
||||
|
||||
def test_invalid_local_source_does_not_install_archives(self):
|
||||
(self.root / "esp32s3/libmbedtls.a").write_bytes(b"wrong")
|
||||
result = self.fetch("esp32s3", MBEDTLS_4K_LOCAL=str(self.root / "esp32s3"))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse((self.root / ".mbedtls-4k/esp32s3").exists())
|
||||
|
||||
def test_unknown_arch_fails_without_download(self):
|
||||
result = self.fetch("unknown")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse((self.root / "curl.log").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Exercise reduced-TLS selection and fail-closed archive/map validation."""
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
HOOK = Path(__file__).resolve().parents[1] / "mbedtls_4k.py"
|
||||
ARCHIVES = ("libmbedcrypto.a", "libmbedtls_2.a", "libmbedtls.a", "libmbedx509.a")
|
||||
|
||||
|
||||
class ScriptReturn(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BuildEnv(dict):
|
||||
def __init__(self, root, arch, flags, board_flags):
|
||||
super().__init__(CPPDEFINES=[])
|
||||
self.root = root
|
||||
self.board = {"build.mcu": arch, "build.extra_flags": board_flags}
|
||||
self.flags = flags
|
||||
self.actions = []
|
||||
self.alias = None
|
||||
|
||||
def subst(self, value):
|
||||
return {"$PROJECT_DIR": str(self.root), "$PIOENV": "fixture",
|
||||
"$BUILD_DIR": str(self.root / "build"), "${PROGNAME}": self.get("PROGNAME", "firmware")}[value]
|
||||
|
||||
def BoardConfig(self):
|
||||
return self.board
|
||||
|
||||
def GetProjectOption(self, name, default):
|
||||
assert name == "build_flags"
|
||||
return self.flags
|
||||
|
||||
def ParseFlags(self, flags):
|
||||
if isinstance(flags, list):
|
||||
return {"CPPDEFINES": [d for f in flags for d in self.ParseFlags(f)["CPPDEFINES"]]}
|
||||
tokens = iter(shlex.split(flags))
|
||||
defines = []
|
||||
for token in tokens:
|
||||
if token == "-D":
|
||||
token += next(tokens)
|
||||
if token.startswith("-D"):
|
||||
defines.append(token[2:].split("=", 1) if "=" in token else token[2:])
|
||||
return {"CPPDEFINES": defines}
|
||||
|
||||
def PioPlatform(self):
|
||||
root = self.root
|
||||
|
||||
class Platform:
|
||||
name = "espressif32"
|
||||
version = "6.11.0"
|
||||
|
||||
def get_package_dir(self, package):
|
||||
return str(root / "framework")
|
||||
|
||||
return Platform()
|
||||
|
||||
def Prepend(self, **kwargs):
|
||||
self.update(kwargs)
|
||||
|
||||
def AppendUnique(self, **kwargs):
|
||||
for key, value in kwargs.items():
|
||||
self.setdefault(key, []).extend(value)
|
||||
|
||||
def AddPostAction(self, target, action):
|
||||
self.actions.append(action)
|
||||
|
||||
def Alias(self, name, target=None, action=None):
|
||||
self.alias = (name, target, action)
|
||||
return name
|
||||
|
||||
def AlwaysBuild(self, target):
|
||||
self.always = target
|
||||
|
||||
def Depends(self, target, dependency):
|
||||
self.dependency = (target, dependency)
|
||||
|
||||
def Default(self, target):
|
||||
self.default = target
|
||||
|
||||
def Exit(self, code):
|
||||
raise SystemExit(code)
|
||||
|
||||
|
||||
class ReducedTlsTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
(self.root / "scripts").mkdir()
|
||||
(self.root / "build").mkdir()
|
||||
staged = self.root / ".mbedtls-4k/esp32s3"
|
||||
stock = self.root / "framework/tools/sdk/esp32s3/lib"
|
||||
staged.mkdir(parents=True)
|
||||
stock.mkdir(parents=True)
|
||||
lines = ["release mbedtls-4k", "platform espressif32@6.11.0"]
|
||||
for arch, directory, content in (("esp32s3", staged, b"reduced"),
|
||||
("stock:esp32s3", stock, b"stock")):
|
||||
for name in ARCHIVES:
|
||||
(directory / name).write_bytes(content)
|
||||
lines.append(f"{arch} {hashlib.sha256(content).hexdigest()} {name}")
|
||||
(self.root / "scripts/mbedtls_4k_manifest.txt").write_text("\n".join(lines))
|
||||
self.env = BuildEnv(self.root, "esp32s3", ["-D WITH_MQTT_BRIDGE=1"], [])
|
||||
self.output = io.StringIO()
|
||||
|
||||
def run_hook(self, mode="auto"):
|
||||
variables = {} if mode is None else {"MESHCORE_REDUCED_TLS": mode}
|
||||
|
||||
def script_return():
|
||||
raise ScriptReturn()
|
||||
|
||||
namespace = {"Import": lambda name: None, "Return": script_return, "env": self.env}
|
||||
with patch.dict(os.environ, variables, clear=True), contextlib.redirect_stdout(self.output), \
|
||||
patch("atexit.register") as register:
|
||||
try:
|
||||
exec(compile(HOOK.read_text(), str(HOOK), "exec"), namespace)
|
||||
except ScriptReturn:
|
||||
pass
|
||||
self.exit_summary = register.call_args
|
||||
return namespace
|
||||
|
||||
def verify(self):
|
||||
with contextlib.redirect_stdout(self.output), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.env.alias[2](None, None, self.env)
|
||||
|
||||
def test_active_only_after_valid_map_and_once_on_cached_check(self):
|
||||
self.run_hook()
|
||||
self.assertEqual(self.output.getvalue(), "")
|
||||
self.assertIn(("MQTT_TLS_OUT_RECORD_LEN", 4096), self.env["CPPDEFINES"])
|
||||
self.assertEqual(self.env.always, self.env.default)
|
||||
self.assertEqual(self.env.dependency[1], self.env.default)
|
||||
(self.root / "build/firmware.map").write_text("\n".join(
|
||||
f".mbedtls-4k/esp32s3/{name}(member.o)" for name in ARCHIVES))
|
||||
self.verify()
|
||||
self.verify()
|
||||
self.assertEqual(self.output.getvalue().count("reduced-TLS: fixture: active"), 1)
|
||||
|
||||
def test_pre_hook_resolves_default_and_custom_program_names(self):
|
||||
for name, expected in (("program", "firmware"), ("custom", "custom")):
|
||||
with self.subTest(name=name):
|
||||
self.env["PROGNAME"] = name
|
||||
self.run_hook()
|
||||
self.assertEqual(self.env.alias[1], str(self.root / "build" / (expected + ".elf")))
|
||||
|
||||
def test_incomplete_build_prints_one_nonactive_summary_at_exit(self):
|
||||
self.run_hook()
|
||||
callback, status = self.exit_summary.args
|
||||
with contextlib.redirect_stdout(self.output):
|
||||
callback(status)
|
||||
callback(status)
|
||||
self.assertEqual(self.output.getvalue(),
|
||||
"reduced-TLS: fixture: not applied (linker map check did not run)\n")
|
||||
|
||||
def test_selection_uses_project_and_board_flags(self):
|
||||
for flags, board, arch, reason in (
|
||||
(["-DWITH_MQTT_BRIDGE=1"], ["-DBOARD_HAS_PSRAM"], "esp32s3", "PSRAM"),
|
||||
(["-DWITH_MQTT_BRIDGE=1", "-DBOARD_HAS_PSRAM"], [], "esp32s3", "PSRAM"),
|
||||
(["-DOTHER"], [], "esp32s3", "not an observer"),
|
||||
(["-D WITH_MQTT_BRIDGE=1"], [], "esp32", "no archives for esp32"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.output = io.StringIO()
|
||||
self.env = BuildEnv(self.root, arch, flags, board)
|
||||
self.run_hook()
|
||||
self.assertEqual(self.output.getvalue(), f"reduced-TLS: fixture: not applied ({reason})\n")
|
||||
self.assertIsNone(self.env.alias)
|
||||
|
||||
def test_unset_is_silent_and_off_values_report_disabled(self):
|
||||
for mode in (None, "", "0"):
|
||||
self.output = io.StringIO()
|
||||
self.run_hook(mode)
|
||||
expected = "" if mode is None else "reduced-TLS: fixture: not applied (disabled)\n"
|
||||
self.assertEqual(self.output.getvalue(), expected)
|
||||
self.assertIsNone(self.env.alias)
|
||||
|
||||
def test_force_ignores_psram_but_requires_manifest_arch(self):
|
||||
self.env.board["build.extra_flags"] = ["-DBOARD_HAS_PSRAM"]
|
||||
self.run_hook("1")
|
||||
self.assertIsNotNone(self.env.alias)
|
||||
self.env.board["build.mcu"] = "esp32"
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
self.run_hook("1")
|
||||
self.assertNotIn(": active", self.output.getvalue())
|
||||
|
||||
def test_missing_or_changed_archives_fail_closed(self):
|
||||
for path in (".mbedtls-4k/esp32s3/libmbedtls.a", "framework/tools/sdk/esp32s3/lib/libmbedtls.a"):
|
||||
archive = self.root / path
|
||||
original = archive.read_bytes()
|
||||
for content in (None, b"wrong"):
|
||||
with self.subTest(path=path, content=content):
|
||||
self.output = io.StringIO()
|
||||
if content is None:
|
||||
archive.unlink()
|
||||
else:
|
||||
archive.write_bytes(content)
|
||||
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
self.run_hook()
|
||||
self.assertNotIn(": active", self.output.getvalue())
|
||||
archive.write_bytes(original)
|
||||
|
||||
def test_missing_partial_or_stock_map_cannot_report_active(self):
|
||||
self.run_hook()
|
||||
map_path = self.root / "build/firmware.map"
|
||||
for content in (None, ".mbedtls-4k/esp32s3/libmbedtls.a(member.o)", "\n".join(
|
||||
f"framework/tools/sdk/esp32s3/lib/{name}(member.o)" for name in ARCHIVES)):
|
||||
with self.subTest(content=content):
|
||||
if content is not None:
|
||||
map_path.write_text(content)
|
||||
with self.assertRaises(SystemExit):
|
||||
self.verify()
|
||||
self.assertNotIn(": active", self.output.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1016,6 +1016,10 @@ void MQTTBridge::begin() {
|
||||
MQTT_DEBUG_PRINTLN("PSRAM: not configured for this board (no BOARD_HAS_PSRAM)");
|
||||
#endif
|
||||
|
||||
#ifdef MQTT_TLS_OUT_RECORD_LEN
|
||||
MQTT_DEBUG_PRINTLN("TLS outbound record: %d bytes (reduced)", MQTT_TLS_OUT_RECORD_LEN);
|
||||
#endif
|
||||
|
||||
// Install the TLS allocator before the bridge task exists, so no TLS session depends on NTP ordering.
|
||||
installTlsAllocatorOnce();
|
||||
|
||||
|
||||
Reference in new issue
Block a user