Merge remote-tracking branch 'review/observer-firmware' into keymindCascade

# Conflicts:
#	.github/workflows/build-observer-firmwares.yml
#	.gitignore
#	MQTT_IMPLEMENTATION.md
#	MQTT_INTERNALS.md
#	README.md
#	STABILITY_TESTABILITY_HANDOFF.md
#	docs/cli_commands.md
#	examples/companion_radio/MyMesh.cpp
#	examples/simple_repeater/MyMesh.cpp
#	examples/simple_repeater/UITask.cpp
#	examples/simple_room_server/MyMesh.cpp
#	examples/simple_room_server/UITask.cpp
#	examples/simple_sensor/SensorMesh.cpp
#	platformio.ini
#	scripts/generate_webconfig_html.py
#	scripts/webconfig_mock_server.py
#	src/helpers/CommonCLI.cpp
#	src/helpers/CommonCLI.h
#	src/helpers/JWTHelper.cpp
#	src/helpers/MQTTDefaults.h
#	src/helpers/MQTTMessageBuilder.cpp
#	src/helpers/MQTTPayloadBuilder.h
#	src/helpers/MQTTPresets.h
#	src/helpers/bridges/MQTTBridge.h
#	src/helpers/esp32/WebConfigServer.cpp
#	src/helpers/esp32/WebConfigServer.h
#	src/helpers/ui/SH1106Display.cpp
#	variants/lilygo_tbeam_SX1262/platformio.ini
#	variants/lilygo_tbeam_SX1276/platformio.ini
#	variants/lilygo_tlora_v2_1/platformio.ini
#	variants/thinknode_m7/platformio.ini
#	webui/index.html
This commit is contained in:
mikecarper committed 2026-08-14 08:53:02 -07:00
commit a04a284a3f
74 files changed
+7857 -2483

No files matched your search

+3 -2
View File
@@ -28,14 +28,15 @@ does not reflect the GoogleTest count -- run the built binary directly
| `test_webconfig_keys` | `src/helpers/WebConfigKeys.h` | POST-key allowlist, secret detection, admin-password and browser-terminal command validation, slot-index bounds, and short-input guards |
| `test_webconfig_batch` | `src/helpers/WebConfigBatch.h` | config POST/replay/busy decisions; paced command drain; setup WiFi validation/IP handoff; reboot confirmation/fallback; stop/refcount gating; exact timing and rollover boundaries |
| `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_topic_router` | `src/helpers/MQTTTopicRouter.h` | complete preset/custom topic-routing contract; MeshRank all types except raw; 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_wifi_reconnect_policy` | `src/helpers/WiFiReconnectPolicy.h` | five-minute forced reconnect cadence, connection resets, duplicate disconnect observations, and 32-bit `millis()` rollover |
| `test_radio_liveness` | `src/helpers/RadioLivenessTracker.h`, `src/helpers/radiolib/RxBoostedGainDefaults.h` | staged radio recovery, activity reset and rollover handling; target-specific RX boosted-gain defaults and SX126x precedence |
| `test_lr1110_rx_recovery` | `src/helpers/radiolib/LR1110RxRecovery.h` | LR1110 four-byte RX-buffer shift signature; captured and accumulated shifts; ordinary/scoped packet exclusions |
| `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_packet_filter` | `src/helpers/MQTTPacketFilter.h` | per-slot 0-15 allowlist parsing/formatting, numeric and named spellings; exact bounds; membership; candidate/eligible split and retry-completion policy; pre-queue union gate; default-mask detection |
| `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_codec` | `src/helpers/MQTTPrefsStorage.h`, `src/helpers/MQTTPrefsCodec.h` | binary pre-slot/3-slot/6-slot migration fixtures; v1 header integrity; downgrade preservation; shortest-payload write policy (default filters stay downgrade-readable) |
| `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_prefs_save_routing` | `src/helpers/PrefsSaveRouting.h` | runtime common/observer setters write only their owning preference image; mixed-owner setters and migrations can deliberately write both |
| `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 |
+3
View File
@@ -0,0 +1,3 @@
#pragma once
class TwoWire { };
@@ -0,0 +1,303 @@
#include <gtest/gtest.h>
#include "helpers/MQTTPacketFilter.h"
namespace Filter = MQTTPacketFilter;
TEST(MQTTPacketFilter, EmptyAndAllMeanEveryType) {
for (const char* value : {"", " ", "\tall\r\n"}) {
uint16_t mask = 0;
ASSERT_TRUE(Filter::parse(value, &mask)) << value;
EXPECT_EQ(Filter::kAllPacketTypes, mask);
}
}
TEST(MQTTPacketFilter, NoneMeansNoTypes) {
uint16_t mask = Filter::kAllPacketTypes;
ASSERT_TRUE(Filter::parse(" none ", &mask));
EXPECT_EQ(0u, mask);
}
TEST(MQTTPacketFilter, ParsesDecimalCsvWithWhitespaceAndDuplicates) {
uint16_t mask = 0;
ASSERT_TRUE(Filter::parse(" 2, 4,\t15,2 ", &mask));
EXPECT_EQ(static_cast<uint16_t>((1u << 2) | (1u << 4) | (1u << 15)), mask);
}
TEST(MQTTPacketFilter, FullNumericListCanonicalizesToAll) {
uint16_t mask = 0;
ASSERT_TRUE(Filter::parse("0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15", &mask));
EXPECT_EQ(Filter::kAllPacketTypes, mask);
char output[Filter::kFilterTextSize];
ASSERT_TRUE(Filter::format(mask, output, sizeof(output)));
EXPECT_STREQ("all", output);
}
TEST(MQTTPacketFilter, ParsesPayloadTypeNames) {
uint16_t mask = 0;
ASSERT_TRUE(Filter::parse("advert", &mask));
EXPECT_EQ(static_cast<uint16_t>(1u << 4), mask);
ASSERT_TRUE(Filter::parse(" txt_msg , grp_txt ", &mask));
EXPECT_EQ(static_cast<uint16_t>((1u << 2) | (1u << 5)), mask);
// Names and numbers are interchangeable within one list.
ASSERT_TRUE(Filter::parse("advert,2,raw_custom", &mask));
EXPECT_EQ(static_cast<uint16_t>((1u << 4) | (1u << 2) | (1u << 15)), mask);
// Output stays numeric regardless of how the value was spelled.
char output[Filter::kFilterTextSize];
ASSERT_TRUE(Filter::format(mask, output, sizeof(output)));
EXPECT_STREQ("2,4,15", output);
}
TEST(MQTTPacketFilter, EveryNamedTypeResolvesToItsPacketHeaderValue) {
// Pins the table against src/Packet.h's PAYLOAD_TYPE_* values.
const struct { const char* name; uint8_t type; } expected[] = {
{"req", 0}, {"response", 1}, {"txt_msg", 2}, {"ack", 3}, {"advert", 4},
{"grp_txt", 5}, {"grp_data", 6}, {"anon_req", 7}, {"path", 8},
{"trace", 9}, {"multipart", 10}, {"control", 11}, {"raw_custom", 15},
};
for (const auto& e : expected) {
uint16_t mask = 0;
ASSERT_TRUE(Filter::parse(e.name, &mask)) << e.name;
EXPECT_EQ(static_cast<uint16_t>(1u << e.type), mask) << e.name;
}
// Reserved types have no name and stay reachable by number only.
size_t count = 0;
const Filter::NamedPacketType* names = Filter::namedPacketTypes(&count);
EXPECT_EQ(sizeof(expected) / sizeof(expected[0]), count);
for (size_t i = 0; i < count; ++i) {
EXPECT_TRUE(names[i].type < 12 || names[i].type == 15) << names[i].name;
}
}
TEST(MQTTPacketFilter, RejectsMalformedOrOutOfRangeValuesWithoutChangingOutput) {
const char* invalid[] = {
",", "1,", ",1", "1,,2", "1, ,2", "-1", "+1", "0x2", "16",
"999999999999999999999", "ALL", "All", "all,2", "none,2", "2-4", "2x",
// Names are lowercase, exact, and are not whole-value keywords.
"ADVERT", "Advert", "advert_", "adver", "advertx", "reserved", "12_reserved",
"2,all", "advert,none", "advert advert", "advert;2",
};
for (const char* value : invalid) {
uint16_t mask = 0x1234;
EXPECT_FALSE(Filter::parse(value, &mask)) << value;
EXPECT_EQ(0x1234, mask) << value;
}
EXPECT_FALSE(Filter::parse(nullptr, nullptr));
}
TEST(MQTTPacketFilter, FormatsSubsetsInAscendingOrder) {
const uint16_t mask = static_cast<uint16_t>(
(1u << 15) | (1u << 2) | (1u << 10) | (1u << 0));
char output[Filter::kFilterTextSize];
ASSERT_TRUE(Filter::format(mask, output, sizeof(output)));
EXPECT_STREQ("0,2,10,15", output);
}
TEST(MQTTPacketFilter, FormatsNoneAndHonorsExactBufferBoundaries) {
char none[5];
ASSERT_TRUE(Filter::format(0, none, sizeof(none)));
EXPECT_STREQ("none", none);
char too_small[4] = {'x', 'x', 'x', '\0'};
EXPECT_FALSE(Filter::format(0, too_small, sizeof(too_small)));
EXPECT_STREQ("", too_small);
char all_types[Filter::kFilterTextSize];
const uint16_t subset = static_cast<uint16_t>(Filter::kAllPacketTypes & ~(1u << 14));
ASSERT_TRUE(Filter::format(subset, all_types, sizeof(all_types)));
EXPECT_STREQ("0,1,2,3,4,5,6,7,8,9,10,11,12,13,15", all_types);
char one_short[34];
EXPECT_FALSE(Filter::format(subset, one_short, sizeof(one_short)));
EXPECT_STREQ("", one_short);
}
TEST(MQTTPacketFilter, MembershipIsBoundedToFourBitTypes) {
EXPECT_TRUE(Filter::allows(static_cast<uint16_t>(1u << 0), 0));
EXPECT_TRUE(Filter::allows(static_cast<uint16_t>(1u << 15), 15));
EXPECT_FALSE(Filter::allows(Filter::kAllPacketTypes, 16));
EXPECT_FALSE(Filter::allows(0, 0));
}
TEST(MQTTPacketFilter, EligibilityIgnoresConnectionButRequiresTopicAndFilter) {
const uint16_t only_advert = static_cast<uint16_t>(1u << 4);
EXPECT_TRUE(Filter::slotEligible(true, true, only_advert, 4));
EXPECT_FALSE(Filter::slotEligible(false, true, only_advert, 4));
EXPECT_FALSE(Filter::slotEligible(true, false, only_advert, 4));
EXPECT_FALSE(Filter::slotEligible(true, true, only_advert, 2));
}
TEST(MQTTPacketFilter, AllFilteredOrTopicIncompatibleTargetsCompleteIntentionally) {
const uint16_t only_text = static_cast<uint16_t>(1u << 2);
const bool filtered = Filter::slotEligible(true, true, only_text, 4);
const bool topic_incompatible =
Filter::slotEligible(true, false, Filter::kAllPacketTypes, 4);
EXPECT_FALSE(filtered || topic_incompatible);
EXPECT_TRUE(Filter::publishComplete(filtered || topic_incompatible, false));
}
TEST(MQTTPacketFilter, EligibleDisconnectedTargetStillRequiresRetry) {
const uint16_t only_advert = static_cast<uint16_t>(1u << 4);
// Connection state is intentionally absent from slotEligible(): the first
// slot remains a target while disconnected. A second connected slot whose
// filter rejects the advert cannot turn that into intentional completion.
const bool disconnected_eligible =
Filter::slotEligible(true, true, only_advert, 4);
const bool connected_filtered =
Filter::slotEligible(true, true, static_cast<uint16_t>(1u << 2), 4);
ASSERT_TRUE(disconnected_eligible);
ASSERT_FALSE(connected_filtered);
EXPECT_FALSE(Filter::publishComplete(
disconnected_eligible || connected_filtered, false));
}
TEST(MQTTPacketFilter, PublishFailureRetriesAndAnySuccessCompletes) {
EXPECT_FALSE(Filter::publishComplete(true, false));
EXPECT_TRUE(Filter::publishComplete(true, true));
EXPECT_TRUE(Filter::publishComplete(false, true)); // defensive: success wins
}
TEST(MQTTPacketFilter, UnsupportedRawPathCannotHideEligiblePacketFailure) {
const bool packet_eligible = true;
const bool packet_published = false;
const bool raw_eligible = false; // e.g. MeshRank has no raw topic
const bool raw_published = false;
EXPECT_FALSE(Filter::publishComplete(
packet_eligible || raw_eligible,
packet_published || raw_published));
EXPECT_TRUE(Filter::publishComplete(false, false));
}
TEST(MQTTPacketFilter, PacketAndRawCanShareTheSameMaskDecision) {
const uint16_t text_and_advert = static_cast<uint16_t>((1u << 2) | (1u << 4));
for (uint8_t type = 0; type <= 15; ++type) {
const bool expected = type == 2 || type == 4;
EXPECT_EQ(expected, Filter::allows(text_and_advert, type)) << unsigned(type);
}
}
TEST(MQTTPacketFilter, CandidateIsTheTopicFreePartOfEligibility) {
const uint16_t only_advert = static_cast<uint16_t>(1u << 4);
EXPECT_TRUE(Filter::slotCandidate(true, only_advert, 4));
EXPECT_FALSE(Filter::slotCandidate(false, only_advert, 4));
EXPECT_FALSE(Filter::slotCandidate(true, only_advert, 2));
// A candidate is exactly an eligible slot minus the topic-support term. The
// bridge evaluates the cheap half first and only builds a topic for slots
// that pass it, so the two must stay in this exact relationship.
for (int enabled = 0; enabled <= 1; ++enabled) {
for (int topic = 0; topic <= 1; ++topic) {
for (uint8_t type = 0; type <= 15; ++type) {
EXPECT_EQ(Filter::slotCandidate(enabled != 0, only_advert, type) && topic != 0,
Filter::slotEligible(enabled != 0, topic != 0, only_advert, type));
}
}
}
}
// The gate has to resolve topic support before anything expensive runs: a
// connected slot that cannot form a topic (MeshRank raw, or a meshcore preset
// with no IATA) must reach "intentionally complete" without a serialisation.
TEST(MQTTPacketFilter, TopicIncompatibleTargetsAreCompleteWithoutPublishing) {
const uint16_t all = Filter::kAllPacketTypes;
for (uint8_t type = 0; type <= 15; ++type) {
const bool eligible = Filter::slotEligible(true, false, all, type);
EXPECT_FALSE(eligible) << unsigned(type);
EXPECT_TRUE(Filter::publishComplete(eligible, false)) << unsigned(type);
}
// With topic support restored the same slot becomes a retry target again.
EXPECT_TRUE(Filter::slotEligible(true, true, all, 4));
EXPECT_FALSE(Filter::publishComplete(Filter::slotEligible(true, true, all, 4), false));
}
TEST(MQTTPacketFilter, EnabledUnionIgnoresDisabledSlotsAndGatesTheQueue) {
const uint16_t masks[3] = {
static_cast<uint16_t>(1u << 2), // text only
static_cast<uint16_t>(1u << 4), // adverts only
Filter::kAllPacketTypes, // everything, but disabled below
};
const bool enabled[3] = {true, true, false};
const uint16_t combined = Filter::enabledUnion(masks, enabled, 3);
EXPECT_EQ(static_cast<uint16_t>((1u << 2) | (1u << 4)), combined);
EXPECT_TRUE(Filter::allows(combined, 2));
EXPECT_TRUE(Filter::allows(combined, 4));
EXPECT_FALSE(Filter::allows(combined, 3)); // no enabled slot wants ACKs
// A null `enabled` array counts every slot; no slots means no destination.
EXPECT_EQ(Filter::kAllPacketTypes, Filter::enabledUnion(masks, nullptr, 3));
EXPECT_EQ(0u, Filter::enabledUnion(masks, enabled, 0));
EXPECT_EQ(0u, Filter::enabledUnion(nullptr, enabled, 3));
// The union must never reject a type any single slot would have published.
for (uint8_t type = 0; type <= 15; ++type) {
const bool any_slot_allows =
(enabled[0] && Filter::allows(masks[0], type)) ||
(enabled[1] && Filter::allows(masks[1], type)) ||
(enabled[2] && Filter::allows(masks[2], type));
EXPECT_EQ(any_slot_allows, Filter::allows(combined, type)) << unsigned(type);
}
}
TEST(MQTTPacketFilter, AllMasksDefaultDrivesTheShortPrefsPayload) {
uint16_t masks[6];
for (int i = 0; i < 6; ++i) masks[i] = Filter::kAllPacketTypes;
EXPECT_TRUE(Filter::allMasksDefault(masks, 6));
EXPECT_TRUE(Filter::allMasksDefault(nullptr, 6));
EXPECT_TRUE(Filter::allMasksDefault(masks, 0));
// Any slot off the default -- including "none" -- opts into the longer payload.
for (int i = 0; i < 6; ++i) {
masks[i] = 0;
EXPECT_FALSE(Filter::allMasksDefault(masks, 6)) << i;
masks[i] = static_cast<uint16_t>(Filter::kAllPacketTypes & ~1u);
EXPECT_FALSE(Filter::allMasksDefault(masks, 6)) << i;
masks[i] = Filter::kAllPacketTypes;
}
EXPECT_TRUE(Filter::allMasksDefault(masks, 6));
}
// countTypes() backs the diag line's fallback when the exact list won't fit,
// so it has to agree with what format() would have emitted.
TEST(MQTTPacketFilter, CountTypesMatchesTheFormattedList) {
EXPECT_EQ(0, Filter::countTypes(0));
EXPECT_EQ(16, Filter::countTypes(Filter::kAllPacketTypes));
EXPECT_EQ(1, Filter::countTypes(static_cast<uint16_t>(1u << 15)));
for (uint32_t mask = 0; mask <= 0xFFFFu; ++mask) {
uint8_t expected = 0;
for (uint8_t type = 0; type <= 15; ++type) {
if ((mask & (1u << type)) != 0) expected++;
}
ASSERT_EQ(expected, Filter::countTypes(static_cast<uint16_t>(mask))) << mask;
}
}
// The diag fallback exists because a clipped list parses as a real, different
// allowlist. Pin that hazard so the fallback is never "simplified" away.
TEST(MQTTPacketFilter, ClippedListStillParsesAsADifferentAllowlist) {
const uint16_t configured = static_cast<uint16_t>(Filter::kAllPacketTypes & ~1u);
char text[Filter::kFilterTextSize];
ASSERT_TRUE(Filter::format(configured, text, sizeof(text)));
ASSERT_STREQ("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15", text);
// Drop the trailing "15" the way a bounded reply buffer would.
char clipped[Filter::kFilterTextSize];
memcpy(clipped, text, sizeof(clipped));
clipped[strlen("1,2,3,4,5,6,7,8,9,10,11,12,13,14,")] = '\0';
uint16_t misread = 0;
ASSERT_FALSE(Filter::parse(clipped, &misread)); // trailing comma is rejected
clipped[strlen("1,2,3,4,5,6,7,8,9,10,11,12,13,14")] = '\0';
ASSERT_TRUE(Filter::parse(clipped, &misread)); // but one char earlier reads clean
EXPECT_NE(configured, misread) << "a clipped list must not be mistaken for the real one";
EXPECT_EQ(14, Filter::countTypes(misread));
EXPECT_EQ(15, Filter::countTypes(configured));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -13,6 +13,12 @@ namespace {
constexpr const char* kTimestamp = "2026-07-18T12:34:56.123456+00:00";
struct RejectAllJsonAllocations : ArduinoJson::Allocator {
void* allocate(size_t) override { return nullptr; }
void deallocate(void*) override {}
void* reallocate(void*, size_t) override { return nullptr; }
};
static int buildMinimalStatus(JsonDocument& scratch, char* buffer, size_t buffer_size) {
return MQTTPayloadBuilder::buildStatusMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", "Heltec V3", "v1.16.0",
@@ -250,8 +256,8 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", kTimestamp, "DEN,APRS",
neighbors, 2, buffer, sizeof(buffer));
scratch, "DEN Repeater", "0123456789ABCDEF", kTimestamp, "DEN,APRS", "*",
neighbors, 2, buffer, sizeof(buffer), 5, 2, true);
ASSERT_GT(len, 0);
EXPECT_EQ(static_cast<size_t>(len), strlen(buffer));
@@ -261,6 +267,10 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
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*>());
EXPECT_STREQ("*", parsed["self"]["default_scope"].as<const char*>());
EXPECT_EQ(5, parsed["total_neighbors"].as<int>());
EXPECT_EQ(2, parsed["queried_neighbors"].as<int>());
EXPECT_TRUE(parsed["truncated"].as<bool>());
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_EQ(2U, arr.size());
@@ -274,17 +284,128 @@ TEST(MQTTPayloadBuilder, NeighborsMessageRoundTripsSelfAndEntries) {
EXPECT_STREQ("stale", arr[1]["status"].as<const char*>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageMeasurementsMatchCompletePayload) {
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[] = {
{"0011223344556677", 9.75f, UINT32_MAX, "DEN,APRS", "responded"},
{"8899AABBCCDDEEFF", -3.5f, UINT32_MAX, "", "timeout"},
};
size_t measured =
MQTTPayloadBuilder::measureNeighborsMessageBase(
"DEN Repeater", "0123456789ABCDEF", kTimestamp, "DEN,APRS", "*", 2)
+ MQTTPayloadBuilder::measureNeighborsMessageEntry(neighbors[0])
+ 1 // array comma
+ MQTTPayloadBuilder::measureNeighborsMessageEntry(neighbors[1]);
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "DEN Repeater", "0123456789ABCDEF", kTimestamp, "DEN,APRS", "*",
neighbors, 2, buffer, sizeof(buffer), 2, 2, false);
ASSERT_GT(len, 0);
EXPECT_EQ(measured, static_cast<size_t>(len));
}
TEST(MQTTPayloadBuilder, NeighborsMessageMeasuredPrefixStopsBeforeOverflow) {
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[20];
static char keys[20][17];
static char long_scopes[96];
memset(long_scopes, 'S', sizeof(long_scopes) - 1);
long_scopes[sizeof(long_scopes) - 1] = '\0';
for (int i = 0; i < 20; i++) {
snprintf(keys[i], sizeof(keys[i]), "%016X", i);
neighbors[i] = {
keys[i], static_cast<float>(i), UINT32_MAX,
long_scopes, "responded"};
}
constexpr size_t kBufferSize = 512;
size_t used = MQTTPayloadBuilder::measureNeighborsMessageBase(
"node", "id", kTimestamp, "DEN", "*", 20);
int published = 0;
int queried = 0;
while (queried < 20) {
size_t added =
MQTTPayloadBuilder::measureNeighborsMessageEntry(neighbors[queried])
+ (published > 0 ? 1U : 0U);
queried++;
if (used + added >= kBufferSize) break;
used += added;
published++;
}
ASSERT_GT(published, 0);
ASSERT_LT(published, 20);
ASSERT_EQ(published + 1, queried); // only the non-fitting candidate was extra
JsonDocument scratch;
char buffer[kBufferSize];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", "*",
neighbors, published, buffer, sizeof(buffer),
20, queried, true);
ASSERT_GT(len, 0);
EXPECT_LT(static_cast<size_t>(len), sizeof(buffer));
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
EXPECT_EQ(static_cast<size_t>(published),
parsed["neighbors"].as<JsonArray>().size());
EXPECT_EQ(20, parsed["total_neighbors"].as<int>());
EXPECT_EQ(queried, parsed["queried_neighbors"].as<int>());
EXPECT_TRUE(parsed["truncated"].as<bool>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageFallbackMarksTruncated) {
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[] = {
{"0011223344556677", 9.75f, 1, "DEN", "responded"},
{"8899AABBCCDDEEFF", -3.5f, 2, "APRS", "responded"},
};
size_t first_only_size =
MQTTPayloadBuilder::measureNeighborsMessageBase(
"node", "id", kTimestamp, "DEN", "*", 2)
+ MQTTPayloadBuilder::measureNeighborsMessageEntry(neighbors[0]);
std::vector<char> buffer(first_only_size + 1);
JsonDocument scratch;
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", "*",
neighbors, 2, buffer.data(), buffer.size(),
2, 2, false);
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer.data()));
EXPECT_EQ(1U, parsed["neighbors"].as<JsonArray>().size());
EXPECT_TRUE(parsed["truncated"].as<bool>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageFailsCleanlyOnAllocationFailure) {
MQTTPayloadBuilder::NeighborsMessageEntry neighbor = {
"0011223344556677", 9.75f, 1, "DEN", "responded"};
RejectAllJsonAllocations allocator;
JsonDocument scratch(&allocator);
char buffer[512];
EXPECT_EQ(0, MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", "*",
&neighbor, 1, buffer, sizeof(buffer),
1, 1, false));
}
TEST(MQTTPayloadBuilder, NeighborsMessageHandlesEmptyTableAndNullScopes) {
JsonDocument scratch;
char buffer[256];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, nullptr, nullptr, 0,
scratch, "node", "id", kTimestamp, nullptr, 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*>());
EXPECT_STREQ("", parsed["self"]["default_scope"].as<const char*>());
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_TRUE(arr.isNull() == false);
EXPECT_EQ(0U, arr.size());
@@ -300,6 +421,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageDropsTailWhenBufferFills) {
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].heard_unknown = false;
neighbors[i].scopes = "DEN";
neighbors[i].status = "active";
}
@@ -307,7 +429,7 @@ TEST(MQTTPayloadBuilder, NeighborsMessageDropsTailWhenBufferFills) {
JsonDocument scratch;
char buffer[512];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", neighbors, 20,
scratch, "node", "id", kTimestamp, "DEN", "*", neighbors, 20,
buffer, sizeof(buffer));
ASSERT_GT(len, 0);
@@ -318,10 +440,52 @@ TEST(MQTTPayloadBuilder, NeighborsMessageDropsTailWhenBufferFills) {
ASSERT_FALSE(arr.isNull());
EXPECT_GT(arr.size(), 0U);
EXPECT_LT(arr.size(), 20U);
EXPECT_FALSE(parsed["truncated"].is<JsonVariant>());
// Kept entries are the head of the input, in order.
EXPECT_STREQ(keys[0], arr[0]["pubkey"].as<const char*>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageRendersUnknownHeardAgeAsNull) {
// A neighbour stamped before the clock was set has no usable age. The key
// stays present and null so a consumer cannot read it as "heard just now".
MQTTPayloadBuilder::NeighborsMessageEntry neighbors[2];
neighbors[0] = {"0011223344556677", 9.75f, 42, "DEN", "responded"};
neighbors[1] = {"8899AABBCCDDEEFF", -3.5f, 0, "DEN", "responded"};
neighbors[1].heard_unknown = true;
JsonDocument scratch;
char buffer[1024];
int len = MQTTPayloadBuilder::buildNeighborsMessage(
scratch, "node", "id", kTimestamp, "DEN", "*", neighbors, 2,
buffer, sizeof(buffer), 2, 2, false);
ASSERT_GT(len, 0);
JsonDocument parsed;
ASSERT_FALSE(deserializeJson(parsed, buffer));
JsonArray arr = parsed["neighbors"].as<JsonArray>();
ASSERT_EQ(2U, arr.size());
EXPECT_EQ(42U, arr[0]["heard_secs_ago"].as<uint32_t>());
EXPECT_FALSE(arr[0]["heard_secs_ago"].isNull());
EXPECT_TRUE(arr[1]["heard_secs_ago"].isNull());
EXPECT_NE(nullptr, strstr(buffer, "\"heard_secs_ago\":null"));
// The rest of the entry still renders.
EXPECT_STREQ("8899AABBCCDDEEFF", arr[1]["pubkey"].as<const char*>());
EXPECT_STREQ("responded", arr[1]["status"].as<const char*>());
}
TEST(MQTTPayloadBuilder, NeighborsMessageUnknownHeardAgeFitsMeasuredWidth) {
// Paced discovery measures each entry with a known UINT32_MAX age; a null age
// must never serialize wider than what that reserved.
MQTTPayloadBuilder::NeighborsMessageEntry measured = {
"0011223344556677", 9.75f, UINT32_MAX, "DEN", "responded"};
MQTTPayloadBuilder::NeighborsMessageEntry unknown = measured;
unknown.heard_unknown = true;
unknown.heard_secs_ago = 0;
EXPECT_LE(MQTTPayloadBuilder::measureNeighborsMessageEntry(unknown),
MQTTPayloadBuilder::measureNeighborsMessageEntry(measured));
}
} // namespace
int main(int argc, char** argv) {
@@ -5,6 +5,7 @@
#define WITH_MQTT_BRIDGE 1
#include "helpers/MQTTPrefsCodec.h"
#include "helpers/MQTTPacketFilter.h"
namespace Codec = MQTTPrefsCodec;
@@ -20,6 +21,7 @@ MQTTPrefs defaults() {
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);
prefs.mqtt_slot_packet_filter[i] = MQTTPacketFilter::kAllPacketTypes;
}
strncpy(prefs.snmp_community, "public", sizeof(prefs.snmp_community) - 1);
prefs.radio_watchdog_minutes = 5;
@@ -218,6 +220,10 @@ TEST(MQTTPrefsCodec, MigratesAllLegacySixSlotPrefixesWithoutClobberingDefaults)
} else {
EXPECT_STREQ("time.example", prefs.mqtt_ntp_server);
}
for (int slot = 0; slot < MQTT_PREFS_SLOT_COUNT; ++slot) {
EXPECT_EQ(MQTTPacketFilter::kAllPacketTypes,
prefs.mqtt_slot_packet_filter[slot]) << size << ":" << slot;
}
}
}
@@ -228,6 +234,9 @@ TEST(MQTTPrefsCodec, CurrentVersionedPayloadRoundTripsExactly) {
strncpy(source.alert_region, "PNW", sizeof(source.alert_region) - 1);
source.mqtt_neighbors_enabled = 1;
source.mqtt_neighbors_interval = MQTT_NEIGHBORS_MAX_INTERVAL_MS;
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
source.mqtt_slot_packet_filter[i] = static_cast<uint16_t>(1u << i);
}
std::vector<uint8_t> bytes(Codec::kEncodedSize);
ASSERT_EQ(Codec::kEncodedSize, Codec::encode(source, bytes.data(), bytes.size()));
@@ -240,6 +249,114 @@ TEST(MQTTPrefsCodec, CurrentVersionedPayloadRoundTripsExactly) {
EXPECT_EQ(0, memcmp(&source, &loaded, sizeof(source)));
}
// /mqtt_prefs also carries the WiFi credentials, so a payload older firmware
// rejects strands a downgraded node with no network and no way to save. The
// filter tail is only written once it actually holds something.
TEST(MQTTPrefsCodec, DefaultFiltersKeepTheDowngradeReadablePayloadLength) {
MQTTPrefs source = defaults();
strncpy(source.wifi_ssid, "home-net", sizeof(source.wifi_ssid) - 1);
strncpy(source.mqtt_slot_preset[0], "analyzer-us", sizeof(source.mqtt_slot_preset[0]) - 1);
ASSERT_EQ(Codec::kV1PreFilterPayloadSize, Codec::payloadLenFor(source));
std::vector<uint8_t> bytes(Codec::kEncodedSize, 0xEE);
const size_t written = Codec::encode(source, bytes.data(), bytes.size());
ASSERT_EQ(sizeof(MQTTPrefsHeader) + Codec::kV1PreFilterPayloadSize, written);
EXPECT_LT(written, Codec::kEncodedSize);
MQTTPrefsHeader header;
memcpy(&header, bytes.data(), sizeof(header));
EXPECT_EQ(Codec::kV1PreFilterPayloadSize, header.payload_len);
// Nothing past the boundary was touched, so the file really is the short one.
for (size_t i = written; i < bytes.size(); ++i) {
EXPECT_EQ(0xEE, bytes[i]) << i;
}
bytes.resize(written);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1PreFilterPayloadSize, plan.payload_len);
ASSERT_FALSE(plan.preserve_file);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(0, memcmp(&source, &loaded, sizeof(source)));
}
TEST(MQTTPrefsCodec, AnyNonDefaultFilterOptsIntoTheLongerPayload) {
MQTTPrefs source = defaults();
strncpy(source.wifi_ssid, "home-net", sizeof(source.wifi_ssid) - 1);
// "none" is as much a real setting as a subset, and must survive a reload.
for (int slot = 0; slot < MQTT_PREFS_SLOT_COUNT; ++slot) {
for (uint16_t mask : {static_cast<uint16_t>(0),
static_cast<uint16_t>(1u << 4),
static_cast<uint16_t>(MQTTPacketFilter::kAllPacketTypes & ~1u)}) {
source.mqtt_slot_packet_filter[slot] = mask;
ASSERT_EQ(Codec::kV1BaselinePayloadSize, Codec::payloadLenFor(source)) << slot;
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::kV1BaselinePayloadSize, plan.payload_len);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(mask, loaded.mqtt_slot_packet_filter[slot]) << slot;
EXPECT_EQ(0, memcmp(&source, &loaded, sizeof(source)));
}
source.mqtt_slot_packet_filter[slot] = MQTTPacketFilter::kAllPacketTypes;
}
// Clearing the last non-default filter returns the node to the short payload.
EXPECT_EQ(Codec::kV1PreFilterPayloadSize, Codec::payloadLenFor(source));
}
TEST(MQTTPrefsCodec, EncodeRefusesAnOutputBufferShorterThanItsChosenPayload) {
MQTTPrefs shortest = defaults();
const size_t short_size = sizeof(MQTTPrefsHeader) + Codec::kV1PreFilterPayloadSize;
std::vector<uint8_t> bytes(Codec::kEncodedSize);
EXPECT_EQ(0u, Codec::encode(shortest, bytes.data(), short_size - 1));
EXPECT_EQ(short_size, Codec::encode(shortest, bytes.data(), short_size));
EXPECT_EQ(0u, Codec::encode(shortest, nullptr, bytes.size()));
// A buffer that fits the short payload is not enough for the long one.
MQTTPrefs longest = defaults();
longest.mqtt_slot_packet_filter[0] = 0;
EXPECT_EQ(0u, Codec::encode(longest, bytes.data(), short_size));
EXPECT_EQ(Codec::kEncodedSize, Codec::encode(longest, bytes.data(), bytes.size()));
}
TEST(MQTTPrefsCodec, PreFilterV1PayloadDefaultsEverySlotToAllTypes) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "pre-filter-node", sizeof(source.mqtt_origin) - 1);
source.mqtt_neighbors_enabled = 1;
source.mqtt_neighbors_interval = MQTT_NEIGHBORS_MAX_INTERVAL_MS;
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
source.mqtt_slot_packet_filter[i] = 0;
}
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + Codec::kV1PreFilterPayloadSize, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1PreFilterPayloadSize));
memcpy(bytes.data() + sizeof(MQTTPrefsHeader), &source, Codec::kV1PreFilterPayloadSize);
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
ASSERT_EQ(Codec::kV1PreFilterPayloadSize, plan.payload_len);
ASSERT_TRUE(plan.observer_fields_present);
ASSERT_FALSE(plan.preserve_file);
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_STREQ("pre-filter-node", loaded.mqtt_origin);
EXPECT_EQ(1u, loaded.mqtt_neighbors_enabled);
EXPECT_EQ(MQTT_NEIGHBORS_MAX_INTERVAL_MS, loaded.mqtt_neighbors_interval);
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
EXPECT_EQ(MQTTPacketFilter::kAllPacketTypes,
loaded.mqtt_slot_packet_filter[i]) << i;
}
}
TEST(MQTTPrefsCodec, CompatibleShortV1PayloadPreservesDefaultsBeyondObserverBoundary) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "short-v1-node", sizeof(source.mqtt_origin) - 1);
@@ -304,6 +421,10 @@ TEST(MQTTPrefsCodec, PreNeighborsV1PayloadLoadsObserverFieldsAndDefaultsNeighbor
// 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);
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
EXPECT_EQ(MQTTPacketFilter::kAllPacketTypes,
loaded.mqtt_slot_packet_filter[i]) << i;
}
}
TEST(MQTTPrefsCodec, CorruptOrShortVersionedInputsArePreserved) {
@@ -378,18 +499,83 @@ TEST(MQTTPrefsCodec, UnsupportedHeaderlessSizesArePreserved) {
}
}
TEST(MQTTPrefsCodec, NewerAndSameVersionExtendedPayloadsAreHeld) {
// A different version tag means the layout may have changed shape, so it is
// still refused outright. That refusal is what makes reading longer same-version
// payloads safe, so the two belong in one test.
TEST(MQTTPrefsCodec, ADifferentVersionTagIsStillRefusedAndHeld) {
std::vector<uint8_t> newer(sizeof(MQTTPrefsHeader), 0);
writeHeader(&newer, MQTT_PREFS_VERSION + 1, 0);
Codec::DecodePlan plan = classify(newer);
const 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);
// The downgrade contract: a v1 payload longer than this build's baseline was
// appended to by a later build, so the baseline prefix is present verbatim.
// Read it and drop the tail -- never refuse the file, which would cost the
// operator WiFi and every broker slot to save settings they don't understand.
TEST(MQTTPrefsCodec, LongerSameVersionPayloadLoadsTheBaselineAndIgnoresTheTail) {
MQTTPrefs source = defaults();
strncpy(source.mqtt_origin, "future-node", sizeof(source.mqtt_origin) - 1);
strncpy(source.wifi_ssid, "field-ssid", sizeof(source.wifi_ssid) - 1);
strncpy(source.wifi_password, "field-secret", sizeof(source.wifi_password) - 1);
strncpy(source.mqtt_iata, "SEA", sizeof(source.mqtt_iata) - 1);
strncpy(source.mqtt_slot_preset[0], "meshrank", sizeof(source.mqtt_slot_preset[0]) - 1);
source.mqtt_neighbors_enabled = 1;
for (int i = 0; i < MQTT_PREFS_SLOT_COUNT; ++i) {
source.mqtt_slot_packet_filter[i] = static_cast<uint16_t>(1u << i);
}
// Baseline image plus a 40-byte tail of fields this build has never heard of.
const size_t kTail = 40;
const size_t payload_len = Codec::kV1BaselinePayloadSize + kTail;
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + payload_len, 0xA5);
writeHeader(&bytes, MQTT_PREFS_VERSION, static_cast<uint16_t>(payload_len));
memcpy(bytes.data() + sizeof(MQTTPrefsHeader), &source, sizeof(source));
const Codec::DecodePlan plan = classify(bytes);
ASSERT_EQ(Codec::Source::Current, plan.source);
EXPECT_FALSE(plan.preserve_file) << "refusing the file would strand the node";
EXPECT_TRUE(plan.observer_fields_present);
EXPECT_FALSE(plan.rewrite_legacy);
ASSERT_EQ(Codec::kV1BaselinePayloadSize, plan.payload_len);
// Reading plan.payload_len bytes recovers this build's whole struct exactly,
// and cannot run past it into the unknown tail.
MQTTPrefs loaded = defaults();
memcpy(&loaded, bytes.data() + sizeof(MQTTPrefsHeader), plan.payload_len);
EXPECT_EQ(0, memcmp(&source, &loaded, sizeof(source)));
EXPECT_STREQ("future-node", loaded.mqtt_origin);
EXPECT_STREQ("field-ssid", loaded.wifi_ssid);
EXPECT_STREQ("field-secret", loaded.wifi_password);
EXPECT_STREQ("meshrank", loaded.mqtt_slot_preset[0]);
EXPECT_EQ(1u, loaded.mqtt_neighbors_enabled);
EXPECT_EQ(1u, loaded.mqtt_slot_packet_filter[0]);
}
// The rule has to hold for any appended size, including a single byte and a
// tail far larger than the baseline.
TEST(MQTTPrefsCodec, EveryLongerSameVersionLengthReadsTheBaseline) {
for (const size_t tail : {size_t(1), size_t(2), size_t(12), size_t(64),
size_t(512), size_t(4096)}) {
const size_t payload_len = Codec::kV1BaselinePayloadSize + tail;
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + payload_len, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION, static_cast<uint16_t>(payload_len));
const Codec::DecodePlan plan = classify(bytes);
EXPECT_EQ(Codec::Source::Current, plan.source) << tail;
EXPECT_FALSE(plan.preserve_file) << tail;
EXPECT_EQ(Codec::kV1BaselinePayloadSize, plan.payload_len) << tail;
}
}
// A length that merely *declares* a longer payload without the bytes to back it
// is still corrupt -- the header/file-size agreement check must run first.
TEST(MQTTPrefsCodec, LongerDeclaredLengthWithoutTheBytesIsStillCorrupt) {
std::vector<uint8_t> bytes(sizeof(MQTTPrefsHeader) + Codec::kV1BaselinePayloadSize, 0);
writeHeader(&bytes, MQTT_PREFS_VERSION,
static_cast<uint16_t>(Codec::kV1BaselinePayloadSize + 16));
const Codec::DecodePlan plan = classify(bytes);
EXPECT_EQ(Codec::Source::Corrupt, plan.source);
EXPECT_TRUE(plan.preserve_file);
}
@@ -44,24 +44,27 @@ TEST(MQTTTopicRouter, EveryMeshCorePresetSupportsEveryPublicationType) {
}
}
TEST(MQTTTopicRouter, MeshRankContractIsPacketsOnly) {
// Guards the raw exclusion: a merge from observer-firmware must not re-enable it.
TEST(MQTTTopicRouter, MeshRankTakesEveryTypeExceptRaw) {
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);
for (const TypeCase& type : kTypes) {
char topic[128];
if (type.type == MQTT_PUBLICATION_RAW) {
EXPECT_FALSE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, type.type, nullptr,
IATA, DEVICE, TOKEN, topic, sizeof(topic)));
EXPECT_STREQ("", topic);
continue;
}
ASSERT_TRUE(mqttBuildPublicationTopic(MQTT_ROUTE_MESHRANK, type.type, nullptr,
IATA, DEVICE, TOKEN, topic, sizeof(topic)))
<< type.name;
EXPECT_EQ(std::string("meshrank/uplink/account-token/0123456789ABCDEF/") + type.name,
topic)
<< type.name;
}
}
TEST(MQTTTopicRouter, MeshCoreRequiresUsableIataAndDevice) {
@@ -210,6 +210,108 @@ TEST(WebConfigBatch, StopWarnsOnceAfterTheDeadlineThenKeepsWaiting) {
EXPECT_EQ(Batch::StopAction::Wait, Batch::stopStep(2, false, 0, 999999));
}
// --------------------------------------------------------------------------
// CLI sequences (/api/cli), which share the deferred-command slot
// --------------------------------------------------------------------------
TEST(WebConfigBatch, CliReadPagesResultsAndNeverOverrunsWhatHasDrained) {
const int page = Batch::kCliResultPage;
// Nothing drained past the cursor yet.
EXPECT_EQ(0, Batch::cliPageCount(/*from=*/0, /*produced=*/0, page));
EXPECT_EQ(0, Batch::cliPageCount(/*from=*/3, /*produced=*/3, page));
// Partial progress: hand back exactly what exists.
EXPECT_EQ(3, Batch::cliPageCount(0, 3, page));
EXPECT_EQ(2, Batch::cliPageCount(5, 7, page));
// More available than fits in one read: cap at the page size.
EXPECT_EQ(page, Batch::cliPageCount(0, page + 5, page));
// A cursor beyond what has drained (stale or crafted) yields nothing rather
// than a negative count that would index backwards through the batch.
EXPECT_EQ(0, Batch::cliPageCount(/*from=*/9, /*produced=*/4, page));
}
TEST(WebConfigBatch, CliReadIsDoneOnlyOnceEveryResultHasBeenHandedOver) {
// Still executing: never final, however much has been read.
EXPECT_FALSE(Batch::cliReadIsFinal(State::Pending, /*from=*/0, /*page=*/8, /*total=*/8));
// Execution finished but the client has only seen the first page. Reporting
// "done" here would make a client that stops polling lose the rest.
EXPECT_FALSE(Batch::cliReadIsFinal(State::Done, /*from=*/0, /*page=*/8, /*total=*/20));
EXPECT_FALSE(Batch::cliReadIsFinal(State::Done, /*from=*/8, /*page=*/8, /*total=*/20));
// The read that hands over the last result is the final one.
EXPECT_TRUE(Batch::cliReadIsFinal(State::Done, /*from=*/16, /*page=*/4, /*total=*/20));
// Re-reading past the end stays final (polls after the last page).
EXPECT_TRUE(Batch::cliReadIsFinal(State::Done, /*from=*/20, /*page=*/0, /*total=*/20));
}
// Every string below is a literal lifted from CommonCLI.cpp /
// CommonCLI_Observer.cpp. Testing only for an "Err" prefix passed five of these
// off as success, which both coloured them green and let a queued reboot go
// ahead after them.
TEST(WebConfigBatch, CliFailureRepliesAreRecognisedInEveryShapeCommonCLIEmits) {
const char* failures[] = {
"Err - bad params", // MyMesh setperm
"ERR: bad pubkey", // neighbor.remove
"Error: IATA code must be exactly 3 letters",// observer setters
"(ERR: clock cannot go backwards)", // clock sync, parenthesised
"Unknown command", // top-level fallthrough
"unknown config: mqtt.nope", // set fallthrough
"??: mqtt.nope", // get fallthrough
"Can't find GPS", // gps
"File system erase: Err", // failure reported at the end
};
for (const char* f : failures) {
EXPECT_TRUE(Batch::cliReplyIsFailure(f)) << f;
}
const char* successes[] = {
"OK",
"OK - slot 1 preset: meshrank",
"> 22", // getter value
"> msgs: on, 1: analyzer-us (ok)", // getter, contains "ok"
"File system erase: OK", // same shape, succeeded
"Free: 142832, Min: 126808", // memory
"v1.16.0 (Build: 6 Jun 2026)", // ver
};
for (const char* s : successes) {
EXPECT_FALSE(Batch::cliReplyIsFailure(s)) << s;
}
// An empty reply is normalised to "OK" before it ever reaches the client.
EXPECT_FALSE(Batch::cliReplyIsFailure(""));
EXPECT_FALSE(Batch::cliReplyIsFailure(NULL));
}
TEST(WebConfigBatch, OnlyWritesGateTheDeferredReboot) {
// Writes gate it: these are what can leave a config not worth rebooting into.
EXPECT_TRUE(Batch::cliReplyGatesReboot("set tx 22"));
EXPECT_TRUE(Batch::cliReplyGatesReboot("set mqtt1.preset meshrank"));
EXPECT_TRUE(Batch::cliReplyGatesReboot("password hunter2"));
// Diagnostics do not. `memory` answering "Free: ..." must not be read as a
// failure and strand the operator's reboot, and a getter's "> value" must not
// be read as a success either -- neither is asked.
EXPECT_FALSE(Batch::cliReplyGatesReboot("memory"));
EXPECT_FALSE(Batch::cliReplyGatesReboot("get tx"));
EXPECT_FALSE(Batch::cliReplyGatesReboot("reboot"));
EXPECT_FALSE(Batch::cliReplyGatesReboot("advert"));
EXPECT_FALSE(Batch::cliReplyGatesReboot(NULL));
// "settle" must not be mistaken for a `set`; the space is part of the token.
EXPECT_FALSE(Batch::cliReplyGatesReboot("settle"));
// A write counts only on the "OK" prefix every setter keeps.
EXPECT_TRUE(Batch::cliWriteSucceeded("OK"));
EXPECT_TRUE(Batch::cliWriteSucceeded("OK - reboot to apply"));
EXPECT_FALSE(Batch::cliWriteSucceeded("unknown config: nope"));
EXPECT_FALSE(Batch::cliWriteSucceeded("Error: expected a number"));
EXPECT_FALSE(Batch::cliWriteSucceeded(""));
}
TEST(WebConfigBatch, CliRebootIsWithheldWhenAnyCommandInTheSequenceFailed) {
EXPECT_TRUE(Batch::cliRebootAllowed(/*has_reboot=*/true, /*all_ok=*/true));
// Same rule a config save follows: do not reboot into a half-applied config
// over a link the operator may not get back.
EXPECT_FALSE(Batch::cliRebootAllowed(true, false));
// No `reboot` in the sequence: nothing to allow either way.
EXPECT_FALSE(Batch::cliRebootAllowed(false, true));
EXPECT_FALSE(Batch::cliRebootAllowed(false, false));
}
// --------------------------------------------------------------------------
// Wrap-around guard shared with the production _reboot_at assignments
// --------------------------------------------------------------------------
@@ -22,6 +22,7 @@ TEST(WebConfigKeys, AllowsPerSlotKeys) {
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.preset"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.server"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt1.token"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt2.filter"));
EXPECT_TRUE(wcIsAllowedSetKey("mqtt6.audience")); // MAX_MQTT_SLOTS == 6
}
@@ -102,6 +103,7 @@ 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("mqtt1.filter"));
EXPECT_FALSE(wcIsSecretKey("mqtt.origin"));
EXPECT_FALSE(wcIsSecretKey("name"));
EXPECT_FALSE(wcIsSecretKey(""));
@@ -117,6 +119,45 @@ TEST(WebConfigKeys, EverySecretKeyIsAlsoAllowed) {
}
}
// ---- CLI secret reads ----------------------------------------------------
// The web CLI runs commands with sender_timestamp 0, which is how CommonCLI
// recognises the serial console and answers secret getters in plaintext. These
// are the reads that must be masked back down for an HTTP caller.
TEST(WebConfigKeys, MasksEverySecretReadTheCliCanReach) {
const char* masked[] = {
"get prv.key", // this node's identity -- the worst one to leak
"get wifi.pwd", // grants the operator's LAN, not just the node
"get guest.password",
"get alert.psk",
"get bridge.secret",
"get mqtt1.password", "get mqtt1.token",
"get mqtt6.password", "get mqtt6.token",
"get wifi.pwd", // extra space after the verb
};
for (const char* c : masked) EXPECT_TRUE(wcIsSecretReadCommand(c)) << c;
}
TEST(WebConfigKeys, DoesNotMaskReadsThatCarryNoSecret) {
const char* plain[] = {
"get wifi.ssid", "get mqtt1.username", "get mqtt1.server", "get tx",
"get public.key", // public half, safe to read
"get mqtt.owner", // an owner's public key, not a credential
};
for (const char* c : plain) EXPECT_FALSE(wcIsSecretReadCommand(c)) << c;
}
TEST(WebConfigKeys, OnlyMasksReads) {
// Writing a secret has always been the portal's job and reveals nothing;
// only the read is restricted. Nor may a prefix be mistaken for a `get`.
EXPECT_FALSE(wcIsSecretReadCommand("set wifi.pwd hunter2"));
EXPECT_FALSE(wcIsSecretReadCommand("set prv.key aabb"));
EXPECT_FALSE(wcIsSecretReadCommand("password hunter2"));
EXPECT_FALSE(wcIsSecretReadCommand("getwifi.pwd"));
EXPECT_FALSE(wcIsSecretReadCommand("get"));
EXPECT_FALSE(wcIsSecretReadCommand(""));
}
// ---- request correlation -------------------------------------------------
TEST(WebConfigKeys, AcceptsExactHexRequestIds) {