Harden marathon-tested OTA and hardware paths

Add durable TempRadio, ACL, clock, bridge, GPS/I2C, USB logging, and Indicator recovery safeguards together with expanded automation, build/profile contracts, release metadata, and the hardware validation ledger.
This commit is contained in:
mikecarper committed 2026-08-30 19:26:15 -07:00
1 parent e26d48e4ca
commit 9fd580c89e
109 files changed
+18697 -1094

No files matched your search

+14
View File
@@ -14,8 +14,13 @@ pio test -e native # all suites except KISS modem
pio test -e native_kiss_modem # KISS modem suite
pio test -e native -f test_webconfig_keys # a single suite
python3 test/test_indicator_display_profile.py # Indicator RAM/scale contract
python3 test/test_indicator_font_recovery.py # Indicator TLS/SD font recovery contract
python3 test/test_companion_terminal_profile.py # Companion CLI capability gates
python3 test/test_client_login_profile_contract.py # ACL login ordering/role contract
python3 test/test_esp32_full_partition.py # Full partition-preservation policy
python3 test/test_esp32_usb_serial_hygiene.py # Single-TTY diagnostics/NVS contract
python3 test/test_temp_radio_reply_delivery_contract.py # TempRadio ACK path/barrier integration
python3 test/test_tls_download_clock_gates.py # Fresh-NTP/TLS download integration contract
```
A green `[PASSED]` per suite means GoogleTest returned 0 (all assertions
@@ -44,6 +49,7 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_mqtt_prefs_atomic_store` | `src/helpers/MQTTPrefsAtomicStore.h` | transactional MQTT writes and legacy `/node_prefs` handoff; exact short-write detection; begin/finish/rename failure cleanup; original-file preservation |
| `test_mqtt_prefs_json_import` | `src/helpers/MQTTPrefsJsonImport.h`, `src/helpers/MQTTPrefsSerializer.h` | one-time observer `/mqtt.json` v1 import grammar, strict schema/repair rules, binary-first precedence, future/artifact preservation, display-tail encoding, and atomic commit failure routing |
| `test_display_viewport` | `src/helpers/ui/DisplayViewport.h`, `src/helpers/ui/DisplayFrameSignature.h` | portrait logical-to-physical mapping, span coverage, fitted-width conversion, text scaling, and visible-frame signatures |
| `test_indicator_font_stage_v2_protocol` | `src/helpers/IndicatorFontStageV2Protocol.h` | fail-closed STAGEV2 negotiation and legacy fallback; exact cumulative ACK parsing; 512-byte block boundaries, short final blocks, and real font-asset transfer geometry |
| `test_radio_activity_window` | `src/helpers/RadioActivityWindow.h` | rolling minute buckets, derived rates, expiry, warm-up, silence, saturation, and `millis()` rollover |
| `test_observer_dashboard` | `src/helpers/ui/ObserverDashboard.h` | landscape and portrait dashboard layout bounds, compact formatting, graph scaling, row signatures, and partial repaint policy |
| `test_touch_tap_detector` | `src/helpers/ui/TouchTapDetector.h` | debounced one-shot taps, bounce and long-press handling, minimum gaps, reset, and `millis()` rollover |
@@ -55,6 +61,8 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_cli_command_utils` | `src/helpers/CLICommandUtils.h`, `src/helpers/ContactListOrder.h`, `src/helpers/TerminalCommandTracker.h`, `src/helpers/TerminalDisplayFilter.h`, `src/helpers/WiFiChannelPolicy.h`, `src/helpers/bridges/ESPNowBridgeFormat.h` | terminal verb/argument/path parsing; routed receive labels; quiet display defaults and independent emergency filtering; favorite-first contact ordering; standalone WiFi validation including 64-hex WPA/WPA2 PSKs; strict ESP-NOW channel and bridge-format parsing/range/fallback; single-command reply matching, round-trip timing, and rollover-safe expiration |
| `test_espnow_raw_fragmentation` | `src/helpers/ESPNowRawFragmentation.h` | byte-exact legacy raw frames; 251-255-byte two-frame encoding; CRC-32 integrity; source-MAC-keyed bounded reassembly; malformed, duplicate, out-of-order, timeout, rollover, and capacity handling |
| `test_gps_time_validation` | `src/helpers/sensors/GpsTimeValidation.h` | complete NMEA UTC validation; leap years and calendar bounds; rejection of receiver-default and signed-32-bit-out-of-range dates |
| `test_i2c_address_claim_policy` | `src/helpers/sensors/I2CAddressClaimPolicy.h`, `src/helpers/sensors/NmeaSentenceProbe.h` | a positively identified I2C GPS owns only its address on its bus; an INA3221 identity match blocks conflicting u-blox writes; UART GPS detection requires a complete checksum-valid GPS NMEA sentence |
| `test_gps_transport_ownership` | `src/helpers/SensorManager.cpp` | temporary bridge ownership cancels GPS acquisition/holds, preserves user preference/cache, and restores GPS only after the UART is released |
| `test_identity_generation` | `src/helpers/IdentityGeneration.h` | reserved-prefix rejection; bounded retries; final provisioned attempt; fail-closed exhaustion |
| `test_remote_cli_reply_cache` | `src/helpers/RemoteCliReplyCache.h`, `src/helpers/RemoteCliRequest.h`, `src/helpers/RemoteCliTimeout.h` | authenticated logical-request matching; bounded recent-reply history; backward-compatible retry identity; 300% response timeout; empty-response completion; on-air truncation and clearing |
| `test_companion_frame_queue` | `src/helpers/CompanionFrameQueue.h`, `src/helpers/CompanionHardwareCommandCompat.h` | response/required/best-effort classification; reserved capacity; stable priority; safe eviction; message-waiting coalescing; command `0x42` framed-CLI disambiguation and deprecated hardware-alias mapping |
@@ -64,6 +72,11 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_ble_tx_stall_watchdog` | `src/helpers/BleTxStallWatchdog.h` | exact BLE fragment progress; blocked-reply timeout; rollover-safe elapsed time; disconnect recovery retry and completion |
| `test_ble_mota_control` | `src/helpers/BleMotaStream.h`, `CompanionMotaControl.h` | encrypted mOTA channel ring buffering, overflow fail-closed behavior, request gating, and strict rejection of injected or USB-ownership control commands |
| `test_atomic_file_writer` | `src/helpers/AtomicFileWriter.h` | verified temporary-file commit; short-write, readback, validation, and rename failures; preservation of the live file and stale-temp cleanup |
| `test_client_login_persistence` | `src/helpers/ClientLoginPersistence.h`, `LazyPersistence.h` | pre-allocation durable replay reservations; reboot, ACL-eviction, and revoked-admin tombstones; bounded-store policy (low-trust no-insert, privileged fail-closed); atomic replay-file recovery, including post-commit cleanup failure; preauthorized transient refresh; admin/guest promotion and downgrade; force-flood preservation; role masking and fixed-size secret copy |
| `test_client_path_persistence` | `src/helpers/ClientPathPersistence.h`, `LazyPersistence.h` | encoded path identity and byte lengths; unknown, zero-hop, force-flood, and nonpersistent clients; replay-unqualified RAM-only routes preserve an earlier operator route across unrelated save/reload |
| `test_temp_radio_reply_barrier` | `src/helpers/TempRadioReplyBarrier.h`, `TempRadioLeaseDeadline.h` | exact single-copy queued reply completion/failure handoff; suppression of untracked alternate/retry copies; rejection of foreign callbacks; cancellation; monotonic hard expiry that a backward wall-clock correction cannot extend; bounded remaining-time reporting |
| `test_lazy_persistence` | `src/helpers/LazyPersistence.h` | first-write scheduling without postponement, zero-sentinel rollover preservation, capped exponential save-failure backoff that mutations cannot defeat, and reset only after success |
| `test_client_acl_file_transaction` | `src/helpers/ClientACLFileTransaction.h` | verified temp publication, preservation of the prior ACL on verification/rename failure, post-commit cleanup-failure handling, and recovery at every temp/backup/primary boundary |
| `test_cad_timing` | `src/helpers/radiolib/CadTiming.h`, `LR2021SideDetectorConfig.h`, `RadioAirtime.h` | Cascade and slow-profile CAD deadlines; invalid airtime handling; bounded LR2021 side-detector parsing and LDRO recomputation |
| `test_companion_node_prefs` | `examples/companion_radio/NodePrefs.h` | independent device power saving, RXPS, Wi-Fi, and FEM preferences; one-time migration of the regressed power-saving default |
| `test_config_serializer` | `src/helpers/ConfigSerializer.cpp`, Companion `NodePrefs` | escaped config save/load, whitespace and malformed input, unknown fields, and FEM/ESP-NOW bridge-format preference round trips |
@@ -88,6 +101,7 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_user_gpio` | `src/helpers/UserGpio.cpp`, `UserGpioReplyTracker.h` | board-approved pins, get/set/reset, timed nonblocking transitions, duplicate suppression, rollover, and completion-reply routing |
| `test_utf8_helpers` | `src/helpers/UTF8Helpers.h` | byte-limit truncation at complete code-point boundaries and rejection of malformed or truncated UTF-8 |
| `test_wifi_ota_seeder_policy` | `src/helpers/WiFiOtaSeederPolicy.h`, `WiFiOtaSeederStatus.h` | listener state versus network availability, serial/TCP folder ownership, detach detection, and bounded status formatting |
| `test_tls_clock_validity` | `src/helpers/esp32/TlsClockValidity.h` | signed wall-clock minimum and the fresh-proof/WiFi/time conjunction required before certificate-validating downloads |
| `test_ota` | `src/helpers/ota/` | v2 application/v3 bootloader parser separation; legacy XIAO, generic internal, and exact MeshTower V2 SD embedded identity, vector, capability, explicit-confirmation, codec-isolation, scratch-headroom/shared-slot no-EndF gates, and no-autofetch gates; container and EndF integrity; protocol codecs; transfer, resume, and layered apply safety; adaptive 2-to-4 block-request window growth and stall contraction; active-transfer priority classification |
| `test_trace_retry` | `src/Mesh.cpp`, `RTCClock`, `ClockSyncUtils.h`, retry and relay policy | app-v2 and boot-v3 traffic sharing `PAYLOAD_TYPE_OTA=0x0C` and the TempRadio suspend policy; opaque OTA relay behavior; background discovery priority; immediate primary transfer relay, receive-delay bypass, fast CAD retry, and no generic flood retry; trace and non-OTA flood retry timing; backward RTC correction; clock consensus/path policy and the 10-minute default drift threshold |
| `test_utils` | `src/Utils.cpp` | `Utils::toHex` (upstream) |
+11
View File
@@ -6,6 +6,17 @@
class CayenneLPP {
public:
explicit CayenneLPP(size_t) {}
void addGPS(uint8_t, float latitude, float longitude, float altitude) {
gps_count++;
last_latitude = latitude;
last_longitude = longitude;
last_altitude = altitude;
}
const uint8_t* getBuffer() const { return nullptr; }
uint16_t getSize() const { return 0; }
uint16_t gps_count = 0;
float last_latitude = 0;
float last_longitude = 0;
float last_altitude = 0;
};
@@ -26,6 +26,9 @@ TEST(BleMotaControl, AllowsOnlyBoundedOtaSessionCommands) {
EXPECT_FALSE(allowed("otafolder status"));
EXPECT_FALSE(allowed("ota folder on"));
EXPECT_FALSE(allowed("ota folder off"));
// Sharing local command routing with the text/rescue CLI must not expand
// the deliberately narrow Bluetooth mOTA control allowlist.
EXPECT_FALSE(allowed("set pin 123456"));
EXPECT_FALSE(allowed("reboot"));
}
+91
View File
@@ -12,6 +12,30 @@ fail() {
[ "$OPTION3_BUILD_WORKERS" -eq 1 ] \
|| fail "logging matrix permits concurrent PlatformIO target builds"
# Reduced RAK profiles all retain the compact INA set, but GPS depends on
# whether the bridge already owns Serial1. Keep those independent contracts so
# a valid Serial1 image cannot fail release qualification for an absent GPS
# marker, and so its manifest never advertises impossible hardware support.
for rak_target in \
RAK_3401_repeater_lora_ota_no_external_sensors \
RAK_4631_repeater_lora_ota_no_external_sensors \
RAK_4631_repeater_bridge_rs232_serial1_lora_ota_no_external_sensors \
RAK_4631_repeater_bridge_rs232_serial2_lora_ota_no_external_sensors; do
is_rak_i2c_voltage_monitor_ota_target "$rak_target" \
|| fail "$rak_target lost the retained INA contract"
done
for rak_target in \
RAK_3401_repeater_lora_ota_no_external_sensors \
RAK_4631_repeater_lora_ota_no_external_sensors \
RAK_4631_repeater_bridge_rs232_serial2_lora_ota_no_external_sensors; do
is_rak_gps_retaining_ota_target "$rak_target" \
|| fail "$rak_target lost its compatible GPS contract"
done
if is_rak_gps_retaining_ota_target \
RAK_4631_repeater_bridge_rs232_serial1_lora_ota_no_external_sensors; then
fail "RAK4631 Serial1 RS-232 target incorrectly promises GPS"
fi
# The expanded-profile marker applied below must select a real, nonzero
# boot-local setup window. Keep the build overlay, WebConfig compile-time
# mapping, and pure timing policy tied together.
@@ -351,6 +375,8 @@ for full_env in "${SUPPORTED_PIO_ENVS[@]}"; do
[ "${MESHCORE_ESP32_FULL_PARTITION_TABLE:-}" \
= "variants/sensecap_indicator-espnow/dual_ota_2560k_preserve_spiffs.csv" ] \
|| fail "$full_env omitted the Indicator preserve-SPIFFS table"
[[ "$PLATFORMIO_BUILD_FLAGS" == *"INDICATOR_WIFI_FONT_RECOVERY=1"* ]] \
|| fail "$full_env omitted WiFi font recovery"
;;
*)
[ -z "${MESHCORE_ESP32_FULL_PARTITION_TABLE:-}" ] \
@@ -551,6 +577,60 @@ fi
uses_merged_standard_usb_logging esp_repeater \
|| fail "standard ESP32 target omitted logging because FULL also exists"
# A standard ESP32 field image may omit LoRa OTA for size, but it must never
# also omit the compact browser updater. This is the exact profile combination
# that previously produced Heltec V4 repeaters where both `ota` and `start ota`
# were dead ends.
verify_esp32_field_browser_ota() {
local env_name=$1
local PLATFORMIO_BUILD_FLAGS=""
local PLATFORMIO_BUILD_UNFLAGS=""
local BUILD_PROFILE_FOR_TARGET=standard
local ESP32_FULL_BUILD=0
local -a BUILD_CAPABILITIES=()
local -a BUILD_REDUCTIONS=()
local -a BUILD_EXPECTATIONS=()
local capabilities reductions expectations
PIO_ENV_PLATFORM_BY_NAME[$env_name]=ESP32_PLATFORM
PIO_ENV_OTA_BY_NAME[$env_name]=0
apply_esp32_lora_ota_size_profile "$env_name"
[[ "$PLATFORMIO_BUILD_FLAGS" == *-DLIGHTWEIGHT_WIFI_OTA=1* ]] \
|| fail "$env_name omitted its browser OTA fail-safe"
[[ "$PLATFORMIO_BUILD_FLAGS" == *-UDISABLE_WIFI_OTA* ]] \
|| fail "$env_name did not remove a board-level WiFi OTA disable"
[[ "$PLATFORMIO_BUILD_FLAGS" != *-DDISABLE_WIFI_OTA=1* ]] \
|| fail "$env_name still explicitly disables browser OTA"
capabilities=" ${BUILD_CAPABILITIES[*]} "
[[ "$capabilities" == *" web.lightweight_browser_ota "* ]] \
|| fail "$env_name did not declare browser OTA"
reductions=" ${BUILD_REDUCTIONS[*]} "
[[ "$reductions" != *"web.browser_ota omitted"* ]] \
|| fail "$env_name still records browser OTA as omitted"
declare_build_capability_contract "$env_name" ESP32_PLATFORM
expectations=" ${BUILD_EXPECTATIONS[*]} "
[[ "$expectations" == *"web.lightweight_browser_ota=MeshCore firmware update"* ]] \
|| fail "$env_name does not verify browser OTA in the linked image"
}
verify_esp32_field_browser_ota heltec_v4_repeater
verify_esp32_field_browser_ota heltec_v4_room_server
verify_esp32_field_browser_ota heltec_v4_sensor
# Personal/attached roles can retain their established transport policy; the
# fail-safe is deliberately scoped to remotely installed field/server images.
PIO_ENV_PLATFORM_BY_NAME[heltec_v4_terminal_chat]=ESP32_PLATFORM
PLATFORMIO_BUILD_FLAGS=""
PLATFORMIO_BUILD_UNFLAGS=""
BUILD_PROFILE_FOR_TARGET=standard
BUILD_CAPABILITIES=()
BUILD_REDUCTIONS=()
apply_esp32_lora_ota_size_profile heltec_v4_terminal_chat
[[ "$PLATFORMIO_BUILD_FLAGS" == *-DDISABLE_WIFI_OTA=1* ]] \
|| fail "attached terminal unexpectedly changed its WiFi policy"
PLATFORMIO_BUILD_FLAGS=""
MESHDEBUG_OVERRIDE=""
PACKET_LOGGING_OVERRIDE=""
@@ -816,6 +896,17 @@ expectations=" ${BUILD_EXPECTATIONS[*]} "
[[ "$expectations" != *"Full Companion terminal listening"* ]] \
|| fail "ESP32 Full contract still depends on optional debug logging"
BUILD_CAPABILITIES=()
BUILD_REDUCTIONS=()
BUILD_EXPECTATIONS=()
declare_build_capability_contract \
SenseCapIndicator-LoRa_companion_radio_full ESP32_PLATFORM
expectations=" ${BUILD_EXPECTATIONS[*]} "
[[ "$expectations" == *"indicator.font_recovery_ntp_gate=requesting fresh NTP time before download"* ]] \
|| fail "Indicator Full contract omitted the fresh-NTP font-download gate"
[[ "$expectations" == *"indicator.font_recovery_tls=opening TLS connection to"* ]] \
|| fail "Indicator Full contract omitted the TLS font-recovery marker"
pio_env_option_contains() {
[ "$1" = Heltec_v3_companion_radio_full ] \
&& [ "$2" = build_flags ] \
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Regression tests for serial-zero roots in the ESP32 CA bundle."""
import contextlib
import io
import os
from pathlib import Path
import runpy
import struct
import tempfile
import unittest
import warnings
from cryptography.utils import CryptographyDeprecationWarning
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "generate_cert_bundle.py"
NON_POSITIVE_SERIAL_WARNING = (
"Parsed a serial number which wasn't positive (i.e., it was negative or zero), "
"which is disallowed by RFC 5280. Loading this certificate will cause an "
"exception in a future release of cryptography."
)
# Go Daddy Root Certificate Authority - G2, one of the serial-zero roots in
# Mozilla and Adafruit trust bundles.
SERIAL_ZERO_ROOT = """-----BEGIN CERTIFICATE-----
MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx
EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT
EUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp
ZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz
NTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH
EwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE
AxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD
E6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH
/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy
DfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh
GkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR
tDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA
AaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
FDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX
WWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu
9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr
gIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo
2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO
LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI
4uJEvlz36hz1
-----END CERTIFICATE-----
"""
class FakeEnvironment:
def subst(self, value):
if value != "$PIOENV":
raise AssertionError(f"unexpected substitution: {value}")
return "certificate_filter_test"
def GetProjectOption(self, name):
if name != "board_ssl_cert_source":
raise AssertionError(f"unexpected project option: {name}")
# An unrecognized source skips the download path. The fixture is then
# loaded through the script's supported extra-certificate path.
return "fixture-only"
def Execute(self, _command):
raise AssertionError("test requires cryptography to be preinstalled")
class CertificateBundleWarningFilterTest(unittest.TestCase):
def test_serial_zero_root_is_retained_and_filter_is_narrow(self):
with tempfile.TemporaryDirectory() as temporary_directory:
temporary = Path(temporary_directory)
certificates = temporary / "ssl_certs"
certificates.mkdir()
(certificates / "serial_zero.pem").write_text(
SERIAL_ZERO_ROOT, encoding="utf-8"
)
previous_directory = Path.cwd()
stderr = io.StringIO()
try:
os.chdir(temporary)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
with contextlib.redirect_stderr(stderr):
runpy.run_path(
str(SCRIPT),
init_globals={
"Import": lambda _name: None,
"env": FakeEnvironment(),
},
)
warnings.warn(
NON_POSITIVE_SERIAL_WARNING,
CryptographyDeprecationWarning,
)
warnings.warn(
"unrelated cryptography deprecation",
CryptographyDeprecationWarning,
)
finally:
os.chdir(previous_directory)
self.assertEqual(len(caught), 1)
self.assertEqual(
str(caught[0].message), "unrelated cryptography deprecation"
)
self.assertIs(
caught[0].category, CryptographyDeprecationWarning
)
output = temporary / "src" / "certs" / "x509_crt_bundle.bin"
bundle = output.read_bytes()
self.assertEqual(struct.unpack(">H", bundle[:2])[0], 1)
self.assertGreater(len(bundle), 256)
self.assertIn(
"Successfully added 1 certificates in total",
stderr.getvalue(),
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,295 @@
#include <gtest/gtest.h>
#include <set>
#include <string>
#include <vector>
#include <map>
#include <helpers/ClientACLFileTransaction.h>
#include <helpers/ClientACLFileIntegrity.h>
namespace {
class FakeFilesystem {
public:
std::set<std::string> files;
std::set<std::string> valid_files;
std::map<std::string, std::vector<uint8_t> > images;
std::string fail_from;
std::string fail_to;
std::string fail_remove;
bool exists(const char* path) const {
return files.count(path) != 0;
}
bool remove(const char* path) {
if (fail_remove == path) return false;
images.erase(path);
valid_files.erase(path);
return files.erase(path) != 0;
}
bool rename(const char* from, const char* to) {
if (fail_from == from && fail_to == to) return false;
if (!exists(from) || exists(to)) return false;
files.erase(from);
files.insert(to);
if (valid_files.erase(from) != 0) valid_files.insert(to);
std::map<std::string, std::vector<uint8_t> >::iterator image =
images.find(from);
if (image != images.end()) {
images[to] = image->second;
images.erase(image);
}
return true;
}
};
bool isValid(FakeFilesystem* fs, const char* path) {
return fs->valid_files.count(path) != 0;
}
TEST(ClientACLFileTransaction, FailedVerificationPreservesPrimary) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
EXPECT_FALSE(mesh::publishVerifiedClientACLTemp(&fs, false));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
}
TEST(ClientACLFileTransaction, VerifiedTempPublishesThroughBackup) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
EXPECT_TRUE(mesh::publishVerifiedClientACLTemp(&fs, true));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, PrimaryRenameFailureLeavesOldImage) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
fs.fail_from = mesh::CLIENT_ACL_PRIMARY_PATH;
fs.fail_to = mesh::CLIENT_ACL_BACKUP_PATH;
EXPECT_FALSE(mesh::publishVerifiedClientACLTemp(&fs, true));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
}
TEST(ClientACLFileTransaction, PublishFailureRestoresBackup) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
fs.fail_from = mesh::CLIENT_ACL_TEMP_PATH;
fs.fail_to = mesh::CLIENT_ACL_PRIMARY_PATH;
EXPECT_FALSE(mesh::publishVerifiedClientACLTemp(&fs, true));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, BootRecoveryKeepsPublishedPrimary) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH,
mesh::CLIENT_ACL_TEMP_PATH,
mesh::CLIENT_ACL_BACKUP_PATH,
};
EXPECT_TRUE(mesh::recoverClientACLFiles(&fs));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, BootRecoveryRestoresInterruptedPublish) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_TEMP_PATH, mesh::CLIENT_ACL_BACKUP_PATH};
EXPECT_TRUE(mesh::recoverClientACLFiles(&fs));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, CorruptPrimaryFallsBackToValidBackup) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_BACKUP_PATH};
fs.valid_files = {mesh::CLIENT_ACL_BACKUP_PATH};
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, isValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(mesh::CLIENT_ACL_PRIMARY_PATH) != 0);
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, CorruptPublishedPrimaryRestoresOldImage) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
fs.valid_files = {mesh::CLIENT_ACL_PRIMARY_PATH};
EXPECT_FALSE(mesh::publishVerifiedClientACLTemp(&fs, true, isValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(mesh::CLIENT_ACL_PRIMARY_PATH) != 0);
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, PublishedPrimarySurvivesBackupCleanupFailure) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
fs.valid_files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_TEMP_PATH};
fs.fail_remove = mesh::CLIENT_ACL_BACKUP_PATH;
EXPECT_TRUE(mesh::publishVerifiedClientACLTemp(&fs, true, isValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(mesh::CLIENT_ACL_PRIMARY_PATH) != 0);
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
// A later recovery pass can finish the best-effort cleanup without
// changing which image is authoritative.
fs.fail_remove.clear();
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, isValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
TEST(ClientACLFileTransaction, ValidPrimaryLoadsWhenCleanupCannotFinish) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH,
mesh::CLIENT_ACL_TEMP_PATH,
mesh::CLIENT_ACL_BACKUP_PATH,
};
fs.valid_files = {mesh::CLIENT_ACL_PRIMARY_PATH};
fs.fail_remove = mesh::CLIENT_ACL_BACKUP_PATH;
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, isValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_TEMP_PATH));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
}
std::vector<uint8_t> crcImage(size_t records) {
std::vector<uint8_t> image(records * 201, 0x5A);
uint32_t crc = mesh::updateClientACLCRC(
0xFFFFFFFFUL, image.data(), image.size()) ^ 0xFFFFFFFFUL;
image.insert(image.end(), mesh::CLIENT_ACL_CRC_MAGIC,
mesh::CLIENT_ACL_CRC_MAGIC + 4);
const uint8_t* bytes = reinterpret_cast<const uint8_t*>(&crc);
image.insert(image.end(), bytes, bytes + sizeof(crc));
return image;
}
bool realImageIsValid(FakeFilesystem* fs, const char* path) {
std::map<std::string, std::vector<uint8_t> >::const_iterator found =
fs->images.find(path);
if (found == fs->images.end()) return false;
const mesh::ClientACLImageKind kind = mesh::classifyClientACLImage(
found->second.data(), found->second.size(), 201, 136);
const bool publication_in_progress = std::string(path)
== mesh::CLIENT_ACL_PRIMARY_PATH
&& fs->exists(mesh::CLIENT_ACL_BACKUP_PATH);
return publication_in_progress ? kind == mesh::CLIENT_ACL_IMAGE_CRC
: kind != mesh::CLIENT_ACL_IMAGE_INVALID;
}
TEST(ClientACLFileTransaction, RealCRCClassifierRejectsTornTrailer) {
std::vector<uint8_t> image = crcImage(2);
EXPECT_EQ(mesh::classifyClientACLImage(image.data(), image.size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_CRC);
image.resize(image.size() - 8); // exactly 201*N: ambiguous standalone legacy
EXPECT_EQ(mesh::classifyClientACLImage(image.data(), image.size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_LEGACY);
// Recovery resolves this ambiguity from transaction state: if a backup is
// present, only CRC kind is acceptable for the newly published primary.
EXPECT_TRUE(mesh::classifyClientACLImage(
image.data(), image.size(), 201, 136) != mesh::CLIENT_ACL_IMAGE_CRC);
}
TEST(ClientACLFileTransaction, RealClassifierCoversRecordBoundaryTruncations) {
std::vector<uint8_t> image = crcImage(4);
image.resize(3 * 201);
EXPECT_EQ(mesh::classifyClientACLImage(image.data(), image.size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_LEGACY);
image.resize(2 * 136);
EXPECT_EQ(mesh::classifyClientACLImage(image.data(), image.size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_LEGACY);
image.resize(2 * 136 - 1);
EXPECT_EQ(mesh::classifyClientACLImage(image.data(), image.size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_INVALID);
}
TEST(ClientACLFileTransaction, TornTrailerRestoresRealValidatedBackup) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_BACKUP_PATH};
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH] = crcImage(2);
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].resize(2 * 201);
fs.images[mesh::CLIENT_ACL_BACKUP_PATH] = std::vector<uint8_t>(136, 0x33);
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, realImageIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
EXPECT_EQ(fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].size(), 136u);
}
TEST(ClientACLFileTransaction, TornTrailerRestoresCRCValidatedBackup) {
FakeFilesystem fs;
fs.files = {
mesh::CLIENT_ACL_PRIMARY_PATH, mesh::CLIENT_ACL_BACKUP_PATH};
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH] = crcImage(2);
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].resize(2 * 201);
fs.images[mesh::CLIENT_ACL_BACKUP_PATH] = crcImage(1);
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, realImageIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_ACL_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
EXPECT_EQ(mesh::classifyClientACLImage(
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].data(),
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_CRC);
}
TEST(ClientACLFileTransaction, StandaloneNoCRCLayoutsMigrateOnNextPublish) {
const size_t standalone_sizes[] = {136, 201};
for (size_t standalone_size : standalone_sizes) {
FakeFilesystem fs;
fs.files = {mesh::CLIENT_ACL_PRIMARY_PATH};
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH] =
std::vector<uint8_t>(standalone_size, 0x33);
EXPECT_TRUE(mesh::recoverClientACLFilesVerified(&fs, realImageIsValid));
EXPECT_EQ(mesh::classifyClientACLImage(
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].data(),
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_LEGACY);
fs.files.insert(mesh::CLIENT_ACL_TEMP_PATH);
fs.images[mesh::CLIENT_ACL_TEMP_PATH] = crcImage(1);
EXPECT_TRUE(mesh::publishVerifiedClientACLTemp(
&fs, true, realImageIsValid));
EXPECT_FALSE(fs.exists(mesh::CLIENT_ACL_BACKUP_PATH));
EXPECT_EQ(mesh::classifyClientACLImage(
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].data(),
fs.images[mesh::CLIENT_ACL_PRIMARY_PATH].size(), 201, 136),
mesh::CLIENT_ACL_IMAGE_CRC);
}
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,479 @@
#include <gtest/gtest.h>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include <helpers/ClientLoginPersistence.h>
#include <helpers/LazyPersistence.h>
namespace {
static constexpr uint8_t ROLE_MASK = 0x07;
static constexpr uint8_t ROLE_GUEST = 0x00;
static constexpr uint8_t ROLE_READ_ONLY = 0x01;
static constexpr uint8_t ROLE_READ_WRITE = 0x02;
static constexpr uint8_t ROLE_ADMIN = 0x03;
static constexpr uint8_t UNKNOWN_PATH = 0xFF;
static constexpr uint8_t FORCE_FLOOD_PATH = 0xFE;
struct ClientState {
uint8_t permissions = ROLE_ADMIN;
uint8_t out_path_len = UNKNOWN_PATH;
bool out_path_is_persistable = true;
uint8_t shared_secret[4] = {1, 2, 3, 4};
uint32_t last_timestamp = 10;
uint32_t last_activity = 20;
};
bool applyLogin(ClientState& client, bool existed, const uint8_t* secret,
uint8_t role = ROLE_ADMIN, bool is_flood = false) {
return mesh::applySuccessfulClientLogin(
client, existed, role, ROLE_MASK, secret,
100, 200, is_flood, UNKNOWN_PATH);
}
bool loginNeedsSave(bool existed, uint8_t previous, uint8_t next,
bool changed) {
return mesh::successfulClientLoginNeedsPersistence(
existed, previous, next, ROLE_MASK, 0, changed);
}
TEST(ClientLoginPersistence, UnchangedAdminLoginRefreshesOnlyTransientState) {
ClientState client;
const uint8_t same_secret[4] = {1, 2, 3, 4};
EXPECT_FALSE(applyLogin(client, true, same_secret));
EXPECT_EQ(client.last_timestamp, 100u);
EXPECT_EQ(client.last_activity, 200u);
EXPECT_EQ(client.permissions, ROLE_ADMIN);
EXPECT_EQ(client.out_path_len, UNKNOWN_PATH);
EXPECT_EQ(memcmp(client.shared_secret, same_secret, 4), 0);
}
TEST(ClientLoginPersistence, NewAdminNeedsPersistenceAndArmsFirstWrite) {
ClientState client;
const uint8_t same_secret[4] = {1, 2, 3, 4};
unsigned long pending = 0;
const bool changed = applyLogin(client, false, same_secret);
EXPECT_TRUE(changed);
EXPECT_TRUE(loginNeedsSave(false, 0, ROLE_ADMIN, changed));
EXPECT_TRUE(mesh::armFirstLazyPersistence(
pending, 5000,
loginNeedsSave(false, 0, ROLE_ADMIN, changed)));
EXPECT_EQ(pending, 5000UL);
EXPECT_EQ(client.last_timestamp, 100u);
EXPECT_EQ(client.last_activity, 200u);
}
TEST(ClientLoginPersistence, NewGuestStaysRuntimeOnly) {
ClientState client;
client.permissions = 0;
const uint8_t same_secret[4] = {1, 2, 3, 4};
unsigned long pending = 0;
const bool changed = applyLogin(client, false, same_secret, 0);
EXPECT_TRUE(changed);
EXPECT_EQ(client.permissions & ROLE_MASK, 0);
EXPECT_FALSE(loginNeedsSave(false, 0, 0, changed));
EXPECT_FALSE(mesh::armFirstLazyPersistence(
pending, 5000, loginNeedsSave(false, 0, 0, changed)));
EXPECT_EQ(pending, 0UL);
}
TEST(ClientLoginPersistence, GuestPromotionToAdminNeedsPersistence) {
ClientState client;
client.permissions = 0;
const uint8_t same_secret[4] = {1, 2, 3, 4};
const bool changed = applyLogin(client, true, same_secret, ROLE_ADMIN);
EXPECT_TRUE(changed);
EXPECT_TRUE(loginNeedsSave(true, 0, ROLE_ADMIN, changed));
EXPECT_EQ(client.permissions, ROLE_ADMIN);
}
TEST(ClientLoginPersistence, AdminDowngradeToGuestRemovesPersistedEntry) {
ClientState client;
client.permissions = 0x83;
const uint8_t same_secret[4] = {1, 2, 3, 4};
const bool changed = applyLogin(client, true, same_secret, 0);
EXPECT_TRUE(changed);
EXPECT_EQ(client.permissions & ROLE_MASK, 0);
EXPECT_EQ(client.permissions, 0x80);
EXPECT_FALSE(mesh::clientRoleIsPersisted(
client.permissions, ROLE_MASK, 0));
EXPECT_TRUE(loginNeedsSave(true, ROLE_ADMIN, 0, changed));
}
TEST(ClientLoginPersistence, GuestUpperPermissionBitsNeverMakeItPersistent) {
EXPECT_FALSE(mesh::clientRoleIsPersisted(0x00, ROLE_MASK, 0));
EXPECT_FALSE(mesh::clientRoleIsPersisted(0x80, ROLE_MASK, 0));
EXPECT_TRUE(mesh::clientRoleIsPersisted(0x81, ROLE_MASK, 0));
}
TEST(ClientLoginPersistence, PreauthorizedLoginStillRefreshesReplayState) {
ClientState client;
client.permissions = 1;
const uint8_t same_secret[4] = {1, 2, 3, 4};
EXPECT_FALSE(applyLogin(client, true, same_secret, 1));
EXPECT_EQ(client.permissions, 1);
EXPECT_EQ(client.last_timestamp, 100u);
EXPECT_EQ(client.last_activity, 200u);
}
TEST(ClientLoginPersistence, PersistedRoleOrSecretChangesNeedPersistence) {
const uint8_t same_secret[4] = {1, 2, 3, 4};
const uint8_t changed_secret[4] = {4, 3, 2, 1};
ClientState role_changed;
role_changed.permissions = 0xA1;
EXPECT_TRUE(applyLogin(role_changed, true, same_secret, 0xFB));
EXPECT_EQ(role_changed.permissions, 0xA3);
ClientState secret_changed;
EXPECT_TRUE(applyLogin(secret_changed, true, changed_secret));
EXPECT_EQ(memcmp(secret_changed.shared_secret, changed_secret, 4), 0);
}
TEST(ClientLoginPersistence, FloodPathResetPersistsOnlyWhenValueChanges) {
const uint8_t same_secret[4] = {1, 2, 3, 4};
ClientState known_path;
known_path.out_path_len = 2;
EXPECT_TRUE(applyLogin(
known_path, true, same_secret, ROLE_ADMIN, true));
EXPECT_EQ(known_path.out_path_len, UNKNOWN_PATH);
EXPECT_TRUE(known_path.out_path_is_persistable);
ClientState already_unknown;
EXPECT_FALSE(applyLogin(
already_unknown, true, same_secret, ROLE_ADMIN, true));
}
TEST(ClientLoginPersistence, FloodLoginNeverDestroysForceFlood) {
const uint8_t same_secret[4] = {1, 2, 3, 4};
ClientState client;
client.out_path_len = FORCE_FLOOD_PATH;
const bool reset_out_path = client.out_path_len != FORCE_FLOOD_PATH;
EXPECT_FALSE(mesh::applySuccessfulClientLogin(
client, true, ROLE_ADMIN, ROLE_MASK, same_secret,
100, 200, reset_out_path, UNKNOWN_PATH));
EXPECT_EQ(client.out_path_len, FORCE_FLOOD_PATH);
EXPECT_TRUE(client.out_path_is_persistable);
}
TEST(ClientLoginPersistence, ReplayValidationPrecedesAllocation) {
EXPECT_FALSE(mesh::isFreshClientLoginTimestamp(false, 0, 0));
EXPECT_TRUE(mesh::isFreshClientLoginTimestamp(false, 1, 0));
EXPECT_FALSE(mesh::isFreshClientLoginTimestamp(true, 0, 50));
EXPECT_FALSE(mesh::isFreshClientLoginTimestamp(true, 49, 50));
EXPECT_FALSE(mesh::isFreshClientLoginTimestamp(true, 50, 50));
EXPECT_TRUE(mesh::isFreshClientLoginTimestamp(true, 51, 50));
}
TEST(ClientLoginPersistence, DurableReservationSurvivesReboot) {
const auto first = mesh::planClientLoginReplay(0, 0, 100);
ASSERT_TRUE(first.fresh);
ASSERT_TRUE(first.reservation_needed);
EXPECT_EQ(first.reservation_ceiling, 160u);
// Once this boot has accepted 100, reconnects advance against the exact RAM
// floor and consume the already durable reservation without another write.
const auto reconnect = mesh::planClientLoginReplay(
100, first.reservation_ceiling, 101);
EXPECT_TRUE(reconnect.fresh);
EXPECT_FALSE(reconnect.reservation_needed);
// A reboot has no exact RAM floor. It deliberately skips the unused tail,
// so neither accepted timestamp can become fresh again.
const auto replay_after_reboot = mesh::planClientLoginReplay(
0, first.reservation_ceiling, 101);
EXPECT_FALSE(replay_after_reboot.fresh);
const auto after_reserved_tail = mesh::planClientLoginReplay(
0, first.reservation_ceiling, 161);
EXPECT_TRUE(after_reserved_tail.fresh);
EXPECT_TRUE(after_reserved_tail.reservation_needed);
EXPECT_EQ(after_reserved_tail.reservation_ceiling, 221u);
}
TEST(ClientLoginPersistence, EvictionCannotEraseReplayFloor) {
const uint32_t tombstone_ceiling = 460;
// Eviction removes the live ClientInfo and therefore its exact timestamp.
// The absent runtime floor must fall back to the per-identity tombstone.
EXPECT_FALSE(mesh::planClientLoginReplay(
0, tombstone_ceiling, 400).fresh);
EXPECT_FALSE(mesh::planClientLoginReplay(
0, tombstone_ceiling, tombstone_ceiling).fresh);
EXPECT_TRUE(mesh::planClientLoginReplay(
0, tombstone_ceiling, tombstone_ceiling + 1).fresh);
}
TEST(ClientLoginPersistence, RevokedAdminReplayUsesTombstoneNotRole) {
const uint32_t revoked_admin_floor = 1060;
// Role removal is intentionally absent from the planner: replay history is
// keyed by public identity and outlives the ACL record/permissions.
const uint8_t current_role = 0; // guest/deleted
(void)current_role;
EXPECT_FALSE(mesh::planClientLoginReplay(
0, revoked_admin_floor, 1000).fresh);
EXPECT_FALSE(mesh::planClientLoginReplay(
0, revoked_admin_floor, 1001).fresh);
}
TEST(ClientLoginPersistence, ReservationSaturatesWithoutWrapping) {
EXPECT_EQ(mesh::reserveClientLoginTimestamp(UINT32_MAX - 10, 60),
UINT32_MAX);
EXPECT_FALSE(mesh::planClientLoginReplay(
UINT32_MAX, UINT32_MAX, UINT32_MAX).fresh);
}
TEST(ClientLoginPersistence, GuestAndReadOnlyDoNotAllocateDurableIdentity) {
EXPECT_FALSE(mesh::clientLoginRoleNeedsDurableReplay(
ROLE_GUEST, ROLE_MASK, ROLE_GUEST, ROLE_READ_ONLY));
EXPECT_FALSE(mesh::clientLoginRoleNeedsDurableReplay(
ROLE_READ_ONLY, ROLE_MASK, ROLE_GUEST, ROLE_READ_ONLY));
// Unrelated upper permission bits do not turn a low-trust role into a
// durable replay-store consumer.
EXPECT_FALSE(mesh::clientLoginRoleNeedsDurableReplay(
0x81, ROLE_MASK, ROLE_GUEST, ROLE_READ_ONLY));
const auto first_guest = mesh::planClientLoginReplay(
0, 0, 100);
EXPECT_TRUE(first_guest.fresh);
EXPECT_TRUE(first_guest.reservation_needed);
// A full durable store is irrelevant because policy selects no write for a
// missing low-trust identity.
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
first_guest.reservation_needed, false, false),
mesh::ClientLoginReplayReservationAction::None);
}
TEST(ClientLoginPersistence, LowTrustLoginStillEnforcesExistingFloors) {
const uint32_t privileged_tombstone = 460;
EXPECT_FALSE(mesh::planClientLoginReplay(
0, privileged_tombstone, 400).fresh);
EXPECT_FALSE(mesh::planClientLoginReplay(
0, privileged_tombstone, privileged_tombstone).fresh);
const auto newer = mesh::planClientLoginReplay(
0, privileged_tombstone, privileged_tombstone + 1);
EXPECT_TRUE(newer.fresh);
EXPECT_TRUE(newer.reservation_needed);
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
newer.reservation_needed, true, false),
mesh::ClientLoginReplayReservationAction::UpdateExisting);
// Once admitted, the exact RAM floor still rejects same-boot replay even
// for a missing low-trust identity which deliberately performs no write.
EXPECT_FALSE(mesh::planClientLoginReplay(
privileged_tombstone + 1, privileged_tombstone,
privileged_tombstone + 1).fresh);
}
TEST(ClientLoginPersistence, FullStoreFailsOnlyNewPrivilegedIdentity) {
for (uint8_t role : {ROLE_READ_WRITE, ROLE_ADMIN, (uint8_t)4, (uint8_t)5}) {
EXPECT_TRUE(mesh::clientLoginRoleNeedsDurableReplay(
role, ROLE_MASK, ROLE_GUEST, ROLE_READ_ONLY));
}
const auto privileged = mesh::planClientLoginReplay(0, 0, 100);
ASSERT_TRUE(privileged.fresh);
ASSERT_TRUE(privileged.reservation_needed);
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
privileged.reservation_needed, false, true),
mesh::ClientLoginReplayReservationAction::CreateNew);
EXPECT_FALSE(mesh::clientLoginReplayCanInsert(
mesh::MAX_CLIENT_LOGIN_REPLAY_IDENTITIES));
EXPECT_TRUE(mesh::clientLoginReplayCanInsert(
mesh::MAX_CLIENT_LOGIN_REPLAY_IDENTITIES - 1));
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
privileged.reservation_needed, true, true),
mesh::ClientLoginReplayReservationAction::UpdateExisting);
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
privileged.reservation_needed, true, false),
mesh::ClientLoginReplayReservationAction::UpdateExisting);
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
privileged.reservation_needed, false, false),
mesh::ClientLoginReplayReservationAction::None);
EXPECT_EQ(mesh::selectClientLoginReplayReservation(
false, false, true),
mesh::ClientLoginReplayReservationAction::None);
}
std::vector<uint8_t> replayImage(
const std::vector<std::pair<std::vector<uint8_t>, uint32_t> >& records) {
std::vector<uint8_t> image;
uint32_t crc = 0xFFFFFFFFUL;
for (const auto& record : records) {
EXPECT_EQ(record.first.size(), 32u);
image.insert(image.end(), record.first.begin(), record.first.end());
crc = mesh::updateClientLoginReplayCRC(
crc, record.first.data(), record.first.size());
const uint8_t* floor =
reinterpret_cast<const uint8_t*>(&record.second);
image.insert(image.end(), floor, floor + sizeof(record.second));
crc = mesh::updateClientLoginReplayCRC(
crc, floor, sizeof(record.second));
}
image.insert(image.end(), mesh::CLIENT_LOGIN_REPLAY_MAGIC,
mesh::CLIENT_LOGIN_REPLAY_MAGIC + 4);
const uint32_t final_crc = crc ^ 0xFFFFFFFFUL;
const uint8_t* trailer =
reinterpret_cast<const uint8_t*>(&final_crc);
image.insert(image.end(), trailer, trailer + sizeof(final_crc));
return image;
}
TEST(ClientLoginPersistence, ReplayImageIntegrityRejectsTornOrChangedState) {
std::vector<uint8_t> key(32, 0xA5);
std::vector<uint8_t> image = replayImage({{key, 160}});
ASSERT_TRUE(mesh::validateClientLoginReplayImage(
image.data(), image.size()));
std::vector<uint8_t> changed = image;
changed[32] ^= 1;
EXPECT_FALSE(mesh::validateClientLoginReplayImage(
changed.data(), changed.size()));
image.pop_back();
EXPECT_FALSE(mesh::validateClientLoginReplayImage(
image.data(), image.size()));
}
class ReplayFakeFilesystem {
public:
std::set<std::string> files;
std::set<std::string> valid_files;
std::string fail_from;
std::string fail_to;
std::string fail_remove;
bool exists(const char* path) const {
return files.count(path) != 0;
}
bool remove(const char* path) {
if (fail_remove == path) return false;
valid_files.erase(path);
return files.erase(path) != 0;
}
bool rename(const char* from, const char* to) {
if (fail_from == from && fail_to == to) return false;
if (!exists(from) || exists(to)) return false;
files.erase(from);
files.insert(to);
if (valid_files.erase(from) != 0) valid_files.insert(to);
return true;
}
};
bool replayFileIsValid(ReplayFakeFilesystem* fs, const char* path) {
return fs->valid_files.count(path) != 0;
}
TEST(ClientLoginPersistence, InterruptedReplayPublishRestoresOldFloorImage) {
ReplayFakeFilesystem fs;
fs.files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
};
fs.valid_files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
};
fs.fail_from = mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH;
fs.fail_to = mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH;
EXPECT_FALSE(mesh::publishClientLoginReplayTemp(
&fs, true, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH) != 0);
EXPECT_FALSE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
}
TEST(ClientLoginPersistence, PublishedReplaySurvivesBackupCleanupFailure) {
ReplayFakeFilesystem fs;
fs.files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
};
fs.valid_files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
};
fs.fail_remove = mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH;
EXPECT_TRUE(mesh::publishClientLoginReplayTemp(
&fs, true, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH) != 0);
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
fs.fail_remove.clear();
EXPECT_TRUE(mesh::recoverClientLoginReplayFiles(
&fs, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
}
TEST(ClientLoginPersistence, ValidReplayLoadsWhenCleanupCannotFinish) {
ReplayFakeFilesystem fs;
fs.files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH,
};
fs.valid_files = {mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH};
fs.fail_remove = mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH;
EXPECT_TRUE(mesh::recoverClientLoginReplayFiles(
&fs, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
}
TEST(ClientLoginPersistence, BootRecoveryRestoresValidReplayBackup) {
ReplayFakeFilesystem fs;
fs.files = {
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH,
mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH,
mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH,
};
fs.valid_files = {mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH};
EXPECT_TRUE(mesh::recoverClientLoginReplayFiles(
&fs, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
EXPECT_TRUE(fs.valid_files.count(
mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH) != 0);
EXPECT_FALSE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
EXPECT_FALSE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH));
}
TEST(ClientLoginPersistence, CorruptReplayStateFailsClosed) {
ReplayFakeFilesystem fs;
fs.files = {mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH};
EXPECT_FALSE(mesh::recoverClientLoginReplayFiles(
&fs, replayFileIsValid));
EXPECT_TRUE(fs.exists(mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH));
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Static regression contract for ClientACL-backed login handlers."""
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PROFILES = (
(ROOT / "examples/simple_repeater/MyMesh.cpp", 4, "perms"),
(ROOT / "examples/simple_sensor/SensorMesh.cpp", 4, "role_permissions"),
(ROOT / "examples/simple_room_server/MyMesh.cpp", 8, "perm"),
)
def handler_body(path: Path) -> str:
source = path.read_text(encoding="utf-8")
marker = "handleLoginReq" if "simple_room_server" not in str(path) else "onAnonDataRecv"
start = source.index(marker)
end = source.index("RESP_SERVER_LOGIN_OK", start)
return source[start:end]
for profile, minimum_anon_length, login_permissions in PROFILES:
body = handler_body(profile)
freshness = body.index("authorizeLoginTimestamp")
allocation = body.index("putClient")
assert freshness < allocation, (
f"{profile}: durable replay authorization must precede allocation"
)
assert "applySuccessfulClientLogin" in body, f"{profile}: unmasked role transition"
assert "PERM_ACL_ROLE_MASK" in body, f"{profile}: missing role mask"
assert "OUT_PATH_FORCE_FLOOD" in body, f"{profile}: flood login destroys force-flood"
authorization = body[
freshness : body.index(")", freshness) + 1
]
assert re.search(
rf"previous_timestamp\s*,\s*{re.escape(login_permissions)}\s*\)",
authorization,
), f"{profile}: replay admission is not bound to the authenticated role"
source = profile.read_text(encoding="utf-8")
anon_start = source.index("onAnonDataRecv")
first_field_read = source.index("memcpy(", anon_start)
length_guard = source.index(f"len < {minimum_anon_length}", anon_start)
assert length_guard < first_field_read, (
f"{profile}: anonymous request fields read before minimum-length guard"
)
print("client login profile contract: PASS")
@@ -0,0 +1,245 @@
#include <gtest/gtest.h>
#include <helpers/ClientPathPersistence.h>
#include <helpers/LazyPersistence.h>
namespace {
static constexpr uint8_t UNKNOWN_PATH = 0xFF;
static constexpr uint8_t FORCE_FLOOD_PATH = 0xFE;
struct ClientState {
uint8_t permissions = 3;
uint8_t out_path_len = UNKNOWN_PATH;
uint8_t out_path[64] = {};
bool out_path_is_persistable = true;
};
TEST(ClientPathPersistence, UnknownToLearnedPathNeedsPersistence) {
ClientState client;
const uint8_t path[] = {0x10, 0x11, 0x12, 0x13};
const auto result = mesh::applyReceivedClientPath(
client, path, 0x42, true, FORCE_FLOOD_PATH);
EXPECT_TRUE(result.changed);
EXPECT_TRUE(result.persistence_needed);
EXPECT_TRUE(client.out_path_is_persistable);
EXPECT_EQ(client.out_path_len, 0x42);
EXPECT_EQ(memcmp(client.out_path, path, sizeof(path)), 0);
}
TEST(ClientPathPersistence, SameEncodedLengthAndBytesIsUnchanged) {
ClientState client;
client.out_path_len = 0x42;
const uint8_t path[] = {0x10, 0x11, 0x12, 0x13};
memcpy(client.out_path, path, sizeof(path));
client.out_path[10] = 0xA5; // stale capacity is not part of the path
const auto result = mesh::applyReceivedClientPath(
client, path, 0x42, true, FORCE_FLOOD_PATH);
EXPECT_FALSE(result.changed);
EXPECT_FALSE(result.persistence_needed);
EXPECT_TRUE(client.out_path_is_persistable);
EXPECT_EQ(client.out_path[10], 0xA5);
}
TEST(ClientPathPersistence, SameEncodedLengthDifferentBytesChanges) {
ClientState client;
client.out_path_len = 2;
client.out_path[0] = 0x10;
client.out_path[1] = 0x11;
const uint8_t path[] = {0x10, 0x22};
const auto result = mesh::applyReceivedClientPath(
client, path, 2, true, FORCE_FLOOD_PATH);
EXPECT_TRUE(result.changed);
EXPECT_TRUE(result.persistence_needed);
EXPECT_EQ(client.out_path[1], 0x22);
}
TEST(ClientPathPersistence, DifferentEncodingChangesEvenAtSameByteLength) {
ClientState client;
client.out_path_len = 2; // two one-byte hashes
client.out_path[0] = 0x10;
client.out_path[1] = 0x11;
const uint8_t path[] = {0x10, 0x11};
const auto result = mesh::applyReceivedClientPath(
client, path, 0x41, true, FORCE_FLOOD_PATH); // one two-byte hash
EXPECT_TRUE(result.changed);
EXPECT_TRUE(result.persistence_needed);
EXPECT_EQ(client.out_path_len, 0x41);
}
TEST(ClientPathPersistence, EncodingValidationMatchesPacketPathRules) {
EXPECT_TRUE(mesh::isValidEncodedClientPathLength(0, 64));
EXPECT_TRUE(mesh::isValidEncodedClientPathLength(0x5F, 64));
EXPECT_FALSE(mesh::isValidEncodedClientPathLength(0x61, 64));
EXPECT_FALSE(mesh::isValidEncodedClientPathLength(0xC0, 64));
}
TEST(ClientPathPersistence, ZeroHopIsARealLogicalPath) {
ClientState client;
const auto result = mesh::applyReceivedClientPath(
client, nullptr, 0, true, FORCE_FLOOD_PATH);
EXPECT_TRUE(result.changed);
EXPECT_TRUE(result.persistence_needed);
EXPECT_EQ(client.out_path_len, 0);
const auto repeated = mesh::applyReceivedClientPath(
client, nullptr, 0, true, FORCE_FLOOD_PATH);
EXPECT_FALSE(repeated.changed);
}
TEST(ClientPathPersistence, ForceFloodIsNeverOverwritten) {
ClientState client;
client.out_path_len = FORCE_FLOOD_PATH;
client.out_path[0] = 0x55;
const uint8_t path[] = {0x10};
const auto result = mesh::applyReceivedClientPath(
client, path, 1, true, FORCE_FLOOD_PATH);
EXPECT_FALSE(result.changed);
EXPECT_FALSE(result.persistence_needed);
EXPECT_EQ(client.out_path_len, FORCE_FLOOD_PATH);
EXPECT_EQ(client.out_path[0], 0x55);
}
TEST(ClientPathPersistence, NonpersistentClientStillGetsLatestRamPath) {
ClientState client;
client.permissions = 0;
const uint8_t path[] = {0x33};
const auto result = mesh::applyReceivedClientPath(
client, path, 1, false, FORCE_FLOOD_PATH);
EXPECT_TRUE(result.changed);
EXPECT_FALSE(result.persistence_needed);
EXPECT_EQ(client.out_path_len, 1);
EXPECT_EQ(client.out_path[0], 0x33);
EXPECT_FALSE(client.out_path_is_persistable);
}
TEST(ClientPathPersistence, NoReplayProofForcesRamOnlyPath) {
ClientState client;
const uint8_t path[] = {0x44};
EXPECT_FALSE(mesh::clientPathPersistenceAllowed(true, false));
const auto result = mesh::applyReceivedClientPath(
client, path, 1,
mesh::clientPathPersistenceAllowed(true, false),
FORCE_FLOOD_PATH);
EXPECT_TRUE(result.changed);
EXPECT_FALSE(result.persistence_needed);
EXPECT_EQ(client.out_path[0], 0x44);
EXPECT_FALSE(client.out_path_is_persistable);
EXPECT_EQ(mesh::storedClientPathLength(
client.out_path_is_persistable, client.out_path_len, UNKNOWN_PATH),
UNKNOWN_PATH);
}
TEST(ClientPathPersistence, IdenticalProvenPathPromotesRamRouteToDurable) {
ClientState client;
const uint8_t path[] = {0x44};
ASSERT_TRUE(mesh::applyReceivedClientPath(
client, path, 1, false, FORCE_FLOOD_PATH).changed);
ASSERT_FALSE(client.out_path_is_persistable);
const auto promoted = mesh::applyReceivedClientPath(
client, path, 1, true, FORCE_FLOOD_PATH);
EXPECT_TRUE(promoted.changed);
EXPECT_TRUE(promoted.persistence_needed);
EXPECT_TRUE(client.out_path_is_persistable);
}
TEST(ClientPathPersistence,
TransientLearnedPathCannotEraseOperatorPathOnUnrelatedSaveReload) {
ClientState client;
const uint8_t operator_path[] = {0x11, 0x22};
client.out_path_len = 2;
memcpy(client.out_path, operator_path, sizeof(operator_path));
client.out_path_is_persistable = true;
// This represents the already-published /s_contacts record.
uint8_t published_path[64] = {};
memcpy(published_path, client.out_path, sizeof(published_path));
uint8_t published_path_len = client.out_path_len;
const uint8_t learned_path[] = {0x33, 0x44};
const auto learned = mesh::applyReceivedClientPath(
client, learned_path, 2, false, FORCE_FLOOD_PATH);
ASSERT_TRUE(learned.changed);
ASSERT_FALSE(learned.persistence_needed);
ASSERT_FALSE(client.out_path_is_persistable);
ASSERT_EQ(client.out_path[0], 0x33);
// An unrelated permissions/ACL save must select the prior durable route,
// not UNKNOWN and not the replay-unproven runtime route.
const uint8_t empty_path[64] = {};
const auto selected = mesh::selectStoredClientPath(
client.out_path_is_persistable,
client.out_path_len,
client.out_path,
true,
published_path_len,
published_path,
UNKNOWN_PATH,
empty_path);
EXPECT_EQ(selected.encoded_path_len, 2);
EXPECT_EQ(memcmp(selected.path, operator_path, sizeof(operator_path)), 0);
// Emulate reload from that just-written record.
ClientState reloaded;
reloaded.out_path_len = selected.encoded_path_len;
memcpy(reloaded.out_path, selected.path, sizeof(reloaded.out_path));
reloaded.out_path_is_persistable = true;
EXPECT_EQ(reloaded.out_path_len, 2);
EXPECT_EQ(memcmp(reloaded.out_path, operator_path,
sizeof(operator_path)), 0);
}
TEST(ClientPathPersistence, TransientPathWithoutPriorRecordSavesUnknown) {
ClientState client;
const uint8_t learned_path[] = {0x55};
ASSERT_TRUE(mesh::applyReceivedClientPath(
client, learned_path, 1, false, FORCE_FLOOD_PATH).changed);
const uint8_t empty_path[64] = {};
const auto selected = mesh::selectStoredClientPath(
client.out_path_is_persistable,
client.out_path_len,
client.out_path,
false,
UNKNOWN_PATH,
empty_path,
UNKNOWN_PATH,
empty_path);
EXPECT_EQ(selected.encoded_path_len, UNKNOWN_PATH);
EXPECT_EQ(selected.path, empty_path);
}
TEST(ClientPathPersistence, PendingWriteKeepsFirstDeadlineAndLatestRamPath) {
ClientState client;
unsigned long pending = 0;
const uint8_t first[] = {0x11};
const uint8_t latest[] = {0x22};
auto result = mesh::applyReceivedClientPath(
client, first, 1, true, FORCE_FLOOD_PATH);
EXPECT_TRUE(mesh::armFirstLazyPersistence(
pending, 5000, result.persistence_needed));
result = mesh::applyReceivedClientPath(
client, latest, 1, true, FORCE_FLOOD_PATH);
EXPECT_FALSE(mesh::armFirstLazyPersistence(
pending, 9000, result.persistence_needed));
EXPECT_EQ(pending, 5000UL);
EXPECT_EQ(client.out_path[0], 0x22);
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+30
View File
@@ -24,16 +24,46 @@ assert re.search(
assert "offline_queue_len" in local
assert "getOfflineQueueCapacity()" in local
# Mutable local settings must be dispatched before the terminal's generic
# `set` fallback. `set pin` used to exist only in handleCommand(), so the
# text terminal intercepted it as an unknown setting while framed/rescue CLI
# happened to work.
assert local.count('strncmp(command, "set pin", 7) == 0') == 1
assert "mesh::cli::parseIntegerStrict(value, parsed)" in local
assert "const uint32_t previous = _prefs.ble_pin;" in local
assert "_prefs.ble_pin = previous;" in local
terminal_start = source.index("void MyMesh::handleTerminalCommand(")
terminal_end = source.index("\nvoid MyMesh::enterCLIRescue()", terminal_start)
terminal = source[terminal_start:terminal_end]
assert terminal.index("handleLocalControlCommand(") < terminal.index(
'strncmp(command, "set ", 4) == 0'
)
assert 'terminalOutput().print(" board\\r\\n")' in terminal
assert 'terminalOutput().print(" set pin <0-999999>\\r\\n")' in terminal
assert re.search(
r"#if COMPANION_FEATURE_MEMORY_DIAGNOSTICS\s+"
r'terminalOutput\(\)\.print\(" memory\\r\\n"\);\s+#endif',
terminal,
)
# Terminal-specific handlers keep precedence, then both the generic `set`
# fallthrough and the final unknown-command fallthrough delegate to the shared
# framed/rescue command surface. This keeps get/set radio, get name, and
# variant commands available without routing terminal-only commands twice.
assert terminal.count("handleCommand(command, 0, local_reply)") == 2
assert terminal.index('strncmp(config, "tx ", 3)') < terminal.index(
"handleCommand(command, 0, local_reply)"
)
assert terminal.rindex('strcmp(command, "ver") == 0') < terminal.rindex(
"handleCommand(command, 0, local_reply)"
)
command_start = source.index("bool MyMesh::handleCommand(")
command_end = source.index("\nvoid MyMesh::checkCLIRescueCmd()", command_start)
command_handler = source[command_start:command_end]
assert 'strncmp(command, "set pin' not in command_handler
# This compile-time contract prevents either the implementation or help entry
# from leaking onto a non-ESP32 build merely because a recipe set the flag.
assert re.search(
@@ -1,8 +1,10 @@
#include <gtest/gtest.h>
#include <helpers/ui/DisplayDriver.h>
#include <helpers/ui/DisplayTextLayout.h>
#include <string>
#include <vector>
namespace {
@@ -32,7 +34,16 @@ bool isValidUTF8(const char* text) {
class TestDisplay : public DisplayDriver {
public:
struct DrawnText {
int x;
int y;
std::string text;
};
std::string printed;
std::vector<DrawnText> rows;
int cursor_x = 0;
int cursor_y = 0;
TestDisplay() : DisplayDriver(100, 100) {}
@@ -43,8 +54,14 @@ public:
void startFrame(ColorVal) override {}
void setTextSize(int) override {}
void setColor(ColorVal) override {}
void setCursor(int, int) override {}
void print(const char* str) override { printed = str; }
void setCursor(int x, int y) override {
cursor_x = x;
cursor_y = y;
}
void print(const char* str) override {
printed = str;
rows.push_back({cursor_x, cursor_y, str});
}
void fillRect(int, int, int, int) override {}
void drawRect(int, int, int, int) override {}
void drawXbm(int, int, const uint8_t*, int, int) override {}
@@ -77,6 +94,43 @@ TEST(DisplayDriver, FixedBufferDoesNotSplitUTF8Codepoint) {
EXPECT_TRUE(isValidUTF8(display.printed.c_str()));
}
TEST(DisplayDriver, WrapsCompleteTextAcrossAvailableRows) {
TestDisplay display;
EXPECT_EQ(3, mesh::ui::drawTextWrapped(
display, 4, 10, 3, 9, 3, "ABCDEFG"));
ASSERT_EQ(3U, display.rows.size());
EXPECT_EQ(4, display.rows[0].x);
EXPECT_EQ(10, display.rows[0].y);
EXPECT_EQ("ABC", display.rows[0].text);
EXPECT_EQ(4, display.rows[1].x);
EXPECT_EQ(19, display.rows[1].y);
EXPECT_EQ("DEF", display.rows[1].text);
EXPECT_EQ(28, display.rows[2].y);
EXPECT_EQ("G", display.rows[2].text);
}
TEST(DisplayDriver, WrappedTextKeepsUTF8CodepointsIntact) {
TestDisplay display;
EXPECT_EQ(2, mesh::ui::drawTextWrapped(
display, 0, 0, 3, 10, 2, "AB\xF0\x9F\x98\x80" "CDE"));
ASSERT_EQ(2U, display.rows.size());
EXPECT_EQ("AB\xF0\x9F\x98\x80", display.rows[0].text);
EXPECT_EQ("CDE", display.rows[1].text);
EXPECT_TRUE(isValidUTF8(display.rows[0].text.c_str()));
EXPECT_TRUE(isValidUTF8(display.rows[1].text.c_str()));
}
TEST(DisplayDriver, KeepsMaximumLengthSSIDWithoutEllipsis) {
TestDisplay display;
const std::string ssid = "1234567890ABCDEF1234567890ABCDEF";
EXPECT_EQ(3, mesh::ui::drawTextWrapped(
display, 0, 0, 12, 10, 3, ssid.c_str()));
ASSERT_EQ(3U, display.rows.size());
EXPECT_EQ(ssid,
display.rows[0].text + display.rows[1].text
+ display.rows[2].text);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
import re
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
def source(path: str) -> str:
return (ROOT / path).read_text()
class Esp32UsbSerialHygieneTest(unittest.TestCase):
def test_operational_wifi_diagnostics_use_runtime_logging_port(self):
for relative in (
"src/helpers/ESP32Board.cpp",
"src/helpers/CompanionMqttSetupPortal.cpp",
"src/helpers/JWTHelper.cpp",
"src/helpers/bridges/MQTTBridge.cpp",
"src/helpers/esp32/WiFiOtaSeeder.cpp",
"src/helpers/esp32/WebConfigServer.cpp",
"src/helpers/WiFiSetupPortal.cpp",
):
text = source(relative)
self.assertIn("UsbLogging.h", text, relative)
self.assertNotRegex(
text,
r"\bSerial\.(?:print|println|printf|write)\s*\(",
relative,
)
self.assertIn("mesh::usbLoggingPort()", text, relative)
def test_v4_companion_uses_usb_serial_jtag_mode(self):
platformio = source("variants/heltec_v4/platformio.ini")
base = platformio[
platformio.index("[Heltec_lora32_v4]") :
platformio.index("[heltec_v4_oled]")
]
self.assertIn("-D ARDUINO_USB_MODE=1", base)
self.assertNotIn("ARDUINO_USB_MODE=0", base)
board = source("boards/heltec_v4.json")
self.assertIn('"-DARDUINO_USB_CDC_ON_BOOT=1"', board)
self.assertIn('"-DARDUINO_USB_MODE=1"', board)
def test_mqtt_ntp_detail_never_bypasses_logging_mode(self):
text = source("src/helpers/bridges/MQTTBridge.cpp")
self.assertIn(
"if (verbose && mesh::isUsbLoggingEnabled())", text
)
self.assertIn("Stream& output = mesh::usbLoggingPort();", text)
def test_framework_diagnostics_follow_same_runtime_gate(self):
text = source("src/helpers/UsbLogging.cpp")
self.assertIn("Serial.setDebugOutput(enabled);", text)
setter = text[
text.index("void setUsbLoggingEnabled(") :
text.index("bool saveUsbLoggingBootPreference(")
]
self.assertIn("setPlatformDebugOutputEnabled(enabled);", setter)
begin = text[
text.index("void beginUsbLoggingPort(") :
text.index("void serviceUsbLoggingPort(")
]
self.assertIn(
"setPlatformDebugOutputEnabled(isUsbLoggingEnabled());", begin
)
def test_expected_fresh_nvs_state_is_silent(self):
wifi_setup = source("src/helpers/WiFiSetupPortal.cpp")
webconfig = source("src/helpers/esp32/WebConfigServer.cpp")
radio_policy = source("src/helpers/esp32/WiFiRadioPolicy.h")
mqtt_setup = source("src/helpers/CompanionMqttSetupPortal.cpp")
for text in (wifi_setup, webconfig, radio_policy, mqtt_setup):
self.assertNotRegex(
text,
r'\.begin\("mesh-(?:wifi|webui|mqtt)",\s*true\)',
)
self.assertNotIn("nvs.begin(NVS_NAMESPACE, true)", mqtt_setup)
for text in (wifi_setup, webconfig):
self.assertIn('isKey("ssid")', text)
self.assertIn('isKey("password")', text)
self.assertIn('isKey("enabled")', webconfig)
self.assertIn('isKey("cli")', webconfig)
self.assertIn('isKey("powersave")', webconfig)
self.assertIn('isKey("espnow_ch")', radio_policy)
self.assertIn("nvs.isKey(NVS_VERSION_KEY)", mqtt_setup)
self.assertIn("nvs.isKey(NVS_PREFS_KEY)", mqtt_setup)
def test_indicator_reports_specific_hardware(self):
header = source("variants/sensecap_indicator-espnow/target.h")
implementation = source("variants/sensecap_indicator-espnow/target.cpp")
self.assertIn(
"class SenseCapIndicatorBoard : public ESP32Board", header
)
self.assertIn('return "Seeed SenseCAP Indicator";', header)
self.assertIn("extern SenseCapIndicatorBoard board;", header)
self.assertIn("SenseCapIndicatorBoard board;", implementation)
if __name__ == "__main__":
unittest.main()
+80 -1
View File
@@ -572,12 +572,91 @@ const mergedRs232 = [
installKinds: ["uf2"],
});
});
const mergedRs232Visible = picker.applyMergedRak4631RepeaterCapabilities(
picker.omitTransportsReplacedByFull(mergedRs232)
);
assert.deepStrictEqual(
picker.omitTransportsReplacedByFull(mergedRs232).map(function (item) {
mergedRs232Visible.map(function (item) {
return item.target;
}),
["RAK_4631_repeater"]
);
assert.deepStrictEqual(
picker.profileFieldValues(mergedRs232Visible[0], "mode"),
["standard", "rs232"]
);
assert(picker.profileMatches(
mergedRs232Visible[0],
{ mode: "standard" },
["mode"]
));
assert(picker.profileMatches(
mergedRs232Visible[0],
{ mode: "rs232" },
["mode"]
));
// Exact legacy target rows must stay attached to their own compatibility
// downloads. They disappear only from recommendations when the canonical
// merged image is present; advertising RS232 on that image must not rewrite
// or coalesce the legacy files into the canonical profile.
const rakCompatibilityCatalog = picker.buildCatalog([
release(family, "2026-08-23T13:00:02Z", []),
release("repeater-room-" + family, "2026-08-23T13:00:01Z", [
asset("RAK_4631_repeater-" + family + ".uf2"),
asset(
"RAK_4631_repeater_bridge_rs232_serial1-" + family + ".uf2"
),
asset(
"RAK_4631_repeater_bridge_rs232_serial2-" + family + ".uf2"
),
]),
release("lora-ota-" + family, "2026-08-23T13:00:00Z", [
asset(
"RAK_4631_repeater_lora_ota_no_external_sensors-ota-" +
family + ".zip"
),
asset(
"RAK_4631_repeater_bridge_rs232_serial1_" +
"lora_ota_no_external_sensors-ota-" + family + ".zip"
),
asset(
"RAK_4631_repeater_bridge_rs232_serial2_" +
"lora_ota_no_external_sensors-ota-" + family + ".zip"
),
]),
]);
const expectedCompatibilityTargets = [
"RAK_4631_repeater_bridge_rs232_serial1",
"RAK_4631_repeater_bridge_rs232_serial2",
"RAK_4631_repeater_bridge_rs232_serial1_lora_ota_no_external_sensors",
"RAK_4631_repeater_bridge_rs232_serial2_lora_ota_no_external_sensors",
];
expectedCompatibilityTargets.forEach(function (target) {
assert(rakCompatibilityCatalog.rows.some(function (row) {
return row.target === target;
}), "missing exact compatibility row " + target);
assert(!rakCompatibilityCatalog.profiles.some(function (item) {
return item.target === target;
}), "legacy compatibility target was recommended " + target);
});
[
"RAK_4631_repeater",
"RAK_4631_repeater_lora_ota_no_external_sensors",
].forEach(function (target) {
const canonical = rakCompatibilityCatalog.profiles.find(function (item) {
return item.target === target;
});
assert(canonical, "missing canonical RAK4631 profile " + target);
assert.deepStrictEqual(
picker.profileFieldValues(canonical, "mode"),
["standard", "rs232"]
);
assert(canonical.files.every(function (file) {
return file.target === target;
}), "legacy compatibility file was mapped to " + target);
});
const constrainedRs232 = [
"wio-e5_repeater",
"wio-e5-repeater_bridge_rs232",
@@ -0,0 +1,106 @@
#include <gtest/gtest.h>
#include <Arduino.h>
#define ENV_INCLUDE_GPS 1
#include "../../src/helpers/SensorManager.cpp"
class TestGpsSensorManager : public SensorManager {
public:
bool detected = true;
bool active = false;
uint8_t starts = 0;
uint8_t stops = 0;
void setUserEnabled(bool enabled) { setGpsTelemetryUserEnabled(enabled); }
void setTransportAvailable(bool available) {
setGpsTelemetryTransportAvailable(available);
}
bool receiverRequired(unsigned long now) const {
return gpsTelemetryReceiverRequired(now);
}
bool queryLocation(CayenneLPP& telemetry) {
return queryGpsTelemetry(TELEM_PERM_LOCATION, telemetry);
}
void acceptFix(float lat, float lon, float altitude, unsigned long now) {
processGpsTelemetryFix(lat, lon, altitude, now);
}
void stopReceiver() { telemetryGpsStop(); }
protected:
bool telemetryGpsDetected() const override { return detected; }
bool telemetryGpsActive() const override { return active; }
void telemetryGpsStart() override {
active = true;
starts++;
}
void telemetryGpsStop() override {
active = false;
stops++;
}
};
TEST(GpsTransportOwnership, BlockingCancelsAcquisitionAndRemoteHold) {
resetArduinoMock();
TestGpsSensorManager sensors;
CayenneLPP telemetry(64);
EXPECT_FALSE(sensors.queryLocation(telemetry));
EXPECT_TRUE(sensors.active);
EXPECT_TRUE(sensors.receiverRequired(millis()));
// Hardware-specific ownership code stops the receiver before handing its
// UART to the bridge; the base transition clears acquisition and hold state.
sensors.stopReceiver();
sensors.setTransportAvailable(false);
EXPECT_FALSE(sensors.active);
EXPECT_FALSE(sensors.receiverRequired(millis()));
EXPECT_FALSE(sensors.queryLocation(telemetry));
EXPECT_EQ(1, sensors.starts);
}
TEST(GpsTransportOwnership, UserPreferenceSurvivesBlockAndRestartsOnRelease) {
resetArduinoMock();
TestGpsSensorManager sensors;
sensors.setUserEnabled(true);
ASSERT_TRUE(sensors.active);
ASSERT_EQ(1, sensors.starts);
sensors.stopReceiver();
sensors.setTransportAvailable(false);
EXPECT_FALSE(sensors.active);
sensors.setTransportAvailable(true);
EXPECT_TRUE(sensors.active);
EXPECT_EQ(2, sensors.starts);
}
TEST(GpsTransportOwnership, LastGoodCacheSurvivesTemporaryUartOwnership) {
resetArduinoMock();
TestGpsSensorManager sensors;
CayenneLPP telemetry(64);
EXPECT_FALSE(sensors.queryLocation(telemetry));
sensors.acceptFix(47.61f, -122.33f, 125.0f, millis());
g_mock_millis += 31000;
sensors.acceptFix(47.61f, -122.33f, 125.0f, millis());
ASSERT_TRUE(sensors.queryLocation(telemetry));
ASSERT_EQ(1, telemetry.gps_count);
sensors.stopReceiver();
sensors.setTransportAvailable(false);
EXPECT_TRUE(sensors.queryLocation(telemetry));
EXPECT_EQ(2, telemetry.gps_count);
EXPECT_FALSE(sensors.receiverRequired(millis()));
sensors.setTransportAvailable(true);
EXPECT_TRUE(sensors.queryLocation(telemetry));
EXPECT_EQ(3, telemetry.gps_count);
EXPECT_FLOAT_EQ(47.61f, telemetry.last_latitude);
EXPECT_FLOAT_EQ(-122.33f, telemetry.last_longitude);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,131 @@
#include <gtest/gtest.h>
#include <cstdio>
#include <string>
#include "helpers/sensors/I2CAddressClaimPolicy.h"
#include "helpers/sensors/NmeaSentenceProbe.h"
static std::string nmeaSentence(const char* body) {
uint8_t checksum = 0;
for (const char* cursor = body; *cursor; ++cursor) {
checksum ^= static_cast<uint8_t>(*cursor);
}
char suffix[8];
std::snprintf(suffix, sizeof(suffix), "*%02X\r\n", checksum);
return std::string("$") + body + suffix;
}
static bool feed(mesh::NmeaSentenceProbe& probe, const std::string& bytes) {
bool found = false;
for (unsigned char byte : bytes) found = probe.ingest(byte) || found;
return found;
}
TEST(I2CAddressClaimPolicy, SkipsOnlyTheAddressClaimedByGps) {
EXPECT_TRUE(mesh::shouldSkipSensorAtClaimedGpsAddress(
true, true, 0x42, 0x42));
EXPECT_FALSE(mesh::shouldSkipSensorAtClaimedGpsAddress(
true, true, 0x43, 0x42));
}
TEST(I2CAddressClaimPolicy, FailedOrAbsentGpsLeavesSensorsAvailable) {
EXPECT_FALSE(mesh::shouldSkipSensorAtClaimedGpsAddress(
false, true, 0x42, 0x42));
}
TEST(I2CAddressClaimPolicy, SameNumericAddressOnAnotherBusIsIndependent) {
EXPECT_FALSE(mesh::shouldSkipSensorAtClaimedGpsAddress(
true, false, 0x42, 0x42));
}
TEST(I2CAddressClaimPolicy, GpsProbeFailsClosedOnInaOrIncompleteIdentity) {
EXPECT_FALSE(mesh::shouldProbeI2cGps(
mesh::I2cIdentityProbeResult::Match));
EXPECT_FALSE(mesh::shouldProbeI2cGps(
mesh::I2cIdentityProbeResult::Inconclusive));
EXPECT_FALSE(mesh::shouldProbeI2cGps(
mesh::I2cIdentityProbeResult::NoResponse));
EXPECT_TRUE(mesh::shouldProbeI2cGps(
mesh::I2cIdentityProbeResult::NotMatch));
}
TEST(I2CAddressClaimPolicy, RejectsReservedAndOutOfRangeAddresses) {
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0x00));
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0x07));
EXPECT_TRUE(mesh::isValidI2cPeripheralAddress(0x08));
EXPECT_TRUE(mesh::isValidI2cPeripheralAddress(0x42));
EXPECT_TRUE(mesh::isValidI2cPeripheralAddress(0x77));
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0x78));
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0xFF));
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0x142));
EXPECT_FALSE(mesh::isValidI2cPeripheralAddress(0x10042));
}
TEST(I2CAddressClaimPolicy, RejectsUnsafePinPairsBeforeGpioAccess) {
EXPECT_TRUE(mesh::isValidI2cPinPair(8, 7, 23));
EXPECT_FALSE(mesh::isValidI2cPinPair(-1, 7, 23));
EXPECT_FALSE(mesh::isValidI2cPinPair(8, -1, 23));
EXPECT_FALSE(mesh::isValidI2cPinPair(23, 7, 23));
EXPECT_FALSE(mesh::isValidI2cPinPair(8, 23, 23));
EXPECT_FALSE(mesh::isValidI2cPinPair(7, 7, 23));
}
TEST(I2CAddressClaimPolicy, ClassifiesInaIdentityWithoutAssumingDynamicBytesMatch) {
using Status = mesh::I2cRegisterProbeStatus;
using Result = mesh::I2cIdentityProbeResult;
constexpr uint16_t kManufacturer = 0x5449;
constexpr uint16_t kDie = 0x3220;
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::Success, kManufacturer,
Status::Success, kDie, kManufacturer, kDie),
Result::Match);
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::NoResponse, 0,
Status::Inconclusive, 0, kManufacturer, kDie),
Result::NoResponse);
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::Success, kManufacturer,
Status::Inconclusive, 0, kManufacturer, kDie),
Result::Inconclusive);
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::Success, kManufacturer,
Status::Success, 0x1234, kManufacturer, kDie),
Result::Inconclusive);
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::Success, 0x0001,
Status::Success, 0x0002, kManufacturer, kDie),
Result::NotMatch);
EXPECT_EQ(mesh::classifyIna3221Identity(
Status::Success, 0x0001,
Status::Success, kManufacturer, kManufacturer, kDie),
Result::Inconclusive);
}
TEST(NmeaSentenceProbe, AcceptsChecksumValidGpsTalkersIncrementally) {
mesh::NmeaSentenceProbe gps;
EXPECT_TRUE(feed(gps, nmeaSentence("GNGGA,123519,,,,,0,00,99.99,,,,,,")));
EXPECT_TRUE(gps.found());
mesh::NmeaSentenceProbe beidou;
EXPECT_TRUE(feed(beidou, nmeaSentence("BDRMC,123519,V,,,,,,,300826,,,N")));
}
TEST(NmeaSentenceProbe, RejectsNoiseBadChecksumsAndNonGpsTalkers) {
mesh::NmeaSentenceProbe probe;
EXPECT_FALSE(feed(probe, "noise\x00\xff$GNGGA,123*00\r\n"));
EXPECT_FALSE(feed(probe, nmeaSentence("AAGGA,123519,,,,,0,00,99.99,,,,,,")));
EXPECT_FALSE(probe.found());
}
TEST(NmeaSentenceProbe, NewDollarRestartsAnIncompleteSentence) {
mesh::NmeaSentenceProbe probe;
const std::string valid = nmeaSentence("GPGGA,123519,,,,,0,00,99.99,,,,,,");
EXPECT_TRUE(feed(probe, "$GPGGA,broken" + valid));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+880
View File
@@ -0,0 +1,880 @@
#!/usr/bin/env python3
import base64
import hashlib
import re
from pathlib import Path
import unittest
import zlib
ROOT = Path(__file__).resolve().parents[1]
POLICY = ROOT / "variants/sensecap_indicator-espnow/IndicatorFontRecoveryPolicy.h"
CLIENT = ROOT / "variants/sensecap_indicator-espnow/IndicatorFontClient.cpp"
DISPLAY = ROOT / "variants/sensecap_indicator-espnow/SCIndicatorDisplay.h"
PROFILE = ROOT / "variants/sensecap_indicator-espnow/platformio.ini"
RP2040 = ROOT / "tools/sensecap_indicator_rp2040/src/main.cpp"
STAGE_V2_PROTOCOL = ROOT / "src/helpers/IndicatorFontStageV2Protocol.h"
ASSET = ROOT / "variants/sensecap_indicator-espnow/sd/ui-font.vlw"
def source(path: Path) -> str:
return path.read_text()
def function_body(text: str, signature: str, next_signature: str) -> str:
start = text.index(signature)
end = text.index(next_signature, start)
return text[start:end]
def profile_section(name: str) -> str:
text = source(PROFILE)
match = re.search(
rf"^\[{re.escape(name)}\]\n(?P<body>.*?)(?=^\[|\Z)",
text,
re.MULTILINE | re.DOTALL,
)
if match is None:
raise AssertionError(f"missing profile section {name}")
return match.group("body")
class IndicatorFontRecoveryTest(unittest.TestCase):
def test_compiled_asset_identity_matches_checked_in_file(self):
policy = source(POLICY)
client = source(CLIENT)
data = ASSET.read_bytes()
size = int(re.search(r"kAssetSize = (\d+)", policy).group(1))
crc = int(re.search(r"kAssetCrc32 = 0x([0-9a-f]+)", policy).group(1), 16)
sha = re.search(r'kAssetSha256\[\] =\s*"([0-9a-f]{64})"', policy).group(1)
self.assertEqual(len(data), size)
self.assertEqual(zlib.crc32(data) & 0xFFFFFFFF, crc)
self.assertEqual(hashlib.sha256(data).hexdigest(), sha)
digest_initializer = client[
client.index("EXPECTED_SHA256[32]") : client.index(
"enum class FontInfoResult"
)
]
compiled_digest = bytes(
int(value, 16)
for value in re.findall(r"0x([0-9a-f]{2})", digest_initializer)
)
self.assertEqual(compiled_digest.hex(), sha)
def test_source_is_immutable_https_and_tls_is_never_disabled(self):
policy = source(POLICY)
client = source(CLIENT)
url_literals = re.findall(
r'"([^"]*)"',
policy[policy.index("kAssetUrl") : policy.index("kAssetSize")],
)
url = "".join(url_literals)
self.assertRegex(
url,
r"^https://api\.github\.com/repos/mikecarper/MeshCore/git/blobs/"
r"[0-9a-f]{40}$",
)
self.assertNotIn("setInsecure", client)
self.assertNotIn("client.setCACertBundle(", client)
self.assertIn("client.setCACert(FONT_TLS_GITHUB_ROOT_CA)", client)
self.assertIn("Accept: application/vnd.github.raw+json", client)
self.assertIn("X-GitHub-Api-Version: 2026-03-10", client)
self.assertIn("parseHttpStatusCode(line, status_code)", client)
pem_match = re.search(
r'FONT_TLS_GITHUB_ROOT_CA\[\].*?R"CERT\((.*?)\)CERT";',
client,
re.DOTALL,
)
self.assertIsNotNone(pem_match)
pem_lines = [
line.strip() for line in pem_match.group(1).strip().splitlines()
]
self.assertEqual(pem_lines[0], "-----BEGIN CERTIFICATE-----")
self.assertEqual(pem_lines[-1], "-----END CERTIFICATE-----")
der = base64.b64decode("".join(pem_lines[1:-1]), validate=True)
self.assertEqual(
hashlib.sha256(der).hexdigest(),
"c90f26f0fb1b4018b22227519b5ca2b53e2ca5b3be5cf18efe1bef47380c5383",
)
def test_wifi_only_recovery_bootstraps_a_bounded_tls_clock(self):
policy = source(POLICY)
client = source(CLIENT)
proof = function_body(
client, "bool fontTlsClockProofValid", "bool prepareTlsClock"
)
callback = function_body(
client, "void clearFontNtpCallback", "bool fontTlsClockProofValid"
)
clock = function_body(
client, "bool prepareTlsClock", "uint32_t remainingHttpHeaderTimeout"
)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
transfer = function_body(
client,
"RecoveryAttemptOutcome downloadAndInstallAsset",
"void finishRecoveryFailure",
)
self.assertIn("kAssetPublishedEpoch = 1787708237UL", policy)
self.assertIn("kNtpSyncWaitMillis = 15000UL", policy)
self.assertIn(
"fontNtpTimeReceived.store(false, std::memory_order_release)",
clock,
)
self.assertIn("sntp_set_time_sync_notification_cb(noteFontNtpTime)", clock)
self.assertIn("sntp_set_sync_status(SNTP_SYNC_STATUS_RESET)", clock)
self.assertIn('configTime(0, 0, "time.cloudflare.com"', clock)
self.assertIn("OperationLease sntp_operation", clock)
self.assertIn("processWideCoordinator()", clock)
self.assertIn("if (!sntp_operation.tryAcquire())", clock)
self.assertNotIn("sntp_set_time_sync_notification_cb(nullptr)", clock)
self.assertIn("sntp_set_time_sync_notification_cb(nullptr)", callback)
self.assertIn("processWideCoordinator().owns(generation)", callback)
self.assertIn(
"fontNtpTimeReceived.load(std::memory_order_acquire)", proof
)
self.assertIn("WiFi.status() == WL_CONNECTED", proof)
self.assertIn("mesh::tls_clock::proofIsValid", proof)
self.assertIn("mesh::tls_clock::proofAgeIsValid", proof)
self.assertIn("mesh::tls_clock::proofGenerationIsValid", proof)
self.assertIn("FONT_TLS_PROOF_MAX_AGE_MS = 300000UL", client)
self.assertIn("const time_t now = time(nullptr)", clock)
self.assertIn("fontTlsClockProofValid(now)", clock)
self.assertIn(
"now >= (time_t)mesh::indicator_font::kAssetPublishedEpoch", clock
)
self.assertNotIn("(uint32_t)time(nullptr)", clock)
self.assertIn("WiFi.status() != WL_CONNECTED", clock)
self.assertNotIn("alreadyPlausible", clock)
self.assertTrue(clock.rstrip().endswith("}"))
self.assertIn("return false;", clock)
self.assertIn("prepareTlsClock()", transfer)
self.assertLess(
transfer.index("prepareTlsClock()"),
transfer.index("openAssetResponse("),
)
self.assertIn("const time_t tls_now = time(nullptr)", response)
proof_check = response.index("fontTlsClockProofValid(tls_now)")
tls_connect = response.index("client.connect(host, 443)")
self.assertLess(proof_check, tls_connect)
self.assertIn(
"std::atomic<bool> fontNtpTimeReceived{false}", client
)
self.assertIn(
"fontNtpTimeReceived.store(true, std::memory_order_release)",
client,
)
def test_release_source_has_no_forced_download_interruption(self):
client = source(CLIENT)
self.assertNotIn("DOWNLOAD_TEST_INTERRUPT_AT", client)
self.assertNotIn("test hook: closing initial HTTP response", client)
def test_http_headers_have_one_total_deadline(self):
client = source(CLIENT)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
self.assertIn("HTTP_HEADER_TOTAL_TIMEOUT_MS = 30000UL", client)
self.assertIn("remainingHttpHeaderTimeout(headerStarted)", response)
self.assertNotIn(
"readHttpLine(client, line, sizeof(line), HTTP_LINE_TIMEOUT_MS)",
response,
)
def test_http_wire_parser_is_bounded_and_rejects_ambiguous_framing(self):
client = source(CLIENT)
reader = function_body(
client, "HttpLineResult readHttpLine", "bool isSecurityCriticalHttpHeader"
)
decimal = function_body(
client, "bool parseUnsignedDecimalHeader", "bool parseHttpStatusCode"
)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
self.assertRegex(client, r"HTTP_HEADER_LIMIT = (?:6[4-9]|[7-9][0-9]|\d{3,})")
self.assertIn("HTTP_WIRE_LINE_LIMIT = 2048", client)
drain = reader.index("while (client.available())")
self.assertIn(
"millis() - started >= timeout_millis", reader[drain:]
)
self.assertIn("++wire_length > HTTP_WIRE_LINE_LIMIT", reader)
self.assertIn("HttpLineResult::TooLong", reader)
# Decimal framing accepts digits only, with optional surrounding OWS;
# strtoul-style signs and overflow are not accepted.
self.assertIn("*value < '0' || *value > '9'", decimal)
self.assertIn("UINT64_MAX - digit", decimal)
self.assertNotIn("strtoul", response)
self.assertIn("parsed > MAX_FONT_BYTES", response)
# Reject every obsolete folded field before handling either retained
# or overflowed extension headers.
obs_fold = response.index("if (line[0] == ' ' || line[0] == '\\t')")
overflow = response.index("if (line_result == HttpLineResult::Overflow)")
self.assertLess(obs_fold, overflow)
def test_non_200_headers_are_parsed_and_failures_are_classified(self):
client = source(CLIENT)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
classify = function_body(
client, "RecoveryAttemptOutcome classifyHttpResponse", "bool splitHttpsUrl"
)
finish = function_body(
client,
"void finishRecoveryFailure(const RecoveryAttemptOutcome& outcome)",
"void finishRecoveryFailure()",
)
# The status is recorded first, but classification happens only after
# Retry-After and X-RateLimit-Reset have been read from the full block.
self.assertIn('"Retry-After:"', response)
self.assertIn('"X-RateLimit-Reset:"', response)
self.assertGreater(
response.index("classifyHttpResponse("),
response.index("while (header_count <= HTTP_HEADER_LIMIT)"),
)
self.assertNotIn("status_code != 200", response)
self.assertIn("status_code == 403 || status_code == 429", classify)
self.assertIn("retry_after_seconds", classify)
self.assertIn("rate_reset_epoch", classify)
self.assertIn("HTTP_RATE_LIMIT_MIN_DELAY_MS", classify)
self.assertIn("HTTP_RATE_LIMIT_FALLBACK_DELAY_MS", classify)
self.assertIn("RecoveryAttemptDisposition::RateLimited", classify)
self.assertIn("status_code >= 500 && status_code <= 599", classify)
self.assertIn("RecoveryAttemptDisposition::RetryableFailure", classify)
self.assertTrue(
classify.rstrip().endswith(
"return recoveryOutcome(RecoveryAttemptDisposition::PermanentFailure);\n}"
)
)
self.assertIn("outcome.retryDelayMillis > delay_millis", finish)
self.assertIn("outcome.retryDelayMillis", finish)
self.assertIn(
"outcome.disposition == RecoveryAttemptDisposition::PermanentFailure",
finish,
)
self.assertIn("recoveryState = RecoveryState::Exhausted", finish)
def test_valid_current_font_does_not_arm_download(self):
client = source(CLIENT)
load = client[client.index("uint8_t* IndicatorFontClient::load") :]
self.assertIn("if (!loaded.currentAsset)", load)
self.assertNotIn(
"armRecovery(mesh::indicator_font::RecoveryNeed::None)", load
)
self.assertIn("loaded.currentAsset = loaded.size ==", client)
self.assertIn("memcmp(digest, EXPECTED_SHA256", client)
def test_length_and_digest_fail_before_commit(self):
client = source(CLIENT)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
transfer = function_body(
client,
"RecoveryAttemptOutcome downloadAndInstallAsset",
"void finishRecoveryFailure",
)
self.assertIn("mesh::indicator_font::kAssetSize - requested_offset", response)
self.assertIn("content_length != expected_content_length", response)
self.assertIn("Transfer-Encoding:", response)
self.assertIn("Content-Encoding:", response)
self.assertIn("HTTP_HEADER_LIMIT", response)
self.assertIn("DOWNLOAD_TOTAL_TIMEOUT_MS", transfer)
self.assertIn("DOWNLOAD_IDLE_TIMEOUT_MS", transfer)
self.assertLess(transfer.index("digest_ok"), transfer.index("MCFONT COMMIT"))
self.assertLess(transfer.index("if (!digest_ok)"), transfer.index("Serial2.begin"))
def test_range_resume_keeps_one_buffer_and_sha_stream_and_is_strict(self):
client = source(CLIENT)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
transfer = function_body(
client,
"RecoveryAttemptOutcome downloadAndInstallAsset",
"void finishRecoveryFailure",
)
content_range = function_body(
client, "bool parseContentRangeHeader", "bool parseStrongEtagHeader"
)
strong_etag = function_body(
client, "bool parseStrongEtagHeader", "bool parseHttpStatusCode"
)
self.assertIn("DOWNLOAD_MAX_RESUME_RECONNECTS = 2", client)
self.assertIn("const bool is_resume = expected_etag != nullptr", response)
self.assertIn('"Range: bytes=%lu-%lu\\r\\nIf-Range: %s\\r\\n"', response)
self.assertIn("const int expected_status = is_resume ? 206 : 200", response)
self.assertIn("status_code != expected_status", response)
self.assertIn("content_length != expected_content_length", response)
self.assertIn("parseContentRangeHeader", response)
self.assertIn("parseStrongEtagHeader", response)
self.assertIn("content_range_first != requested_offset", response)
self.assertIn(
"content_range_last != mesh::indicator_font::kAssetSize - 1",
response,
)
self.assertIn(
"content_range_total != mesh::indicator_font::kAssetSize", response
)
self.assertIn("strcmp(response_etag, expected_etag) != 0", response)
self.assertIn("if (content_range_seen)", response)
self.assertIn("!etag_seen || !etag_valid", response)
self.assertIn("transfer_encoding_seen", response)
self.assertIn("!content_encoding_identity", response)
# Content-Range and reflected If-Range inputs use strict decimal and
# quoted-tag grammars; signs, overflow, weak tags, control bytes, and
# embedded quotes cannot pass or inject another request field.
self.assertIn('strncasecmp(value, "bytes ", 6)', content_range)
self.assertIn("parsed_first > parsed_last", content_range)
self.assertIn("parsed_last >= parsed_total", content_range)
self.assertIn("parsed_total > MAX_FONT_BYTES", content_range)
self.assertIn("value[0] != '\"'", strong_etag)
self.assertIn("value[length - 1] != '\"'", strong_etag)
self.assertIn("byte < 0x21 || byte > 0x7e || byte == '\"'", strong_etag)
# One fresh SNTP reply covers the bounded 180-second transfer. Every
# initial/Range TLS handshake revalidates that proof and the signed
# wall clock centrally in openAssetResponse().
self.assertEqual(transfer.count("prepareTlsClock()"), 1)
proof_check = response.index("fontTlsClockProofValid(tls_now)")
tls_connect = response.index("client.connect(host, 443)")
self.assertLess(proof_check, tls_connect)
self.assertEqual(
transfer.count("mbedtls_sha256_starts_ret(&sha, 0)"), 1
)
self.assertEqual(
transfer.count("ps_malloc(mesh::indicator_font::kAssetSize)"), 1
)
initial = transfer.index("client, 0, nullptr, asset_etag")
resume = transfer.index("client, received, asset_etag, nullptr, 0")
self.assertLess(initial, resume)
self.assertIn(
"resume_reconnects >= DOWNLOAD_MAX_RESUME_RECONNECTS", transfer
)
self.assertIn("discarding %lu unverified bytes", transfer)
self.assertIn("last_progress = millis()", transfer[resume:])
# `received` moves only after the complete block has entered the one
# SHA stream. A failed partial block is overwritten at that boundary.
update = transfer.index("mbedtls_sha256_update_ret")
advance = transfer.index("received += wanted", update)
resume_call = transfer.index("openAssetResponse(", advance)
self.assertLess(update, advance)
self.assertLess(advance, resume_call)
self.assertNotIn("received += filled", transfer)
self.assertEqual(transfer.count("uint32_t started = millis();"), 1)
self.assertNotIn("\n started = millis();", transfer[resume:])
self.assertLess(transfer.index("digest_ok"), transfer.index("Serial2.begin"))
def test_download_is_buffered_before_receiver_paced_staging(self):
client = source(CLIENT)
protocol = source(STAGE_V2_PROTOCOL)
transfer = function_body(
client,
"RecoveryAttemptOutcome downloadAndInstallAsset",
"void finishRecoveryFailure",
)
self.assertIn("kStageV2ChunkBytes = 512", protocol)
self.assertIn("ps_malloc(mesh::indicator_font::kAssetSize)", transfer)
self.assertIn("if (wanted > 16 * 1024) wanted = 16 * 1024", transfer)
self.assertIn("client.read(asset + received + filled", transfer)
self.assertLess(transfer.index("client.stop()"), transfer.index("Serial2.begin"))
self.assertLess(transfer.index("if (!digest_ok)"), transfer.index("Serial2.begin"))
self.assertIn("free(asset)", transfer)
self.assertIn("writeAll(Serial2, asset + staged_bytes", transfer)
self.assertIn("stagedChunkAcknowledged(Serial2, next_staged)", transfer)
self.assertIn("stageV2ChunkSize(", transfer)
self.assertIn("advanceStageV2Offset(", transfer)
self.assertIn("delay(LEGACY_STAGE_PACE_MS)", transfer)
def test_stage_v2_is_receiver_paced_and_legacy_fallback_is_explicit(self):
client = source(CLIENT)
rp = source(RP2040)
protocol = source(STAGE_V2_PROTOCOL)
negotiate = function_body(
client, "bool beginStagedUpload", "bool stagedChunkAcknowledged"
)
acknowledge = function_body(
client,
"bool stagedChunkAcknowledged",
"RecoveryAttemptOutcome downloadAndInstallAsset",
)
receiver = function_body(
rp, "void receiveFontStage2", "struct CommandReader"
)
self.assertIn("IndicatorFontStageV2Protocol.h", client)
self.assertIn("IndicatorFontStageV2Protocol.h", rp)
self.assertIn("kStageV2ChunkBytes = 512", protocol)
self.assertIn('kStageV2ReadyReply[] = "READY 2 512"', protocol)
self.assertIn(
'kStageV2LegacyUnsupportedReply[] = "ERROR COMMAND"', protocol
)
self.assertIn('"MCFONT STAGEV2 %lu %08lx %lu"', negotiate)
self.assertNotIn('"MCFONT STAGE2 ', negotiate)
self.assertNotIn('"MCFONT STAGE2 ', rp)
self.assertIn("classifyStageV2BeginReply(replied, reply)", negotiate)
self.assertIn("StageV2BeginAction::UseAcknowledged", negotiate)
self.assertIn("StageV2BeginAction::UseLegacy", negotiate)
# A missing/delayed protocol-2 reply fails closed. Only the old
# service's explicit unsupported-command response can reach STAGE.
timeout_failure = negotiate.index("action !=")
legacy_command = negotiate.index('"MCFONT STAGE %lu %08lx"')
self.assertLess(timeout_failure, legacy_command)
self.assertIn("return false;", negotiate[timeout_failure:legacy_command])
self.assertIn("if (!replied)", negotiate[timeout_failure:legacy_command])
self.assertIn("parseStageV2Ack(reply, expected_offset)", acknowledge)
self.assertNotIn("strtoul", acknowledge)
self.assertIn("RECEIVE_TOTAL_TIMEOUT_MS = 180000", rp)
self.assertIn("output.print(mesh::indicator_font::kStageV2ReadyReply)", receiver)
self.assertIn("stageV2ChunkSize(expectedSize, received)", receiver)
fragment_loop = receiver.index("while (chunkReceived < chunkSize)")
write = receiver.index("font.write(buffer, chunkSize)")
ack = receiver.index('output.printf("ACK %lu\\n"')
self.assertLess(fragment_loop, write)
self.assertIn("chunkReceived += actual", receiver[fragment_loop:write])
self.assertLess(write, ack)
self.assertIn("advanceStageV2Offset(", receiver[write:ack])
self.assertIn("received = nextReceived", receiver[write:ack])
checksum = receiver.index("~crc != expectedCrc")
metadata = receiver.index("writeMetadata(STAGED_META_PATH")
staged = receiver.index('output.print("STAGED\\n")')
close = receiver.index("font.close()")
post_close_deadline = receiver.index(
"espStage2LastElapsedMs >= RECEIVE_TOTAL_TIMEOUT_MS", close
)
failure_handling = receiver.index(
"if (failure != Stage2Result::Idle)", post_close_deadline
)
self.assertLess(ack, checksum)
self.assertLess(close, post_close_deadline)
self.assertLess(post_close_deadline, failure_handling)
self.assertLess(checksum, metadata)
self.assertLess(metadata, staged)
self.assertIn(
'"MCFONT STAGEV2 %lu %lx %lu %n"',
rp,
)
self.assertIn("reader.line[consumed] == 0", rp)
def test_rp2040_retries_a_transient_sd_mount_for_a_bounded_window(self):
rp = source(RP2040)
mount = function_body(rp, "bool mountSdCard", "void serviceSdMount")
service = function_body(rp, "void serviceSdMount", "void sendInfo")
setup = function_body(rp, "void setup()", "void loop()")
loop = rp[rp.index("void loop()") :]
self.assertIn("SD_MOUNT_RETRY_INTERVAL_MS = 2000", rp)
self.assertIn("SD_MOUNT_MAX_ATTEMPTS = 30", rp)
self.assertIn("sdMountAttempts >= SD_MOUNT_MAX_ATTEMPTS", mount)
self.assertIn("if (sdMountAttempts != 0) SD.end(false)", mount)
self.assertLess(mount.index("++sdMountAttempts"), mount.index("SD.begin("))
self.assertIn("sdMountNextAttempt = millis() +", mount)
self.assertIn("sdMountAttempts >= SD_MOUNT_MAX_ATTEMPTS", service)
self.assertIn("now - sdMountNextAttempt", service)
self.assertIn("serviceSdMount(millis())", setup)
self.assertIn("serviceSdMount(millis())", loop)
self.assertNotIn("SD.begin(", setup)
def test_legacy_stage_and_usb_put_have_idle_and_total_deadlines(self):
rp = source(RP2040)
receive = function_body(rp, "void receiveFont(Stream&", "// STAGEV2")
self.assertIn("const uint32_t started = millis()", receive)
self.assertIn("now - started >= RECEIVE_TOTAL_TIMEOUT_MS", receive)
self.assertIn("now - lastProgress >= RECEIVE_IDLE_TIMEOUT_MS", receive)
self.assertIn("timedOut = true", receive)
self.assertGreater(
receive.index("millis() - started >= RECEIVE_TOTAL_TIMEOUT_MS"),
receive.index("font.close()"),
)
self.assertIn('timedOut ? "ERROR TIMEOUT\\n"', receive)
def test_interrupted_stage_cannot_replace_live_font(self):
rp = source(RP2040)
recovery = function_body(rp, "void recoverFontTransaction", "bool refreshFontInfo")
mount = function_body(rp, "bool mountSdCard", "void serviceSdMount")
stage_install = function_body(rp, "bool installStagedPair", "enum class ReceiveMode")
receive = function_body(rp, "void receiveFont", "struct CommandReader")
self.assertNotIn("STAGED_FONT_PATH", recovery)
self.assertNotIn("STAGED_META_PATH", recovery)
self.assertIn("cleanStagedFiles();", mount)
self.assertLess(stage_install.index("validatePairCrc"),
stage_install.index("installTemporaryPair"))
self.assertIn("removeIfPresent(destinationFont)", receive)
self.assertIn("ReceiveMode::StageOnly", receive)
self.assertIn('output.print("STAGED\\n")', receive)
def test_interrupted_pair_renames_are_crc_checked_and_recoverable(self):
rp = source(RP2040)
validator = function_body(
rp, "bool validateStoredPairCrc", "void removeIfPresent"
)
promotion = function_body(rp, "bool promotePair", "void recoverFontTransaction")
recovery = function_body(
rp, "void recoverFontTransaction", "bool refreshFontInfo"
)
self.assertIn("validatePairCrc(fontPath, metadataPath, size, crc)", validator)
for font_path, metadata_path in (
("FONT_PATH", "TEMP_META_PATH"),
("FONT_PATH", "BACKUP_META_PATH"),
("BACKUP_FONT_PATH", "FONT_META_PATH"),
("TEMP_FONT_PATH", "TEMP_META_PATH"),
("BACKUP_FONT_PATH", "BACKUP_META_PATH"),
):
self.assertIn(
f"validateStoredPairCrc({font_path}, {metadata_path}", recovery
)
# A reset while moving the old pair to backup leaves its metadata at
# the live name. Complete that backup before trying the new temp pair,
# so a failed temp promotion still has a rollback candidate.
split_backup = recovery.index(
"validateStoredPairCrc(BACKUP_FONT_PATH, FONT_META_PATH"
)
temp_promotion = recovery.index(
"validateStoredPairCrc(TEMP_FONT_PATH, TEMP_META_PATH"
)
self.assertLess(split_backup, temp_promotion)
self.assertIn("SD.rename(FONT_META_PATH, BACKUP_META_PATH)", recovery)
# Once the source font has moved, a metadata-rename failure must leave
# the split pair intact. Recovery also stops after trying any CRC-valid
# candidate so later fallbacks/cleanup cannot erase that retry state.
self.assertEqual(promotion.count("removeIfPresent(FONT_PATH)"), 1)
self.assertNotIn(
"if (SD.rename(sourceMetadata, FONT_META_PATH)) return true;\n"
" removeIfPresent(FONT_PATH)",
promotion,
)
self.assertIn(
"if (validateStoredPairCrc(TEMP_FONT_PATH, TEMP_META_PATH, size, crc))",
recovery,
)
self.assertIn(
"if (validateStoredPairCrc(BACKUP_FONT_PATH, BACKUP_META_PATH, size, crc))",
recovery,
)
temp_start = recovery.index(
"if (validateStoredPairCrc(TEMP_FONT_PATH, TEMP_META_PATH"
)
backup_start = recovery.index(
"if (validateStoredPairCrc(BACKUP_FONT_PATH, BACKUP_META_PATH"
)
cleanup_start = recovery.index("removeIfPresent(FONT_PATH)", backup_start)
for block in (
recovery[temp_start:backup_start],
recovery[backup_start:cleanup_start],
):
self.assertIn("promotePair", block)
self.assertIn("return;", block)
# Keep the ordinary healthy-boot INFO path fast; full-file CRC reads
# are reserved for abnormal transaction candidates.
healthy = recovery.index("validatePair(FONT_PATH, FONT_META_PATH")
first_transaction_crc = recovery.index("validateStoredPairCrc(")
self.assertLess(healthy, first_transaction_crc)
def test_internal_uart_commit_is_separate_from_usb_put(self):
rp = source(RP2040)
self.assertIn(
"CommandReader usbCommands = {Serial, Serial, true, false, false}", rp
)
self.assertIn(
"CommandReader espCommands = {Serial1, Serial1, false, true, true}", rp
)
self.assertIn("if (!reader.allowStagedUpload)", rp)
self.assertIn("if (!reader.allowUpload)", rp)
def test_retry_budget_and_backoff_are_bounded(self):
policy = source(POLICY)
client = source(CLIENT)
self.assertIn("kMaximumAttemptsPerBoot = 4", policy)
self.assertIn("30000UL", policy)
self.assertIn("120000UL", policy)
self.assertIn("600000UL", policy)
self.assertIn(
"recoveryAttempts >= mesh::indicator_font::kMaximumAttemptsPerBoot",
client,
)
self.assertIn("RecoveryState::Exhausted", client)
self.assertIn("WiFi.status() == WL_CONNECTED", client)
def test_initial_unavailable_service_gets_bounded_post_wifi_reprobe(self):
policy = source(POLICY)
client = source(CLIENT)
load = function_body(
client,
"uint8_t* IndicatorFontClient::load",
"uint8_t* IndicatorFontClient::serviceRecovery",
)
probe = function_body(client, "void serviceProbeTask", "void recoveryTask")
service = function_body(
client,
"uint8_t* IndicatorFontClient::serviceRecovery",
"void IndicatorFontClient::noteRuntimeFontInstalled",
)
self.assertIn("armServiceProbe();", load)
self.assertIn("RecoveryState::ProbeWaiting", service)
self.assertIn("WiFi.status() == WL_CONNECTED", service)
self.assertIn("++serviceProbeAttempts", service)
self.assertIn("xTaskCreatePinnedToCore(serviceProbeTask", service)
self.assertIn("LoadedFont loaded = loadFromService();", probe)
self.assertIn("if (loaded.currentAsset)", probe)
self.assertIn("RecoveryState::Ready", probe)
self.assertIn("RecoveryNeed::Missing", probe)
self.assertIn("RecoveryNeed::Corrupt", probe)
self.assertIn("RecoveryNeed::VersionMismatch, true", probe)
self.assertIn("finishServiceProbeFailure();", probe)
self.assertIn("kMaximumServiceProbeAttemptsPerBoot = 4", policy)
self.assertIn("serviceProbeRetryDelayAfter", policy)
self.assertIn("2000UL", policy)
self.assertIn("5000UL", policy)
self.assertIn("15000UL", policy)
self.assertIn(
">= mesh::indicator_font::kMaximumServiceProbeAttemptsPerBoot",
client,
)
def test_acknowledged_commit_uses_bounded_local_reprobe_not_redownload(self):
policy = source(POLICY)
client = source(CLIENT)
transfer = function_body(
client,
"RecoveryAttemptOutcome downloadAndInstallAsset",
"void finishRecoveryFailure",
)
arm = function_body(
client, "void armPostCommitProbe", "enum class HttpLineResult"
)
finish = function_body(
client,
"void finishPostCommitProbeFailure",
"void serviceProbeTask",
)
probe = function_body(
client, "void postCommitProbeTask", "void recoveryTask"
)
recovery = function_body(
client, "void recoveryTask", "#endif // INDICATOR_WIFI_FONT_RECOVERY"
)
service = function_body(
client,
"uint8_t* IndicatorFontClient::serviceRecovery",
"void IndicatorFontClient::noteRuntimeFontInstalled",
)
# An acknowledged COMMIT is distinct from a network/staging failure.
# A transient post-commit INFO failure, or an ambiguous/missing COMMIT
# reply, enters the local-only state. Only an explicit ERROR is allowed
# to resume network attempts.
self.assertIn("RecoveryAttemptDisposition::CommittedNeedsProbe", client)
commit = transfer.index("const bool commitReplied = commandReply(")
committed = transfer.index("const bool committed =", commit)
rejected = transfer.index("const bool commitExplicitlyRejected", committed)
verified = transfer.index("bool postCommitVerified = false", commit)
probe_outcome = transfer.index(
"RecoveryAttemptDisposition::CommittedNeedsProbe", verified
)
self.assertLess(commit, committed)
self.assertLess(committed, rejected)
self.assertLess(rejected, verified)
self.assertLess(verified, probe_outcome)
self.assertIn("if (!committed)", transfer[commit:probe_outcome])
unresolved = transfer[
transfer.index("if (!committed)", commit) :
transfer.index("return recoveryOutcome(postCommitVerified", commit)
]
self.assertIn("commitExplicitlyRejected", unresolved)
self.assertIn("RecoveryAttemptDisposition::RetryableFailure", unresolved)
self.assertIn("RecoveryAttemptDisposition::CommittedNeedsProbe", unresolved)
self.assertIn("armPostCommitProbe(activateCommittedLive)", recovery)
network_failure = function_body(
client,
"void finishRecoveryFailure(const RecoveryAttemptOutcome& outcome)",
"void finishRecoveryFailure()",
)
self.assertIn(
"RecoveryAttemptDisposition::CommittedNeedsProbe",
network_failure,
)
self.assertIn("RecoveryState::Exhausted", network_failure)
local_load = recovery.index("LoadedFont loaded = loadFromService()")
local_failure = recovery.index("loaded.data == nullptr", local_load)
local_success = recovery.index("data = loaded.data", local_failure)
self.assertIn("armPostCommitProbe(true)", recovery[local_failure:local_success])
self.assertNotIn(
"finishRecoveryFailure", recovery[local_failure:local_success]
)
# The local path preserves the consumed download budget, needs no
# Wi-Fi/NTP/TLS, and can only become Ready/Complete or retry/exhaust.
self.assertNotIn("recoveryAttempts =", arm)
self.assertIn("RecoveryNeed::None", arm)
self.assertIn("RecoveryState::PostCommitProbeWaiting", arm)
info_only = probe[
probe.index("if (!activateLive)") :
probe.index("LoadedFont loaded = loadFromService();")
]
self.assertIn("probeServiceInfo(size, crc)", info_only)
self.assertIn("mesh::indicator_font::kAssetSize", info_only)
self.assertIn("mesh::indicator_font::kAssetCrc32", info_only)
self.assertIn("RecoveryState::Complete", info_only)
self.assertNotIn("ps_malloc", info_only)
self.assertNotIn("loadFromService", info_only)
self.assertIn("LoadedFont loaded = loadFromService();", probe)
self.assertIn("loaded.data != nullptr && loaded.currentAsset", probe)
self.assertIn("RecoveryState::Ready", probe)
self.assertIn("RecoveryState::Complete", probe)
self.assertIn("finishPostCommitProbeFailure();", probe)
for forbidden in (
"downloadAndInstallAsset",
"armRecovery",
"finishRecoveryFailure",
"prepareTlsClock",
"WiFi.status",
):
self.assertNotIn(forbidden, probe)
self.assertIn(
"kMaximumPostCommitProbeAttemptsPerBoot = 4", policy
)
post_commit_policy = policy[
policy.index("postCommitProbeRetryDelayAfter") :
policy.index("constexpr bool deadlineReached")
]
self.assertIn("2000UL", post_commit_policy)
self.assertIn("5000UL", post_commit_policy)
self.assertIn("15000UL", post_commit_policy)
self.assertIn("RecoveryState::Exhausted", finish)
self.assertIn("RecoveryState::PostCommitProbeWaiting", finish)
self.assertNotIn("RecoveryState::Waiting", finish)
post_commit_branch = service[
service.index("RecoveryState::PostCommitProbeWaiting") :
service.index("RecoveryState::ProbeWaiting")
]
self.assertNotIn("wifiConnected", post_commit_branch)
self.assertIn("++postCommitProbeAttempts", post_commit_branch)
self.assertIn("launchPostCommitProbe = true", post_commit_branch)
self.assertIn("xTaskCreatePinnedToCore(", service)
self.assertIn("postCommitProbeTask", service)
self.assertIn("finishPostCommitProbeFailure();", service)
maximum = int(
re.search(
r"kMaximumPostCommitProbeAttemptsPerBoot = (\d+)", policy
).group(1)
)
downloads_started = 1
state = "PostCommitProbeWaiting"
for attempt in range(1, maximum + 1):
state = (
"Exhausted"
if attempt >= maximum
else "PostCommitProbeWaiting"
)
self.assertEqual(downloads_started, 1)
self.assertEqual(state, "Exhausted")
def test_rejected_exact_recovered_font_cannot_redownload(self):
client = source(CLIENT)
display = source(DISPLAY)
rejected = function_body(
client,
"void IndicatorFontClient::noteRecoveredFontInvalid",
"#endif",
)
service = function_body(
display,
"void serviceFontRecovery",
"void turnOn",
)
self.assertIn("noteRecoveredFontInvalid()", service)
self.assertIn("RecoveryNeed::None", rejected)
self.assertIn("RecoveryState::Exhausted", rejected)
self.assertNotIn("armRecovery", rejected)
self.assertNotIn("finishRecoveryFailure", rejected)
self.assertNotIn("finishPostCommitProbeFailure", rejected)
self.assertNotIn("RecoveryState::Waiting", rejected)
self.assertNotIn("RecoveryState::PostCommitProbeWaiting", rejected)
self.assertNotIn("recoveryAttempts =", rejected)
self.assertNotIn("downloadAndInstallAsset", rejected)
def test_missing_corrupt_and_version_mismatch_are_distinct(self):
policy = source(POLICY)
client = source(CLIENT)
for state in ("Missing", "Corrupt", "VersionMismatch"):
self.assertIn(state, policy)
self.assertIn(f"RecoveryNeed::{state}", client)
def test_live_activation_only_replaces_fallback_font(self):
policy = source(POLICY)
client = source(CLIENT)
display = source(DISPLAY)
self.assertIn(
"need == RecoveryNeed::Missing || need == RecoveryNeed::Corrupt",
policy,
)
self.assertIn("!hadRuntimeFont", client)
self.assertIn("IndicatorFontClient::serviceRecovery", display)
self.assertIn("installRuntimeFont(fontData, fontSize)", display)
self.assertIn("noteRuntimeFontInstalled", display)
self.assertIn("noteRuntimeFontInvalid", display)
def test_tls_cost_and_global_state_are_limited_to_wifi_indicator_profile(self):
wifi = profile_section("env:SenseCapIndicator-LoRa_comp_radio_usb_wifi")
usb = profile_section("env:SenseCapIndicator-LoRa_comp_radio_usb")
self.assertIn("INDICATOR_WIFI_FONT_RECOVERY=1", wifi)
self.assertNotIn("board_build.embed_files", wifi)
self.assertNotIn("INDICATOR_WIFI_FONT_RECOVERY", usb)
self.assertNotIn("board_build.embed_files", usb)
def test_core2_timeout_and_worker_stack_fit_internal_tls_buffers(self):
client = source(CLIENT)
response = function_body(
client, "RecoveryAttemptOutcome openAssetResponse", "bool writeAll"
)
service = function_body(
client,
"uint8_t* IndicatorFontClient::serviceRecovery",
"void IndicatorFontClient::noteRuntimeFontInstalled",
)
self.assertIn("ESP_ARDUINO_VERSION_MAJOR >= 3", response)
self.assertIn("HTTP_LINE_TIMEOUT_MS / 1000UL", response)
self.assertIn("RECOVERY_TASK_STACK_BYTES = 8192UL", client)
self.assertIn("RECOVERY_TASK_STACK_BYTES", service)
self.assertNotIn('"indicator-font", 24576', service)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,132 @@
#include <gtest/gtest.h>
#include <helpers/IndicatorFontStageV2Protocol.h>
using mesh::indicator_font::StageV2BeginAction;
TEST(IndicatorFontStageV2Protocol, BeginReplyIsExactAndFallbackFailsClosed) {
using mesh::indicator_font::classifyStageV2BeginReply;
EXPECT_EQ(classifyStageV2BeginReply(true, "READY 2 512"),
StageV2BeginAction::UseAcknowledged);
EXPECT_EQ(classifyStageV2BeginReply(true, "ERROR COMMAND"),
StageV2BeginAction::UseLegacy);
// A missing response is ambiguous: the receiver may already be waiting for
// binary data after its READY was lost. It must never trigger legacy bytes.
EXPECT_EQ(classifyStageV2BeginReply(false, nullptr),
StageV2BeginAction::Fail);
EXPECT_EQ(classifyStageV2BeginReply(false, "ERROR COMMAND"),
StageV2BeginAction::Fail);
EXPECT_EQ(classifyStageV2BeginReply(true, nullptr),
StageV2BeginAction::Fail);
for (const char* reply : {
"", "READY", "READY 2", "READY 2 0512", "READY 2 512 ",
"ERROR COMMAND ", "ERROR SD", "ERROR OPEN", "ERROR CHUNK",
"STAGED",
}) {
EXPECT_EQ(classifyStageV2BeginReply(true, reply),
StageV2BeginAction::Fail)
<< reply;
}
}
TEST(IndicatorFontStageV2Protocol, ChunkBoundariesIncludeShortFinalBlock) {
using mesh::indicator_font::stageV2ChunkSize;
EXPECT_EQ(stageV2ChunkSize(0, 0), 0u);
EXPECT_EQ(stageV2ChunkSize(64, 0), 64u);
EXPECT_EQ(stageV2ChunkSize(64, 64), 0u);
EXPECT_EQ(stageV2ChunkSize(511, 0), 511u);
EXPECT_EQ(stageV2ChunkSize(512, 0), 512u);
EXPECT_EQ(stageV2ChunkSize(512, 512), 0u);
EXPECT_EQ(stageV2ChunkSize(513, 0), 512u);
EXPECT_EQ(stageV2ChunkSize(513, 512), 1u);
EXPECT_EQ(stageV2ChunkSize(513, 513), 0u);
EXPECT_EQ(stageV2ChunkSize(513, 514), 0u);
}
TEST(IndicatorFontStageV2Protocol, RealAssetHasCanonicalAckSchedule) {
using mesh::indicator_font::advanceStageV2Offset;
using mesh::indicator_font::kStageV2ChunkBytes;
using mesh::indicator_font::stageV2ChunkSize;
constexpr size_t assetSize = 1302608;
size_t offset = 0;
size_t fullBlocks = 0;
size_t shortBlocks = 0;
size_t blocks = 0;
while (offset < assetSize) {
const size_t chunk = stageV2ChunkSize(assetSize, offset);
ASSERT_GT(chunk, 0u);
size_t next = 0;
ASSERT_TRUE(advanceStageV2Offset(assetSize, offset, chunk, next));
ASSERT_GT(next, offset);
ASSERT_LE(next, assetSize);
if (chunk == kStageV2ChunkBytes) {
++fullBlocks;
} else {
++shortBlocks;
EXPECT_EQ(chunk, 80u);
EXPECT_EQ(next, assetSize);
}
offset = next;
ASSERT_LT(++blocks, 3000u);
}
EXPECT_EQ(offset, assetSize);
EXPECT_EQ(fullBlocks, 2544u);
EXPECT_EQ(shortBlocks, 1u);
EXPECT_EQ(blocks, 2545u);
}
TEST(IndicatorFontStageV2Protocol, OffsetAdvancesOnlyForACompleteBlock) {
using mesh::indicator_font::advanceStageV2Offset;
size_t next = 999;
EXPECT_FALSE(advanceStageV2Offset(1025, 0, 0, next));
EXPECT_FALSE(advanceStageV2Offset(1025, 0, 511, next));
EXPECT_FALSE(advanceStageV2Offset(1025, 0, 513, next));
EXPECT_EQ(next, 999u);
ASSERT_TRUE(advanceStageV2Offset(1025, 0, 512, next));
EXPECT_EQ(next, 512u);
ASSERT_TRUE(advanceStageV2Offset(1025, next, 512, next));
EXPECT_EQ(next, 1024u);
ASSERT_TRUE(advanceStageV2Offset(1025, next, 1, next));
EXPECT_EQ(next, 1025u);
EXPECT_FALSE(advanceStageV2Offset(1025, next, 1, next));
}
TEST(IndicatorFontStageV2Protocol, AckMustBeCanonicalAndCumulative) {
using mesh::indicator_font::parseStageV2Ack;
EXPECT_TRUE(parseStageV2Ack("ACK 512", 512));
EXPECT_TRUE(parseStageV2Ack("ACK 1024", 1024));
EXPECT_TRUE(parseStageV2Ack("ACK 1302608", 1302608));
EXPECT_FALSE(parseStageV2Ack(nullptr, 512));
EXPECT_FALSE(parseStageV2Ack("", 512));
EXPECT_FALSE(parseStageV2Ack("ACK", 512));
EXPECT_FALSE(parseStageV2Ack("ACK ", 512));
EXPECT_FALSE(parseStageV2Ack("ACK 0", 0));
EXPECT_FALSE(parseStageV2Ack("ACK 0512", 512));
EXPECT_FALSE(parseStageV2Ack("ACK +512", 512));
EXPECT_FALSE(parseStageV2Ack("ACK -512", 512));
EXPECT_FALSE(parseStageV2Ack("ACK 512", 512));
EXPECT_FALSE(parseStageV2Ack("ACK 512 ", 512));
EXPECT_FALSE(parseStageV2Ack("ACK 512x", 512));
EXPECT_FALSE(parseStageV2Ack("ACK 184467440737095516160", 512));
EXPECT_FALSE(parseStageV2Ack("READY 2 512", 512));
EXPECT_FALSE(parseStageV2Ack("STAGED", 512));
// A prior or future block's otherwise valid ACK cannot release this block.
EXPECT_FALSE(parseStageV2Ack("ACK 512", 1024));
EXPECT_FALSE(parseStageV2Ack("ACK 1024", 512));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,82 @@
#include <gtest/gtest.h>
#include <helpers/LazyPersistence.h>
TEST(LazyPersistence, ArmsOnlyTheFirstPendingDeadline) {
unsigned long pending = 0;
EXPECT_TRUE(mesh::armFirstLazyPersistence(pending, 5000, true));
EXPECT_EQ(pending, 5000UL);
EXPECT_FALSE(mesh::armFirstLazyPersistence(pending, 9000, true));
EXPECT_EQ(pending, 5000UL);
EXPECT_FALSE(mesh::armFirstLazyPersistence(pending, 9000, false));
}
TEST(LazyPersistence, SuccessfulSaveClearsPendingWrite) {
unsigned long pending = 5000;
mesh::completeLazyPersistenceSave(pending, true, 9000);
EXPECT_EQ(pending, 0UL);
}
TEST(LazyPersistence, FailedSaveRearmsInsteadOfTightLooping) {
unsigned long pending = 5000;
mesh::completeLazyPersistenceSave(pending, false, 10000);
EXPECT_EQ(pending, 10000UL);
}
TEST(LazyPersistence, WrappedDeadlineNeverLosesPendingWrite) {
unsigned long pending = 0;
EXPECT_TRUE(mesh::armFirstLazyPersistence(pending, 0, true));
EXPECT_EQ(pending, 1UL);
mesh::completeLazyPersistenceSave(pending, false, 0);
EXPECT_EQ(pending, 1UL);
}
TEST(LazyPersistence, MutationDoesNotPostponeFirstPendingWrite) {
unsigned long pending = 0;
uint8_t failures = 0;
EXPECT_TRUE(mesh::scheduleLazyPersistenceMutation(
pending, failures, 5000));
EXPECT_FALSE(mesh::scheduleLazyPersistenceMutation(
pending, failures, 9000));
EXPECT_EQ(pending, 5000UL);
EXPECT_EQ(failures, 0);
}
TEST(LazyPersistence, FailedSavesBackOffAndCap) {
uint8_t failures = 0;
EXPECT_EQ(mesh::recordLazyPersistenceSaveFailure(
failures, 5000, 300000), 5000u);
EXPECT_EQ(mesh::recordLazyPersistenceSaveFailure(
failures, 5000, 300000), 10000u);
EXPECT_EQ(mesh::recordLazyPersistenceSaveFailure(
failures, 5000, 300000), 20000u);
for (int i = 0; i < 20; i++) {
EXPECT_LE(mesh::recordLazyPersistenceSaveFailure(
failures, 5000, 300000), 300000u);
}
EXPECT_EQ(mesh::recordLazyPersistenceSaveFailure(
failures, 5000, 300000), 300000u);
}
TEST(LazyPersistence, MutationCannotDefeatFailedSaveBackoff) {
unsigned long pending = 300000;
uint8_t failures = 6;
EXPECT_FALSE(mesh::scheduleLazyPersistenceMutation(
pending, failures, 5000));
EXPECT_EQ(pending, 300000UL);
EXPECT_EQ(failures, 6);
}
TEST(LazyPersistence, SuccessfulSaveResetsTimerAndBackoff) {
unsigned long pending = 300000;
uint8_t failures = 6;
mesh::resetLazyPersistenceAfterSuccess(pending, failures);
EXPECT_EQ(pending, 0UL);
EXPECT_EQ(failures, 0);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -13,6 +13,74 @@ TEST(MQTTConnectionPolicy, ElapsedTimeHandlesNormalAndWrappedClocks) {
EXPECT_EQ(150U, Policy::elapsedMs(50U, before_wrap));
}
TEST(MQTTConnectionPolicy, NtpRefreshHasExactDailyBoundaryAndHandlesRollover) {
EXPECT_EQ(86400000U, Policy::kNtpRefreshIntervalMs);
EXPECT_FALSE(Policy::ntpRefreshDue(
Policy::kNtpRefreshIntervalMs - 1U, 0U, 0U));
EXPECT_TRUE(Policy::ntpRefreshDue(
Policy::kNtpRefreshIntervalMs, 0U, 0U));
const uint32_t last = std::numeric_limits<uint32_t>::max() - 999U;
EXPECT_FALSE(Policy::ntpRefreshDue(
last + Policy::kNtpRefreshIntervalMs - 1U, last, 0U));
EXPECT_TRUE(Policy::ntpRefreshDue(
last + Policy::kNtpRefreshIntervalMs, last, 0U));
}
TEST(MQTTConnectionPolicy, NtpShortRetryOverridesDailySchedule) {
const uint32_t retry_at = Policy::kNtpRefreshIntervalMs + 100U;
EXPECT_FALSE(Policy::ntpRefreshDue(
Policy::kNtpRefreshIntervalMs + 99U, 0U, retry_at));
EXPECT_TRUE(Policy::ntpRefreshDue(retry_at, 0U, retry_at));
}
TEST(MQTTConnectionPolicy, NtpRetryDeadlineHandlesZeroSentinelAtRollover) {
EXPECT_EQ(5000U, Policy::kNtpRetryMs);
EXPECT_EQ(5000U, Policy::ntpRetryAt(0U));
const uint32_t now = std::numeric_limits<uint32_t>::max() - 4999U;
const uint32_t retry_at = Policy::ntpRetryAt(now);
EXPECT_EQ(1U, retry_at);
EXPECT_FALSE(Policy::ntpRefreshDue(
std::numeric_limits<uint32_t>::max(), 0U, retry_at));
EXPECT_FALSE(Policy::ntpRefreshDue(0U, 0U, retry_at));
EXPECT_TRUE(Policy::ntpRefreshDue(1U, 0U, retry_at));
}
TEST(MQTTConnectionPolicy, NtpReconnectRefreshDiscardsOldDeadlineSafely) {
EXPECT_EQ(1U, Policy::ntpReconnectRefreshAt(0U));
EXPECT_FALSE(Policy::ntpRefreshDue(
0U, Policy::kNtpRefreshIntervalMs - 1U,
Policy::ntpReconnectRefreshAt(0U)));
EXPECT_TRUE(Policy::ntpRefreshDue(
1U, Policy::kNtpRefreshIntervalMs - 1U,
Policy::ntpReconnectRefreshAt(0U)));
const uint32_t reconnected_at = 123456U;
EXPECT_EQ(reconnected_at,
Policy::ntpReconnectRefreshAt(reconnected_at));
EXPECT_TRUE(Policy::ntpRefreshDue(
reconnected_at, reconnected_at - 1000U,
Policy::ntpReconnectRefreshAt(reconnected_at)));
}
TEST(MQTTConnectionPolicy, NtpReconnectLatchPreservesEdgesUntilConnected) {
Policy::NtpReconnectLatch latch;
EXPECT_FALSE(latch.consumeIfConnected(true));
latch.noteGotIp();
EXPECT_FALSE(latch.consumeIfConnected(false));
EXPECT_TRUE(latch.consumeIfConnected(true));
EXPECT_FALSE(latch.consumeIfConnected(true));
// An edge arriving after one exchange remains available to the next task
// tick, which is the short-flap/store-after-exchange case.
latch.noteGotIp();
EXPECT_TRUE(latch.consumeIfConnected(true));
latch.noteGotIp();
EXPECT_TRUE(latch.consumeIfConnected(true));
}
TEST(MQTTConnectionPolicy, CrossSlotReconnectGuardHasExactBoundary) {
EXPECT_TRUE(Policy::reconnectGuardActive(14999U, 0U));
EXPECT_FALSE(Policy::reconnectGuardActive(15000U, 0U));
@@ -295,6 +363,30 @@ TEST(StaleToken, FailedMintAlwaysDefers) {
using Policy::ClockSource;
TEST(FallbackClock, RejectsSignedFailureAndRtcRangeOverflow) {
const uint32_t floor = 1767225600UL;
uint32_t accepted = 1234U;
EXPECT_FALSE(Policy::checkedRtcEpoch(-1, floor, accepted));
EXPECT_EQ(0U, accepted);
EXPECT_FALSE(Policy::checkedRtcEpoch(
static_cast<int64_t>(UINT32_MAX) + 1, floor, accepted));
EXPECT_EQ(0U, accepted);
}
TEST(FallbackClock, AcceptsOnlyPlausibleValuesWithinRtcRange) {
const uint32_t floor = 1767225600UL;
uint32_t accepted = 0;
EXPECT_FALSE(Policy::checkedRtcEpoch(
static_cast<int64_t>(floor) - 1, floor, accepted));
EXPECT_EQ(0U, accepted);
EXPECT_TRUE(Policy::checkedRtcEpoch(floor, floor, accepted));
EXPECT_EQ(floor, accepted);
EXPECT_TRUE(Policy::checkedRtcEpoch(UINT32_MAX, floor, accepted));
EXPECT_EQ(UINT32_MAX, accepted);
}
TEST(FallbackClock, PrefersSystemThenRtcAndRejectsInvalidSources) {
const uint32_t floor = 1767225600U;
const uint32_t old_time = 1715770351U;
@@ -0,0 +1,202 @@
#include <gtest/gtest.h>
#include <string>
#define ARDUINO 1
#define NRF52_PLATFORM 1
#define MESH_DEBUG 1
#define BRIDGE_DEBUG 1
#define POWERSAVING_DEBUG 1
#include <MeshCore.h>
namespace {
class CapacityStream : public Stream {
public:
void reset(int capacity) {
capacity_ = capacity;
available_calls_ = 0;
write_calls_ = 0;
oversized_write_ = false;
reenter_on_write_ = false;
reentrant_stream_ = nullptr;
reentrant_result_ = 0;
output_.clear();
}
int availableForWrite() override {
available_calls_++;
return capacity_;
}
size_t write(const uint8_t* buffer, size_t size) override {
write_calls_++;
if (size > static_cast<size_t>(capacity_)) {
oversized_write_ = true;
return 0;
}
if (reenter_on_write_) {
reenter_on_write_ = false;
if (reentrant_stream_ != nullptr) {
static const uint8_t nested[] = {'n', 'e', 's', 't', 'e', 'd'};
reentrant_result_ = reentrant_stream_->write(nested, sizeof(nested));
} else {
MESH_DEBUG_PRINTLN("nested record must be dropped");
}
}
output_.append(reinterpret_cast<const char*>(buffer), size);
capacity_ -= static_cast<int>(size);
return size;
}
int capacity_ = 0;
int available_calls_ = 0;
int write_calls_ = 0;
bool oversized_write_ = false;
bool reenter_on_write_ = false;
Stream* reentrant_stream_ = nullptr;
size_t reentrant_result_ = 0;
std::string output_;
};
CapacityStream logging_port;
mesh::WholeRecordNonBlockingStream<> bounded_logging_port(logging_port);
bool logging_enabled = true;
} // namespace
const char* getLogDateTime() {
return "12:34";
}
namespace mesh {
bool isUsbLoggingEnabled() {
return logging_enabled;
}
Stream& usbLoggingPort() {
return bounded_logging_port;
}
} // namespace mesh
class Nrf52DebugOutputTest : public testing::Test {
protected:
void SetUp() override {
logging_enabled = true;
logging_port.reset(256);
}
};
TEST_F(Nrf52DebugOutputTest, WritesACompleteFormattedRecordWhenItFits) {
MESH_DEBUG_PRINTLN("value=%d", 42);
EXPECT_EQ(logging_port.output_, "DEBUG: value=42\n");
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 1);
EXPECT_FALSE(logging_port.oversized_write_);
}
TEST_F(Nrf52DebugOutputTest, DropsTheWholeRecordWhenFifoCannotFitIt) {
logging_port.reset(10);
MESH_DEBUG_PRINTLN("this record is longer than ten bytes");
EXPECT_TRUE(logging_port.output_.empty());
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 0);
EXPECT_FALSE(logging_port.oversized_write_);
}
TEST_F(Nrf52DebugOutputTest, AnUndrainedFullFifoNeverCallsTheWriter) {
logging_port.reset(0);
MESH_DEBUG_PRINTLN("must not wait");
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 0);
}
TEST_F(Nrf52DebugOutputTest, LongLinesAreBoundedAndVisiblyTruncated) {
const std::string payload(600, 'x');
MESH_DEBUG_PRINTLN("%s", payload.c_str());
ASSERT_EQ(logging_port.output_.size(), 255U);
EXPECT_EQ(logging_port.output_.substr(0, 7), "DEBUG: ");
EXPECT_EQ(logging_port.output_.substr(logging_port.output_.size() - 4),
"...\n");
EXPECT_EQ(logging_port.write_calls_, 1);
EXPECT_FALSE(logging_port.oversized_write_);
}
TEST_F(Nrf52DebugOutputTest, DisabledLoggingDoesNotTouchThePort) {
logging_enabled = false;
MESH_DEBUG_PRINTLN("disabled");
EXPECT_EQ(logging_port.available_calls_, 0);
EXPECT_EQ(logging_port.write_calls_, 0);
}
TEST_F(Nrf52DebugOutputTest, ReentrantDebugOutputIsDroppedWithoutWaiting) {
logging_port.reenter_on_write_ = true;
MESH_DEBUG_PRINTLN("outer record");
EXPECT_EQ(logging_port.output_, "DEBUG: outer record\n");
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 1);
}
TEST_F(Nrf52DebugOutputTest, BridgeAndPowerDebugUseTheSameBoundedPath) {
BRIDGE_DEBUG_PRINTLN("started\n");
POWERSAVING_DEBUG_PRINTLN("sleeping");
EXPECT_EQ(logging_port.output_,
"12:34 BRIDGE: started\nPOWERSAVING: sleeping\n");
EXPECT_EQ(logging_port.write_calls_, 2);
EXPECT_FALSE(logging_port.oversized_write_);
}
TEST_F(Nrf52DebugOutputTest, DedicatedFacadeRejectsAStalePrintfLength) {
mesh::WholeRecordNonBlockingStream<> nonblocking_port(logging_port);
const std::string oversized(600, 'x');
const size_t written = nonblocking_port.write(
reinterpret_cast<const uint8_t*>(oversized.data()), oversized.size());
EXPECT_EQ(written, 0U);
EXPECT_EQ(logging_port.available_calls_, 0);
EXPECT_EQ(logging_port.write_calls_, 0);
}
TEST_F(Nrf52DebugOutputTest, DedicatedFacadeChecksThenWritesOnce) {
mesh::WholeRecordNonBlockingStream<> nonblocking_port(logging_port);
const uint8_t record[] = {'o', 'k', '\n'};
logging_port.reset(sizeof(record));
EXPECT_EQ(nonblocking_port.write(record, sizeof(record)), sizeof(record));
EXPECT_EQ(logging_port.output_, "ok\n");
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 1);
}
TEST_F(Nrf52DebugOutputTest, DedicatedFacadeDropsAReentrantWriter) {
mesh::WholeRecordNonBlockingStream<> nonblocking_port(logging_port);
const uint8_t outer[] = {'o', 'u', 't', 'e', 'r'};
logging_port.reenter_on_write_ = true;
logging_port.reentrant_stream_ = &nonblocking_port;
EXPECT_EQ(nonblocking_port.write(outer, sizeof(outer)), sizeof(outer));
EXPECT_EQ(logging_port.output_, "outer");
EXPECT_EQ(logging_port.reentrant_result_, 0U);
EXPECT_EQ(logging_port.available_calls_, 1);
EXPECT_EQ(logging_port.write_calls_, 1);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Static integration guards for nRF52 nonblocking USB diagnostics."""
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
class Nrf52UsbLoggingContractTest(unittest.TestCase):
def test_all_nrf52_logging_ports_return_the_nonblocking_facade(self):
source = (ROOT / "src/helpers/UsbLogging.cpp").read_text()
self.assertIn(
"nonblocking_dedicated_usb_logging_port(dedicated_usb_logging_port)",
source,
)
self.assertIn("nonblocking_primary_usb_logging_port(Serial)", source)
self.assertIn("return nonblocking_dedicated_usb_logging_port;", source)
self.assertIn("return nonblocking_primary_usb_logging_port;", source)
# ESP32 and other platforms retain their original Serial path.
self.assertIn("#else\n return Serial;\n #endif", source)
def test_facade_uses_a_zero_wait_gate_around_capacity_and_write(self):
source = (ROOT / "src/helpers/NonBlockingWriteStream.h").read_text()
enter = source.index("_writer_busy.test_and_set")
capacity = source.index("_delegate.availableForWrite()", enter)
write = source.index("_delegate.write(data, size)")
release = source.index("_writer_busy.clear")
self.assertLess(enter, capacity)
self.assertLess(capacity, write)
self.assertLess(write, release)
self.assertIn("size > MAX_WRITE_SIZE", source)
def test_meshcore_debug_macros_use_the_bounded_formatter_only_on_nrf52(self):
source = (ROOT / "src/MeshCore.h").read_text()
self.assertIn("#if defined(NRF52_PLATFORM)", source)
self.assertIn('mesh::nrf52DebugPrintf("DEBUG: " F', source)
self.assertIn(
'mesh::usbLoggingPort().printf("DEBUG: " F',
source,
)
if __name__ == "__main__":
unittest.main()
+440
View File
@@ -0,0 +1,440 @@
#!/usr/bin/env python3
"""Static safety contracts for nRF52840 variants with incompatible layouts."""
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
def ini_section(source: str, name: str) -> str:
"""Return one PlatformIO section without resolving its inheritance."""
match = re.search(
rf"^\[{re.escape(name)}\]\s*$\n(?P<body>.*?)(?=^\[|\Z)",
source,
re.MULTILINE | re.DOTALL,
)
if match is None:
raise AssertionError(f"missing PlatformIO section [{name}]")
return match.group("body")
def hex_define(source: str, name: str) -> int:
"""Read a simple hexadecimal preprocessor address definition."""
match = re.search(
rf"^\s*#define\s+{re.escape(name)}\s+(0x[0-9A-Fa-f]+)\b",
source,
re.MULTILINE,
)
if match is None:
raise AssertionError(f"missing hexadecimal definition for {name}")
return int(match.group(1), 16)
class Nrf52VariantContractsTest(unittest.TestCase):
def test_rak3401_wisblock_i2c_aliases_are_complete(self) -> None:
variant = (ROOT / "variants/rak3401/variant.h").read_text()
self.assertRegex(variant, r"#define\s+WB_I2C1_SDA\s+\(13\)")
self.assertRegex(variant, r"#define\s+WB_I2C1_SCL\s+\(14\)")
self.assertRegex(
variant, r"#define\s+PIN_WIRE_SDA\s+\(WB_I2C1_SDA\)"
)
self.assertRegex(
variant, r"#define\s+PIN_WIRE_SCL\s+\(WB_I2C1_SCL\)"
)
self.assertRegex(variant, r"#define\s+PIN_BOARD_SDA\s+PIN_WIRE_SDA")
self.assertRegex(variant, r"#define\s+PIN_BOARD_SCL\s+PIN_WIRE_SCL")
def test_rak3401_gps_uart_is_cross_connected(self) -> None:
variant = (ROOT / "variants/rak3401/variant.h").read_text()
self.assertRegex(variant, r"#define\s+PIN_SERIAL1_RX\s+\(15\)")
self.assertRegex(variant, r"#define\s+PIN_SERIAL1_TX\s+\(16\)")
self.assertRegex(variant, r"#define\s+PIN_GPS_RX\s+PIN_SERIAL1_TX")
self.assertRegex(variant, r"#define\s+PIN_GPS_TX\s+PIN_SERIAL1_RX")
def test_rak3401_bsec_opt_in_requires_hard_float_recipe(self) -> None:
recipe = (ROOT / "variants/rak3401/platformio.ini").read_text()
shared = (ROOT / "platformio.ini").read_text()
sensor_base = re.search(
r"^\[sensor_base\]\s*$\n(?P<body>.*?)(?=^\[|\Z)",
shared,
re.MULTILINE | re.DOTALL,
)
self.assertIsNotNone(sensor_base)
effective_recipe = sensor_base.group("body") + recipe
if re.search(
r"^\s*-D\s*ENV_INCLUDE_BME680_BSEC(?:=1)?\s*$",
effective_recipe,
re.MULTILINE,
):
self.assertIn("fix_bsec_lib.py", recipe)
self.assertIn("BSEC Software Library", recipe)
def test_rak3401_reduced_profile_names_its_narrow_sensor_trim(self) -> None:
recipe = (ROOT / "variants/rak3401/platformio.ini").read_text()
shared = (ROOT / "platformio.ini").read_text()
build_script = (ROOT / "build.sh").read_text()
expected_ina = {
"ENV_INCLUDE_INA219",
"ENV_INCLUDE_INA226",
"ENV_INCLUDE_INA260",
"ENV_INCLUDE_INA3221",
}
voltage_monitor_section = ini_section(shared, "i2c_voltage_monitor_base")
enabled_monitors = set(
re.findall(
r"-D\s+(ENV_INCLUDE_[A-Z0-9_]+)=1\b",
voltage_monitor_section,
)
)
self.assertEqual(enabled_monitors, expected_ina)
reduced_sensor_section = ini_section(
shared, "nrf52_reduced_sensors_keep_ina_gps"
)
self.assertIn(
"${nrf52_external_environmental_sensor_trim.build_flags}",
reduced_sensor_section,
)
self.assertIn(
"${i2c_voltage_monitor_base.build_flags}", reduced_sensor_section
)
self.assertNotRegex(reduced_sensor_section, r"-U\s*ENV_INCLUDE_GPS\b")
reduced_target = ini_section(
recipe, "env:RAK_3401_repeater_lora_ota_no_external_sensors"
)
self.assertIn(
"${nrf52_reduced_sensors_keep_ina_gps.build_flags}", reduced_target
)
monitor_flags = re.search(
r'^\s*local voltage_monitor_flags="(?P<flags>[^"]+)"',
build_script,
re.MULTILINE,
)
self.assertIsNotNone(monitor_flags)
self.assertEqual(set(monitor_flags.group("flags").split()), expected_ina)
self.assertIn(
"selected optional environmental/ranging drivers omitted",
build_script,
)
self.assertIn("board display/RTC/GPS retained", build_script)
self.assertIn("GPS conflicts with RS-232 on Serial1", build_script)
self.assertNotIn("sensors.external omitted except", build_script)
self.assertIn("environmental telemetry sensors", recipe)
self.assertIn("both RAK12500 I2C and RAK12501 UART GPS paths", recipe)
def test_rak3401_reduced_profile_retains_non_ina_i2c_peripherals(self) -> None:
recipe = (ROOT / "variants/rak3401/platformio.ini").read_text()
target = (ROOT / "variants/rak3401/target.cpp").read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
rtc = (ROOT / "src/helpers/AutoDiscoverRTCClock.cpp").read_text()
display = (ROOT / "src/helpers/ui/SSD1306Display.h").read_text()
reduced_target = ini_section(
recipe, "env:RAK_3401_repeater_lora_ota_no_external_sensors"
)
self.assertRegex(reduced_target, r"-D\s+DISPLAY_CLASS=SSD1306Display\b")
self.assertIn("SparkFun u-blox GNSS Arduino Library", reduced_target)
self.assertIn("AutoDiscoverRTCClock rtc_clock", target)
self.assertIn("rtc_clock.begin(Wire)", target)
self.assertIn("MicroNMEALocationProvider(Serial1, &rtc_clock)", target)
self.assertIn(
"ublox_GNSS.begin(Wire, gps_i2c_address)", sensors
)
self.assertIn(
"shouldSkipSensorAtClaimedGpsAddress(", sensors
)
self.assertIn("i2cGPSFlag, TELEM_WIRE == &Wire", sensors)
self.assertIn(
"probeIna3221Identity(&Wire, gps_i2c_address)", sensors
)
self.assertIn("static_cast<uint32_t>(TELEM_RAK12500_ADDRESS)", sensors)
self.assertIn("I2cRegisterProbeStatus::Inconclusive", sensors)
self.assertIn("serialHasValidGpsSentence(Serial1", sensors)
self.assertNotIn("else if (Serial1.available())", sensors)
self.assertEqual(hex_define(display, "DISPLAY_ADDRESS"), 0x3C)
self.assertEqual(
{
"DS3231": hex_define(rtc, "DS3231_ADDRESS"),
"RV3028": hex_define(rtc, "RV3028_ADDRESS"),
"PCF8563": hex_define(rtc, "PCF8563_ADDRESS"),
"RX8130CE": hex_define(rtc, "RX8130CE_ADDRESS"),
},
{
"DS3231": 0x68,
"RV3028": 0x52,
"PCF8563": 0x51,
"RX8130CE": 0x32,
},
)
def test_i2c_recovery_uses_board_remapped_primary_pins(self) -> None:
recipe = (ROOT / "variants/promicro/platformio.ini").read_text()
board = (ROOT / "variants/promicro/PromicroBoard.cpp").read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
self.assertRegex(recipe, r"-D\s+PIN_BOARD_SDA=8\b")
self.assertRegex(recipe, r"-D\s+PIN_BOARD_SCL=7\b")
self.assertIn("Wire.setPins(PIN_BOARD_SDA, PIN_BOARD_SCL)", board)
board_pin_branch = sensors.index(
"defined(PIN_BOARD_SDA) && defined(PIN_BOARD_SCL)"
)
variant_pin_branch = sensors.index(
"defined(PIN_WIRE_SDA) && defined(PIN_WIRE_SCL)"
)
self.assertLess(board_pin_branch, variant_pin_branch)
self.assertIn("Wire.setPins(static_cast<uint8_t>(sda)", sensors)
def test_rak3401_rak12500_ina3221_address_collision_is_explicit(self) -> None:
recipe = (ROOT / "variants/rak3401/platformio.ini").read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
gps_address = hex_define(sensors, "TELEM_RAK12500_ADDRESS")
ina3221_address = hex_define(sensors, "TELEM_INA3221_ADDRESS")
self.assertEqual(gps_address, 0x42)
self.assertEqual(ina3221_address, 0x42)
self.assertEqual(gps_address, ina3221_address)
self.assertIn(
"RAK12500 and the configured INA3221 both use I2C address 0x42",
recipe,
)
self.assertIn("cannot be installed", recipe)
self.assertIn("strap INA3221 A0 to SCL for 0x43", recipe)
self.assertIn("-DTELEM_INA3221_ADDRESS=0x43", recipe)
def test_rak4631_shared_sensor_rail_stays_enabled(self) -> None:
recipe = (ROOT / "variants/rak4631/platformio.ini").read_text()
board = (ROOT / "variants/rak4631/RAK4631Board.cpp").read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
self.assertRegex(recipe, r"-D\s+FORCE_GPS_ALIVE\b")
self.assertIn("pinMode(WB_IO2, OUTPUT)", board)
self.assertIn("digitalWrite(WB_IO2, HIGH)", board)
self.assertIn("setRakGpsControl(ioPin, shared_power_rail, true)", sensors)
self.assertIn("setRakGpsControl(ioPin, shared_power_rail, false)", sensors)
def test_rak4631_ethernet_does_not_suppress_shared_rail_gps(self) -> None:
recipe = (ROOT / "variants/rak4631/platformio.ini").read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
ethernet = ini_section(recipe, "env:RAK_4631_repeater_ethernet")
self.assertRegex(ethernet, r"-D\s+ETHERNET_ENABLED=1\b")
self.assertNotIn(
"#if defined(ETHERNET_ENABLED) && defined(RAK_BOARD)", sensors
)
self.assertNotIn("if (ioPin == WB_IO2)", sensors)
self.assertIn(
"setRakGpsControl(ioPin, shared_power_rail, true)", sensors
)
def test_rak4631_runtime_bridge_arbitrates_only_uart_gps(self) -> None:
recipe = (ROOT / "variants/rak4631/platformio.ini").read_text()
mesh_header = (
ROOT / "examples/simple_repeater/MyMesh.h"
).read_text()
sensor_header = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.h"
).read_text()
sensors = (
ROOT / "src/helpers/sensors/EnvironmentSensorManager.cpp"
).read_text()
cli = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
begin = mesh_header[
mesh_header.index("bool beginRS232Bridge()"):
mesh_header.index("bool endRS232Bridge()")
]
end = mesh_header[
mesh_header.index("bool endRS232Bridge()"):
mesh_header.index("bool setBridgeState(bool enable)")
]
can_yield = sensors[
sensors.index("bool EnvironmentSensorManager::gpsSerialTransportCanYield"):
sensors.index("bool EnvironmentSensorManager::setGpsSerialTransportBlocked")
]
block = sensors[
sensors.index("bool EnvironmentSensorManager::setGpsSerialTransportBlocked"):
sensors.index("#if ENV_INCLUDE_GPS || defined(ENV_INCLUDE_BME680_BSEC)")
]
self.assertLess(
begin.index("setGpsSerialTransportBlocked(selected_uart, true)"),
begin.index("bridge->begin()"),
)
self.assertLess(
begin.index("active_rs232_bridge_uart = selected_uart"),
begin.index("bridge->begin()"),
)
failed_start = begin[
begin.index("if (!bridge->isRunning())"):
begin.index(
"active_rs232_bridge_uart = selected_uart",
begin.index("bridge->begin()"),
)
]
self.assertIn(
"if (sensors.setGpsSerialTransportBlocked(selected_uart, false))",
failed_start,
)
self.assertIn("active_rs232_bridge_uart = 0", failed_start)
self.assertLess(
begin.index("gpsSerialTransportMayConflict(selected_uart)"),
begin.index("bridge->begin()"),
)
self.assertLess(
end.index("if (bridge && bridge->isRunning())"),
end.index("bridge->end()"),
)
self.assertLess(
end.index("bridge->end()"),
end.index("setGpsSerialTransportBlocked(released_uart, false)"),
)
self.assertIn("gpsUsesSerialUart(uint8_t uart) const override", sensor_header)
self.assertIn(
"gpsSerialTransportMayConflict(uint8_t uart) const override",
sensor_header,
)
self.assertIn("-D WITH_RS232_BRIDGE_GPS_CONFLICT_UART=1", recipe)
self.assertIn(
"if (uart == WITH_RS232_BRIDGE_GPS_CONFLICT_UART) return true;",
sensors,
)
self.assertIn(
"return uart == 1 && gps_detected && gps_serial_transport", sensors
)
self.assertIn(
"#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)",
can_yield,
)
forced_rak = can_yield[
can_yield.index(
"#if defined(RAK_WISBLOCK_GPS) && defined(FORCE_GPS_ALIVE)"
):
can_yield.index("#elif defined(RAK_WISBLOCK_GPS)")
]
self.assertIn("return false;", forced_rak)
refusal = block.index(
"if (blocked && !gpsSerialTransportCanYield(uart)) return false;"
)
for mutation in (
"setGpsTelemetryTransportAvailable(false)",
"gps_serial_transport_blocked = true",
"stop_gps()",
"Serial1.end()",
):
self.assertLess(refusal, block.index(mutation))
self.assertIn("setGpsTelemetryTransportAvailable(false)", sensors)
self.assertIn("setGpsTelemetryTransportAvailable(true)", sensors)
self.assertNotIn(
"turn the RS232 bridge off or select another UART first", cli
)
self.assertNotIn("Error: turn GPS off or select another UART first", cli)
def test_bridge_reports_runtime_state_and_rolls_back_failed_changes(self) -> None:
implementation = (
ROOT / "examples/simple_repeater/MyMesh.cpp"
).read_text()
header = (ROOT / "examples/simple_repeater/MyMesh.h").read_text()
cli = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
self.assertIn("bool isBridgeRunning() const override", header)
self.assertIn("if (isBridgeRunning()) reply_data[8] |= 0x01", implementation)
self.assertIn("if (isBridgeRunning()) reply_data[8] |= 0x03", implementation)
boot_failure = implementation[
implementation.index("if (!bridge || !beginRS232Bridge())"):
implementation.index("#else", implementation.index(
"if (!bridge || !beginRS232Bridge())"
))
]
self.assertIn("setBridgeState(false)", boot_failure)
self.assertNotIn("_prefs.bridge_enabled", boot_failure)
self.assertIn("parseOnOffStrict(&config[15], enable)", cli)
self.assertIn("parseUnsignedIntegerStrict(&config[12], baud)", cli)
self.assertIn("_prefs->bridge_baud = previous_baud", cli)
self.assertIn("_prefs->bridge_uart = previous_uart", cli)
self.assertIn("bridge state change failed; setting unchanged", cli)
self.assertIn('configKeyEquals(config, "bridge.running")', cli)
self.assertIn('_prefs->bridge_pkt_src ? "rx" : "tx"', cli)
self.assertIn("!defined(RS232_BRIDGE_DEFAULT_ON)", cli)
def test_default_on_rs232_profile_skips_default_off_tail_migration(self) -> None:
cli = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
xiao = (ROOT / "variants/xiao_nrf52/platformio.ini").read_text()
dedicated = ini_section(
xiao, "env:solarxiao_30S_repeater_bridge_rs232"
)
self.assertIn("extends = env:solarxiao_30S_repeater", dedicated)
self.assertRegex(dedicated, r"-D\s+RS232_BRIDGE_DEFAULT_ON=1\b")
guard = (
"#if defined(WITH_RS232_BRIDGE) && defined(RS232_BRIDGE_MERGED) \\\n"
" && !defined(RS232_BRIDGE_DEFAULT_ON)"
)
# Declaration, persisted-tail detection, and migration must share the
# same guard. A broader use breaks dedicated default-on bridge builds.
self.assertEqual(cli.count(guard), 3)
self.assertEqual(cli.count("has_runtime_bridge_uart"), 3)
def test_gat562_30s_gps_enable_and_buzzer_pins_are_distinct(self) -> None:
recipe = (
ROOT / "variants/gat562_30s_mesh_kit/platformio.ini"
).read_text()
variant = (ROOT / "variants/gat562_30s_mesh_kit/variant.h").read_text()
# GAT562 30S Mesh KIT V1.1 schematic: IO2 is nRF P1.01 (Arduino
# GPIO 33) and drives the GPS supply; BEE_EN is P1.02 (GPIO 34).
gps_pin = re.search(
r"#define\s+PIN_GPS_EN\s+\((\d+)\)", variant
)
buzzer_pin = re.search(r"-D\s+PIN_BUZZER=(\d+)\b", recipe)
self.assertIsNotNone(gps_pin)
self.assertIsNotNone(buzzer_pin)
self.assertEqual(int(gps_pin.group(1)), 33)
self.assertEqual(int(buzzer_pin.group(1)), 34)
self.assertNotEqual(gps_pin.group(1), buzzer_pin.group(1))
def test_xiao_and_mesh_pocket_softdevice_layouts_are_not_interchangeable(
self,
) -> None:
xiao = (ROOT / "variants/xiao_nrf52/platformio.ini").read_text()
mesh_pocket = (ROOT / "variants/mesh_pocket/platformio.ini").read_text()
self.assertRegex(
xiao,
re.compile(
r"^\[Xiao_nrf52\].*?^board_build\.ldscript\s*=\s*"
r"boards/nrf52840_s140_v7\.ld$",
re.MULTILINE | re.DOTALL,
),
)
self.assertRegex(
mesh_pocket,
re.compile(
r"^\[Mesh_pocket\].*?^board_build\.ldscript\s*=\s*"
r"boards/nrf52840_s140_v6\.ld$",
re.MULTILINE | re.DOTALL,
),
)
if __name__ == "__main__":
unittest.main()
+2 -1
View File
@@ -37,6 +37,7 @@ TEST(OtaBootResult, AcceptsOnlyOtafixApplyDiagnostics) {
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xB0), 0xB0);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xB8), 0xB8);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xBC), 0xBC);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xBD), 0xBD); // SD authorization failure
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xC0), 0xC0);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xC8), 0xC8);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xCF), 0xCF);
@@ -50,7 +51,7 @@ TEST(OtaBootResult, AcceptsOnlyOtafixApplyDiagnostics) {
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xD4), 0x00); // legacy handoff
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xED), 0x00); // expanded handoff
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xE0), 0x00); // retired handoff remains non-result
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xBD), 0x00);
EXPECT_EQ(ota_nrf52_boot_result_or_zero(0xBE), 0x00);
}
TEST(OtaPolicy, TrustedAutoInstallIsStrictlyForwardOnly) {
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
source build.sh
fail() {
echo "test_rak4631_ota_compatibility: $*" >&2
exit 1
}
assert_array_equals() {
local label=$1
local actual_name=$2
shift 2
local -n actual=$actual_name
local -a expected=("$@")
local index
[ "${#actual[@]}" -eq "${#expected[@]}" ] \
|| fail "$label count was ${#actual[@]}, expected ${#expected[@]}: ${actual[*]}"
for index in "${!expected[@]}"; do
[ "${actual[$index]}" = "${expected[$index]}" ] \
|| fail "$label[$index] was ${actual[$index]}, expected ${expected[$index]}"
done
}
compatibility_targets=(
RAK_4631_repeater_bridge_rs232_serial1_lora_ota_no_external_sensors
RAK_4631_repeater_bridge_rs232_serial2_lora_ota_no_external_sensors
)
mapfile -t declared_compatibility_targets < <(
get_deployed_lora_ota_compatibility_targets
)
assert_array_equals \
"declared compatibility targets" declared_compatibility_targets \
"${compatibility_targets[@]}"
for target in "${compatibility_targets[@]}"; do
is_deployed_lora_ota_compatibility_target "$target" \
|| fail "$target lost its deployed-node compatibility classification"
if is_redundant_bulk_build_target "$target"; then
fail "$target was omitted from canonical bulk builds"
fi
done
if is_deployed_lora_ota_compatibility_target RAK_4631_repeater; then
fail "canonical RAK4631 repeater was classified as a legacy OTA identity"
fi
[ "$(get_merged_rs232_repeater_replacement "${compatibility_targets[0]}")" \
= RAK_4631_repeater_lora_ota_no_external_sensors ] \
|| fail "Serial1 compatibility target lost its canonical recommendation"
[ "$(get_merged_rs232_repeater_replacement "${compatibility_targets[1]}")" \
= RAK_4631_repeater_lora_ota_no_external_sensors ] \
|| fail "Serial2 compatibility target lost its canonical recommendation"
canonical_target=RAK_4631_repeater
canonical_ota_target=RAK_4631_repeater_lora_ota_no_external_sensors
legacy_install_targets=(
RAK_4631_repeater_bridge_rs232_serial1
RAK_4631_repeater_bridge_rs232_serial2
)
SUPPORTED_PIO_ENVS=(
"$canonical_target"
"$canonical_ota_target"
"${legacy_install_targets[@]}"
"${compatibility_targets[@]}"
)
for target in "${SUPPORTED_PIO_ENVS[@]}"; do
PIO_ENV_PLATFORM_BY_NAME[$target]=NRF52_PLATFORM
done
mapfile -t all_targets < <(resolve_all_firmwares)
assert_array_equals \
"canonical bulk target list" all_targets \
"$canonical_target" \
"$canonical_ota_target" \
"${compatibility_targets[@]}"
mapfile -t release_targets < <(
print_release_firmware_targets get-repeater-firmwares-to-build
)
assert_array_equals \
"repeater release target list" release_targets \
"$canonical_target" \
"${compatibility_targets[@]}"
echo "test_rak4631_ota_compatibility: OK"
@@ -555,6 +555,27 @@ TEST(SerialFlowControl, FinishesAnUnexpectedShortWriteBeforeNextFrame) {
EXPECT_FALSE(interface.hasPendingIO());
}
TEST(SerialFlowControl, RetriesAZeroLengthWriteWithoutLosingTheFrame) {
BufferStream stream;
stream.write_capacity = MAX_FRAME_SIZE + 3;
stream.max_write = 0;
ArduinoSerialInterface interface;
interface.begin(stream);
interface.enableFlowControl(true);
interface.enable();
const uint8_t payload[] = {0x88, 0x11, 0x22};
EXPECT_EQ(interface.writeFrame(payload, sizeof(payload)), sizeof(payload));
EXPECT_TRUE(stream.output.empty());
EXPECT_TRUE(interface.hasPendingIO());
stream.max_write = std::numeric_limits<size_t>::max();
interface.loop();
const std::vector<uint8_t> expected = {'>', 3, 0, 0x88, 0x11, 0x22};
EXPECT_EQ(stream.output, expected);
EXPECT_FALSE(interface.hasPendingIO());
}
TEST(SerialFlowControl, DrainsFramesThroughAFifoSmallerThanTheFrame) {
BufferStream stream;
stream.write_capacity = 4;
@@ -0,0 +1,35 @@
#include <gtest/gtest.h>
#include <helpers/TempRadioLeaseDeadline.h>
TEST(TempRadioLeaseDeadline, EpochWindowGetsAnIndependentUptimeEnd) {
const uint64_t hard_end = mesh::TempRadioLeaseDeadline::fromEpochEnd(
50'000ULL, 1'800'000'000UL, 1'800'000'180UL);
EXPECT_EQ(hard_end, 230'000ULL);
EXPECT_FALSE(mesh::TempRadioLeaseDeadline::expired(229'999ULL, hard_end));
EXPECT_TRUE(mesh::TempRadioLeaseDeadline::expired(230'000ULL, hard_end));
}
TEST(TempRadioLeaseDeadline, BackwardRtcCorrectionCannotExtendLease) {
const uint64_t hard_end = mesh::TempRadioLeaseDeadline::fromEpochEnd(
10'000ULL, 1'800'000'000UL, 1'800'000'180UL);
// The wall clock has moved backward by an hour and no longer considers the
// epoch end due. Uptime remains authoritative for the safety bound.
const uint32_t corrected_wall_clock = 1'799'996'580UL;
EXPECT_LT(corrected_wall_clock, 1'800'000'180UL);
EXPECT_TRUE(mesh::TempRadioLeaseDeadline::expired(190'000ULL, hard_end));
}
TEST(TempRadioLeaseDeadline, PendingWindowAlsoExpiresAndBoundsSleep) {
const uint64_t hard_end = mesh::TempRadioLeaseDeadline::fromEpochEnd(
4'000ULL, 1'800'000'000UL, 1'800'000'181UL);
EXPECT_EQ(
mesh::TempRadioLeaseDeadline::secondsUntil(180'001ULL, hard_end),
5U);
EXPECT_EQ(
mesh::TempRadioLeaseDeadline::secondsUntil(185'000ULL, hard_end),
0U);
}
@@ -0,0 +1,66 @@
#include <gtest/gtest.h>
#include <helpers/TempRadioReplyBarrier.h>
TEST(TempRadioReplyBarrier, WaitsForTheExactReplyPacket) {
mesh::TempRadioReplyBarrier barrier;
int reply_packet = 1;
int unrelated_packet = 2;
EXPECT_FALSE(barrier.waiting());
barrier.arm(&reply_packet);
EXPECT_TRUE(barrier.waiting());
EXPECT_FALSE(barrier.complete(&unrelated_packet));
EXPECT_TRUE(barrier.waiting());
EXPECT_TRUE(barrier.complete(&reply_packet));
EXPECT_FALSE(barrier.waiting());
}
TEST(TempRadioReplyBarrier, ExactTransmitFailureReleasesForFailClosedCleanup) {
mesh::TempRadioReplyBarrier barrier;
int reply_packet = 1;
barrier.arm(&reply_packet);
EXPECT_TRUE(barrier.fail(&reply_packet));
EXPECT_FALSE(barrier.waiting());
EXPECT_FALSE(barrier.fail(&reply_packet));
}
TEST(TempRadioReplyBarrier, UntrackedAlternateCannotResolveAuthoritativeReply) {
mesh::TempRadioReplyBarrier barrier;
int primary_reply = 1;
int alternate_reply = 2;
barrier.arm(&primary_reply);
// TempRadio mutation acknowledgements deliberately queue only the primary
// copy, without an alternate-path copy or a transport retry. If an
// obsolete/foreign packet callback arrives anyway, it must not release or
// fail the authoritative handoff.
EXPECT_FALSE(barrier.complete(&alternate_reply));
EXPECT_FALSE(barrier.fail(&alternate_reply));
EXPECT_TRUE(barrier.waiting());
EXPECT_TRUE(barrier.complete(&primary_reply));
EXPECT_FALSE(barrier.waiting());
}
TEST(TempRadioReplyBarrier, ClearCancelsAnObsoleteHandoff) {
mesh::TempRadioReplyBarrier barrier;
int old_reply = 1;
int new_reply = 2;
barrier.arm(&old_reply);
barrier.clear();
EXPECT_FALSE(barrier.complete(&old_reply));
barrier.arm(&new_reply);
EXPECT_FALSE(barrier.complete(&old_reply));
EXPECT_TRUE(barrier.complete(&new_reply));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Static integration contract for TempRadio's single-copy reply barrier."""
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "examples/simple_repeater/MyMesh.cpp"
def function_body(text: str, signature: str, next_signature: str) -> str:
start = text.index(signature)
end = text.index(next_signature, start)
return text[start:end]
class TempRadioReplyDeliveryContractTest(unittest.TestCase):
def test_exact_packet_tracking_suppresses_all_untracked_copies(self):
source = SOURCE.read_text(encoding="utf-8")
reply = function_body(
source,
"bool MyMesh::sendRemoteCliReply(",
"void MyMesh::onUserGpioTimerCompleted(",
)
delivery = function_body(
source,
"bool MyMesh::sendClientReplyWithFallbackScope(",
"bool MyMesh::floodChannelDataHopApplies(",
)
self.assertIn(
"const bool allow_redundant_copies = queued_packet == NULL;", reply
)
self.assertIn("fallback_scope,\n allow_redundant_copies", reply)
self.assertIn(
"if (allow_redundant_copies\n"
" && mesh::Packet::isValidPathLen(client->alt_path_len)",
delivery,
)
self.assertIn(
"if (!allow_redundant_copies) _prefs.direct_retry_enabled = 0;",
delivery,
)
self.assertIn(
"if (!allow_redundant_copies) _prefs.flood_retry_attempts = 0;",
delivery,
)
def test_only_successful_parameterized_temp_radio_requests_track_reply(self):
source = SOURCE.read_text(encoding="utf-8")
receive = function_body(
source,
"void MyMesh::onPeerDataRecv(",
"bool MyMesh::sendRemoteCliReply(",
)
command = function_body(
source,
"void __attribute__((noinline)) MyMesh::processDeferredCliCommand()",
"bool MyMesh::onPeerPathRecv(",
)
self.assertIn(
'strncmp(deferred_cli_command.command, "tempradio ", 10)', command
)
self.assertIn('strncmp(reply, "OK - temp params for ", 21)', command)
self.assertIn("arms_temp_radio ? &queued_reply : NULL", command)
# A packet-level retry can arrive after the success text was cached but
# before the authoritative reply drains. It must not create a second,
# untracked success packet either.
self.assertIn("const bool cached_temp_radio_success", receive)
suppress_start = receive.index("if (cached_temp_radio_success)")
replay_start = receive.index("} else {", suppress_start)
replay_end = receive.index(
"} else if (deferred_cli_command.matches", replay_start
)
self.assertNotIn(
"sendRemoteCliReply(", receive[suppress_start:replay_start]
)
self.assertIn("sendRemoteCliReply(", receive[replay_start:replay_end])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,20 @@
#include <helpers/esp32/SntpOperationCoordinator.h>
namespace {
mesh::sntp_coord::OperationLease peer_lease(
mesh::sntp_coord::processWideCoordinator());
} // namespace
extern "C" void* sntpCoordinatorPeerAddress() {
return &mesh::sntp_coord::processWideCoordinator();
}
extern "C" bool sntpCoordinatorPeerAcquire() {
return peer_lease.tryAcquire();
}
extern "C" bool sntpCoordinatorPeerRelease() {
return peer_lease.release();
}
@@ -0,0 +1,102 @@
#include <gtest/gtest.h>
#include <helpers/esp32/SntpOperationCoordinator.h>
#include <helpers/esp32/TlsClockValidity.h>
namespace Clock = mesh::tls_clock;
extern "C" void* sntpCoordinatorPeerAddress();
extern "C" bool sntpCoordinatorPeerAcquire();
extern "C" bool sntpCoordinatorPeerRelease();
namespace {
int cleanup_calls = 0;
void recordCleanup() {
++cleanup_calls;
}
} // namespace
TEST(TlsClockValidity, RejectsNegativeAndPreMinimumEpochs) {
EXPECT_FALSE(Clock::timeIsValid((time_t)-1));
EXPECT_FALSE(Clock::timeIsValid(Clock::kMinimumValidEpoch - 1));
}
TEST(TlsClockValidity, AcceptsTheExactMinimumAndLaterEpochs) {
EXPECT_TRUE(Clock::timeIsValid(Clock::kMinimumValidEpoch));
EXPECT_TRUE(Clock::timeIsValid(Clock::kMinimumValidEpoch + 1));
}
TEST(TlsClockValidity, RequiresFreshProofAndConnectedWiFi) {
const time_t now = Clock::kMinimumValidEpoch;
EXPECT_FALSE(Clock::proofIsValid(false, true, now));
EXPECT_FALSE(Clock::proofIsValid(true, false, now));
EXPECT_FALSE(Clock::proofIsValid(true, true, now - 1));
EXPECT_TRUE(Clock::proofIsValid(true, true, now));
}
TEST(TlsClockValidity, ProofAgeIsBoundedAndMillisRolloverSafe) {
EXPECT_FALSE(Clock::proofAgeIsValid(false, 100, 90, 10));
EXPECT_TRUE(Clock::proofAgeIsValid(true, 100, 90, 10));
EXPECT_FALSE(Clock::proofAgeIsValid(true, 101, 90, 10));
const uint32_t before_wrap = UINT32_MAX - 5U;
EXPECT_TRUE(Clock::proofAgeIsValid(true, 4, before_wrap, 10));
EXPECT_FALSE(Clock::proofAgeIsValid(true, 5, before_wrap, 10));
}
TEST(TlsClockValidity, LateCallbackGenerationFailsClosed) {
EXPECT_FALSE(Clock::proofGenerationIsValid(false, 7, 7));
EXPECT_FALSE(Clock::proofGenerationIsValid(true, 7, 0));
EXPECT_FALSE(Clock::proofGenerationIsValid(true, 6, 7));
EXPECT_TRUE(Clock::proofGenerationIsValid(true, 7, 7));
}
TEST(SntpOperationCoordinator, IsNonBlockingAndOnlyOwnerRunsCleanup) {
mesh::sntp_coord::OperationCoordinator coordinator;
cleanup_calls = 0;
mesh::sntp_coord::OperationLease first(coordinator, recordCleanup);
mesh::sntp_coord::OperationLease second(coordinator, recordCleanup);
ASSERT_TRUE(first.tryAcquire());
const uint32_t first_generation = first.generation();
EXPECT_NE(first_generation, 0U);
EXPECT_TRUE(first.owns());
EXPECT_FALSE(second.tryAcquire());
EXPECT_EQ(cleanup_calls, 0);
EXPECT_TRUE(first.release());
EXPECT_EQ(cleanup_calls, 1);
EXPECT_FALSE(first.release());
EXPECT_EQ(cleanup_calls, 1);
ASSERT_TRUE(second.tryAcquire());
EXPECT_NE(second.generation(), first_generation);
EXPECT_TRUE(second.owns());
// A stale/repeated release from the first lease cannot clear the new owner.
EXPECT_FALSE(first.release());
EXPECT_TRUE(second.owns());
EXPECT_EQ(cleanup_calls, 1);
EXPECT_TRUE(second.release());
EXPECT_EQ(cleanup_calls, 2);
}
TEST(SntpOperationCoordinator, ProcessWideAccessorReturnsOneInstance) {
EXPECT_EQ(&mesh::sntp_coord::processWideCoordinator(),
sntpCoordinatorPeerAddress());
mesh::sntp_coord::OperationLease local(
mesh::sntp_coord::processWideCoordinator());
ASSERT_TRUE(local.tryAcquire());
EXPECT_FALSE(sntpCoordinatorPeerAcquire());
ASSERT_TRUE(local.release());
EXPECT_TRUE(sntpCoordinatorPeerAcquire());
EXPECT_TRUE(sntpCoordinatorPeerRelease());
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+376
View File
@@ -0,0 +1,376 @@
#!/usr/bin/env python3
from pathlib import Path
import re
import unittest
ROOT = Path(__file__).resolve().parents[1]
ESP32_BOARD = ROOT / "src/helpers/ESP32Board.cpp"
INDICATOR_FONT = ROOT / "variants/sensecap_indicator-espnow/IndicatorFontClient.cpp"
OBSERVER_CLI = ROOT / "src/helpers/CommonCLI_Observer.cpp"
TLS_POLICY = ROOT / "src/helpers/esp32/TlsClockValidity.h"
SNTP_COORDINATOR = ROOT / "src/helpers/esp32/SntpOperationCoordinator.h"
MQTT_BRIDGE = ROOT / "src/helpers/bridges/MQTTBridge.h"
MQTT_BRIDGE_IMPL = ROOT / "src/helpers/bridges/MQTTBridge.cpp"
MQTT_POLICY = ROOT / "src/helpers/MQTTConnectionPolicy.h"
def source(path: Path) -> str:
return path.read_text()
def section(text: str, start: str, end: str) -> str:
first = text.index(start)
return text[first:text.index(end, first)]
class TlsDownloadClockGateTest(unittest.TestCase):
def test_outbound_secure_socket_inventory_has_no_unreviewed_path(self):
# Keep this inventory deliberately small and explicit. A new direct
# WiFiClientSecure connect is a new certificate-validating network
# boundary; adding one must also add its clock/proof contract here.
runtime_roots = (ROOT / "src", ROOT / "examples", ROOT / "variants")
secure_connect_files = set()
for runtime_root in runtime_roots:
for path in runtime_root.rglob("*.cpp"):
implementation = source(path)
if "WiFiClientSecure" in implementation and ".connect(" in implementation:
secure_connect_files.add(path.relative_to(ROOT).as_posix())
self.assertEqual(
secure_connect_files,
{
"src/helpers/CommonCLI_Observer.cpp", # connect-only CA diagnostic
"src/helpers/ESP32Board.cpp", # manifest + firmware pull OTA
"variants/sensecap_indicator-espnow/IndicatorFontClient.cpp",
},
)
# These higher-level outbound HTTP clients can hide their TLS connect
# from the inventory above. None is currently used by device runtime
# code; fail visibly if one is introduced without a matching audit.
combined_runtime = "\n".join(
source(path)
for runtime_root in runtime_roots
for path in runtime_root.rglob("*.cpp")
)
for helper in ("HTTPClient", "esp_https_ota", "esp_http_client"):
self.assertNotIn(helper, combined_runtime)
def test_shared_policy_uses_signed_time_and_requires_every_input(self):
policy = source(TLS_POLICY)
self.assertIn("constexpr bool timeIsValid(time_t now)", policy)
self.assertIn("now >= kMinimumValidEpoch", policy)
self.assertIn("fresh_proof && wifi_connected && timeIsValid(now)", policy)
self.assertNotIn("timeIsValid(uint32_t now", policy)
self.assertNotIn("proofIsValid(bool fresh_proof, bool wifi_connected,\n uint32_t now", policy)
def test_pull_ota_awaits_fresh_ntp_before_the_https_sequence(self):
board = source(ESP32_BOARD)
prepare = section(
board, "static bool ota_prepareTlsClock", "struct OtaHttpResponse"
)
implementation = section(
board,
"bool ESP32Board::otaFromManifestImpl",
"#else\nbool ESP32Board::otaFromManifest",
)
self.assertIn(
"ota_tls_fresh_ntp_received.store(false, std::memory_order_release)",
prepare,
)
self.assertIn("sntp_set_time_sync_notification_cb(ota_noteNtpTime)", prepare)
self.assertIn("sntp_set_sync_status(SNTP_SYNC_STATUS_RESET)", prepare)
self.assertIn('configTime(0, 0, "time.cloudflare.com"', prepare)
self.assertIn("const time_t now = time(nullptr)", prepare)
self.assertIn("ota_tlsClockProofValid()", prepare)
self.assertIn("OTA_NTP_SYNC_WAIT_MS", prepare)
self.assertNotIn("(uint32_t)time(nullptr)", prepare)
self.assertIn("OperationLease sntp_operation", prepare)
self.assertIn("processWideCoordinator()", prepare)
self.assertIn("if (!sntp_operation.tryAcquire())", prepare)
self.assertNotIn("sntp_set_time_sync_notification_cb(nullptr)", prepare)
gate = implementation.index(
"if (!dry_run && !ota_prepareTlsClock(reply))"
)
manifest_client = implementation.index("WiFiClientSecure mclient")
manifest_log = implementation.index("OTA: downloading manifest")
manifest_fetch = implementation.index(
"ota_fetchManifest(mclient, murl, true, doc, reply)"
)
self.assertLess(gate, manifest_client)
self.assertLess(gate, manifest_log)
self.assertLess(manifest_log, manifest_fetch)
self.assertIn(
"ota_openHttp(uclient, file_url, true, response, reply)",
implementation,
)
def test_every_pull_ota_tls_connect_revalidates_the_bounded_proof(self):
board = source(ESP32_BOARD)
proof = section(
board, "static bool ota_tlsClockProofValid", "static bool ota_prepareTlsClock"
)
request = section(board, "static bool ota_openHttp", "static bool ota_fetchManifest")
self.assertIn("ota_tls_fresh_ntp_received.load", proof)
self.assertIn("WiFi.status() == WL_CONNECTED", proof)
self.assertIn("time(nullptr)", proof)
self.assertIn("OTA_TLS_PROOF_MAX_AGE_MS", proof)
self.assertIn("mesh::tls_clock::proofAgeIsValid", proof)
self.assertIn("mesh::tls_clock::proofGenerationIsValid", proof)
guard = request.index("require_tls && !ota_tlsClockProofValid()")
connect = request.index("client.connect(host, port)")
self.assertLess(guard, connect)
self.assertEqual(request.count("client.connect("), 1)
def test_all_sntp_callback_owners_share_one_nonblocking_generation_lease(self):
board = source(ESP32_BOARD)
indicator = source(INDICATOR_FONT)
coordinator = source(SNTP_COORDINATOR)
self.assertIn("compare_exchange_strong", coordinator)
self.assertIn("if (!owns(generation)) return false", coordinator)
cleanup = coordinator.index("if (cleanup != nullptr) cleanup()")
publish_free = coordinator.index("expected, 0", cleanup)
self.assertLess(cleanup, publish_free)
self.assertIn("~OperationLease() { release(); }", coordinator)
for implementation, callback, cleanup_name in (
(board, "ota_noteNtpTime", "ota_clearNtpCallback"),
(indicator, "noteFontNtpTime", "clearFontNtpCallback"),
):
self.assertIn("processWideCoordinator()", implementation)
self.assertIn("OperationLease sntp_operation", implementation)
self.assertIn("processWideCoordinator().owns(generation)", implementation)
cleanup_body = section(
implementation,
f"void {cleanup_name}",
f"void {callback}",
)
self.assertIn("sntp_set_time_sync_notification_cb(nullptr)", cleanup_body)
self.assertIn(".store(0, std::memory_order_release)", cleanup_body)
def test_tls_bundle_diagnostic_rejects_an_invalid_clock_before_connect(self):
cli = source(OBSERVER_CLI)
diagnostic = section(
cli,
'if (memcmp(command, "tls.bundletest ", 15) == 0)',
'} else if (memcmp(command, "ota check", 9)',
)
signed_clock = diagnostic.index("const time_t tls_now = time(nullptr)")
gate = diagnostic.index("mesh::tls_clock::timeIsValid(tls_now)")
connect = diagnostic.index("client.connect(host, port)")
self.assertLess(signed_clock, gate)
self.assertLess(gate, connect)
def test_mqtt_clock_flag_is_not_documented_as_fresh_ntp_proof(self):
header = source(MQTT_BRIDGE)
self.assertIn("plausible retained RTC/system clock", header)
self.assertNotIn(
"True after this bridge has successfully set the RTC from NTP",
header,
)
def test_every_mqtt_sntp_mutation_is_coordinator_leased(self):
implementation = source(MQTT_BRIDGE_IMPL)
refresh = section(
implementation,
"void MQTTBridge::refreshNTP()",
"bool MQTTBridge::syncTimeWithNTP",
)
sync = section(
implementation,
"bool MQTTBridge::syncTimeWithNTP",
"bool MQTTBridge::requestForcedNtpSync",
)
self.assertIn("SntpOperationCoordinator.h", implementation)
self.assertEqual(len(re.findall(r"(?m)^\s*configTime\(", implementation)), 3)
self.assertEqual(
len(re.findall(r"(?m)^\s*sntp_set_sync_status\(", implementation)),
2,
)
self.assertEqual(
len(re.findall(r"sntp_get_sync_status\(", implementation)),
2,
)
refresh_lease = refresh.index("OperationLease sntp_operation")
refresh_acquire = refresh.index("if (!sntp_operation.tryAcquire())")
refresh_configure = refresh.index("configTime(")
self.assertLess(refresh_lease, refresh_acquire)
self.assertLess(refresh_acquire, refresh_configure)
fallback_start = sync.index(
"// Fallback: use ESP32 built-in SNTP (configTime)"
)
fallback_end = sync.index("\n #endif\n\n if (!ntp_ok) {", fallback_start)
fallback = sync[fallback_start:fallback_end]
fallback_lease = fallback.index("OperationLease sntp_operation")
fallback_acquire = fallback.index("if (!sntp_operation.tryAcquire())")
reset = fallback.index("sntp_set_sync_status(SNTP_SYNC_STATUS_RESET)")
configure = fallback.index("configTime(0, 0, server)")
completed = fallback.index(
"sntp_get_sync_status() != SNTP_SYNC_STATUS_COMPLETED"
)
self.assertLess(fallback_lease, fallback_acquire)
self.assertLess(fallback_acquire, reset)
self.assertLess(reset, configure)
self.assertLess(configure, completed)
final_rearm = section(
sync,
"if (ntp_server_used && !sntp_fallback_configured)",
"if (_rtc)",
)
final_lease = final_rearm.index("OperationLease sntp_operation")
final_acquire = final_rearm.index("if (sntp_operation.tryAcquire())")
final_configure = final_rearm.index("configTime(0, 0, ntp_server_used)")
self.assertLess(final_lease, final_acquire)
self.assertLess(final_acquire, final_configure)
self.assertIn("else if (sntp_fallback_configured)", final_rearm)
def test_mqtt_async_sntp_contention_uses_a_wrap_safe_bounded_retry(self):
header = source(MQTT_BRIDGE)
implementation = source(MQTT_BRIDGE_IMPL)
policy = source(MQTT_POLICY)
refresh = section(
implementation,
"void MQTTBridge::refreshNTP()",
"bool MQTTBridge::syncTimeWithNTP",
)
self.assertIn("unsigned long _ntp_refresh_retry_at", header)
self.assertIn("kNtpRetryMs = 5000UL", policy)
self.assertIn(
"static_cast<int32_t>(now - retry_at) >= 0", policy
)
self.assertIn("return retry_at == 0 ? 1 : retry_at", policy)
self.assertIn("kNtpRefreshIntervalMs = 86400000UL", policy)
self.assertIn(
"elapsedMs(now, last_sync) >= kNtpRefreshIntervalMs", policy
)
self.assertIn("ntpReconnectRefreshAt", policy)
self.assertEqual(
implementation.count(
"MQTTConnectionPolicy::ntpReconnectRefreshAt("
),
2,
)
self.assertGreaterEqual(implementation.count("mqttNtpRefreshDue("), 4)
busy = refresh.index("if (!sntp_operation.tryAcquire())")
retry = refresh.index("mqttNtpRetryAt(now)", busy)
leave = refresh.index("return;", retry)
configure = refresh.index(
"configTime(0, 0, effectiveNtpPrimary(_obs))"
)
self.assertLess(busy, retry)
self.assertLess(retry, leave)
self.assertLess(leave, configure)
self.assertIn("_ntp_refresh_retry_at = 0", refresh[configure:])
sync = section(
implementation,
"bool MQTTBridge::syncTimeWithNTP",
"bool MQTTBridge::requestForcedNtpSync",
)
final_rearm = section(
sync,
"if (ntp_server_used && !sntp_fallback_configured)",
"if (_rtc)",
)
self.assertIn(
"_ntp_refresh_retry_at = mqttNtpRetryAt(millis())",
final_rearm,
)
def test_mqtt_periodic_refresh_updates_rtc_only_after_sntp_completion(self):
header = source(MQTT_BRIDGE)
implementation = source(MQTT_BRIDGE_IMPL)
refresh = section(
implementation,
"void MQTTBridge::refreshNTP()",
"void MQTTBridge::pollNtpRefresh",
)
poll = section(
implementation,
"void MQTTBridge::pollNtpRefresh",
"bool MQTTBridge::syncTimeWithNTP",
)
self.assertIn("unsigned long _ntp_refresh_started_at", header)
self.assertIn("bool _ntp_refresh_pending", header)
self.assertIn("std::atomic<bool> _ntp_synced", header)
self.assertIn(
"MQTTConnectionPolicy::NtpReconnectLatch "
"_ntp_reconnect_latch",
header,
)
self.assertIn("MQTT_NTP_REFRESH_TIMEOUT_MS = 15000UL", implementation)
self.assertEqual(implementation.count("pollNtpRefresh("), 3)
self.assertGreaterEqual(
implementation.count("&& !_ntp_refresh_pending"), 2
)
reset = refresh.index("sntp_set_sync_status(SNTP_SYNC_STATUS_RESET)")
configure = refresh.index(
"configTime(0, 0, effectiveNtpPrimary(_obs))"
)
pending = refresh.index("_ntp_refresh_pending = true", configure)
self.assertLess(reset, configure)
self.assertLess(configure, pending)
self.assertNotIn("_last_ntp_sync =", refresh)
completed = poll.index("sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED")
system_clock = poll.index("time(nullptr)", completed)
valid = poll.index(
"MQTTConnectionPolicy::checkedRtcEpoch(", system_clock
)
self.assertIn("static_cast<int64_t>(raw_system_time)", poll[valid:])
rtc = poll.index("_rtc->setCurrentTime(system_time)", valid)
success = poll.index("_last_ntp_sync = now", rtc)
self.assertLess(completed, system_clock)
self.assertLess(system_clock, valid)
self.assertLess(valid, rtc)
self.assertLess(rtc, success)
self.assertEqual(poll.count("_last_ntp_sync ="), 1)
timeout = poll.index("elapsed >= MQTT_NTP_REFRESH_TIMEOUT_MS")
retry = poll.index("mqttNtpRetryAt(now)", timeout)
self.assertLess(timeout, retry)
self.assertNotIn("_last_ntp_sync =", poll[timeout:])
got_ip = section(
implementation,
"case ARDUINO_EVENT_WIFI_STA_GOT_IP:",
"case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:",
)
self.assertIn("_ntp_reconnect_latch.noteGotIp()", got_ip)
self.assertNotIn("_ntp_synced", got_ip)
self.assertNotIn("_ntp_sync_pending", got_ip)
task_loop = section(
implementation,
"void MQTTBridge::mqttTaskLoop()",
"bool MQTTBridge::isSlotReady",
)
connected = task_loop.index(
"const bool wifi_connected = WiFi.status() == WL_CONNECTED"
)
consume = task_loop.index(
"_ntp_reconnect_latch.consumeIfConnected(wifi_connected)"
)
self.assertLess(connected, consume)
begin = section(
implementation,
"void MQTTBridge::begin()",
"void MQTTBridge::end()",
)
self.assertNotIn("_ntp_reconnect_latch.", begin)
if __name__ == "__main__":
unittest.main()