Merge observer firmware and webconfig updates

# Conflicts:
#	MQTT_INTERNALS.md
#	build.sh
#	docs/cli_commands.md
#	examples/simple_repeater/MyMesh.cpp
#	examples/simple_repeater/MyMesh.h
#	examples/simple_repeater/UITask.cpp
#	examples/simple_room_server/MyMesh.cpp
#	examples/simple_room_server/MyMesh.h
#	examples/simple_room_server/UITask.cpp
#	examples/simple_sensor/SensorMesh.cpp
#	platformio.ini
#	scripts/generate_webconfig_html.py
#	src/MeshCore.h
#	src/helpers/CommonCLI.cpp
#	src/helpers/CommonCLI.h
#	src/helpers/CommonCLI_Observer.cpp
#	src/helpers/ESP32Board.h
#	src/helpers/MQTTMessageBuilder.cpp
#	src/helpers/MQTTPresets.h
#	src/helpers/NRF52Board.cpp
#	src/helpers/NRF52Board.h
#	src/helpers/bridges/MQTTBridge.cpp
#	src/helpers/bridges/MQTTBridge.h
#	src/helpers/esp32/WebConfigServer.cpp
#	src/helpers/esp32/WebConfigServer.h
#	src/helpers/radiolib/RadioLibWrappers.cpp
#	src/helpers/radiolib/RadioLibWrappers.h
#	variants/lilygo_tbeam_SX1262/platformio.ini
#	variants/lilygo_tbeam_SX1276/platformio.ini
#	variants/lilygo_tlora_v2_1/platformio.ini
#	webui/index.html
This commit is contained in:
mikecarper committed 2026-07-24 02:16:47 -07:00
commit c1caa5ad81
109 files changed
+14844 -2297

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
# Host unit tests
Fast, hardware-free unit tests for the fork's pure logic, run on the host with
GoogleTest via PlatformIO's `native` environment. They cover the extractable
observer/WebConfig logic (validation, preset table, topic templates, key
parsing) -- the parts that don't depend on the ESP32, radio, or network stack.
Integration behavior (AsyncTCP transport, WiFi/MQTT, SoftAP) is exercised
separately; see "Local testing without hardware" in `MQTT_IMPLEMENTATION.md`.
## Running
```sh
pio test -e native # all suites
pio test -e native -f test_webconfig_keys # a single suite
```
A green `[PASSED]` per suite means GoogleTest returned 0 (all assertions
passed). PlatformIO's "0 test cases" line is just its Unity-style counter and
does not reflect the GoogleTest count -- run the built binary directly
(`.pio/build/native/program`) to see the per-assertion breakdown.
## Suites
| Suite | Source under test | Covers |
|-------|-------------------|--------|
| `test_mqtt_presets` | `src/helpers/MQTTPresets.h` | preset lookup; table integrity (unique names, non-empty URLs, JWT-audience invariant, names fit the slot buffer); `mqttPresetNeedsSlotCredentials`; slot-count constants |
| `test_observer_validation` | `src/helpers/MQTTObserverValidation.h` | IATA (exactly 3 alphanumerics), owner key (64 hex), NTP hostname, and the buffer-fit check behind the #17 length validation -- including boundaries and nulls |
| `test_webconfig_keys` | `src/helpers/WebConfigKeys.h` | POST-key allowlist, secret detection, admin-password classification/validation, slot-index bounds, and the short-key out-of-bounds guard (attacker-supplied keys) |
| `test_topic_template` | `src/helpers/MQTTTopicTemplate.h` | `{iata}/{device}/{token}/{type}` expansion, overflow/NUL-termination, and a buffer-size fuzz |
| `test_mqtt_topic_router` | `src/helpers/MQTTTopicRouter.h` | complete preset/custom topic-routing contract; MeshRank packets-only behavior; required identifiers; invalid inputs/slots; exact buffer boundaries |
| `test_mqtt_connection_policy` | `src/helpers/MQTTConnectionPolicy.h` | reconnect guard/backoff/stagger and breaker transitions; stable reset; JWT lifetime/renewal policy; exact timing boundaries and 32-bit `millis()` rollover |
| `test_mqtt_packet_queue_policy` | `src/helpers/MQTTPacketQueuePolicy.h` | queue-full eviction; stale-disconnect flush; adaptive drain limits; bounded QoS0 retries; exact timing boundaries and 32-bit `millis()` rollover |
| `test_mqtt_runtime_buffer_lifecycle` | `src/helpers/MQTTRuntimeBufferLifecycle.h` | idempotent allocation/release; partial-allocation degradation; retry of only missing buffers |
| `test_mqtt_prefs_codec` | `src/helpers/MQTTPrefsStorage.h`, `src/helpers/MQTTPrefsCodec.h` | binary pre-slot/3-slot/6-slot migration fixtures; v1 header integrity; downgrade preservation |
| `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_payload_builder` | `src/helpers/MQTTPayloadBuilder.cpp` | status/packet/raw JSON contracts; optional fields; escaping; RX metrics and path; score handling; exact buffer bounds; maximum representative payloads |
| `test_utils` | `src/Utils.cpp` | `Utils::toHex` (upstream) |
## Conventions (and how to add a suite)
- Each `test/test_<name>/` directory builds into its **own** GoogleTest program
and must define its own `main()` (`::testing::InitGoogleTest` + `RUN_ALL_TESTS`).
- Tests are **host-only**: include only pure headers. Arduino/crypto stubs live
in `test/mocks/` (on the include path via `-I test/mocks`).
- Firmware headers are included from `src` (via `-I src`, e.g.
`#include "helpers/MQTTPresets.h"`). Some are guarded or ESP-flavored, so a
suite may need shims **before** the include -- e.g. `test_mqtt_presets` does
`#define WITH_MQTT_BRIDGE 1` (the preset table is behind that flag) and
`#define PROGMEM` (the embedded CA-cert strings are PROGMEM-qualified).
- To add a suite: create `test/test_<name>/test_<name>.cpp` with a `main()`, and
add any host-only source it links to the `native` env's `build_src_filter` in
`platformio.ini` (header-only code needs no source entry). No other wiring.
- Keep logic testable by extracting pure functions into headers (as
`MQTTObserverValidation.h` / `WebConfigKeys.h` / `MQTTTopicTemplate.h` do) and
having the firmware call the same functions.
@@ -0,0 +1,248 @@
#include <gtest/gtest.h>
#include <stdint.h>
#include <limits>
#include "helpers/MQTTConnectionPolicy.h"
namespace Policy = MQTTConnectionPolicy;
TEST(MQTTConnectionPolicy, ElapsedTimeHandlesNormalAndWrappedClocks) {
EXPECT_EQ(4000U, Policy::elapsedMs(5000U, 1000U));
const uint32_t before_wrap = std::numeric_limits<uint32_t>::max() - 99U;
EXPECT_EQ(150U, Policy::elapsedMs(50U, before_wrap));
}
TEST(MQTTConnectionPolicy, CrossSlotReconnectGuardHasExactBoundary) {
EXPECT_TRUE(Policy::reconnectGuardActive(14999U, 0U));
EXPECT_FALSE(Policy::reconnectGuardActive(15000U, 0U));
const uint32_t last = std::numeric_limits<uint32_t>::max() - 9999U;
EXPECT_TRUE(Policy::reconnectGuardActive(4999U, last));
EXPECT_FALSE(Policy::reconnectGuardActive(5000U, last));
}
TEST(MQTTConnectionPolicy, StableResetRequiresARealStartAndFullWindow) {
EXPECT_FALSE(Policy::stableConnection(500000U, 0U));
EXPECT_FALSE(Policy::stableConnection(120999U, 1000U));
EXPECT_TRUE(Policy::stableConnection(121000U, 1000U));
}
TEST(MQTTConnectionPolicy, StableResetWindowSurvivesMillisRollover) {
const uint32_t connected_at = std::numeric_limits<uint32_t>::max() - 59999U;
EXPECT_FALSE(Policy::stableConnection(59999U, connected_at));
EXPECT_TRUE(Policy::stableConnection(60000U, connected_at));
}
TEST(MQTTConnectionPolicy, BackoffLadderSaturatesAtFiveMinutes) {
EXPECT_EQ(10000U, Policy::reconnectBackoffMs(0));
EXPECT_EQ(30000U, Policy::reconnectBackoffMs(1));
EXPECT_EQ(60000U, Policy::reconnectBackoffMs(2));
EXPECT_EQ(120000U, Policy::reconnectBackoffMs(3));
EXPECT_EQ(300000U, Policy::reconnectBackoffMs(4));
EXPECT_EQ(300000U, Policy::reconnectBackoffMs(5));
EXPECT_EQ(300000U, Policy::reconnectBackoffMs(255));
}
TEST(MQTTConnectionPolicy, LaterSlotsReceiveThreeSecondStagger) {
EXPECT_EQ(10000U, Policy::reconnectDelayMs(0, 0));
EXPECT_EQ(13000U, Policy::reconnectDelayMs(0, 1));
EXPECT_EQ(315000U, Policy::reconnectDelayMs(5, 5));
}
TEST(MQTTConnectionPolicy, ReconnectDueUsesDelayBoundaryAndWrapSafeElapsedTime) {
EXPECT_FALSE(Policy::reconnectDue(12999U, 0U, 0, 1));
EXPECT_TRUE(Policy::reconnectDue(13000U, 0U, 0, 1));
const uint32_t last = std::numeric_limits<uint32_t>::max() - 4999U;
EXPECT_FALSE(Policy::reconnectDue(4999U, last, 0, 0));
EXPECT_TRUE(Policy::reconnectDue(5000U, last, 0, 0));
}
TEST(MQTTConnectionPolicy, BackoffAdvanceClimbsThenCountsFailuresAtMaximum) {
Policy::BackoffAdvance first = Policy::advanceBackoff(0, 0);
EXPECT_EQ(1, first.reconnect_backoff);
EXPECT_EQ(0, first.max_backoff_failures);
EXPECT_FALSE(first.circuit_breaker_tripped);
EXPECT_TRUE(first.should_reconnect);
Policy::BackoffAdvance enters_maximum = Policy::advanceBackoff(4, 0);
EXPECT_EQ(5, enters_maximum.reconnect_backoff);
EXPECT_EQ(0, enters_maximum.max_backoff_failures);
EXPECT_FALSE(enters_maximum.circuit_breaker_tripped);
EXPECT_TRUE(enters_maximum.should_reconnect);
Policy::BackoffAdvance first_max_failure = Policy::advanceBackoff(5, 0);
EXPECT_EQ(5, first_max_failure.reconnect_backoff);
EXPECT_EQ(1, first_max_failure.max_backoff_failures);
EXPECT_FALSE(first_max_failure.circuit_breaker_tripped);
EXPECT_TRUE(first_max_failure.should_reconnect);
}
TEST(MQTTConnectionPolicy, ThirdFailureAtMaximumTripsWithoutAnotherHandshake) {
Policy::BackoffAdvance result = Policy::advanceBackoff(5, 2);
EXPECT_EQ(5, result.reconnect_backoff);
EXPECT_EQ(3, result.max_backoff_failures);
EXPECT_TRUE(result.circuit_breaker_tripped);
EXPECT_FALSE(result.should_reconnect);
}
TEST(MQTTConnectionPolicy, CircuitBreakerProbeHasExactThirtyMinuteBoundary) {
EXPECT_FALSE(Policy::circuitBreakerProbeDue(1799999U, 0U));
EXPECT_TRUE(Policy::circuitBreakerProbeDue(1800000U, 0U));
const uint32_t last = std::numeric_limits<uint32_t>::max() - 899999U;
EXPECT_FALSE(Policy::circuitBreakerProbeDue(899999U, last));
EXPECT_TRUE(Policy::circuitBreakerProbeDue(900000U, last));
}
TEST(MQTTConnectionPolicy, JwtLifetimeUsesCappedPerSlotStagger) {
EXPECT_EQ(86400U, Policy::jwtLifetimeSecs(86400U, 0));
EXPECT_EQ(86100U, Policy::jwtLifetimeSecs(86400U, 1));
EXPECT_EQ(84900U, Policy::jwtLifetimeSecs(86400U, 5));
}
TEST(MQTTConnectionPolicy, ShortJwtLifetimeUsesFivePercentPerSlot) {
EXPECT_EQ(3300U, Policy::jwtLifetimeSecs(3300U, 0));
EXPECT_EQ(3135U, Policy::jwtLifetimeSecs(3300U, 1));
EXPECT_EQ(2970U, Policy::jwtLifetimeSecs(3300U, 2));
EXPECT_EQ(85U, Policy::jwtLifetimeSecs(100U, 3));
}
TEST(MQTTConnectionPolicy, JwtLifetimeCannotUnderflowForUnexpectedSlotInput) {
EXPECT_EQ(0U, Policy::jwtLifetimeSecs(100U, 255));
}
TEST(MQTTConnectionPolicy, RenewalBufferHasOneMinuteFloorAndFiveMinuteCap) {
EXPECT_EQ(60U, Policy::renewalBufferSecs(0U));
EXPECT_EQ(60U, Policy::renewalBufferSecs(599U));
EXPECT_EQ(60U, Policy::renewalBufferSecs(600U));
EXPECT_EQ(299U, Policy::renewalBufferSecs(2999U));
EXPECT_EQ(300U, Policy::renewalBufferSecs(3000U));
EXPECT_EQ(300U, Policy::renewalBufferSecs(86400U));
}
TEST(MQTTConnectionPolicy, UnsynchronizedClockOnlyCreatesAMissingToken) {
EXPECT_TRUE(Policy::tokenNeedsRenewal(false, 0U, 0U, 300U));
EXPECT_FALSE(Policy::tokenNeedsRenewal(false, 0U, 1735693200U, 300U));
}
TEST(MQTTConnectionPolicy, SyncedClockRenewsInvalidExpiredOrImminentTokens) {
const uint32_t expires = 1735693200U;
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, 1735689000U, 0U, 300U));
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, 1735689000U, 999999999U, 300U));
EXPECT_FALSE(Policy::tokenNeedsRenewal(true, expires - 301U, expires, 300U));
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, expires - 300U, expires, 300U));
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, expires, expires, 300U));
EXPECT_TRUE(Policy::tokenNeedsRenewal(true, expires + 1U, expires, 300U));
}
TEST(MQTTConnectionPolicy, RenewalThrottleHasExactBoundaryAndHandlesRollover) {
EXPECT_FALSE(Policy::renewalAttemptAllowed(59999U, 0U));
EXPECT_TRUE(Policy::renewalAttemptAllowed(60000U, 0U));
const uint32_t last = std::numeric_limits<uint32_t>::max() - 29999U;
EXPECT_FALSE(Policy::renewalAttemptAllowed(29999U, last));
EXPECT_TRUE(Policy::renewalAttemptAllowed(30000U, last));
}
TEST(MQTTConnectionPolicy, JwtClockNeedsNtpOrAReasonableWallClock) {
EXPECT_FALSE(Policy::jwtClockAvailable(false, Policy::kJwtClockThreshold - 1U));
EXPECT_TRUE(Policy::jwtClockAvailable(false, Policy::kJwtClockThreshold));
EXPECT_TRUE(Policy::jwtClockAvailable(true, 0U));
}
TEST(MQTTConnectionPolicy, WifiBackoffLadderStartsAtFifteenSecondsAndSaturates) {
EXPECT_EQ(15000U, Policy::wifiReconnectBackoffMs(0));
EXPECT_EQ(30000U, Policy::wifiReconnectBackoffMs(1));
EXPECT_EQ(60000U, Policy::wifiReconnectBackoffMs(2));
EXPECT_EQ(120000U, Policy::wifiReconnectBackoffMs(3));
EXPECT_EQ(300000U, Policy::wifiReconnectBackoffMs(4));
// Clamps at the 300 s rung for the saturated attempt count and beyond.
EXPECT_EQ(300000U, Policy::wifiReconnectBackoffMs(5));
EXPECT_EQ(300000U, Policy::wifiReconnectBackoffMs(200));
}
TEST(MQTTConnectionPolicy, WifiBackoffAttemptClimbsThenSaturatesAtFive) {
uint8_t attempt = 0;
for (uint8_t expected = 1; expected <= 5; ++expected) {
attempt = Policy::nextWifiBackoffAttempt(attempt);
EXPECT_EQ(expected, attempt);
}
// Saturated: never advances past 5 (index stays clamped at the 300 s rung).
EXPECT_EQ(5U, Policy::nextWifiBackoffAttempt(attempt));
EXPECT_EQ(5U, Policy::nextWifiBackoffAttempt(5));
}
TEST(MQTTConnectionPolicy, WifiReconnectRequiresBothDownAndSinceAttemptToClearRung) {
const uint32_t down_since = 1000U;
const uint32_t last_attempt = 1000U;
const uint8_t attempt = 0; // 15 s rung
// Neither interval has elapsed yet.
EXPECT_FALSE(Policy::wifiReconnectDue(1000U + 14999U, down_since, last_attempt, attempt));
// Down long enough, but an attempt was made only 5 s ago (since-attempt short).
EXPECT_FALSE(Policy::wifiReconnectDue(1000U + 15000U, down_since, 1000U + 10000U, attempt));
// Both cleared at the exact boundary: due.
EXPECT_TRUE(Policy::wifiReconnectDue(1000U + 15000U, down_since, last_attempt, attempt));
}
TEST(MQTTConnectionPolicy, WifiReconnectDueSurvivesMillisRollover) {
const uint32_t down_since = std::numeric_limits<uint32_t>::max() - 100U;
const uint32_t last_attempt = down_since;
const uint8_t attempt = 0; // 15 s rung
const uint32_t now = down_since + 15000U; // wraps past zero
EXPECT_TRUE(Policy::wifiReconnectDue(now, down_since, last_attempt, attempt));
EXPECT_FALSE(Policy::wifiReconnectDue(down_since + 14999U, down_since, last_attempt, attempt));
}
// --- classifySlotActivation: the "will this slot connect on this hardware" rule
// the CLI uses to warn at `set mqttN.preset` time. Non-PSRAM Heltec V3 is the
// motivating case: RUNTIME_MQTT_SLOTS=3 but only 2 concurrent connections. ---
using Policy::SlotActivation;
TEST(SlotActivation, NonPsramV3FirstTwoConnectThirdIsOverCap) {
// slot_count = 3 (runtime array), max_active = 2 (concurrent cap).
const bool enabled[6] = {true, true, true, false, false, false};
EXPECT_EQ(SlotActivation::Connects, Policy::classifySlotActivation(0, enabled, 3, 2));
EXPECT_EQ(SlotActivation::Connects, Policy::classifySlotActivation(1, enabled, 3, 2));
// slot 3 (index 2) is the case in the field log: iterated, but skipped.
EXPECT_EQ(SlotActivation::OverActiveCap, Policy::classifySlotActivation(2, enabled, 3, 2));
}
TEST(SlotActivation, NonPsramSlotsBeyondRuntimeArrayAreNeverIterated) {
const bool enabled[6] = {true, true, true, true, false, false};
// mqtt4/5/6 (index 3-5) are outside the 3-slot runtime array on non-PSRAM.
EXPECT_EQ(SlotActivation::BeyondArray, Policy::classifySlotActivation(3, enabled, 3, 2));
EXPECT_EQ(SlotActivation::BeyondArray, Policy::classifySlotActivation(5, enabled, 3, 2));
}
TEST(SlotActivation, RankCountsOnlyEnabledLowerSlots) {
// Only slot index 2 enabled (1 and 2 disabled): it is the first enabled slot,
// so it connects even though its index equals the cap.
const bool enabled[6] = {false, false, true, false, false, false};
EXPECT_EQ(SlotActivation::Connects, Policy::classifySlotActivation(2, enabled, 3, 2));
// Gap in the middle: slots 0 and 2 enabled, slot 1 off. Slot 2 is rank 2 <= 2.
const bool enabled2[6] = {true, false, true, false, false, false};
EXPECT_EQ(SlotActivation::Connects, Policy::classifySlotActivation(2, enabled2, 3, 2));
}
TEST(SlotActivation, PsramFiveOfSixConnect) {
// PSRAM: slot_count = 6, max_active = 5. Sixth enabled slot is over the cap.
const bool enabled[6] = {true, true, true, true, true, true};
EXPECT_EQ(SlotActivation::Connects, Policy::classifySlotActivation(4, enabled, 6, 5));
EXPECT_EQ(SlotActivation::OverActiveCap, Policy::classifySlotActivation(5, enabled, 6, 5));
}
TEST(SlotActivation, DisabledAndOutOfRangeSlots) {
const bool enabled[6] = {true, false, true, false, false, false};
EXPECT_EQ(SlotActivation::Disabled, Policy::classifySlotActivation(1, enabled, 3, 2));
EXPECT_EQ(SlotActivation::Disabled, Policy::classifySlotActivation(-1, enabled, 3, 2));
EXPECT_EQ(SlotActivation::Disabled, Policy::classifySlotActivation(0, nullptr, 3, 2));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,450 @@
#include <gtest/gtest.h>
#include <string>
#include <vector>
#include "helpers/MQTTLifecycle.h"
// Phase 4 teardown-focused test seam for the MQTT bridge lifecycle. Every case
// below maps to a bullet in STABILITY_TESTABILITY_HANDOFF.md's "Required
// teardown-focused tests" list or its "OTA Teardown Barrier" scenarios. The
// behavior encoded here is derived from the current MQTTBridge control flow
// (Phase 0 "derive from code + flag" discipline); it is the contract Phase 5
// must preserve when it wires the real bridge into MQTTLifecycle::Coordinator.
namespace L = MQTTLifecycle;
namespace {
// Recording Ops double with a settable clock and an ordered call log.
struct FakeOps : public L::Ops {
uint32_t now = 0;
int start_task_calls = 0;
int deliver_stop_calls = 0;
int release_calls = 0;
int stop_complete_calls = 0;
bool last_stop_clean = false;
std::vector<std::string> log;
uint32_t nowMs() override { return now; }
void startTask() override {
start_task_calls++;
log.push_back("startTask");
}
void deliverStop() override {
deliver_stop_calls++;
log.push_back("deliverStop");
}
void releaseResources() override {
release_calls++;
log.push_back("release");
}
void onStopComplete(bool clean) override {
stop_complete_calls++;
last_stop_clean = clean;
log.push_back(clean ? "otaClean" : "otaDirty");
}
};
const uint32_t kStopTimeoutMs = 5000;
void bringUpToRunning(L::Coordinator& c) {
ASSERT_TRUE(c.requestStart());
ASSERT_EQ(L::State::Starting, c.state());
ASSERT_TRUE(c.onTaskStarted());
ASSERT_EQ(L::State::Running, c.state());
}
} // namespace
// --- Normal ordering -------------------------------------------------------
// Handoff Phase 0: "Normal begin() -> connect -> end() ordering."
TEST(MQTTLifecycle, NormalStartRunStopCycle) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
EXPECT_EQ(L::State::Stopped, c.state());
ASSERT_TRUE(c.requestStart());
EXPECT_EQ(L::State::Starting, c.state());
ASSERT_TRUE(c.onTaskStarted());
EXPECT_EQ(L::State::Running, c.state());
ASSERT_TRUE(c.requestStop());
EXPECT_EQ(L::State::StopRequested, c.state());
ASSERT_TRUE(c.onTaskStopped());
EXPECT_EQ(L::State::Stopped, c.state());
// create_task, then deliver_stop, then a single post-ack resource release
// and a clean OTA-barrier signal -- in that order.
const std::vector<std::string> expected = {"startTask", "deliverStop",
"release", "otaClean"};
EXPECT_EQ(expected, ops.log);
EXPECT_EQ(1, ops.start_task_calls);
EXPECT_EQ(1, ops.deliver_stop_calls);
EXPECT_EQ(1, ops.release_calls);
EXPECT_TRUE(ops.last_stop_clean);
}
// --- Idempotency: "Duplicate stop", "Idempotent start and stop requests" ---
TEST(MQTTLifecycle, StartIsIdempotent) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
ASSERT_TRUE(c.requestStart());
// Second start while Starting is a no-op -- no extra task creation.
EXPECT_FALSE(c.requestStart());
ASSERT_TRUE(c.onTaskStarted());
// And a no-op while Running.
EXPECT_FALSE(c.requestStart());
EXPECT_EQ(1, ops.start_task_calls);
}
TEST(MQTTLifecycle, DuplicateStopIsIdempotent) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ASSERT_TRUE(c.requestStop());
// Duplicate stop requests do not re-deliver the stop.
EXPECT_FALSE(c.requestStop());
EXPECT_FALSE(c.requestStop());
EXPECT_EQ(1, ops.deliver_stop_calls);
ASSERT_TRUE(c.onTaskStopped());
// A stop while already Stopped is also a no-op.
EXPECT_FALSE(c.requestStop());
EXPECT_EQ(1, ops.release_calls);
}
// --- Partial / early lifecycle --------------------------------------------
// Handoff: "stop before full initialization".
TEST(MQTTLifecycle, StopBeforeFullInitialization) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
ASSERT_TRUE(c.requestStart());
EXPECT_EQ(L::State::Starting, c.state());
// Stop arrives before StartCompleted.
ASSERT_TRUE(c.requestStop());
EXPECT_EQ(L::State::StopRequested, c.state());
EXPECT_EQ(1, ops.deliver_stop_calls);
// No resources released until the task acknowledges.
EXPECT_EQ(0, ops.release_calls);
ASSERT_TRUE(c.onTaskStopped());
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_EQ(1, ops.release_calls);
}
// Handoff Phase 2/Phase 0: "Partial initialization failures ... releases only
// resources owned by that attempt." The rollback releases, but no OTA-barrier
// completion is signalled for a failed start.
TEST(MQTTLifecycle, StartFailureRollsBackResources) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
ASSERT_TRUE(c.requestStart());
ASSERT_TRUE(c.onTaskStartFailed());
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_EQ(1, ops.release_calls);
EXPECT_EQ(0, ops.stop_complete_calls);
// Recoverable: a subsequent start is accepted.
EXPECT_TRUE(c.mayRestart());
EXPECT_TRUE(c.requestStart());
EXPECT_EQ(2, ops.start_task_calls);
}
// Handoff: "restart after stop".
TEST(MQTTLifecycle, RestartAfterStop) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ASSERT_TRUE(c.requestStop());
ASSERT_TRUE(c.onTaskStopped());
EXPECT_TRUE(c.mayRestart());
ASSERT_TRUE(c.requestStart());
EXPECT_EQ(L::State::Starting, c.state());
ASSERT_TRUE(c.onTaskStarted());
EXPECT_EQ(L::State::Running, c.state());
EXPECT_EQ(2, ops.start_task_calls);
}
// --- Timeout / fallback ----------------------------------------------------
// Handoff: "Timeout/fallback behavior when the MQTT task or client does not
// acknowledge." Models the reviewed fallback replacing the abrupt vTaskDelete.
TEST(MQTTLifecycle, StopTimeoutFiresReviewedFallback) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ops.now = 1000;
ASSERT_TRUE(c.requestStop());
EXPECT_EQ(L::State::StopRequested, c.state());
// Before the deadline, tick() is inert.
ops.now = 1000 + kStopTimeoutMs - 1;
c.tick();
EXPECT_EQ(L::State::StopRequested, c.state());
EXPECT_EQ(0, ops.release_calls);
// At the deadline the fallback fires: forced release, dirty OTA signal.
ops.now = 1000 + kStopTimeoutMs;
c.tick();
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_TRUE(c.stopTimedOut());
EXPECT_EQ(1, ops.release_calls);
EXPECT_EQ(1, ops.stop_complete_calls);
EXPECT_FALSE(ops.last_stop_clean);
// A late ack after the fallback does not double-release.
EXPECT_FALSE(c.onTaskStopped());
EXPECT_EQ(1, ops.release_calls);
}
TEST(MQTTLifecycle, TickWithoutPendingStopIsNoop) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ops.now = 1'000'000; // far past any deadline
c.tick();
EXPECT_EQ(L::State::Running, c.state());
EXPECT_EQ(0, ops.release_calls);
}
TEST(MQTTLifecycle, AckBeforeTimeoutPreemptsFallback) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ops.now = 100;
ASSERT_TRUE(c.requestStop());
ops.now = 100 + kStopTimeoutMs / 2;
ASSERT_TRUE(c.onTaskStopped());
EXPECT_TRUE(ops.last_stop_clean);
EXPECT_FALSE(c.stopTimedOut());
// A later tick past the original deadline must not fire a second time.
ops.now = 100 + kStopTimeoutMs * 10;
c.tick();
EXPECT_EQ(1, ops.release_calls);
EXPECT_EQ(1, ops.stop_complete_calls);
}
// --- Ownership: no access after release ------------------------------------
// Handoff: "No client, queue, buffer, or task access after its owner releases
// it," and "A completion acknowledgment before the loop task releases queues,
// buffers, or other shared resources."
TEST(MQTTLifecycle, ResourcesReleasedOnlyAfterAcknowledgment) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
EXPECT_TRUE(c.mayTouchOwnedState());
ASSERT_TRUE(c.requestStop());
// Still safe to touch owned state -- resources are not yet released.
EXPECT_TRUE(c.mayTouchOwnedState());
EXPECT_EQ(0, ops.release_calls);
ASSERT_TRUE(c.onStopBegan());
EXPECT_EQ(L::State::Stopping, c.state());
EXPECT_TRUE(c.mayTouchOwnedState());
EXPECT_EQ(0, ops.release_calls);
ASSERT_TRUE(c.onTaskStopped());
// Owner has released; nothing may touch owned state now.
EXPECT_FALSE(c.mayTouchOwnedState());
EXPECT_EQ(1, ops.release_calls);
}
// Handoff: "Cessation of new connects, publishes, retries, and
// reconfigurations" once a stop is requested.
TEST(MQTTLifecycle, NewWorkCeasesOnceStopRequested) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
EXPECT_FALSE(c.acceptsNewWork()); // Stopped
ASSERT_TRUE(c.requestStart());
EXPECT_TRUE(c.acceptsNewWork()); // Starting
ASSERT_TRUE(c.onTaskStarted());
EXPECT_TRUE(c.acceptsNewWork()); // Running
ASSERT_TRUE(c.requestStop());
EXPECT_FALSE(c.acceptsNewWork()); // StopRequested
ASSERT_TRUE(c.onStopBegan());
EXPECT_FALSE(c.acceptsNewWork()); // Stopping
ASSERT_TRUE(c.onTaskStopped());
EXPECT_FALSE(c.acceptsNewWork()); // Stopped
}
// --- Stop while doing X (the activity matrix) ------------------------------
// Handoff: "Stop while connecting, connected, publishing, retrying, renewing a
// token, running NTP, and applying a slot change." Each activity resolves to
// the same ownership contract: the stop is delivered, new work ceases, and
// resources survive until the task acknowledges. "connecting" happens during
// Starting (before StartCompleted); the rest are Running-state activities.
TEST(MQTTLifecycle, StopDuringEveryActivityHonorsTheContract) {
struct Activity {
const char* label;
bool running; // true => Running-state activity, false => Starting
};
const Activity activities[] = {
{"connecting", false}, {"connected", true},
{"publishing", true}, {"retrying", true},
{"renewingToken", true}, {"runningNtp", true},
{"applyingSlotChange", true},
};
for (const auto& a : activities) {
SCOPED_TRACE(a.label);
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
ASSERT_TRUE(c.requestStart());
if (a.running) {
ASSERT_TRUE(c.onTaskStarted());
ASSERT_EQ(L::State::Running, c.state());
} else {
ASSERT_EQ(L::State::Starting, c.state());
}
ASSERT_TRUE(c.requestStop());
EXPECT_EQ(1, ops.deliver_stop_calls);
EXPECT_FALSE(c.acceptsNewWork());
EXPECT_EQ(0, ops.release_calls); // not until ack
ASSERT_TRUE(c.onTaskStopped());
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_EQ(1, ops.release_calls);
EXPECT_TRUE(ops.last_stop_clean);
}
}
// --- Callback delivery timing ----------------------------------------------
// Handoff: "Callback delivered before stop, during stop, after disconnect, and
// after the stop acknowledgment." A callback consults mayTouchOwnedState()
// before touching owned state; only the post-acknowledgment callback is a
// no-op. ("after disconnect" is modeled as StopBegan -> Stopping, i.e. the
// task tearing the client down.)
TEST(MQTTLifecycle, CallbackGuardTracksResourceOwnership) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
EXPECT_TRUE(c.mayTouchOwnedState()); // callback before stop
ASSERT_TRUE(c.requestStop());
EXPECT_TRUE(c.mayTouchOwnedState()); // callback during stop (pre-teardown)
ASSERT_TRUE(c.onStopBegan());
EXPECT_TRUE(c.mayTouchOwnedState()); // callback after disconnect begins
ASSERT_TRUE(c.onTaskStopped());
EXPECT_FALSE(c.mayTouchOwnedState()); // callback after stop-ack => no-op
}
// --- OTA teardown barrier (release-critical) -------------------------------
// Handoff OTA barrier: "firmware erase/write must not begin until MQTT shutdown
// has reached a safe acknowledgment point."
TEST(MQTTLifecycle, OtaFlashBlockedUntilCleanStopAcknowledged) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
EXPECT_FALSE(c.mayBeginFlash()); // Running
ASSERT_TRUE(c.requestStop());
EXPECT_FALSE(c.mayBeginFlash()); // StopRequested -- not yet safe
ASSERT_TRUE(c.onStopBegan());
EXPECT_FALSE(c.mayBeginFlash()); // Stopping -- still not safe
ASSERT_TRUE(c.onTaskStopped());
EXPECT_TRUE(c.mayBeginFlash()); // clean stop => flashing permitted
EXPECT_TRUE(ops.last_stop_clean);
}
// Handoff OTA barrier: "MQTT stop times out: OTA aborts safely rather than
// writing under uncertain ownership."
TEST(MQTTLifecycle, OtaAbortsWhenStopTimesOut) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ops.now = 500;
ASSERT_TRUE(c.requestStop());
ops.now = 500 + kStopTimeoutMs;
c.tick();
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_FALSE(c.mayBeginFlash()); // dirty stop => flashing withheld
EXPECT_FALSE(ops.last_stop_clean);
// A fresh clean start/stop cycle clears the latch and re-enables flashing.
ASSERT_TRUE(c.requestStart());
EXPECT_FALSE(c.stopTimedOut());
ASSERT_TRUE(c.onTaskStarted());
ASSERT_TRUE(c.requestStop());
ASSERT_TRUE(c.onTaskStopped());
EXPECT_TRUE(c.mayBeginFlash());
}
// Handoff OTA barrier: "the bridge must not be restarted while flash writing is
// active" -- expressed here as: no restart while a stop is in progress.
TEST(MQTTLifecycle, NoRestartWhileStopInProgress) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
bringUpToRunning(c);
ASSERT_TRUE(c.requestStop());
EXPECT_FALSE(c.mayRestart());
EXPECT_FALSE(c.requestStart()); // rejected while StopRequested
ASSERT_TRUE(c.onStopBegan());
EXPECT_FALSE(c.mayRestart());
EXPECT_FALSE(c.requestStart()); // rejected while Stopping
ASSERT_TRUE(c.onTaskStopped());
EXPECT_TRUE(c.mayRestart());
EXPECT_TRUE(c.requestStart());
}
// Handoff OTA barrier: "Repeated failed OTA attempts do not ... leave the
// bridge permanently stopped."
TEST(MQTTLifecycle, RepeatedFailedStopsLeaveBridgeRestartable) {
FakeOps ops;
L::Coordinator c(ops, kStopTimeoutMs);
for (int attempt = 0; attempt < 3; ++attempt) {
SCOPED_TRACE(attempt);
ASSERT_TRUE(c.requestStart());
ASSERT_TRUE(c.onTaskStarted());
ops.now += 1000;
ASSERT_TRUE(c.requestStop());
ops.now += kStopTimeoutMs;
c.tick(); // times out (dirty)
EXPECT_EQ(L::State::Stopped, c.state());
EXPECT_TRUE(c.mayRestart()); // never permanently stuck
}
EXPECT_EQ(3, ops.start_task_calls);
}
// --- Diagnostics -----------------------------------------------------------
TEST(MQTTLifecycle, StateAndEventNamesAreStable) {
EXPECT_STREQ("Stopped", L::stateName(L::State::Stopped));
EXPECT_STREQ("Running", L::stateName(L::State::Running));
EXPECT_STREQ("StopRequested", L::stateName(L::State::StopRequested));
EXPECT_STREQ("StartRequested", L::eventName(L::Event::StartRequested));
EXPECT_STREQ("StopTimedOut", L::eventName(L::Event::StopTimedOut));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,180 @@
#include <gtest/gtest.h>
#include <stdint.h>
#include "helpers/MQTTPacketQueuePolicy.h"
namespace QueuePolicy = MQTTPacketQueuePolicy;
TEST(MQTTPacketQueuePolicy, EnqueuesWhileCapacityRemains) {
EXPECT_EQ(QueuePolicy::EnqueueAction::Enqueue,
QueuePolicy::enqueueAction(0, 6));
EXPECT_EQ(QueuePolicy::EnqueueAction::Enqueue,
QueuePolicy::enqueueAction(5, 6));
}
TEST(MQTTPacketQueuePolicy, EvictsOldestAtOrAboveCapacity) {
EXPECT_EQ(QueuePolicy::EnqueueAction::EvictOldestThenEnqueue,
QueuePolicy::enqueueAction(6, 6));
EXPECT_EQ(QueuePolicy::EnqueueAction::EvictOldestThenEnqueue,
QueuePolicy::enqueueAction(7, 6));
}
TEST(MQTTPacketQueuePolicy, RejectsQueueWithZeroCapacity) {
EXPECT_EQ(QueuePolicy::EnqueueAction::Reject,
QueuePolicy::enqueueAction(0, 0));
}
TEST(MQTTPacketQueuePolicy, DisconnectedQueueFlushesAtExactStaleBoundary) {
const uint32_t started = 1000;
EXPECT_FALSE(QueuePolicy::shouldFlushDisconnected(
started + QueuePolicy::kDisconnectedStaleMs - 1, started));
EXPECT_TRUE(QueuePolicy::shouldFlushDisconnected(
started + QueuePolicy::kDisconnectedStaleMs, started));
EXPECT_TRUE(QueuePolicy::shouldFlushDisconnected(
started + QueuePolicy::kDisconnectedStaleMs + 1, started));
}
TEST(MQTTPacketQueuePolicy, ZeroDisconnectedTimestampMeansNotStarted) {
EXPECT_FALSE(QueuePolicy::shouldFlushDisconnected(UINT32_MAX, 0));
}
TEST(MQTTPacketQueuePolicy, DisconnectedStaleTimerSurvivesMillisWrap) {
const uint32_t started = UINT32_MAX - 100;
EXPECT_FALSE(QueuePolicy::shouldFlushDisconnected(198, started, 300));
EXPECT_TRUE(QueuePolicy::shouldFlushDisconnected(199, started, 300));
}
TEST(MQTTPacketQueuePolicy, DrainIsGentleThroughFivePackets) {
for (size_t count = 0; count <= QueuePolicy::kBacklogThreshold; ++count) {
const QueuePolicy::DrainBudget budget = QueuePolicy::drainBudget(count);
EXPECT_EQ(QueuePolicy::kGentleDrainCount, budget.max_packets) << count;
EXPECT_EQ(QueuePolicy::kGentleDrainBudgetMs, budget.max_time_ms) << count;
}
}
TEST(MQTTPacketQueuePolicy, DrainBurstsAboveFivePackets) {
const QueuePolicy::DrainBudget budget =
QueuePolicy::drainBudget(QueuePolicy::kBacklogThreshold + 1);
EXPECT_EQ(QueuePolicy::kBurstDrainCount, budget.max_packets);
EXPECT_EQ(QueuePolicy::kBurstDrainBudgetMs, budget.max_time_ms);
}
TEST(MQTTPacketQueuePolicy, DrainTimeBudgetUsesInclusiveBoundary) {
EXPECT_TRUE(QueuePolicy::drainTimeAvailable(129, 100, 30));
EXPECT_TRUE(QueuePolicy::drainTimeAvailable(130, 100, 30));
EXPECT_FALSE(QueuePolicy::drainTimeAvailable(131, 100, 30));
}
TEST(MQTTPacketQueuePolicy, DrainTimeBudgetSurvivesMillisWrap) {
const uint32_t started = UINT32_MAX - 10;
EXPECT_TRUE(QueuePolicy::drainTimeAvailable(19, started, 30));
EXPECT_FALSE(QueuePolicy::drainTimeAvailable(20, started, 30));
}
TEST(MQTTPacketQueuePolicy, NewPacketIsReadyWithoutRetryDeadline) {
EXPECT_TRUE(QueuePolicy::retryReady(100, 0, 0));
EXPECT_TRUE(QueuePolicy::retryReady(100, 500, 0));
}
TEST(MQTTPacketQueuePolicy, RetryBecomesReadyAtExactDeadline) {
EXPECT_FALSE(QueuePolicy::retryReady(499, 500, 1));
EXPECT_TRUE(QueuePolicy::retryReady(500, 500, 1));
EXPECT_TRUE(QueuePolicy::retryReady(501, 500, 1));
}
TEST(MQTTPacketQueuePolicy, RetryDeadlineSurvivesMillisWrap) {
const uint32_t deadline = 100;
EXPECT_FALSE(QueuePolicy::retryReady(UINT32_MAX - 50, deadline, 1));
EXPECT_FALSE(QueuePolicy::retryReady(99, deadline, 1));
EXPECT_TRUE(QueuePolicy::retryReady(100, deadline, 1));
}
TEST(MQTTPacketQueuePolicy, WrappedZeroIsARealRetryDeadline) {
EXPECT_FALSE(QueuePolicy::retryReady(UINT32_MAX, 0, 1));
EXPECT_TRUE(QueuePolicy::retryReady(0, 0, 1));
}
TEST(MQTTPacketQueuePolicy, SuccessfulPublishCompletesWithoutChangingAttempts) {
const QueuePolicy::RetryDecision decision =
QueuePolicy::retryDecision(true, 2, 1234);
EXPECT_EQ(QueuePolicy::RetryAction::Complete, decision.action);
EXPECT_EQ(2, decision.retry_attempts);
EXPECT_EQ(0U, decision.delay_ms);
EXPECT_EQ(0U, decision.next_retry_ms);
}
TEST(MQTTPacketQueuePolicy, FailedPublishSchedulesBoundedRetry) {
const QueuePolicy::RetryDecision minimum =
QueuePolicy::retryDecision(false, 0, 400);
EXPECT_EQ(QueuePolicy::RetryAction::Schedule, minimum.action);
EXPECT_EQ(1, minimum.retry_attempts);
EXPECT_EQ(300U, minimum.delay_ms);
EXPECT_EQ(700U, minimum.next_retry_ms);
const QueuePolicy::RetryDecision maximum =
QueuePolicy::retryDecision(false, 1, 599);
EXPECT_EQ(QueuePolicy::RetryAction::Schedule, maximum.action);
EXPECT_EQ(2, maximum.retry_attempts);
EXPECT_EQ(499U, maximum.delay_ms);
EXPECT_EQ(1098U, maximum.next_retry_ms);
}
TEST(MQTTPacketQueuePolicy, ThirdFailedPublishSchedulesFinalRetry) {
const QueuePolicy::RetryDecision decision =
QueuePolicy::retryDecision(false, 2, 1000);
EXPECT_EQ(QueuePolicy::RetryAction::Schedule, decision.action);
EXPECT_EQ(QueuePolicy::kMaxQos0RetryAttempts, decision.retry_attempts);
}
TEST(MQTTPacketQueuePolicy, FailureAfterFinalRetryDropsPacket) {
const QueuePolicy::RetryDecision decision =
QueuePolicy::retryDecision(false, QueuePolicy::kMaxQos0RetryAttempts, 1000);
EXPECT_EQ(QueuePolicy::RetryAction::Drop, decision.action);
EXPECT_EQ(QueuePolicy::kMaxQos0RetryAttempts, decision.retry_attempts);
EXPECT_EQ(0U, decision.delay_ms);
EXPECT_EQ(0U, decision.next_retry_ms);
}
TEST(MQTTPacketQueuePolicy, RetrySchedulingDeadlineMayWrapToZero) {
// This timestamp has jitter 98, so its 398 ms delay wraps to exactly zero.
const uint32_t now = UINT32_MAX - 397;
ASSERT_EQ(98U, now % QueuePolicy::kRetryDelayJitterMs);
const QueuePolicy::RetryDecision decision =
QueuePolicy::retryDecision(false, 0, now);
EXPECT_EQ(QueuePolicy::RetryAction::Schedule, decision.action);
EXPECT_EQ(398U, decision.delay_ms);
EXPECT_EQ(0U, decision.next_retry_ms);
EXPECT_FALSE(QueuePolicy::retryReady(UINT32_MAX, decision.next_retry_ms,
decision.retry_attempts));
EXPECT_TRUE(QueuePolicy::retryReady(0, decision.next_retry_ms,
decision.retry_attempts));
}
TEST(MQTTPacketQueuePolicy, PartialPublishCountsAsDeliveredEitherWay) {
EXPECT_TRUE(QueuePolicy::queuedPacketPublished(true, true));
EXPECT_TRUE(QueuePolicy::queuedPacketPublished(true, false)); // packet ok, raw failed
EXPECT_TRUE(QueuePolicy::queuedPacketPublished(false, true)); // raw ok, packet failed
EXPECT_FALSE(QueuePolicy::queuedPacketPublished(false, false)); // neither reached a slot
}
TEST(MQTTPacketQueuePolicy, PublishOutcomePairingDrivesRetryDecision) {
// packet succeeds / raw fails -> completed, no retry.
QueuePolicy::RetryDecision d =
QueuePolicy::retryDecision(QueuePolicy::queuedPacketPublished(true, false), 0, 1234U);
EXPECT_EQ(QueuePolicy::RetryAction::Complete, d.action);
// raw succeeds / packet fails -> also completed.
d = QueuePolicy::retryDecision(QueuePolicy::queuedPacketPublished(false, true), 0, 1234U);
EXPECT_EQ(QueuePolicy::RetryAction::Complete, d.action);
// both fail on a fresh packet -> scheduled for a bounded retry.
d = QueuePolicy::retryDecision(QueuePolicy::queuedPacketPublished(false, false), 0, 1234U);
EXPECT_EQ(QueuePolicy::RetryAction::Schedule, d.action);
EXPECT_EQ(1U, d.retry_attempts);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,316 @@
#include <gtest/gtest.h>
#include <ArduinoJson.h>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include "helpers/MQTTPayloadBuilder.h"
namespace {
constexpr const char* kTimestamp = "2026-07-18T12:34:56.123456+00:00";
static int buildMinimalStatus(JsonDocument& scratch, char* buffer, size_t buffer_size) {
return MQTTPayloadBuilder::buildStatusMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", "Heltec V3", "v1.16.0",
"915.000000,62.5,7,5", "MeshCore", "online", kTimestamp,
buffer, buffer_size);
}
static int buildRepresentativePacket(JsonDocument& scratch, const char* direction,
float score, const uint8_t* path, int path_hops,
int path_hash_size, const char* raw,
char* buffer, size_t buffer_size) {
return MQTTPayloadBuilder::buildPacketMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", kTimestamp, direction,
"12:34:56", "18/07/2026", 42, 4, "D", 20, raw,
10.26f, -87, score, "89ABCDEF01234567", path, path_hops,
path_hash_size, 64, buffer, buffer_size);
}
TEST(MQTTPayloadBuilder, MinimalStatusHasExactRequiredContract) {
JsonDocument scratch;
char buffer[768];
int len = buildMinimalStatus(scratch, buffer, sizeof(buffer));
ASSERT_GT(len, 0);
EXPECT_EQ(static_cast<size_t>(len), strlen(buffer));
EXPECT_STREQ(
"{\"status\":\"online\",\"timestamp\":\"2026-07-18T12:34:56.123456+00:00\","
"\"origin\":\"DEN Repeater\",\"origin_id\":\"0123456789ABCDEF\","
"\"model\":\"Heltec V3\",\"firmware_version\":\"v1.16.0\","
"\"radio\":\"915.000000,62.5,7,5\",\"client_version\":\"MeshCore\"}",
buffer);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_FALSE(parsed["repeat"].is<JsonVariant>());
EXPECT_FALSE(parsed["stats"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, StatusIncludesRepeatAndEveryRequestedStatistic) {
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildStatusMessage(
scratch, "node", "id", "model", "firmware", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer), 4200, 86400, 3, 6, -112,
11, 22, 4, 180864, 31, 47, "on");
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("on", parsed["repeat"].as<const char*>());
JsonObject stats = parsed["stats"].as<JsonObject>();
ASSERT_FALSE(stats.isNull());
EXPECT_EQ(4200, stats["battery_mv"].as<int>());
EXPECT_EQ(86400, stats["uptime_secs"].as<int>());
EXPECT_EQ(3, stats["errors"].as<int>());
EXPECT_EQ(6, stats["queue_len"].as<int>());
EXPECT_EQ(-112, stats["noise_floor"].as<int>());
EXPECT_EQ(11, stats["tx_air_secs"].as<int>());
EXPECT_EQ(22, stats["rx_air_secs"].as<int>());
EXPECT_EQ(4, stats["recv_errors"].as<int>());
EXPECT_EQ(180864, stats["internal_heap"].as<int>());
EXPECT_EQ(31, stats["packets_sent"].as<int>());
EXPECT_EQ(47, stats["packets_received"].as<int>());
}
TEST(MQTTPayloadBuilder, StatusOmissionSentinelsRemainOmitted) {
JsonDocument scratch;
char buffer[768];
int len = MQTTPayloadBuilder::buildStatusMessage(
scratch, "node", "id", "model", "firmware", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer), -1, -1, -1, -1, -999,
-1, -1, -1, -1, -1, -1, nullptr);
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_FALSE(parsed["stats"].is<JsonVariant>());
EXPECT_FALSE(parsed["repeat"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, StringsAreEscapedAndRoundTrip) {
const char* origin = "node \"north\"\\rack\nline";
const char* model = "Heltec\tV3";
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildStatusMessage(
scratch, origin, "id", model, "v1", "radio", "client", "online",
kTimestamp, buffer, sizeof(buffer));
ASSERT_GT(len, 0);
EXPECT_NE(std::string::npos, std::string(buffer).find("\\\"north\\\""));
EXPECT_NE(std::string::npos, std::string(buffer).find("\\\\rack\\nline"));
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ(origin, parsed["origin"].as<const char*>());
EXPECT_STREQ(model, parsed["model"].as<const char*>());
}
TEST(MQTTPayloadBuilder, RxPacketIncludesMetricsScaledScoreAndPath) {
const uint8_t path[] = {0xAA, 0xBB, 0x01, 0x2F};
JsonDocument scratch;
char buffer[2048];
int len = buildRepresentativePacket(
scratch, "rx", 0.125f, path, 2, 2, "A0B1C2D3", buffer, sizeof(buffer));
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("PACKET", parsed["type"].as<const char*>());
EXPECT_STREQ("rx", parsed["direction"].as<const char*>());
EXPECT_STREQ("42", parsed["len"].as<const char*>());
EXPECT_STREQ("4", parsed["packet_type"].as<const char*>());
EXPECT_STREQ("20", parsed["payload_len"].as<const char*>());
EXPECT_STREQ("10.3", parsed["SNR"].as<const char*>());
EXPECT_STREQ("-87", parsed["RSSI"].as<const char*>());
EXPECT_STREQ("125", parsed["score"].as<const char*>());
JsonArray parsed_path = parsed["path"].as<JsonArray>();
ASSERT_EQ(2U, parsed_path.size());
EXPECT_STREQ("aabb", parsed_path[0].as<const char*>());
EXPECT_STREQ("012f", parsed_path[1].as<const char*>());
}
TEST(MQTTPayloadBuilder, TxPacketOmitsReceiveOnlyMetricsAndAbsentPath) {
JsonDocument scratch;
char buffer[2048];
int len = buildRepresentativePacket(
scratch, "tx", 0.5f, nullptr, 0, 0, "A0B1", buffer, sizeof(buffer));
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_FALSE(parsed["SNR"].is<JsonVariant>());
EXPECT_FALSE(parsed["RSSI"].is<JsonVariant>());
EXPECT_FALSE(parsed["score"].is<JsonVariant>());
EXPECT_FALSE(parsed["path"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, RxPacketOmitsUnknownNanScore) {
JsonDocument scratch;
char buffer[2048];
int len = buildRepresentativePacket(
scratch, "rx", std::nanf(""), nullptr, 0, 0, "A0B1", buffer, sizeof(buffer));
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_TRUE(parsed["SNR"].is<const char*>());
EXPECT_TRUE(parsed["RSSI"].is<const char*>());
EXPECT_FALSE(parsed["score"].is<JsonVariant>());
}
TEST(MQTTPayloadBuilder, RawMessageHasExactContractAndEscapesData) {
char buffer[512];
int len = MQTTPayloadBuilder::buildRawMessage(
"node \"A\"", "id\\1", kTimestamp, "AA\nBB", buffer, sizeof(buffer));
ASSERT_GT(len, 0);
EXPECT_EQ(static_cast<size_t>(len), strlen(buffer));
EXPECT_STREQ(
"{\"origin\":\"node \\\"A\\\"\",\"origin_id\":\"id\\\\1\","
"\"timestamp\":\"2026-07-18T12:34:56.123456+00:00\","
"\"type\":\"RAW\",\"data\":\"AA\\nBB\"}",
buffer);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("AA\nBB", parsed["data"].as<const char*>());
}
TEST(MQTTPayloadBuilder, ExactOutputSizeSucceedsAndOneByteShortFailsCleanly) {
JsonDocument scratch;
char reference[768];
int reference_len = buildMinimalStatus(scratch, reference, sizeof(reference));
ASSERT_GT(reference_len, 0);
std::vector<char> exact(static_cast<size_t>(reference_len) + 1);
EXPECT_EQ(reference_len, buildMinimalStatus(scratch, exact.data(), exact.size()));
EXPECT_STREQ(reference, exact.data());
std::vector<char> short_buffer(static_cast<size_t>(reference_len), 'x');
EXPECT_EQ(0, buildMinimalStatus(scratch, short_buffer.data(), short_buffer.size()));
EXPECT_EQ('\0', short_buffer[0]);
EXPECT_EQ(0, buildMinimalStatus(scratch, short_buffer.data(), 1));
EXPECT_EQ('\0', short_buffer[0]);
EXPECT_EQ(0, buildMinimalStatus(scratch, nullptr, exact.size()));
}
TEST(MQTTPayloadBuilder, MaximumRepresentativePacketAndRawPayloadsRemainValid) {
uint8_t path[64];
for (size_t i = 0; i < sizeof(path); ++i) path[i] = static_cast<uint8_t>(i);
std::string raw(510, 'A');
JsonDocument scratch;
char packet_buffer[2048];
int packet_len = buildRepresentativePacket(
scratch, "rx", 1.0f, path, 16, 4, raw.c_str(),
packet_buffer, sizeof(packet_buffer));
ASSERT_GT(packet_len, 0);
JsonDocument packet;
ASSERT_FALSE(deserializeJson(packet, packet_buffer));
EXPECT_EQ(510U, strlen(packet["raw"].as<const char*>()));
JsonArray parsed_path = packet["path"].as<JsonArray>();
ASSERT_EQ(16U, parsed_path.size());
EXPECT_STREQ("00010203", parsed_path[0].as<const char*>());
EXPECT_STREQ("3c3d3e3f", parsed_path[15].as<const char*>());
char raw_buffer[1024];
int raw_len = MQTTPayloadBuilder::buildRawMessage(
"node", "0123456789ABCDEF", kTimestamp, raw.c_str(),
raw_buffer, sizeof(raw_buffer));
ASSERT_GT(raw_len, 0);
JsonDocument parsed_raw;
ASSERT_FALSE(deserializeJson(parsed_raw, raw_buffer));
EXPECT_EQ(510U, strlen(parsed_raw["data"].as<const char*>()));
}
TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[] = {
{"0011223344556677", 9.75f, 42, "DEN,APRS", "active"},
{"8899AABBCCDDEEFF", -3.5f, 3600, "", "stale"},
};
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", kTimestamp, "DEN,APRS",
neighbors, 2, buffer, sizeof(buffer));
ASSERT_GT(len, 0);
EXPECT_EQ(static_cast<size_t>(len), strlen(buffer));
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("2026-07-18T12:34:56.123456+00:00", parsed["timestamp"].as<const char*>());
EXPECT_STREQ("DEN Repeater", parsed["origin"].as<const char*>());
EXPECT_STREQ("0123456789ABCDEF", parsed["origin_id"].as<const char*>());
EXPECT_STREQ("DEN,APRS", parsed["self"]["scopes"].as<const char*>());
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_EQ(2U, arr.size());
EXPECT_STREQ("0011223344556677", arr[0]["pubkey"].as<const char*>());
EXPECT_FLOAT_EQ(9.75f, arr[0]["snr"].as<float>());
EXPECT_EQ(42U, arr[0]["heard_secs_ago"].as<uint32_t>());
EXPECT_STREQ("DEN,APRS", arr[0]["scopes"].as<const char*>());
EXPECT_STREQ("active", arr[0]["status"].as<const char*>());
EXPECT_STREQ("8899AABBCCDDEEFF", arr[1]["pubkey"].as<const char*>());
EXPECT_STREQ("", arr[1]["scopes"].as<const char*>());
EXPECT_STREQ("stale", arr[1]["status"].as<const char*>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageHandlesEmptyTableAndNullScopes) {
JsonDocument scratch;
char buffer[256];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, nullptr, nullptr, 0,
buffer, sizeof(buffer));
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_STREQ("", parsed["self"]["scopes"].as<const char*>());
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_TRUE(arr.isNull() == false);
EXPECT_EQ(0U, arr.size());
}
TEST(MQTTPayloadBuilder, NeighborsMessageDropsTailWhenBufferFills) {
// Twenty entries far exceed a tight buffer; the builder must emit a prefix
// that still parses as complete JSON rather than truncating mid-document.
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[20];
static char keys[20][17];
for (int i = 0; i < 20; i++) {
snprintf(keys[i], sizeof(keys[i]), "%016X", i);
neighbors[i].pubkey_hex = keys[i];
neighbors[i].snr = static_cast<float>(i);
neighbors[i].heard_secs_ago = static_cast<uint32_t>(i) * 10U;
neighbors[i].scopes = "DEN";
neighbors[i].status = "active";
}
JsonDocument scratch;
char buffer[512];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", neighbors, 20,
buffer, sizeof(buffer));
ASSERT_GT(len, 0);
EXPECT_LT(static_cast<size_t>(len), sizeof(buffer));
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_FALSE(arr.isNull());
EXPECT_GT(arr.size(), 0U);
EXPECT_LT(arr.size(), 20U);
// Kept entries are the head of the input, in order.
EXPECT_STREQ(keys[0], arr[0]["pubkey"].as<const char*>());
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,623 @@
#include <gtest/gtest.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "helpers/MQTTPrefsAtomicStore.h"
#include "helpers/MQTTPrefsRecovery.h"
namespace AtomicStore = MQTTPrefsAtomicStore;
namespace Recovery = MQTTPrefsRecovery;
namespace {
enum class FailurePoint {
None,
Begin,
HeaderWrite,
PayloadWrite,
ImageWrite,
Finish,
Commit,
};
class InMemoryStore {
public:
explicit InMemoryStore(FailurePoint failure, bool preexisting_recovery_temp = false)
: _failure(failure), _preexisting_recovery_temp(preexisting_recovery_temp) {
_files["/mqtt_prefs"] = {'o', 'l', 'd', '-', 'p', 'r', 'e', 'f', 's'};
if (_preexisting_recovery_temp) _files["/mqtt_prefs.tmp"] = {'r', 'e', 'c', 'o', 'v', 'e', 'r'};
}
bool begin() {
++begin_calls;
if (_preexisting_recovery_temp) return false;
_files.erase("/mqtt_prefs.tmp");
_open = _failure != FailurePoint::Begin;
_owns_temp = _open;
return _open;
}
size_t write(const uint8_t* bytes, size_t size) {
++write_calls;
if (!_open) return 0;
const bool should_fail = (write_calls == 1 && _failure == FailurePoint::HeaderWrite) ||
(write_calls == 2 && _failure == FailurePoint::PayloadWrite);
const size_t written = should_fail && size > 0 ? size - 1 : size;
_staging.insert(_staging.end(), bytes, bytes + written);
return written;
}
bool finish() {
++finish_calls;
_open = false;
if (_failure == FailurePoint::Finish) return false;
_files["/mqtt_prefs.tmp"] = _staging;
_finished = true;
return true;
}
bool commit() {
++commit_calls;
if (_failure == FailurePoint::Commit) return false;
_files["/mqtt_prefs"] = _files["/mqtt_prefs.tmp"];
_files.erase("/mqtt_prefs.tmp");
_finished = false;
return true;
}
void abort() {
++abort_calls;
_open = false;
_staging.clear();
// Mirrors MQTTPrefsFileStore: after finish(), a failed commit may already
// have moved the old primary to .bak, so the verified temp is recovery
// data rather than disposable staging.
if (_owns_temp && !_finished) _files.erase("/mqtt_prefs.tmp");
_finished = false;
_owns_temp = false;
}
const std::vector<uint8_t>& source() const { return _files.at("/mqtt_prefs"); }
bool tempExists() const { return _files.count("/mqtt_prefs.tmp") != 0; }
int begin_calls = 0;
int write_calls = 0;
int finish_calls = 0;
int commit_calls = 0;
int abort_calls = 0;
private:
FailurePoint _failure;
bool _preexisting_recovery_temp = false;
bool _open = false;
bool _finished = false;
bool _owns_temp = false;
std::vector<uint8_t> _staging;
std::map<std::string, std::vector<uint8_t>> _files;
};
AtomicStore::Result run(InMemoryStore* store) {
const uint8_t header[] = {0xf5, 'M', 'Q', 'P', 1, 0, 0x09, 0x00};
const uint8_t payload[] = {'n', 'e', 'w', '-', 'p', 'r', 'e', 'f', 's'};
return AtomicStore::write(*store, header, sizeof(header), payload, sizeof(payload));
}
AtomicStore::Result runWithObserverTail(InMemoryStore* store) {
const uint8_t header[] = {0xf5, 'M', 'Q', 'P', 1, 0, 0x0a, 0x00};
// The final three bytes stand in for the observer tail transferred from a
// legacy /com_prefs file. They must be committed before that source is compacted.
const uint8_t payload[] = {'m', 'i', 'g', 'r', 'a', 't', 'e', 0x91, 0x7e, 0xa5};
return AtomicStore::write(*store, header, sizeof(header), payload, sizeof(payload));
}
class LegacyComPrefs {
public:
LegacyComPrefs() : bytes({'l', 'e', 'g', 'a', 'c', 'y', '-', 'c', 'o', 'm'}) {}
void compactAfterMqttCommit(const std::vector<uint8_t>& mqtt_bytes) {
const std::vector<uint8_t> observer_tail = {0x91, 0x7e, 0xa5};
mqtt_tail_present_before_compaction = mqtt_bytes.size() >= observer_tail.size() &&
std::equal(observer_tail.rbegin(), observer_tail.rend(), mqtt_bytes.rbegin());
bytes = {'c', 'o', 'm', 'p', 'a', 'c', 't'};
++compact_calls;
}
std::vector<uint8_t> bytes;
bool mqtt_tail_present_before_compaction = false;
int compact_calls = 0;
};
class LegacyNodePrefs {
public:
LegacyNodePrefs() : bytes({'l', 'e', 'g', 'a', 'c', 'y', '-', 'n', 'o', 'd', 'e'}) {}
void migrateAfterMqttCommit(const std::vector<uint8_t>& mqtt_bytes) {
const std::vector<uint8_t> observer_tail = {0x91, 0x7e, 0xa5};
mqtt_tail_present_before_removal = mqtt_bytes.size() >= observer_tail.size() &&
std::equal(observer_tail.rbegin(), observer_tail.rend(), mqtt_bytes.rbegin());
bytes.clear(); // model removal after current-layout /com_prefs is written
++migration_calls;
}
std::vector<uint8_t> bytes;
bool mqtt_tail_present_before_removal = false;
int migration_calls = 0;
};
// Models the final old-name migration separately from the MQTT transaction:
// /com_prefs is absent while /node_prefs is authoritative. A failed temp write
// or rename must leave that source as the only usable preference image.
class InMemoryCommonPrefsStore {
public:
explicit InMemoryCommonPrefsStore(FailurePoint failure) : _failure(failure) {
_files["/node_prefs"] = {'l', 'e', 'g', 'a', 'c', 'y', '-', 'n', 'o', 'd', 'e'};
}
bool begin() {
++begin_calls;
_files.erase("/com_prefs.tmp");
_staging.clear();
_open = _failure != FailurePoint::Begin;
return _open;
}
size_t write(const uint8_t* bytes, size_t size) {
++write_calls;
if (!_open) return 0;
const bool should_fail = _failure == FailurePoint::ImageWrite && write_calls == 2;
const size_t written = should_fail && size > 0 ? size - 1 : size;
_staging.insert(_staging.end(), bytes, bytes + written);
return written;
}
bool finish() {
++finish_calls;
_open = false;
if (_failure == FailurePoint::Finish) return false;
_files["/com_prefs.tmp"] = _staging;
return true;
}
bool commit() {
++commit_calls;
if (_failure == FailurePoint::Commit) return false;
_files["/com_prefs"] = _files["/com_prefs.tmp"];
_files.erase("/com_prefs.tmp");
return true;
}
void abort() {
++abort_calls;
_open = false;
_staging.clear();
_files.erase("/com_prefs.tmp");
}
void removeNodeSource() { _files.erase("/node_prefs"); }
const std::vector<uint8_t>& nodeSource() const { return _files.at("/node_prefs"); }
const std::vector<uint8_t>& destination() const { return _files.at("/com_prefs"); }
bool destinationExists() const { return _files.count("/com_prefs") != 0; }
bool tempExists() const { return _files.count("/com_prefs.tmp") != 0; }
bool nodeSourceIsPreferred() const {
return _files.count("/node_prefs") != 0 && _files.count("/com_prefs") == 0;
}
bool nodeSourceExists() const { return _files.count("/node_prefs") != 0; }
int begin_calls = 0;
int write_calls = 0;
int finish_calls = 0;
int commit_calls = 0;
int abort_calls = 0;
private:
FailurePoint _failure;
bool _open = false;
std::vector<uint8_t> _staging;
std::map<std::string, std::vector<uint8_t>> _files;
};
AtomicStore::ImageResult runCommonPrefsImage(InMemoryCommonPrefsStore* store) {
const uint8_t core[] = {'c', 'o', 'm', '-', 'p', 'r', 'e', 'f', 's'};
const uint8_t tail[] = {0x19, 0xa4, 0x7e};
return AtomicStore::writeImage(*store, [&core, &tail](InMemoryCommonPrefsStore& target) {
return target.write(core, sizeof(core)) == sizeof(core) &&
target.write(tail, sizeof(tail)) == sizeof(tail);
});
}
// Models the exact SPIFFS transaction used by MQTTPrefsFileStore. Files only
// move by rename: SPIFFS rejects a destination that already exists, so the old
// primary must remain available as .bak until the new temp owns the primary.
class SpiffsMqttTransaction {
public:
enum class Boundary {
BeforeBackupRename,
AfterBackupRename,
AfterPrimaryRename,
AfterBackupCleanup,
};
SpiffsMqttTransaction() {
_files["/mqtt_prefs"] = oldImage();
}
void writeVerifiedTemp() { _files["/mqtt_prefs.tmp"] = newImage(); }
void cutDuringTempWrite() { _files["/mqtt_prefs.tmp"] = {'n'}; }
void cutAt(Boundary boundary) {
writeVerifiedTemp();
if (boundary == Boundary::BeforeBackupRename) return;
rename("/mqtt_prefs", "/mqtt_prefs.bak");
if (boundary == Boundary::AfterBackupRename) return;
rename("/mqtt_prefs.tmp", "/mqtt_prefs");
if (boundary == Boundary::AfterPrimaryRename) return;
_files.erase("/mqtt_prefs.bak");
}
// Inject ordinary operation failures (as distinct from a power cut). A
// failed temp rename leaves both the verified temp and old backup intact.
bool publish(bool fail_backup_rename, bool fail_temp_rename, bool fail_cleanup) {
writeVerifiedTemp();
if (fail_backup_rename || !rename("/mqtt_prefs", "/mqtt_prefs.bak")) return false;
if (fail_temp_rename || !rename("/mqtt_prefs.tmp", "/mqtt_prefs")) return false;
if (!fail_cleanup) _files.erase("/mqtt_prefs.bak");
return true; // backup cleanup is intentionally non-fatal after publish
}
void recover(Recovery::FileState primary = Recovery::FileState::Usable,
Recovery::FileState temp = Recovery::FileState::Usable,
Recovery::FileState backup = Recovery::FileState::Usable) {
const bool had_primary = _files.count("/mqtt_prefs") != 0;
const auto stateFor = [&](const char* path, Recovery::FileState readable) {
return _files.count(path) == 0 ? Recovery::FileState::Missing : readable;
};
const Recovery::Action action = Recovery::select(
stateFor("/mqtt_prefs", primary), stateFor("/mqtt_prefs.tmp", temp),
stateFor("/mqtt_prefs.bak", backup));
if (action == Recovery::Action::PromoteTemp) {
rename("/mqtt_prefs.tmp", "/mqtt_prefs");
// Match production: once a usable temp becomes primary, every backup is
// stale and is cleared so a second save can start this boot.
if (temp == Recovery::FileState::Usable && backup != Recovery::FileState::Missing) {
_files.erase("/mqtt_prefs.bak");
}
return;
}
if (action == Recovery::Action::PromoteBackup) {
rename("/mqtt_prefs.bak", "/mqtt_prefs");
if (backup == Recovery::FileState::Usable && temp != Recovery::FileState::Missing) {
_files.erase("/mqtt_prefs.tmp");
}
return;
}
// A usable primary is authoritative, so production cleans every stale or
// incomplete transaction artifact. It only preserves artifacts when the
// primary itself is opaque.
if (had_primary && primary == Recovery::FileState::Usable) {
_files.erase("/mqtt_prefs.tmp");
_files.erase("/mqtt_prefs.bak");
}
}
bool has(const char* path) const { return _files.count(path) != 0; }
bool canStartSave() const { return !has("/mqtt_prefs.tmp") && !has("/mqtt_prefs.bak"); }
const std::vector<uint8_t>& primary() const { return _files.at("/mqtt_prefs"); }
static std::vector<uint8_t> oldImage() { return {'o', 'l', 'd'}; }
static std::vector<uint8_t> newImage() { return {'n', 'e', 'w'}; }
private:
bool rename(const char* from, const char* to) {
if (_files.count(from) == 0 || _files.count(to) != 0) return false;
_files[to] = _files[from];
_files.erase(from);
return true;
}
std::map<std::string, std::vector<uint8_t>> _files;
};
} // namespace
TEST(MQTTPrefsAtomicStore, CommitPublishesExactHeaderThenPayload) {
InMemoryStore store(FailurePoint::None);
EXPECT_EQ(AtomicStore::Result::Committed, run(&store));
EXPECT_EQ((std::vector<uint8_t>{0xf5, 'M', 'Q', 'P', 1, 0, 0x09, 0x00,
'n', 'e', 'w', '-', 'p', 'r', 'e', 'f', 's'}),
store.source());
EXPECT_FALSE(store.tempExists());
EXPECT_EQ(1, store.begin_calls);
EXPECT_EQ(2, store.write_calls);
EXPECT_EQ(1, store.finish_calls);
EXPECT_EQ(1, store.commit_calls);
EXPECT_EQ(0, store.abort_calls);
}
TEST(MQTTPrefsAtomicStore, AnyFailureAbortsAndPreservesExistingSource) {
const std::vector<uint8_t> source = {'o', 'l', 'd', '-', 'p', 'r', 'e', 'f', 's'};
const struct {
FailurePoint point;
AtomicStore::Result expected;
int writes;
int finishes;
int commits;
} cases[] = {
{FailurePoint::Begin, AtomicStore::Result::BeginFailed, 0, 0, 0},
{FailurePoint::HeaderWrite, AtomicStore::Result::HeaderWriteFailed, 1, 0, 0},
{FailurePoint::PayloadWrite, AtomicStore::Result::PayloadWriteFailed, 2, 0, 0},
{FailurePoint::Finish, AtomicStore::Result::FinishFailed, 2, 1, 0},
{FailurePoint::Commit, AtomicStore::Result::CommitFailed, 2, 1, 1},
};
for (const auto& test_case : cases) {
InMemoryStore store(test_case.point);
EXPECT_EQ(test_case.expected, run(&store));
EXPECT_EQ(source, store.source());
EXPECT_EQ(test_case.point == FailurePoint::Commit, store.tempExists());
EXPECT_EQ(1, store.begin_calls);
EXPECT_EQ(test_case.writes, store.write_calls);
EXPECT_EQ(test_case.finishes, store.finish_calls);
EXPECT_EQ(test_case.commits, store.commit_calls);
EXPECT_EQ(1, store.abort_calls);
}
}
TEST(MQTTPrefsAtomicStore, BeginFailureDoesNotErasePreexistingRecoveryTemp) {
InMemoryStore store(FailurePoint::Begin, true);
EXPECT_EQ(AtomicStore::Result::BeginFailed, run(&store));
EXPECT_TRUE(store.tempExists());
EXPECT_EQ(1, store.abort_calls);
}
TEST(MQTTPrefsAtomicStore, LegacyCrossFileUpgradeCommitsTailBeforeCompactingComPrefs) {
InMemoryStore mqtt_store(FailurePoint::None);
LegacyComPrefs com_prefs;
AtomicStore::LegacyUpgradeGate gate(true);
gate.requireMqttRewrite();
const AtomicStore::Result result = runWithObserverTail(&mqtt_store);
gate.recordMqttSave(AtomicStore::committed(result));
ASSERT_TRUE(gate.mayRewriteComPrefs());
com_prefs.compactAfterMqttCommit(mqtt_store.source());
gate.recordComPrefsRewrite();
EXPECT_TRUE(com_prefs.mqtt_tail_present_before_compaction);
EXPECT_EQ(1, com_prefs.compact_calls);
EXPECT_EQ((std::vector<uint8_t>{'c', 'o', 'm', 'p', 'a', 'c', 't'}), com_prefs.bytes);
EXPECT_FALSE(gate.mayRewriteComPrefs());
}
TEST(MQTTPrefsAtomicStore, LegacyCrossFilePowerCutPreservesBothSources) {
const std::vector<uint8_t> legacy_mqtt = {'o', 'l', 'd', '-', 'p', 'r', 'e', 'f', 's'};
const std::vector<uint8_t> legacy_com = {'l', 'e', 'g', 'a', 'c', 'y', '-', 'c', 'o', 'm'};
for (const FailurePoint point : {FailurePoint::Begin, FailurePoint::HeaderWrite,
FailurePoint::PayloadWrite, FailurePoint::Finish,
FailurePoint::Commit}) {
InMemoryStore mqtt_store(point);
LegacyComPrefs com_prefs;
AtomicStore::LegacyUpgradeGate gate(true);
gate.requireMqttRewrite();
const AtomicStore::Result result = runWithObserverTail(&mqtt_store);
gate.recordMqttSave(AtomicStore::committed(result));
if (gate.mayRewriteComPrefs()) {
com_prefs.compactAfterMqttCommit(mqtt_store.source());
gate.recordComPrefsRewrite();
}
EXPECT_FALSE(AtomicStore::committed(result));
EXPECT_EQ(legacy_mqtt, mqtt_store.source());
EXPECT_EQ(legacy_com, com_prefs.bytes);
EXPECT_EQ(0, com_prefs.compact_calls);
EXPECT_TRUE(gate.blocksComPrefsRewrite());
}
}
TEST(MQTTPrefsAtomicStore, LegacyNodePrefsMigrationWaitsForObserverTailCommit) {
InMemoryStore mqtt_store(FailurePoint::None);
LegacyNodePrefs node_prefs;
AtomicStore::LegacyUpgradeGate gate(true);
gate.requireMqttRewrite();
const AtomicStore::Result result = runWithObserverTail(&mqtt_store);
gate.recordMqttSave(AtomicStore::committed(result));
ASSERT_TRUE(gate.mayRewriteComPrefs());
node_prefs.migrateAfterMqttCommit(mqtt_store.source());
gate.recordComPrefsRewrite();
EXPECT_TRUE(node_prefs.mqtt_tail_present_before_removal);
EXPECT_EQ(1, node_prefs.migration_calls);
EXPECT_TRUE(node_prefs.bytes.empty());
}
TEST(MQTTPrefsAtomicStore, LegacyNodePrefsPowerCutPreservesSource) {
const std::vector<uint8_t> legacy_mqtt = {'o', 'l', 'd', '-', 'p', 'r', 'e', 'f', 's'};
const std::vector<uint8_t> legacy_node = {
'l', 'e', 'g', 'a', 'c', 'y', '-', 'n', 'o', 'd', 'e'};
for (const FailurePoint point : {FailurePoint::Begin, FailurePoint::HeaderWrite,
FailurePoint::PayloadWrite, FailurePoint::Finish,
FailurePoint::Commit}) {
InMemoryStore mqtt_store(point);
LegacyNodePrefs node_prefs;
AtomicStore::LegacyUpgradeGate gate(true);
gate.requireMqttRewrite();
const AtomicStore::Result result = runWithObserverTail(&mqtt_store);
gate.recordMqttSave(AtomicStore::committed(result));
if (gate.mayRewriteComPrefs()) {
node_prefs.migrateAfterMqttCommit(mqtt_store.source());
gate.recordComPrefsRewrite();
}
EXPECT_FALSE(AtomicStore::committed(result));
EXPECT_EQ(legacy_mqtt, mqtt_store.source());
EXPECT_EQ(legacy_node, node_prefs.bytes);
EXPECT_EQ(0, node_prefs.migration_calls);
EXPECT_TRUE(gate.blocksComPrefsRewrite());
}
}
TEST(MQTTPrefsAtomicStore, NodePrefsMigrationPublishesComPrefsBeforeRemovingSource) {
InMemoryCommonPrefsStore store(FailurePoint::None);
ASSERT_EQ(AtomicStore::ImageResult::Committed, runCommonPrefsImage(&store));
EXPECT_TRUE(store.nodeSourceExists()); // caller removes it only after commit
EXPECT_EQ((std::vector<uint8_t>{'c', 'o', 'm', '-', 'p', 'r', 'e', 'f', 's', 0x19, 0xa4, 0x7e}),
store.destination());
EXPECT_FALSE(store.tempExists());
store.removeNodeSource();
EXPECT_FALSE(store.nodeSourceExists());
EXPECT_TRUE(store.destinationExists());
}
TEST(MQTTPrefsAtomicStore, NodePrefsMigrationFailurePreservesSourceAndNeverPrefersPartialDestination) {
const std::vector<uint8_t> legacy_node = {
'l', 'e', 'g', 'a', 'c', 'y', '-', 'n', 'o', 'd', 'e'};
const struct {
FailurePoint point;
AtomicStore::ImageResult expected;
int writes;
int finishes;
int commits;
} cases[] = {
{FailurePoint::Begin, AtomicStore::ImageResult::BeginFailed, 0, 0, 0},
{FailurePoint::ImageWrite, AtomicStore::ImageResult::WriteFailed, 2, 0, 0},
{FailurePoint::Finish, AtomicStore::ImageResult::FinishFailed, 2, 1, 0},
{FailurePoint::Commit, AtomicStore::ImageResult::CommitFailed, 2, 1, 1},
};
for (const auto& test_case : cases) {
InMemoryCommonPrefsStore store(test_case.point);
EXPECT_EQ(test_case.expected, runCommonPrefsImage(&store));
EXPECT_EQ(legacy_node, store.nodeSource());
EXPECT_TRUE(store.nodeSourceIsPreferred());
EXPECT_FALSE(store.destinationExists());
EXPECT_FALSE(store.tempExists());
EXPECT_EQ(1, store.begin_calls);
EXPECT_EQ(test_case.writes, store.write_calls);
EXPECT_EQ(test_case.finishes, store.finish_calls);
EXPECT_EQ(test_case.commits, store.commit_calls);
EXPECT_EQ(1, store.abort_calls);
}
}
TEST(MQTTPrefsAtomicStore, SpiffsPowerCutsAtEveryPublishBoundaryLeaveRecoverableImage) {
const struct {
SpiffsMqttTransaction::Boundary boundary;
std::vector<uint8_t> expected_after_reboot;
} cases[] = {
// Temp has not become the committed image yet, so the old primary wins.
{SpiffsMqttTransaction::Boundary::BeforeBackupRename, SpiffsMqttTransaction::oldImage()},
// Old primary is .bak and verified new temp wins the recovery race.
{SpiffsMqttTransaction::Boundary::AfterBackupRename, SpiffsMqttTransaction::newImage()},
{SpiffsMqttTransaction::Boundary::AfterPrimaryRename, SpiffsMqttTransaction::newImage()},
{SpiffsMqttTransaction::Boundary::AfterBackupCleanup, SpiffsMqttTransaction::newImage()},
};
for (const auto& test_case : cases) {
SpiffsMqttTransaction store;
store.cutAt(test_case.boundary);
store.recover();
ASSERT_TRUE(store.has("/mqtt_prefs"));
EXPECT_EQ(test_case.expected_after_reboot, store.primary());
EXPECT_FALSE(store.has("/mqtt_prefs.tmp"));
EXPECT_FALSE(store.has("/mqtt_prefs.bak"));
}
}
TEST(MQTTPrefsAtomicStore, PowerCutDuringTempWriteKeepsPrimaryAndAllowsNextSave) {
SpiffsMqttTransaction store;
store.cutDuringTempWrite();
// The partial temp is opaque to the codec, but the existing primary is the
// only committed image. Recovery discards the incomplete transaction rather
// than blocking every later config save behind /mqtt_prefs.tmp.
store.recover(Recovery::FileState::Usable, Recovery::FileState::Preserve);
EXPECT_EQ(SpiffsMqttTransaction::oldImage(), store.primary());
EXPECT_FALSE(store.has("/mqtt_prefs.tmp"));
EXPECT_TRUE(store.canStartSave());
}
TEST(MQTTPrefsAtomicStore, RecoveredUsablePrimaryClearsOpaqueTransactionArtifacts) {
{
SpiffsMqttTransaction store;
store.cutAt(SpiffsMqttTransaction::Boundary::AfterBackupRename);
// A current-format temp wins; the old backup need not be decodable to be
// stale once that usable temp owns the primary name.
store.recover(Recovery::FileState::Usable, Recovery::FileState::Usable,
Recovery::FileState::Preserve);
EXPECT_EQ(SpiffsMqttTransaction::newImage(), store.primary());
EXPECT_TRUE(store.canStartSave());
}
{
SpiffsMqttTransaction store;
store.cutAt(SpiffsMqttTransaction::Boundary::AfterBackupRename);
// Conversely, when the usable backup becomes primary, an opaque temp was
// never published and must not leave saves permanently blocked.
store.recover(Recovery::FileState::Usable, Recovery::FileState::Preserve,
Recovery::FileState::Usable);
EXPECT_EQ(SpiffsMqttTransaction::oldImage(), store.primary());
EXPECT_TRUE(store.canStartSave());
}
}
TEST(MQTTPrefsAtomicStore, SpiffsRenameAndCleanupFailuresRemainRecoverable) {
{
SpiffsMqttTransaction store;
EXPECT_FALSE(store.publish(true, false, false));
store.recover();
EXPECT_EQ(SpiffsMqttTransaction::oldImage(), store.primary());
EXPECT_FALSE(store.has("/mqtt_prefs.tmp"));
EXPECT_FALSE(store.has("/mqtt_prefs.bak"));
}
{
SpiffsMqttTransaction store;
EXPECT_FALSE(store.publish(false, true, false));
EXPECT_FALSE(store.has("/mqtt_prefs"));
EXPECT_TRUE(store.has("/mqtt_prefs.tmp"));
EXPECT_TRUE(store.has("/mqtt_prefs.bak"));
store.recover();
EXPECT_EQ(SpiffsMqttTransaction::newImage(), store.primary());
EXPECT_FALSE(store.has("/mqtt_prefs.tmp"));
EXPECT_FALSE(store.has("/mqtt_prefs.bak"));
}
{
SpiffsMqttTransaction store;
EXPECT_TRUE(store.publish(false, false, true));
EXPECT_EQ(SpiffsMqttTransaction::newImage(), store.primary());
EXPECT_TRUE(store.has("/mqtt_prefs.bak"));
store.recover();
EXPECT_FALSE(store.has("/mqtt_prefs.bak"));
}
}
TEST(MQTTPrefsAtomicStore, RecoveryNeverOverwritesOpaqueNewerLayout) {
// An unreadable primary owns its name, even if an older usable backup and a
// verified temp exist. This is the downgrade-preservation invariant.
EXPECT_EQ(Recovery::Action::KeepPrimary,
Recovery::select(Recovery::FileState::Preserve, Recovery::FileState::Usable,
Recovery::FileState::Usable));
// If there is no primary, a usable backup wins over an opaque temp. Once
// promoted, production treats the backup as authoritative and clears temp.
EXPECT_EQ(Recovery::Action::PromoteBackup,
Recovery::select(Recovery::FileState::Missing, Recovery::FileState::Preserve,
Recovery::FileState::Usable));
// With no other image, an opaque backup is renamed into the empty primary
// name so CommonCLI will hold it rather than silently replace it with defaults.
EXPECT_EQ(Recovery::Action::PromoteBackup,
Recovery::select(Recovery::FileState::Missing, Recovery::FileState::Missing,
Recovery::FileState::Preserve));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+24
View File
@@ -0,0 +1,24 @@
# MQTT preferences fixture provenance
The codec tests construct synthetic, non-secret byte vectors at hard-coded
offsets. They intentionally do not serialize the production structs: a layout
change must disagree with the frozen fixture bytes and fail the field checks.
| Bytes | Historical layout | Source history |
|---:|---|---|
| 472 | Pre-slot, before and after `wifi_power_save` | Initial `/mqtt_prefs` layout; `34c8bea7` inserted WiFi power without changing the padded total size |
| 1032 | Initial three-slot layout | `b43e9618` |
| 1464 | Three slots with token/topic tails | `95874f0c` |
| 2452 | Six slots with token/topic tails | `1b5884bd` |
| 2836 | Six slots with audience tail | `1263e71d` |
| 2840 | Six slots with RX flag | `47b632aa` |
| 2904 | Six slots with NTP server | `7416d632` |
| 2736 / 2860 | Version-1 payload before observer tail / complete payload | `58b9cb66` introduced the eight-byte versioned header; the shorter form exercises its append-compatible prefix contract |
The 3024-byte raw observer-tail form is not accepted as deployed fleet data:
repository history indicates it existed briefly before versioning but was not
shipped. Tests require it to be preserved rather than guessed and rewritten.
Headerless formats have no checksum. Plausibility checks reject obvious random
or malformed content, but cannot authenticate a byte sequence that happens to
look like a valid historical struct.
@@ -0,0 +1,399 @@
#include <gtest/gtest.h>
#include <cstring>
#include <vector>
#define WITH_MQTT_BRIDGE 1
#include "helpers/MQTTPrefsCodec.h"
namespace Codec = MQTTPrefsCodec;
namespace {
MQTTPrefs defaults() {
MQTTPrefs prefs = {};
prefs.mqtt_status_enabled = 1;
prefs.mqtt_packets_enabled = 1;
prefs.mqtt_tx_enabled = 2;
prefs.mqtt_rx_enabled = 1;
prefs.mqtt_status_interval = 300000;
prefs.wifi_power_save = 1;
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
strncpy(prefs.mqtt_slot_preset[i], "none", sizeof(prefs.mqtt_slot_preset[i]) - 1);
}
strncpy(prefs.snmp_community, "public", sizeof(prefs.snmp_community) - 1);
prefs.radio_watchdog_minutes = 5;
prefs.alert_wifi_minutes = 30;
prefs.alert_mqtt_minutes = 240;
prefs.alert_min_interval_min = 60;
return prefs;
}
void writeText(std::vector<uint8_t>* bytes, size_t offset, const char* value) {
const size_t length = strlen(value);
ASSERT_LE(offset + length, bytes->size());
memcpy(bytes->data() + offset, value, length);
}
void writeLe16(std::vector<uint8_t>* bytes, size_t offset, uint16_t value) {
ASSERT_LE(offset + 2, bytes->size());
(*bytes)[offset] = static_cast<uint8_t>(value & 0xff);
(*bytes)[offset + 1] = static_cast<uint8_t>(value >> 8);
}
void writeHeader(std::vector<uint8_t>* bytes, uint16_t version, uint16_t payload_len) {
ASSERT_GE(bytes->size(), sizeof(MQTTPrefsHeader));
(*bytes)[0] = MQTT_PREFS_MAGIC[0];
(*bytes)[1] = MQTT_PREFS_MAGIC[1];
(*bytes)[2] = MQTT_PREFS_MAGIC[2];
(*bytes)[3] = MQTT_PREFS_MAGIC[3];
writeLe16(bytes, 4, version);
writeLe16(bytes, 6, payload_len);
}
Codec::DecodePlan classify(const std::vector<uint8_t>& bytes) {
const size_t prefix_size = bytes.size() < sizeof(MQTTPrefsHeader)
? bytes.size() : sizeof(MQTTPrefsHeader);
return Codec::classify(bytes.data(), prefix_size, bytes.size());
}
void fillHighEntropy(std::vector<uint8_t>* bytes) {
uint32_t state = 0x89abcdef;
for (size_t i = 0; i < bytes->size(); ++i) {
state = state * 1664525u + 1013904223u;
// Keep every byte non-NUL so this is a useful corruption fixture rather
// than a sparse/default-like legacy file.
(*bytes)[i] = static_cast<uint8_t>((state >> 24) | 0x80);
}
}
} // namespace
TEST(MQTTPrefsCodec, MigratesPostWifiPowerPreSlotFixture) {
// Frozen post-WiFi-power pre-slot offsets: status=44, ssid=48, power=144,
// timezone=145, server=178, port=242. Do not derive this fixture from structs.
std::vector<uint8_t> bytes(472, 0);
writeText(&bytes, 0, "legacy-node");
writeText(&bytes, 32, "YYZ");
bytes[40] = 1;
bytes[41] = 1;
bytes[43] = 2;
bytes[144] = 2;
writeText(&bytes, 145, "UTC");
writeText(&bytes, 178, "broker.example");
writeLe16(&bytes, 242, 1883);
writeText(&bytes, 244, "alice");
writeText(&bytes, 276, "secret");
bytes[340] = 1;
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::LegacyPreSlot, plan.source);
ASSERT_TRUE(plan.rewrite_legacy);
ASSERT_FALSE(Codec::looksLikePreWifiPower(bytes.data(), bytes.size()));
ASSERT_TRUE(Codec::isPlausibleLegacy(plan.source, bytes.data(), bytes.size()));
OldMQTTPrefs old_prefs = {};
memcpy(&old_prefs, bytes.data(), sizeof(old_prefs));
MQTTPrefs prefs = defaults();
Codec::migratePreSlot(old_prefs, &prefs);
EXPECT_STREQ("legacy-node", prefs.mqtt_origin);
EXPECT_STREQ("analyzer-us", prefs.mqtt_slot_preset[0]);
EXPECT_STREQ("custom", prefs.mqtt_slot_preset[2]);
EXPECT_STREQ("broker.example", prefs.mqtt_slot_host[2]);
EXPECT_EQ(1883, prefs.mqtt_slot_port[2]);
EXPECT_STREQ("secret", prefs.mqtt_slot_password[2]);
}
TEST(MQTTPrefsCodec, MigratesPreWifiPowerFixtureWithConservativeHeuristic) {
// In the pre-WiFi-power variant timezone starts at 144 and server at 177;
// port still aligns at 242. A non-empty timezone makes the layout unambiguous.
std::vector<uint8_t> bytes(472, 0);
writeText(&bytes, 0, "pre-power");
writeText(&bytes, 144, "PST8PDT");
writeText(&bytes, 177, "old-broker");
writeLe16(&bytes, 242, 8883);
ASSERT_TRUE(Codec::looksLikePreWifiPower(bytes.data(), bytes.size()));
ASSERT_TRUE(Codec::isPlausibleLegacy(Codec::Source::LegacyPreSlot,
bytes.data(), bytes.size()));
PreWifiPowerOldMQTTPrefs old_prefs = {};
memcpy(&old_prefs, bytes.data(), sizeof(old_prefs));
MQTTPrefs prefs = defaults();
Codec::migratePreWifiPower(old_prefs, &prefs);
EXPECT_STREQ("PST8PDT", prefs.timezone_string);
EXPECT_STREQ("old-broker", prefs.mqtt_slot_host[2]);
EXPECT_EQ(8883, prefs.mqtt_slot_port[2]);
EXPECT_EQ(1, prefs.wifi_power_save); // retained current default; old layout had none
}
TEST(MQTTPrefsCodec, DetectsPreWifiPowerFixtureWithOnlyUtcOffsetConfigured) {
std::vector<uint8_t> bytes(472, 0);
bytes[176] = static_cast<uint8_t>(-8);
EXPECT_TRUE(Codec::looksLikePreWifiPower(bytes.data(), bytes.size()));
}
TEST(MQTTPrefsCodec, MigratesThreeSlotBaseAndExtendedFixtures) {
// Frozen 3-slot offsets: presets=178, hosts=250, ports=442, users=448,
// passwords=544, owner=736, tokens=1030, topics=1174. The base file has
// two tail-padding bytes, so its frozen size is 1032.
std::vector<uint8_t> base(1032, 0);
writeText(&base, 0, "three-base");
writeText(&base, 178, "meshmapper");
writeText(&base, 250, "three.example");
writeLe16(&base, 442, 1884);
const Codec::DecodePlan base_plan = classify(base);
ASSERT_EQ(Codec::Source::LegacyThreeSlotBase, base_plan.source);
ASSERT_TRUE(Codec::isPlausibleLegacy(base_plan.source, base.data(), base.size()));
ThreeSlotBaseMQTTPrefs old_base = {};
memcpy(&old_base, base.data(), sizeof(old_base));
MQTTPrefs base_prefs = defaults();
Codec::migrateThreeSlot(old_base, &base_prefs);
EXPECT_STREQ("three-base", base_prefs.mqtt_origin);
EXPECT_STREQ("meshmapper", base_prefs.mqtt_slot_preset[0]);
EXPECT_EQ(1884, base_prefs.mqtt_slot_port[0]);
EXPECT_STREQ("none", base_prefs.mqtt_slot_preset[3]);
std::vector<uint8_t> extended(1464, 0);
writeText(&extended, 0, "three-extended");
writeText(&extended, 178 + 24, "custom");
writeText(&extended, 250 + 64, "slot-two.example");
writeText(&extended, 1030 + 48, "token-two");
writeText(&extended, 1174 + 96, "custom/{type}");
const Codec::DecodePlan extended_plan = classify(extended);
ASSERT_EQ(Codec::Source::LegacyThreeSlot, extended_plan.source);
ASSERT_TRUE(Codec::isPlausibleLegacy(extended_plan.source, extended.data(), extended.size()));
ThreeSlotMQTTPrefs old_extended = {};
memcpy(&old_extended, extended.data(), sizeof(old_extended));
MQTTPrefs extended_prefs = defaults();
Codec::migrateThreeSlot(old_extended, &extended_prefs);
EXPECT_STREQ("custom", extended_prefs.mqtt_slot_preset[1]);
EXPECT_STREQ("token-two", extended_prefs.mqtt_slot_token[1]);
EXPECT_STREQ("custom/{type}", extended_prefs.mqtt_slot_topic[1]);
}
TEST(MQTTPrefsCodec, MigratesAllLegacySixSlotPrefixesWithoutClobberingDefaults) {
// Frozen 6-slot offsets: presets=178, hosts=322, ports=706, tokens=1588,
// topics=1876, audience=2452, rx=2836, ntp=2837.
for (const size_t size : {size_t(2452), size_t(2836), size_t(2840), size_t(2904)}) {
std::vector<uint8_t> bytes(size, 0);
writeText(&bytes, 0, "six-slot");
writeText(&bytes, 178 + 5 * 24, "custom");
writeText(&bytes, 322 + 5 * 64, "six.example");
writeText(&bytes, 1588 + 5 * 48, "token-six");
writeText(&bytes, 1876 + 5 * 96, "six/{type}");
if (size >= 2836) writeText(&bytes, 2452 + 5 * 64, "audience-six");
if (size >= 2840) bytes[2836] = 0;
if (size >= 2904) writeText(&bytes, 2837, "time.example");
const Codec::DecodePlan plan = classify(bytes);
const Codec::Source expected_source = size == 2452 ? Codec::Source::LegacySixSlotBase
: size == 2836 ? Codec::Source::LegacySixSlotAudience
: size == 2840 ? Codec::Source::LegacySixSlotAudienceRx
: Codec::Source::LegacySixSlot;
EXPECT_EQ(expected_source, plan.source) << size;
ASSERT_TRUE(plan.rewrite_legacy);
ASSERT_TRUE(Codec::isPlausibleLegacy(plan.source, bytes.data(), bytes.size())) << size;
Legacy6SlotMQTTPrefs old_prefs = {};
memcpy(&old_prefs, bytes.data(), bytes.size());
MQTTPrefs prefs = defaults();
Codec::migrateLegacySixSlot(old_prefs, plan.source, &prefs);
EXPECT_STREQ("custom", prefs.mqtt_slot_preset[5]);
EXPECT_STREQ("token-six", prefs.mqtt_slot_token[5]);
if (size < 2836) {
EXPECT_EQ('\0', prefs.mqtt_slot_audience[5][0]);
} else {
EXPECT_STREQ("audience-six", prefs.mqtt_slot_audience[5]);
}
if (size < 2840) {
EXPECT_EQ(1, prefs.mqtt_rx_enabled) << size;
} else {
EXPECT_EQ(0, prefs.mqtt_rx_enabled);
}
if (size < 2904) {
EXPECT_EQ('\0', prefs.mqtt_ntp_server[0]);
} else {
EXPECT_STREQ("time.example", prefs.mqtt_ntp_server);
}
}
}
TEST(MQTTPrefsCodec, CurrentVersionedPayloadRoundTripsExactly) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "current-node", sizeof(source.mqtt_origin) - 1);
strncpy(source.mqtt_slot_password[2], "preserve-me", sizeof(source.mqtt_slot_password[2]) - 1);
strncpy(source.alert_region, "PNW", sizeof(source.alert_region) - 1);
source.mqtt_neighbors_enabled = 1;
source.mqtt_neighbors_interval = MQTT_NEIGHBORS_MAX_INTERVAL_MS;
std::vector<uint8_t> bytes(Codec::kEncodedSize);
ASSERT_EQ(Codec::kEncodedSize, Codec::encode(source, bytes.data(), bytes.size()));
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_FALSE(plan.preserve_file);
ASSERT_TRUE(plan.observer_fields_present);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(0, memcmp(&source, &loaded, sizeof(source)));
}
TEST(MQTTPrefsCodec, CompatibleShortV1PayloadPreservesDefaultsBeyondObserverBoundary) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "short-v1-node", sizeof(source.mqtt_origin) - 1);
strncpy(source.mqtt_ntp_server, "ntp.short.example", sizeof(source.mqtt_ntp_server) - 1);
source.snmp_enabled = 1;
strncpy(source.snmp_community, "do-not-copy", sizeof(source.snmp_community) - 1);
source.radio_watchdog_minutes = 99;
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + Codec::kV1PreObserverPayloadSize, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1PreObserverPayloadSize));
memcpy(bytes.data() + sizeof(MQTTPrefsHeader), &source, Codec::kV1PreObserverPayloadSize);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1PreObserverPayloadSize, plan.payload_len);
ASSERT_FALSE(plan.preserve_file);
ASSERT_FALSE(plan.observer_fields_present);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_STREQ("short-v1-node", loaded.mqtt_origin);
EXPECT_STREQ("ntp.short.example", loaded.mqtt_ntp_server);
EXPECT_EQ(0, loaded.snmp_enabled);
EXPECT_STREQ("public", loaded.snmp_community);
EXPECT_EQ(5, loaded.radio_watchdog_minutes);
}
TEST(MQTTPrefsCodec, PreNeighborsV1PayloadLoadsObserverFieldsAndDefaultsNeighborsTail) {
// A /mqtt_prefs written by observer/webconfig firmware before the neighbors
// tail existed: full observer fields, 2860-byte v1 payload. It must still load
// as Current (observer fields present) with the neighbors tail defaulted.
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "pre-neighbors-node", sizeof(source.mqtt_origin) - 1);
strncpy(source.alert_region, "PNW", sizeof(source.alert_region) - 1);
source.snmp_enabled = 1;
source.alert_enabled = 1;
source.mqtt_neighbors_enabled = 0; // old struct's byte 2857 was zero padding
source.mqtt_neighbors_interval = 0x11223344; // must NOT survive a 2860-byte read
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + Codec::kV1PreNeighborsPayloadSize, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1PreNeighborsPayloadSize));
memcpy(bytes.data() + sizeof(MQTTPrefsHeader), &source, Codec::kV1PreNeighborsPayloadSize);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1PreNeighborsPayloadSize, plan.payload_len);
ASSERT_FALSE(plan.preserve_file);
ASSERT_TRUE(plan.observer_fields_present);
MQTTPrefs loaded = defaults();
loaded.mqtt_neighbors_enabled = 1; // pretend stale
loaded.mqtt_neighbors_interval = MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS; // caller's defaulted tail
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_STREQ("pre-neighbors-node", loaded.mqtt_origin);
EXPECT_STREQ("PNW", loaded.alert_region);
EXPECT_EQ(1, loaded.snmp_enabled);
EXPECT_EQ(1, loaded.alert_enabled);
// Enable flag sits at offset 2857 (inside the 2860 read) -> takes the file's 0.
// Interval begins at 2860 (beyond the read) -> keeps the caller's default.
EXPECT_EQ(0u, loaded.mqtt_neighbors_enabled);
EXPECT_EQ(MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS, loaded.mqtt_neighbors_interval);
}
TEST(MQTTPrefsCodec, CorruptOrShortVersionedInputsArePreserved) {
Codec::DecodePlan plan = Codec::classify(nullptr, 0, 0);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> partial_magic = {MQTT_PREFS_MAGIC[0], MQTT_PREFS_MAGIC[1], MQTT_PREFS_MAGIC[2]};
plan = classify(partial_magic);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> short_payload(sizeof(MQTTPrefsHeader) + 4, 0);
writeHeader(&short_payload, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize - 1));
plan = classify(short_payload);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> declared_short_with_full_body(
sizeof(MQTTPrefsHeader) + Codec::kV1BaselinePayloadSize, 0);
writeHeader(&declared_short_with_full_body, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1PreObserverPayloadSize));
plan = classify(declared_short_with_full_body);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> declared_full_with_short_body(
sizeof(MQTTPrefsHeader) + Codec::kV1PreObserverPayloadSize, 0);
writeHeader(&declared_full_with_short_body, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize));
plan = classify(declared_full_with_short_body);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> truncated(sizeof(MQTTPrefsHeader) + Codec::kV1BaselinePayloadSize - 1, 0);
writeHeader(&truncated, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize));
plan = classify(truncated);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> trailing(sizeof(MQTTPrefsHeader) + Codec::kV1BaselinePayloadSize + 1, 0);
writeHeader(&trailing, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize));
plan = classify(trailing);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
}
TEST(MQTTPrefsCodec, LegacyPlausibilityRejectsHighEntropyBytesAtEveryWhitelistedSize) {
// A headerless raw struct has no checksum, so this only reduces false
// migrations; it cannot prove that a plausible-looking file is authentic.
for (const size_t size : {size_t(472), size_t(1032), size_t(1464), size_t(2452),
size_t(2836), size_t(2840), size_t(2904)}) {
std::vector<uint8_t> bytes(size, 0);
fillHighEntropy(&bytes);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_TRUE(plan.rewrite_legacy) << size;
EXPECT_FALSE(Codec::isPlausibleLegacy(plan.source, bytes.data(), bytes.size())) << size;
}
}
TEST(MQTTPrefsCodec, UnsupportedHeaderlessSizesArePreserved) {
// 3024 was produced briefly before versioning, but repository history says
// that raw observer-tail form was not shipped. Preserve it rather than guess.
for (const size_t size : {size_t(471), size_t(473), size_t(1465), size_t(2905), size_t(3024)}) {
std::vector<uint8_t> bytes(size, 0);
const Codec::DecodePlan plan = classify(bytes);
EXPECT_EQ(Codec::Source::Corrupt, plan.source) << size;
EXPECT_TRUE(plan.preserve_file) << size;
}
}
TEST(MQTTPrefsCodec, NewerAndSameVersionExtendedPayloadsAreHeld) {
std::vector<uint8_t> newer(sizeof(MQTTPrefsHeader), 0);
writeHeader(&newer, MQTT_PREFS_VERSION + 1, 0);
Codec::DecodePlan plan = classify(newer);
EXPECT_EQ(Codec::Source::UnsupportedVersion, plan.source);
EXPECT_TRUE(plan.preserve_file);
std::vector<uint8_t> extended(sizeof(MQTTPrefsHeader) + Codec::kV1BaselinePayloadSize + 1, 0);
writeHeader(&extended, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize + 1));
plan = classify(extended);
EXPECT_EQ(Codec::Source::UnsupportedVersion, plan.source);
EXPECT_TRUE(plan.preserve_file);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,170 @@
// Host tests for the MQTT observer preset table and lookup helpers
// (src/helpers/MQTTPresets.h). Pure logic -- no ESP/radio dependencies.
//
// The preset table and lookup functions are compiled only for observer builds,
// so opt into that feature flag before including the header (the definitions are
// pure C++/data with no ESP dependencies).
#define WITH_MQTT_BRIDGE 1
#define MQTT_PRESETS_IMPLEMENTATION
#define PROGMEM // host build: the CA-cert strings in MQTTPresets.h are PROGMEM-qualified
#include <gtest/gtest.h>
#include <cstring>
#include <set>
#include <string>
#include "helpers/MQTTPresets.h"
// ---- findMQTTPreset -------------------------------------------------------
TEST(MQTTPresets, FindKnownPreset) {
const MQTTPresetDef* p = findMQTTPreset("analyzer-us");
ASSERT_NE(nullptr, p);
EXPECT_STREQ("analyzer-us", p->name);
EXPECT_EQ(MQTT_AUTH_JWT, p->auth_type);
EXPECT_EQ(MQTT_TOPIC_MESHCORE, p->topic_style);
}
TEST(MQTTPresets, FindReturnsTablePointer) {
// The returned pointer must be into the table, not a copy.
const MQTTPresetDef* p = findMQTTPreset("meshrank");
ASSERT_NE(nullptr, p);
bool in_table = false;
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
if (p == &MQTT_PRESETS[i]) { in_table = true; break; }
}
EXPECT_TRUE(in_table);
}
TEST(MQTTPresets, UnknownAndEmptyReturnNull) {
EXPECT_EQ(nullptr, findMQTTPreset("does-not-exist"));
EXPECT_EQ(nullptr, findMQTTPreset(""));
EXPECT_EQ(nullptr, findMQTTPreset(nullptr));
}
TEST(MQTTPresets, NoneAndCustomAreNotTablePresets) {
// "none"/"custom" are virtual presets handled by the CLI, not table entries.
EXPECT_EQ(nullptr, findMQTTPreset(MQTT_PRESET_NONE));
EXPECT_EQ(nullptr, findMQTTPreset(MQTT_PRESET_CUSTOM));
EXPECT_STREQ("none", MQTT_PRESET_NONE);
EXPECT_STREQ("custom", MQTT_PRESET_CUSTOM);
}
TEST(MQTTPresets, LookupIsCaseSensitive) {
EXPECT_EQ(nullptr, findMQTTPreset("Analyzer-US"));
}
// ---- table integrity ------------------------------------------------------
TEST(MQTTPresets, EveryNameIsUniqueAndNonEmpty) {
std::set<std::string> names;
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
ASSERT_NE(nullptr, MQTT_PRESETS[i].name) << "preset " << i << " has null name";
EXPECT_NE('\0', MQTT_PRESETS[i].name[0]) << "preset " << i << " has empty name";
auto res = names.insert(MQTT_PRESETS[i].name);
EXPECT_TRUE(res.second) << "duplicate preset name: " << MQTT_PRESETS[i].name;
}
EXPECT_EQ((size_t)MQTT_PRESET_COUNT, names.size());
}
TEST(MQTTPresets, EveryPresetHasAServerUrl) {
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
ASSERT_NE(nullptr, MQTT_PRESETS[i].server_url) << MQTT_PRESETS[i].name;
EXPECT_NE('\0', MQTT_PRESETS[i].server_url[0]) << MQTT_PRESETS[i].name;
}
}
TEST(MQTTPresets, JwtPresetsCarryAnAudience) {
// JWT auth needs an audience (the field doubles as the broker host here).
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
if (MQTT_PRESETS[i].auth_type == MQTT_AUTH_JWT) {
EXPECT_NE(nullptr, MQTT_PRESETS[i].jwt_audience)
<< MQTT_PRESETS[i].name << " is JWT but has no audience";
}
}
}
TEST(MQTTPresets, NamesFitTheSlotPresetBuffer) {
// Stored preset name goes into mqtt_slot_preset[MAX][24]; keep < 24 chars.
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
EXPECT_LT(strlen(MQTT_PRESETS[i].name), (size_t)24)
<< MQTT_PRESETS[i].name << " too long for slot-preset buffer";
}
}
// ---- mqttPresetNeedsSlotCredentials ---------------------------------------
TEST(MQTTPresets, EmbeddedUserpassDoesNotNeedSlotCredentials) {
// tennmesh ships an embedded username+password.
const MQTTPresetDef* p = findMQTTPreset("tennmesh");
ASSERT_NE(nullptr, p);
EXPECT_EQ(MQTT_AUTH_USERPASS, p->auth_type);
EXPECT_FALSE(mqttPresetNeedsSlotCredentials(p));
}
TEST(MQTTPresets, UserpassWithoutEmbeddedCredsNeedsSlotCredentials) {
// inwmesh is USERPASS with null user/pass -> must come from mqttN.username/password.
const MQTTPresetDef* p = findMQTTPreset("inwmesh");
ASSERT_NE(nullptr, p);
EXPECT_EQ(MQTT_AUTH_USERPASS, p->auth_type);
EXPECT_TRUE(mqttPresetNeedsSlotCredentials(p));
EXPECT_TRUE(mqttPresetNeedsSlotUsername(p));
EXPECT_TRUE(mqttPresetNeedsSlotPassword(p));
EXPECT_FALSE(mqttPresetUsesDevicePubkeyUsername(p));
}
TEST(MQTTPresets, NonUserpassNeverNeedsSlotCredentials) {
for (int i = 0; i < MQTT_PRESET_COUNT; i++) {
if (MQTT_PRESETS[i].auth_type != MQTT_AUTH_USERPASS) {
EXPECT_FALSE(mqttPresetNeedsSlotCredentials(&MQTT_PRESETS[i]))
<< MQTT_PRESETS[i].name;
}
}
EXPECT_FALSE(mqttPresetNeedsSlotCredentials(nullptr));
}
TEST(MQTTPresets, MeshrankIsTokenStyleNoAuth) {
const MQTTPresetDef* p = findMQTTPreset("meshrank");
ASSERT_NE(nullptr, p);
EXPECT_EQ(MQTT_TOPIC_MESHRANK, p->topic_style);
EXPECT_EQ(MQTT_AUTH_NONE, p->auth_type);
}
TEST(MQTTPresets, MeshChaun14UsesPubkeyUsernameAndNeedsPassword) {
const MQTTPresetDef* p = findMQTTPreset("mesh-chaun14");
ASSERT_NE(nullptr, p);
EXPECT_EQ(MQTT_AUTH_USERPASS, p->auth_type);
EXPECT_EQ(MQTT_TOPIC_MESHCORE, p->topic_style);
EXPECT_STREQ("mqtt://mqtt.mesh.chaun14.fr:1884", p->server_url);
EXPECT_EQ(nullptr, p->ca_cert);
EXPECT_EQ(60, p->keepalive);
EXPECT_TRUE(mqttPresetUsesDevicePubkeyUsername(p));
EXPECT_STREQ(MQTT_USERPASS_USERNAME_PUBKEY, p->userpass_username);
EXPECT_FALSE(mqttPresetNeedsSlotUsername(p));
EXPECT_TRUE(mqttPresetNeedsSlotPassword(p));
EXPECT_TRUE(mqttPresetNeedsSlotCredentials(p));
}
TEST(MQTTPresets, WcmeshIsJwtWithIsrgRootX1) {
const MQTTPresetDef* p = findMQTTPreset("wcmesh");
ASSERT_NE(nullptr, p);
EXPECT_EQ(MQTT_AUTH_JWT, p->auth_type);
EXPECT_EQ(MQTT_TOPIC_MESHCORE, p->topic_style);
EXPECT_STREQ("wss://mqtt.wcmesh.com:443", p->server_url);
EXPECT_STREQ("mqtt.wcmesh.com", p->jwt_audience);
EXPECT_EQ(ISRG_ROOT_X1, p->ca_cert);
EXPECT_NE(GTS_ROOT_R4, p->ca_cert);
EXPECT_FALSE(mqttPresetNeedsSlotCredentials(p));
EXPECT_FALSE(mqttPresetUsesDevicePubkeyUsername(p));
}
// ---- slot count constants -------------------------------------------------
TEST(MQTTPresets, SlotCountsAreSane) {
EXPECT_GT(RUNTIME_MQTT_SLOTS, 0);
EXPECT_LE(RUNTIME_MQTT_SLOTS, MAX_MQTT_SLOTS);
EXPECT_EQ(6, MAX_MQTT_SLOTS); // persisted layout -- must not drift without migration
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,132 @@
// Host tests for replyAppendf (src/helpers/MQTTReplyFormat.h), the bounded
// clamping printf-append used by MQTTBridge's status/stats/diag CLI formatters.
// Proves the A1 out-of-bounds-write bound holds regardless of input size, rather
// than "by input-size accident" (see the 2026-07-19 MQTT observer review).
#include <gtest/gtest.h>
#include <cstring>
#include "helpers/MQTTReplyFormat.h"
// Lay a canary past the logical buffer so any write at buf[bufsize..] is caught.
// `logical` bytes are the buffer handed to replyAppendf; the trailing GUARD bytes
// must stay 0xAA.
static const size_t GUARD = 8;
struct Canaried {
static const size_t CAP = 256;
char mem[CAP + GUARD];
size_t logical;
explicit Canaried(size_t n) : logical(n) {
memset(mem, 0xAA, sizeof(mem));
mem[0] = '\0';
}
char* buf() { return mem; }
bool guardIntact() const {
for (size_t i = logical; i < logical + GUARD; i++) {
if ((unsigned char)mem[i] != 0xAA) return false;
}
return true;
}
};
TEST(ReplyAppendf, BasicAppendWithinBounds) {
char buf[64];
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "> msgs: %s", "on");
EXPECT_STREQ("> msgs: on", buf);
EXPECT_EQ(pos, 10);
}
TEST(ReplyAppendf, SequenceAccumulates) {
char buf[64];
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "> msgs: %s", "off");
replyAppendf(buf, sizeof(buf), &pos, ", %d: %s (%s)", 1, "denmesh", "ok");
replyAppendf(buf, sizeof(buf), &pos, ", q:%d", 3);
EXPECT_STREQ("> msgs: off, 1: denmesh (ok), q:3", buf);
EXPECT_EQ(pos, (int)strlen(buf));
}
TEST(ReplyAppendf, TruncationClampsPosAndTerminates) {
char buf[16];
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "%s", "0123456789ABCDEF_TOO_LONG");
// Written up to 15 chars + NUL; pos pinned at bufsize-1.
EXPECT_EQ(pos, 15);
EXPECT_EQ(buf[15], '\0');
EXPECT_STREQ("0123456789ABCDE", buf);
}
TEST(ReplyAppendf, AppendAfterFullIsNoOp) {
char buf[8];
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "%s", "AAAAAAAAAAAA"); // overflows
EXPECT_EQ(pos, 7);
char snapshot[8];
memcpy(snapshot, buf, sizeof(buf));
// Further appends must not write anything and must keep pos clamped.
replyAppendf(buf, sizeof(buf), &pos, ", more");
replyAppendf(buf, sizeof(buf), &pos, ", q:%d", 9);
EXPECT_EQ(pos, 7);
EXPECT_EQ(0, memcmp(snapshot, buf, sizeof(buf)));
}
// The A1 reproduction: the old `pos += snprintf(...)` idiom would let pos exceed
// bufsize after a truncated append, so the *next* append wrote at buf+pos with a
// wrapped size_t length. replyAppendf must never touch the guard bytes.
TEST(ReplyAppendf, NoWritePastBufferAcrossOverflowingChain) {
Canaried c(24);
int pos = 0;
// Mimic formatSlotDiagReply's chain, sized to blow well past 24 bytes.
replyAppendf(c.buf(), c.logical, &pos, "> mqtt%d: %s", 6, "no client");
replyAppendf(c.buf(), c.logical, &pos, ", dc:%lu", 4294967295UL);
replyAppendf(c.buf(), c.logical, &pos, ", first_disc:%lus", 4294967295UL);
replyAppendf(c.buf(), c.logical, &pos, ", %s (0x%04X)", "cert verify failed", 0x800Bu);
replyAppendf(c.buf(), c.logical, &pos, ", mbedtls:-0x%04X", 0x8010u);
replyAppendf(c.buf(), c.logical, &pos, ", sock:%d", -2147483647);
replyAppendf(c.buf(), c.logical, &pos, ", %luh ago", 1193046UL);
EXPECT_TRUE(c.guardIntact());
EXPECT_LE(pos, (int)c.logical - 1);
EXPECT_EQ(c.buf()[c.logical - 1], '\0'); // still NUL-terminated
}
TEST(ReplyAppendf, ExactFitBoundary) {
char buf[11]; // room for exactly "0123456789" + NUL
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "%s", "0123456789");
EXPECT_EQ(pos, 10);
EXPECT_STREQ("0123456789", buf);
EXPECT_EQ(buf[10], '\0');
}
TEST(ReplyAppendf, NullAndZeroSizeAreNoOps) {
int pos = 0;
replyAppendf(nullptr, 16, &pos, "x"); // null buf
EXPECT_EQ(pos, 0);
char buf[8] = {'k', 0};
replyAppendf(buf, 0, &pos, "x"); // zero size
EXPECT_STREQ("k", buf);
replyAppendf(buf, sizeof(buf), nullptr, "x"); // null pos
EXPECT_STREQ("k", buf);
}
TEST(ReplyAppendf, BufsizeOneJustTerminates) {
char buf[1];
buf[0] = 'Z';
int pos = 0;
replyAppendf(buf, sizeof(buf), &pos, "anything");
EXPECT_EQ(pos, 0);
EXPECT_EQ(buf[0], '\0');
}
TEST(ReplyAppendf, NegativeIncomingPosTreatedAsZero) {
char buf[16];
memset(buf, 'x', sizeof(buf));
int pos = -5;
replyAppendf(buf, sizeof(buf), &pos, "hi");
EXPECT_EQ(pos, 2);
EXPECT_STREQ("hi", buf);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,70 @@
#include <gtest/gtest.h>
#include <cstdlib>
#include <vector>
#include "helpers/MQTTRuntimeBufferLifecycle.h"
namespace RuntimeBuffers = MQTTRuntimeBufferLifecycle;
TEST(MQTTRuntimeBufferLifecycle, PartialAllocationKeepsOtherBuffersAndRetriesOnlyMissing) {
std::vector<size_t> allocation_sizes;
int allocation_attempt = 0;
const auto allocate = [&allocation_sizes, &allocation_attempt](size_t size) -> void* {
allocation_sizes.push_back(size);
allocation_attempt++;
if (allocation_attempt == 2) {
return nullptr;
}
return std::malloc(size);
};
void* raw = nullptr;
void* publish = nullptr;
void* status = nullptr;
raw = RuntimeBuffers::allocateIfMissing(raw, 256, allocate);
publish = RuntimeBuffers::allocateIfMissing(publish, 2048, allocate);
status = RuntimeBuffers::allocateIfMissing(status, 768, allocate);
ASSERT_NE(nullptr, raw);
EXPECT_EQ(nullptr, publish);
ASSERT_NE(nullptr, status);
ASSERT_EQ(3U, allocation_sizes.size());
void* const initial_raw = raw;
void* const initial_status = status;
raw = RuntimeBuffers::allocateIfMissing(raw, 256, allocate);
publish = RuntimeBuffers::allocateIfMissing(publish, 2048, allocate);
status = RuntimeBuffers::allocateIfMissing(status, 768, allocate);
EXPECT_EQ(4U, allocation_sizes.size());
EXPECT_EQ(2048U, allocation_sizes.back());
EXPECT_EQ(initial_raw, raw);
EXPECT_EQ(initial_status, status);
EXPECT_NE(nullptr, publish);
int releases = 0;
const auto release = [&releases](void* allocation) {
releases++;
std::free(allocation);
};
raw = RuntimeBuffers::release(raw, release);
publish = RuntimeBuffers::release(publish, release);
status = RuntimeBuffers::release(status, release);
EXPECT_EQ(nullptr, raw);
EXPECT_EQ(nullptr, publish);
EXPECT_EQ(nullptr, status);
EXPECT_EQ(3, releases);
raw = RuntimeBuffers::release(raw, release);
publish = RuntimeBuffers::release(publish, release);
status = RuntimeBuffers::release(status, release);
EXPECT_EQ(3, releases);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,198 @@
// Host contract tests for the complete MQTT publication-topic routing policy.
#define WITH_MQTT_BRIDGE 1
#define MQTT_PRESETS_IMPLEMENTATION
#define PROGMEM
#include <gtest/gtest.h>
#include <cstring>
#include <string>
#include "helpers/MQTTPresets.h"
#include "helpers/MQTTTopicRouter.h"
namespace {
constexpr const char* IATA = "DEN";
constexpr const char* DEVICE = "0123456789ABCDEF";
constexpr const char* TOKEN = "account-token";
struct TypeCase {
int type;
const char* name;
};
const TypeCase kTypes[] = {
{MQTT_PUBLICATION_STATUS, "status"},
{MQTT_PUBLICATION_PACKETS, "packets"},
{MQTT_PUBLICATION_RAW, "raw"},
{MQTT_PUBLICATION_NEIGHBORS, "neighbors"},
};
TEST(MQTTTopicRouter, EveryMeshCorePresetSupportsEveryPublicationType) {
for (int preset_index = 0; preset_index < MQTT_PRESET_COUNT; ++preset_index) {
const MQTTPresetDef& preset = MQTT_PRESETS[preset_index];
if (preset.topic_style != MQTT_TOPIC_MESHCORE) continue;
for (const TypeCase& type : kTypes) {
char topic[128];
ASSERT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, type.type, nullptr,
IATA, DEVICE, TOKEN, topic, sizeof(topic)))
<< preset.name << " / " << type.name;
EXPECT_EQ(std::string("meshcore/DEN/0123456789ABCDEF/") + type.name, topic)
<< preset.name;
}
}
}
TEST(MQTTTopicRouter, MeshRankContractIsPacketsOnly) {
const MQTTPresetDef* preset = findMQTTPreset("meshrank");
ASSERT_NE(nullptr, preset);
ASSERT_EQ(MQTT_TOPIC_MESHRANK, preset->topic_style);
char topic[128];
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
ASSERT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_PACKETS,
nullptr, IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("meshrank/uplink/account-token/0123456789ABCDEF/packets", topic);
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_RAW,
nullptr, IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_NEIGHBORS,
nullptr, IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
}
TEST(MQTTTopicRouter, MeshCoreRequiresUsableIataAndDevice) {
char topic[64];
const char* invalid_iatas[] = {nullptr, "", "XX", "XXXX", "X/X", "XXX"};
for (const char* iata : invalid_iatas) {
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, iata, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
}
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, nullptr, TOKEN, topic, sizeof(topic)));
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, "", TOKEN, topic, sizeof(topic)));
}
TEST(MQTTTopicRouter, MeshRankRequiresTokenAndDeviceButNotIata) {
char topic[128];
const char* missing_tokens[] = {nullptr, ""};
for (const char* token : missing_tokens) {
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_PACKETS,
nullptr, nullptr, DEVICE, token, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
}
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_PACKETS,
nullptr, nullptr, nullptr, TOKEN, topic, sizeof(topic)));
EXPECT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, MQTT_PUBLICATION_PACKETS,
nullptr, nullptr, DEVICE, TOKEN, topic, sizeof(topic)));
}
TEST(MQTTTopicRouter, CustomTemplateExpandsEveryType) {
for (const TypeCase& type : kTypes) {
char topic[128];
ASSERT_TRUE(mqttBuildPublicationTopic(
MQTT_ROUTE_CUSTOM, type.type, "custom/{iata}/{token}/{device}/{type}",
IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_EQ(std::string("custom/DEN/account-token/0123456789ABCDEF/") + type.name, topic);
}
}
TEST(MQTTTopicRouter, CustomLiteralDoesNotRequireIataTokenOrDevice) {
char topic[32];
ASSERT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_CUSTOM, MQTT_PUBLICATION_RAW,
"private/raw", nullptr, nullptr, nullptr,
topic, sizeof(topic)));
EXPECT_STREQ("private/raw", topic);
}
TEST(MQTTTopicRouter, EmptyCustomTemplateFailsRatherThanFallingBackImplicitly) {
char topic[64];
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_CUSTOM, MQTT_PUBLICATION_STATUS,
"", IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
// MQTTBridge selects the MeshCore style explicitly for a custom slot whose
// template is empty; make that default contract visible here.
EXPECT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("meshcore/DEN/0123456789ABCDEF/status", topic);
}
TEST(MQTTTopicRouter, FormattedTopicsRequireRoomForTerminator) {
const char* expected = "meshcore/DEN/0123456789ABCDEF/status";
const size_t exact_size = strlen(expected) + 1;
char exact[64];
ASSERT_LE(exact_size, sizeof(exact));
EXPECT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN, exact, exact_size));
EXPECT_STREQ(expected, exact);
char short_buf[64];
memset(short_buf, 0x7f, sizeof(short_buf));
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN,
short_buf, exact_size - 1));
EXPECT_EQ('\0', short_buf[exact_size - 2]);
}
TEST(MQTTTopicRouter, CustomTopicHonorsExactBoundary) {
const char* expected = "custom/DEN/raw";
char exact[15];
static_assert(sizeof(exact) == 15, "fixture includes the terminator");
EXPECT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_CUSTOM, MQTT_PUBLICATION_RAW,
"custom/{iata}/{type}", IATA, DEVICE, TOKEN,
exact, sizeof(exact)));
EXPECT_STREQ(expected, exact);
char short_buf[14];
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_CUSTOM, MQTT_PUBLICATION_RAW,
"custom/{iata}/{type}", IATA, DEVICE, TOKEN,
short_buf, sizeof(short_buf)));
EXPECT_LT(strlen(short_buf), sizeof(short_buf));
}
TEST(MQTTTopicRouter, RejectsInvalidStyleTypeSlotAndOutput) {
char topic[64] = "dirty";
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, 99, nullptr,
IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
EXPECT_FALSE(mqttBuildPublicationTopic(static_cast<MQTTTopicRouteStyle>(99),
MQTT_PUBLICATION_STATUS, nullptr,
IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN, nullptr, 64));
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHCORE, MQTT_PUBLICATION_STATUS,
nullptr, IATA, DEVICE, TOKEN, topic, 0));
EXPECT_FALSE(mqttTopicSlotIndexValid(-1, RUNTIME_MQTT_SLOTS));
EXPECT_TRUE(mqttTopicSlotIndexValid(0, RUNTIME_MQTT_SLOTS));
EXPECT_TRUE(mqttTopicSlotIndexValid(RUNTIME_MQTT_SLOTS - 1, RUNTIME_MQTT_SLOTS));
EXPECT_FALSE(mqttTopicSlotIndexValid(RUNTIME_MQTT_SLOTS, RUNTIME_MQTT_SLOTS));
EXPECT_FALSE(mqttTopicSlotIndexValid(0, 0));
}
TEST(MQTTTopicRouter, PublicationTypeEnumValuesAreFrozen) {
// The bridge passes MQTTBridge::MQTTMessageType to mqttBuildPublicationTopic
// as an int; a compile-time static_assert in the bridge ties the two enums
// together. Freeze the router side here so its values can't drift on their own.
EXPECT_EQ(0, MQTT_PUBLICATION_STATUS);
EXPECT_EQ(1, MQTT_PUBLICATION_PACKETS);
EXPECT_EQ(2, MQTT_PUBLICATION_RAW);
EXPECT_EQ(3, MQTT_PUBLICATION_NEIGHBORS);
EXPECT_STREQ("status", mqttPublicationTypeName(MQTT_PUBLICATION_STATUS));
EXPECT_STREQ("packets", mqttPublicationTypeName(MQTT_PUBLICATION_PACKETS));
EXPECT_STREQ("raw", mqttPublicationTypeName(MQTT_PUBLICATION_RAW));
EXPECT_STREQ("neighbors", mqttPublicationTypeName(MQTT_PUBLICATION_NEIGHBORS));
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,135 @@
// Host tests for the observer input validators shared by the CLI setters
// (src/helpers/MQTTObserverValidation.h): IATA, owner key, NTP hostname, and
// the buffer-fit check behind the #17 length validation.
#include <gtest/gtest.h>
#include <string>
#include "helpers/MQTTObserverValidation.h"
// ---- IATA: exactly 3 alphanumerics ---------------------------------------
TEST(IataValid, AcceptsThreeLetters) {
EXPECT_TRUE(mqttIataValid("DEN"));
EXPECT_TRUE(mqttIataValid("den")); // case handled (setter uppercases after)
EXPECT_TRUE(mqttIataValid("LAX"));
}
TEST(IataValid, AcceptsThreeAlphanumerics) {
EXPECT_TRUE(mqttIataValid("D3N"));
EXPECT_TRUE(mqttIataValid("2M0"));
}
TEST(IataValid, RejectsWrongLength) {
EXPECT_FALSE(mqttIataValid(""));
EXPECT_FALSE(mqttIataValid("D"));
EXPECT_FALSE(mqttIataValid("DE"));
EXPECT_FALSE(mqttIataValid("DENV"));
EXPECT_FALSE(mqttIataValid("DENVER"));
}
TEST(IataValid, RejectsNonAlphanumeric) {
EXPECT_FALSE(mqttIataValid("D-N")); // topic separator-ish
EXPECT_FALSE(mqttIataValid("D N")); // space
EXPECT_FALSE(mqttIataValid("D/N")); // MQTT topic separator
EXPECT_FALSE(mqttIataValid("D+N")); // MQTT wildcard
EXPECT_FALSE(mqttIataValid("D#N")); // MQTT wildcard
}
TEST(IataValid, RejectsNull) {
EXPECT_FALSE(mqttIataValid(nullptr));
}
// ---- owner key: exactly 64 hex -------------------------------------------
static std::string hexKey(int len, char fill = 'a') { return std::string(len, fill); }
TEST(OwnerKeyValid, Accepts64Hex) {
EXPECT_TRUE(mqttOwnerKeyValid(hexKey(64, 'a').c_str()));
EXPECT_TRUE(mqttOwnerKeyValid(hexKey(64, 'F').c_str()));
EXPECT_TRUE(mqttOwnerKeyValid(
"0123456789abcdefABCDEF0123456789abcdefABCDEF0123456789abcdef0123"));
}
TEST(OwnerKeyValid, RejectsWrongLength) {
EXPECT_FALSE(mqttOwnerKeyValid(""));
EXPECT_FALSE(mqttOwnerKeyValid(hexKey(63).c_str()));
EXPECT_FALSE(mqttOwnerKeyValid(hexKey(65).c_str()));
}
TEST(OwnerKeyValid, RejectsNonHex) {
std::string k = hexKey(64);
k[10] = 'g'; // not a hex digit
EXPECT_FALSE(mqttOwnerKeyValid(k.c_str()));
k[10] = 'z';
EXPECT_FALSE(mqttOwnerKeyValid(k.c_str()));
k[10] = ' ';
EXPECT_FALSE(mqttOwnerKeyValid(k.c_str()));
}
TEST(OwnerKeyValid, RejectsNull) {
EXPECT_FALSE(mqttOwnerKeyValid(nullptr));
}
// ---- NTP hostname ---------------------------------------------------------
TEST(NtpHostnameValid, AcceptsTypicalHosts) {
EXPECT_TRUE(mqttNtpHostnameValid("pool.ntp.org"));
EXPECT_TRUE(mqttNtpHostnameValid("time.google.com"));
EXPECT_TRUE(mqttNtpHostnameValid("1.2.3.4"));
EXPECT_TRUE(mqttNtpHostnameValid("a"));
}
TEST(NtpHostnameValid, LengthBoundaryIs63) {
EXPECT_TRUE(mqttNtpHostnameValid(std::string(63, 'a').c_str()));
EXPECT_FALSE(mqttNtpHostnameValid(std::string(64, 'a').c_str()));
}
TEST(NtpHostnameValid, RejectsEmptyAndNull) {
EXPECT_FALSE(mqttNtpHostnameValid(""));
EXPECT_FALSE(mqttNtpHostnameValid(nullptr));
}
TEST(NtpHostnameValid, RejectsLeadingOrTrailingDot) {
EXPECT_FALSE(mqttNtpHostnameValid(".pool.ntp.org"));
EXPECT_FALSE(mqttNtpHostnameValid("pool.ntp.org."));
}
TEST(NtpHostnameValid, RejectsInvalidChars) {
EXPECT_FALSE(mqttNtpHostnameValid("a_b")); // underscore
EXPECT_FALSE(mqttNtpHostnameValid("a b")); // space
EXPECT_FALSE(mqttNtpHostnameValid("http://x")); // scheme / slashes
}
// ---- buffer-fit (the #17 length check) -----------------------------------
TEST(ValueFits, FitsWhenShorterThanBuffer) {
EXPECT_TRUE(mqttValueFits("abc", 4)); // 3 < 4 (room for NUL)
EXPECT_TRUE(mqttValueFits("", 1)); // empty fits any 1+ buffer
}
TEST(ValueFits, RejectsWhenExactlyBufferSizeOrLonger) {
EXPECT_FALSE(mqttValueFits("abcd", 4)); // 4 == 4, no room for NUL
EXPECT_FALSE(mqttValueFits("abcde", 4));
EXPECT_FALSE(mqttValueFits("x", 1));
}
TEST(ValueFits, RealBufferBoundaries) {
// Mirrors the actual MQTTPrefs field sizes the setters pass sizeof() for.
EXPECT_TRUE(mqttValueFits(std::string(63, 'p').c_str(), 64)); // wifi_password[64]
EXPECT_FALSE(mqttValueFits(std::string(64, 'p').c_str(), 64));
EXPECT_TRUE(mqttValueFits(std::string(31, 's').c_str(), 32)); // wifi_ssid[32]
EXPECT_FALSE(mqttValueFits(std::string(32, 's').c_str(), 32));
EXPECT_TRUE(mqttValueFits(std::string(47, 't').c_str(), 48)); // slot token[48]
EXPECT_FALSE(mqttValueFits(std::string(48, 't').c_str(), 48));
EXPECT_TRUE(mqttValueFits(std::string(95, 'x').c_str(), 96)); // slot topic[96]
EXPECT_FALSE(mqttValueFits(std::string(96, 'x').c_str(), 96));
}
TEST(ValueFits, RejectsNullOrZeroBuffer) {
EXPECT_FALSE(mqttValueFits(nullptr, 32));
EXPECT_FALSE(mqttValueFits("abc", 0));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,113 @@
// Host tests for the MQTT custom-topic placeholder expansion
// (src/helpers/MQTTTopicTemplate.h), the pure core of
// MQTTBridge::substituteTopicTemplate.
#include <gtest/gtest.h>
#include <cstring>
#include "helpers/MQTTTopicTemplate.h"
static const char* IATA = "DEN";
static const char* DEV = "abcdef0123456789";
static const char* TOK = "tok123";
TEST(TopicTemplate, SubstitutesAllPlaceholders) {
char buf[128];
ASSERT_TRUE(mqttSubstituteTopic("meshcore/{iata}/{device}/{type}", IATA, DEV, TOK, "status",
buf, sizeof(buf)));
EXPECT_STREQ("meshcore/DEN/abcdef0123456789/status", buf);
}
TEST(TopicTemplate, TokenPlaceholder) {
char buf[128];
ASSERT_TRUE(mqttSubstituteTopic("meshrank/uplink/{token}/{device}/packets",
IATA, DEV, TOK, "packets", buf, sizeof(buf)));
EXPECT_STREQ("meshrank/uplink/tok123/abcdef0123456789/packets", buf);
}
TEST(TopicTemplate, RepeatedPlaceholder) {
char buf[64];
ASSERT_TRUE(mqttSubstituteTopic("{iata}-{iata}", IATA, DEV, TOK, "raw", buf, sizeof(buf)));
EXPECT_STREQ("DEN-DEN", buf);
}
TEST(TopicTemplate, LiteralWithNoPlaceholders) {
char buf[64];
ASSERT_TRUE(mqttSubstituteTopic("plain/topic/path", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_STREQ("plain/topic/path", buf);
}
TEST(TopicTemplate, UnknownBracesCopiedVerbatim) {
char buf[64];
ASSERT_TRUE(mqttSubstituteTopic("a/{bogus}/{iata}", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_STREQ("a/{bogus}/DEN", buf);
}
TEST(TopicTemplate, TypeStringVaries) {
char buf[64];
mqttSubstituteTopic("{type}", IATA, DEV, TOK, "status", buf, sizeof(buf));
EXPECT_STREQ("status", buf);
mqttSubstituteTopic("{type}", IATA, DEV, TOK, "packets", buf, sizeof(buf));
EXPECT_STREQ("packets", buf);
mqttSubstituteTopic("{type}", IATA, DEV, TOK, "raw", buf, sizeof(buf));
EXPECT_STREQ("raw", buf);
}
TEST(TopicTemplate, NullValuesSubstituteEmpty) {
char buf[64];
ASSERT_TRUE(mqttSubstituteTopic("x/{token}/y", IATA, DEV, nullptr, "status", buf, sizeof(buf)));
EXPECT_STREQ("x//y", buf);
}
TEST(TopicTemplate, OverflowReturnsFalseNoWrite) {
// Substituting {device} (16 chars) into a template won't fit an 8-byte buffer.
char buf[8];
EXPECT_FALSE(mqttSubstituteTopic("{device}", IATA, DEV, TOK, "status", buf, sizeof(buf)));
}
TEST(TopicTemplate, LiteralOverflowReturnsFalseAndNulTerminates) {
char buf[5];
// Literal longer than the buffer: fills up to buf_size-1 and NUL-terminates.
EXPECT_FALSE(mqttSubstituteTopic("abcdefghij", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_EQ('\0', buf[4]);
EXPECT_EQ((size_t)4, strlen(buf));
}
TEST(TopicTemplate, LiteralSuffixOverflowAfterSubstitutionReturnsFalse) {
char buf[8];
EXPECT_FALSE(mqttSubstituteTopic("{iata}/tail", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_STREQ("DEN/tai", buf);
}
TEST(TopicTemplate, ExactFitLiteralSucceeds) {
char buf[5];
EXPECT_TRUE(mqttSubstituteTopic("abcd", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_STREQ("abcd", buf);
}
TEST(TopicTemplate, AlwaysNulTerminatedAndBounded) {
// Fuzz-ish: many buffer sizes never overrun and always NUL-terminate.
const char* tmpl = "meshcore/{iata}/{device}/{token}/{type}/tail";
for (size_t sz = 1; sz <= 80; sz++) {
char buf[96];
memset(buf, 0x7f, sizeof(buf));
mqttSubstituteTopic(tmpl, IATA, DEV, TOK, "packets", buf, sz);
EXPECT_LT(strlen(buf), sz) << "size " << sz; // fits with room for NUL
EXPECT_EQ('\0', buf[strlen(buf)]);
}
}
TEST(TopicTemplate, ZeroBufferOrNullFails) {
char buf[8];
EXPECT_FALSE(mqttSubstituteTopic("x", IATA, DEV, TOK, "status", buf, 0));
EXPECT_FALSE(mqttSubstituteTopic("x", IATA, DEV, TOK, "status", nullptr, 8));
}
TEST(TopicTemplate, EmptyTemplateReturnsFalse) {
char buf[8];
EXPECT_FALSE(mqttSubstituteTopic("", IATA, DEV, TOK, "status", buf, sizeof(buf)));
EXPECT_STREQ("", buf);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,206 @@
// Host contract tests for the pure WebConfig config-batch / reboot / stop state
// machine. This spec mirrors src/helpers/esp32/WebConfigServer.cpp; it is not
// yet wired into the bridge (see WebConfigBatch.h scope note).
#include <gtest/gtest.h>
#include <stdint.h>
#include <limits>
#include "helpers/WebConfigBatch.h"
namespace Batch = WebConfigBatch;
using State = WebConfigBatch::State;
// --------------------------------------------------------------------------
// POST accept classification
// --------------------------------------------------------------------------
TEST(WebConfigBatch, IdleAcceptsANewBatchWithChangesOrRebootOnly) {
// A normal save (changes present) is accepted.
EXPECT_EQ(Batch::PostOutcome::Accept,
Batch::classifyPost(State::Idle, /*reqid_matches=*/false, /*count=*/3, false));
// A reboot-only request (no changes) is still accepted.
EXPECT_EQ(Batch::PostOutcome::Accept,
Batch::classifyPost(State::Idle, false, 0, /*reboot_after=*/true));
}
TEST(WebConfigBatch, IdleWithNothingToDoIsNoChanges) {
EXPECT_EQ(Batch::PostOutcome::NoChanges,
Batch::classifyPost(State::Idle, false, 0, false));
}
TEST(WebConfigBatch, SameReqidReplaysWithoutReapplyingWhilePendingOrDone) {
// The idempotent-replay path fires for BOTH in-flight and finished batches
// when the reqid matches; commands are never re-applied.
EXPECT_EQ(Batch::PostOutcome::Replay,
Batch::classifyPost(State::Pending, /*reqid_matches=*/true, 3, false));
EXPECT_EQ(Batch::PostOutcome::Replay,
Batch::classifyPost(State::Done, /*reqid_matches=*/true, 3, false));
// Replay wins even over a would-be no-changes request.
EXPECT_EQ(Batch::PostOutcome::Replay,
Batch::classifyPost(State::Pending, true, 0, false));
// The replay body reports the batch's own state.
EXPECT_STREQ("pending", Batch::replayStateName(State::Pending));
EXPECT_STREQ("done", Batch::replayStateName(State::Done));
}
TEST(WebConfigBatch, DifferentReqidIsBusyOnlyWhilePending) {
// A second client (different reqid) while a batch is still draining => busy.
EXPECT_EQ(Batch::PostOutcome::Busy,
Batch::classifyPost(State::Pending, /*reqid_matches=*/false, 2, false));
// But once the previous batch is DONE, a different reqid is NOT busy: the new
// batch overwrites the finished slot (asymmetry with the Pending case).
EXPECT_EQ(Batch::PostOutcome::Accept,
Batch::classifyPost(State::Done, false, 2, false));
EXPECT_EQ(Batch::PostOutcome::NoChanges,
Batch::classifyPost(State::Done, false, 0, false));
}
// --------------------------------------------------------------------------
// Drain pacing / all_ok / finish
// --------------------------------------------------------------------------
TEST(WebConfigBatch, DrainNeverWaitsBeforeTheFirstOrAfterTheLastCommand) {
// batch_next == 0: the first command runs immediately (fires onConfigBatchStart).
EXPECT_FALSE(Batch::drainMustWait(0, 5, 1000, 1000));
// batch_next >= batch_count: nothing left to pace.
EXPECT_FALSE(Batch::drainMustWait(5, 5, 1000, 1000));
// A single-command (or reboot-only) batch never paces.
EXPECT_FALSE(Batch::drainMustWait(0, 1, 1000, 1000));
EXPECT_FALSE(Batch::drainMustWait(0, 0, 1000, 1000));
}
TEST(WebConfigBatch, DrainPacesTwentyFiveMillisBetweenCommandsWithInclusiveRelease) {
const uint32_t last = 1000;
// 24 ms after the previous command: still waiting.
EXPECT_TRUE(Batch::drainMustWait(2, 5, last + 24, last));
// Exactly 25 ms: the gate releases (production uses `< 25`).
EXPECT_FALSE(Batch::drainMustWait(2, 5, last + 25, last));
EXPECT_FALSE(Batch::drainMustWait(2, 5, last + 26, last));
}
TEST(WebConfigBatch, DrainPacingSurvivesMillisRollover) {
const uint32_t last = std::numeric_limits<uint32_t>::max() - 10;
EXPECT_TRUE(Batch::drainMustWait(2, 5, last + 24, last)); // 24 ms elapsed, wrapped
EXPECT_FALSE(Batch::drainMustWait(2, 5, last + 25, last)); // 25 ms elapsed, wrapped
}
TEST(WebConfigBatch, AllOkIsAStickyAndAcrossCommandReplies) {
bool all_ok = true;
all_ok = Batch::nextAllOk(all_ok, true);
EXPECT_TRUE(all_ok);
all_ok = Batch::nextAllOk(all_ok, false); // one command failed
EXPECT_FALSE(all_ok);
all_ok = Batch::nextAllOk(all_ok, true); // stays false forever after
EXPECT_FALSE(all_ok);
}
TEST(WebConfigBatch, DrainFinishesWhenTheIndexReachesTheCount) {
EXPECT_FALSE(Batch::drainFinished(4, 5));
EXPECT_TRUE(Batch::drainFinished(5, 5));
EXPECT_TRUE(Batch::drainFinished(0, 0)); // reboot-only / empty batch
}
TEST(WebConfigBatch, FinishArmsThirtySecondFallbackOnlyForAFullyOkRebootBatch) {
const uint32_t now = 100000;
EXPECT_EQ(now + Batch::kRebootFallbackMs,
Batch::finishRebootAt(/*reboot=*/true, /*all_ok=*/true, now));
// A partially-failed batch never reboots.
EXPECT_EQ(0u, Batch::finishRebootAt(true, false, now));
// No reboot requested.
EXPECT_EQ(0u, Batch::finishRebootAt(false, true, now));
}
// --------------------------------------------------------------------------
// Result read
// --------------------------------------------------------------------------
TEST(WebConfigBatch, ResultReadClassifiesIdlePendingDoneAndUnknownReqid) {
// Idle: any valid reqid gets "idle" (no reqid check while idle).
EXPECT_EQ(Batch::ResultOutcome::Idle, Batch::classifyResult(State::Idle, false));
EXPECT_EQ(Batch::ResultOutcome::Idle, Batch::classifyResult(State::Idle, true));
// Matching reqid reflects the batch state.
EXPECT_EQ(Batch::ResultOutcome::Pending, Batch::classifyResult(State::Pending, true));
EXPECT_EQ(Batch::ResultOutcome::Done, Batch::classifyResult(State::Done, true));
// A live/finished batch with a mismatched reqid is unknown (404).
EXPECT_EQ(Batch::ResultOutcome::Unknown, Batch::classifyResult(State::Pending, false));
EXPECT_EQ(Batch::ResultOutcome::Unknown, Batch::classifyResult(State::Done, false));
}
TEST(WebConfigBatch, DoneBodyAdvertisesRebootOnlyWhenFullyOk) {
EXPECT_TRUE(Batch::doneReportsReboot(true, true));
EXPECT_FALSE(Batch::doneReportsReboot(true, false));
EXPECT_FALSE(Batch::doneReportsReboot(false, true));
}
TEST(WebConfigBatch, FirstDoneReadArmsTheThreeSecondRebootExactlyOnce) {
const uint32_t now = 500000;
// First read of a fully-OK reboot batch arms.
EXPECT_TRUE(Batch::shouldArmConfirmReboot(State::Done, true, true, /*already_armed=*/false));
EXPECT_EQ(now + Batch::kRebootConfirmMs, Batch::confirmRebootAt(now));
// Already armed => never re-arms (polling can't push the deadline out).
EXPECT_FALSE(Batch::shouldArmConfirmReboot(State::Done, true, true, /*already_armed=*/true));
// Not applicable while pending, without reboot, or after a partial failure.
EXPECT_FALSE(Batch::shouldArmConfirmReboot(State::Pending, true, true, false));
EXPECT_FALSE(Batch::shouldArmConfirmReboot(State::Done, false, true, false));
EXPECT_FALSE(Batch::shouldArmConfirmReboot(State::Done, true, false, false));
}
// --------------------------------------------------------------------------
// Reboot fire / pending
// --------------------------------------------------------------------------
TEST(WebConfigBatch, RebootFiresAtOrAfterTheDeadlineAndNeverWhenUnscheduled) {
EXPECT_FALSE(Batch::rebootDue(0, 1234567)); // 0 == unscheduled
const uint32_t at = 100000;
EXPECT_FALSE(Batch::rebootDue(at, at - 1));
EXPECT_TRUE(Batch::rebootDue(at, at)); // inclusive boundary
EXPECT_TRUE(Batch::rebootDue(at, at + 1));
}
TEST(WebConfigBatch, RebootDueSurvivesMillisRollover) {
const uint32_t at = std::numeric_limits<uint32_t>::max() - 5; // near the top
EXPECT_FALSE(Batch::rebootDue(at, at - 1));
EXPECT_TRUE(Batch::rebootDue(at, at));
EXPECT_TRUE(Batch::rebootDue(at, at + 10)); // now has wrapped past zero
}
TEST(WebConfigBatch, OnlyAConfigSaveRebootInDoneStateReportsPending) {
EXPECT_TRUE(Batch::isConfigRebootPending(/*reboot_at=*/123, /*batch_reboot=*/true, State::Done));
// Manual /api/reboot: reboot_at set but batch_reboot false => not "pending".
EXPECT_FALSE(Batch::isConfigRebootPending(123, false, State::Done));
// Not yet done, or nothing scheduled.
EXPECT_FALSE(Batch::isConfigRebootPending(123, true, State::Pending));
EXPECT_FALSE(Batch::isConfigRebootPending(0, true, State::Done));
}
// --------------------------------------------------------------------------
// Stop gating
// --------------------------------------------------------------------------
TEST(WebConfigBatch, StopFinalizesOnlyWhenNoHandlersAreInFlight) {
EXPECT_EQ(Batch::StopAction::Finalize,
Batch::stopStep(/*refs=*/0, /*warned=*/false, /*warn_at=*/50000, /*now=*/60000));
}
TEST(WebConfigBatch, StopWarnsOnceAfterTheDeadlineThenKeepsWaiting) {
const uint32_t warn_at = 50000;
// Before the warn deadline with handlers in flight: just wait.
EXPECT_EQ(Batch::StopAction::Wait, Batch::stopStep(2, false, warn_at, warn_at - 1));
// At the deadline, not yet warned: warn once.
EXPECT_EQ(Batch::StopAction::Warn, Batch::stopStep(2, false, warn_at, warn_at));
// Already warned: keep waiting (never warns again, never forces teardown).
EXPECT_EQ(Batch::StopAction::Wait, Batch::stopStep(2, true, warn_at, warn_at + 100000));
// An unscheduled warn timer never warns.
EXPECT_EQ(Batch::StopAction::Wait, Batch::stopStep(2, false, 0, 999999));
}
// --------------------------------------------------------------------------
// Wrap-around guard shared with the production _reboot_at assignments
// --------------------------------------------------------------------------
TEST(WebConfigBatch, ScheduleAtNeverReturnsTheUnscheduledSentinel) {
EXPECT_EQ(1000u + 3000u, Batch::scheduleAt(1000, 3000));
// A deadline that lands exactly on 0 is bumped to 1 so it still means "set".
const uint32_t just_below_wrap = std::numeric_limits<uint32_t>::max(); // +1 wraps to 0
EXPECT_EQ(1u, Batch::scheduleAt(just_below_wrap, 1));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,140 @@
// Host tests for the WebConfig key allowlist / secret / slot-prefix helpers
// (src/helpers/WebConfigKeys.h). These parse attacker-supplied POST keys, so
// coverage of the length-guard and boundary cases matters for safety.
#include <gtest/gtest.h>
#include "helpers/WebConfigKeys.h"
// ---- allowlist ------------------------------------------------------------
TEST(WebConfigKeys, AllowsKnownScalarKeys) {
EXPECT_TRUE(wcIsAllowedSetKey("name"));
EXPECT_TRUE(wcIsAllowedSetKey("radio"));
EXPECT_TRUE(wcIsAllowedSetKey("repeat"));
EXPECT_TRUE(wcIsAllowedSetKey("wifi.ssid"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt.iata"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt.neighbors"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt.neighbors.interval"));
EXPECT_TRUE(wcIsAllowedSetKey("snmp.community"));
EXPECT_TRUE(wcIsAllowedSetKey("timezone.offset"));
}
TEST(WebConfigKeys, AllowsPerSlotKeys) {
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.preset"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.server"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.token"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt6.audience")); // MAX_MQTT_SLOTS == 6
}
TEST(WebConfigKeys, RejectsDangerousOrUnknownKeys) {
EXPECT_FALSE(wcIsAllowedSetKey("erase"));
EXPECT_FALSE(wcIsAllowedSetKey("password"));
EXPECT_FALSE(wcIsAllowedSetKey("reboot"));
EXPECT_FALSE(wcIsAllowedSetKey("bogus"));
EXPECT_FALSE(wcIsAllowedSetKey("mqtt1.bogus")); // unknown slot field
EXPECT_FALSE(wcIsAllowedSetKey(""));
}
TEST(WebConfigKeys, AdminPasswordIsNotAnAllowlistedSetKey) {
EXPECT_TRUE(wcIsAdminPasswordKey("password"));
EXPECT_FALSE(wcIsAdminPasswordKey("admin.password"));
EXPECT_FALSE(wcIsAdminPasswordKey(""));
EXPECT_FALSE(wcIsAllowedSetKey("password")); // never reachable as `set password`
}
TEST(WebConfigKeys, AdminPasswordFitsNodePrefsAndRejectsLineBreaks) {
EXPECT_FALSE(wcIsValidAdminPassword(NULL));
EXPECT_FALSE(wcIsValidAdminPassword(""));
EXPECT_TRUE(wcIsValidAdminPassword("new-password"));
EXPECT_TRUE(wcIsValidAdminPassword("123456789012345"));
EXPECT_FALSE(wcIsValidAdminPassword("1234567890123456"));
EXPECT_FALSE(wcIsValidAdminPassword("line\nbreak"));
EXPECT_FALSE(wcIsValidAdminPassword("line\rbreak"));
}
TEST(WebConfigKeys, SlotIndexBoundsMatchMaxSlots) {
EXPECT_FALSE(wcIsAllowedSetKey("mqtt0.preset")); // slot 0 invalid
EXPECT_TRUE(wcIsAllowedSetKey("mqtt6.preset")); // last valid slot
EXPECT_FALSE(wcIsAllowedSetKey("mqtt7.preset")); // beyond MAX_MQTT_SLOTS
EXPECT_FALSE(wcIsAllowedSetKey("mqtt9.preset"));
}
TEST(WebConfigKeys, IsCaseSensitive) {
EXPECT_FALSE(wcIsAllowedSetKey("Name"));
EXPECT_FALSE(wcIsAllowedSetKey("MQTT1.preset"));
}
// ---- short-key OOB guard --------------------------------------------------
// The slot-prefix probe indexes key[4..6]; these short strings must be rejected
// without ever reading past the terminator.
TEST(WebConfigKeys, ShortKeysRejectedSafely) {
EXPECT_FALSE(wcIsSlotKeyPrefix(""));
EXPECT_FALSE(wcIsSlotKeyPrefix("m"));
EXPECT_FALSE(wcIsSlotKeyPrefix("mq"));
EXPECT_FALSE(wcIsSlotKeyPrefix("mqt"));
EXPECT_FALSE(wcIsSlotKeyPrefix("mqtt")); // 4 chars -- no digit/dot
EXPECT_FALSE(wcIsSlotKeyPrefix("mqtt1")); // 5 chars -- no dot
EXPECT_FALSE(wcIsSlotKeyPrefix("mqtt1.")); // 6 chars -- no field char
EXPECT_TRUE(wcIsSlotKeyPrefix("mqtt1.x")); // 7 chars -- minimum valid
// Same guard via the public allowlist/secret entry points:
EXPECT_FALSE(wcIsAllowedSetKey("mqtt"));
EXPECT_FALSE(wcIsSecretKey("m"));
EXPECT_FALSE(wcIsSecretKey("mqtt"));
}
TEST(WebConfigKeys, SlotPrefixDigitRange) {
EXPECT_FALSE(wcIsSlotKeyPrefix("mqtt0.x"));
EXPECT_TRUE(wcIsSlotKeyPrefix("mqtt6.x"));
EXPECT_FALSE(wcIsSlotKeyPrefix("mqtt7.x"));
EXPECT_FALSE(wcIsSlotKeyPrefix("mqttA.x")); // non-digit
}
// ---- secret classification ------------------------------------------------
TEST(WebConfigKeys, SecretKeysDetected) {
EXPECT_TRUE(wcIsSecretKey("wifi.pwd"));
EXPECT_TRUE(wcIsSecretKey("mqtt1.password"));
EXPECT_TRUE(wcIsSecretKey("mqtt3.token"));
EXPECT_TRUE(wcIsSecretKey("mqtt6.password"));
}
TEST(WebConfigKeys, NonSecretKeysNotFlagged) {
EXPECT_FALSE(wcIsSecretKey("wifi.ssid"));
EXPECT_FALSE(wcIsSecretKey("mqtt1.username")); // username is not masked
EXPECT_FALSE(wcIsSecretKey("mqtt1.server"));
EXPECT_FALSE(wcIsSecretKey("mqtt.origin"));
EXPECT_FALSE(wcIsSecretKey("name"));
EXPECT_FALSE(wcIsSecretKey(""));
}
TEST(WebConfigKeys, EverySecretKeyIsAlsoAllowed) {
// A secret key must be one the portal can actually set, or the masking is moot.
const char* secrets[] = {"wifi.pwd", "mqtt1.password", "mqtt1.token",
"mqtt6.password", "mqtt6.token"};
for (const char* k : secrets) {
EXPECT_TRUE(wcIsSecretKey(k)) << k;
EXPECT_TRUE(wcIsAllowedSetKey(k)) << k;
}
}
// ---- request correlation -------------------------------------------------
TEST(WebConfigKeys, AcceptsExactHexRequestIds) {
EXPECT_TRUE(wcIsValidReqId("0123456789abcdef"));
EXPECT_TRUE(wcIsValidReqId("ABCDEF0123456789"));
}
TEST(WebConfigKeys, RejectsMissingMalformedOrWrongLengthRequestIds) {
EXPECT_FALSE(wcIsValidReqId(NULL));
EXPECT_FALSE(wcIsValidReqId(""));
EXPECT_FALSE(wcIsValidReqId("0123456789abcde"));
EXPECT_FALSE(wcIsValidReqId("0123456789abcdef0"));
EXPECT_FALSE(wcIsValidReqId("0123456789abcdeg"));
EXPECT_FALSE(wcIsValidReqId("01234567-9abcdef"));
EXPECT_FALSE(wcIsValidReqId("01234567 9abcdef"));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}