feat(docs): add local testing instructions for MQTT functionality

Include detailed instructions for local testing of observer and WiFi
functionality without hardware. Document the use of a mock backend and
Wokwi ESP32-S3 simulation for easier development and testing.
Enhance the MQTT implementation documentation to improve developer
experience and facilitate testing workflows.
This commit is contained in:
agessaman committed 2026-07-18 13:19:27 -07:00
1 parent b7795720b2
commit cbbd01b620
23 files changed
+1403 -131

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
# 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, 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_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,138 @@
// 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 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));
}
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);
}
// ---- 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,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,101 @@
// 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, LiteralOverflowTruncatesAndNulTerminates) {
char buf[5];
// Literal longer than the buffer: fills up to buf_size-1 and NUL-terminates.
mqttSubstituteTopic("abcdefghij", IATA, DEV, TOK, "status", buf, sizeof(buf));
EXPECT_EQ('\0', buf[4]);
EXPECT_EQ((size_t)4, strlen(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,104 @@
// 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("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, 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;
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}