From 286ba37f8a8bdfbfc4ffcabdd20ffce2291d85b9 Mon Sep 17 00:00:00 2001 From: Jason Huebert Date: Sat, 3 Oct 2026 12:35:51 -0500 Subject: [PATCH] test: give the native feature suites their own selection and sanitizer envs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The generic `pio test -e native` selected test_packet_filter and test_battery_gate, which need their own include paths, source selection and filesystem shim; both errored out and failed the whole command. List them in test_ignore so each runs in the environment that can actually build it. Also correct the safety net the review found unsound: - makePacket() left payload, path and transport codes uninitialized while mesh::Packet's constructor only sets header/path_len/payload_len, so tests hashed whatever the stack held. Initialize them, and clamp payload_len, hsz and hops to the real buffer bounds. LenInterval's 200-byte packet became the 184-byte boundary that actually exists; the hsize=4 case is now labelled artificial, since Packet::setPath rejects hash size 4 as reserved. - filterCLI() was called through a null RegionMap*, and the CLI does call members on it. Provide the real constructor in the stub and pass an instance. - NativeFile::read() formed a data pointer for zero-length and past-EOF reads, so reading an empty file passed nullptr to memcpy. Return 0 first. write() validates its backing store and tracks position; the two-argument open now honours "r"/"w", and flush/rename exist for the persistence work to come. - The CLI helper now replies into the real 160-byte CLI_REPLY_MAX with a canary after it, asserting both no overrun and NUL termination in the window. Add ASan+UBSan environments for both feature suites so "assertions passed" is not mistaken for "no undefined behaviour". The three problems the review found this way — the oversized fixture, the null member call and the empty read — had all been passing their assertions. 54 native + native_kiss_modem cases green; the sanitizer envs report zero diagnostics. --- platformio.ini | 31 +++++++++++++++- test/mocks/SHA256.h | 10 +++++ test/test_packet_filter/FilterTestHelpers.h | 37 ++++++++++++++++--- test/test_packet_filter/NativeShim.h | 28 +++++++++++++- test/test_packet_filter/RegionMapStub.cpp | 13 ++++++- .../test_packet_filter/test_packet_filter.cpp | 7 +++- 6 files changed, 115 insertions(+), 11 deletions(-) diff --git a/platformio.ini b/platformio.ini index b441393c..faefe748 100644 --- a/platformio.ini +++ b/platformio.ini @@ -167,7 +167,13 @@ build_flags = -std=c++17 -I src -I test/mocks test_build_src = yes -test_ignore = test_kiss_modem +; suites needing their own environment (include paths, source selection and +; filesystem shim) must be ignored here or this environment selects them and +; they fail to build +test_ignore = + test_kiss_modem + test_packet_filter + test_battery_gate build_src_filter = -<*> +<../src/Utils.cpp> @@ -244,3 +250,26 @@ build_src_filter = +<../examples/simple_repeater/BatteryGate.cpp> lib_deps = google/googletest @ 1.17.0 + +; Sanitizer builds of the two native feature suites: same source selection, +; include paths, force-included NativeShim and GTEST_HAS_POSIX_RE=0 as the +; ordinary envs, plus ASan + UBSan. Separate env names so the ordinary feature +; objects stay cached and a sanitizer run never replaces them. Both must report +; zero diagnostics — an assertion-only pass does not prove absence of UB +; (see the review's R16: a zero-length read, a null member call and an +; oversized fixture all passed assertions before being caught here). +[env:native_packet_filter_san] +extends = env:native_packet_filter +build_flags = + ${env:native_packet_filter.build_flags} + -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer +link_flags = + -fsanitize=address,undefined + +[env:native_battery_gate_san] +extends = env:native_battery_gate +build_flags = + ${env:native_battery_gate.build_flags} + -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer +link_flags = + -fsanitize=address,undefined diff --git a/test/mocks/SHA256.h b/test/mocks/SHA256.h index 0cefe5c6..361c2151 100644 --- a/test/mocks/SHA256.h +++ b/test/mocks/SHA256.h @@ -8,6 +8,15 @@ // distinguishable results for packets with different payloads. #include +// Test-only instrumentation: number of finalize() calls, so a test can assert +// that a decision path did (or did not) hash a packet. An inline function +// holding the counter gives every native environment one shared instance +// without needing a definition in each build. +inline uint32_t& mockShaFinalizeCount() { + static uint32_t n = 0; + return n; +} + class SHA256 { uint8_t _state[32]; size_t _len; @@ -25,6 +34,7 @@ public: } void finalize(uint8_t* hash, size_t hashLen) { + mockShaFinalizeCount()++; for (size_t i = 0; i < hashLen; i++) { hash[i] = _state[i % 32]; } diff --git a/test/test_packet_filter/FilterTestHelpers.h b/test/test_packet_filter/FilterTestHelpers.h index edac7a47..cb027e28 100644 --- a/test/test_packet_filter/FilterTestHelpers.h +++ b/test/test_packet_filter/FilterTestHelpers.h @@ -11,21 +11,35 @@ #include // g_mock_millis #include // TXT_TYPE_PLAIN #include "PacketFilter.h" +#include "CliUtil.h" // CLI_REPLY_MAX // payload offsets the advert rate limiter samples its 4-byte origin key from // (mirrors the fixed KEY_OFFSETS in PacketFilter.cpp) static const uint8_t ADV_KEY_OFFSETS[4] = { 8, 14, 20, 26 }; -// Build a packet with the given header fields. Path entries are filled with a -// recognisable pattern: entry e, byte b = (e+1)*16 + b, so with hash size 1 +// Build a packet with the given header fields. mesh::Packet's constructor only +// initializes header/path_len/payload_len, so the remaining fields a matcher or +// the packet hash can read are set here explicitly: an uninitialized packet made +// tests hash whatever the stack happened to hold. Path entries are filled with +// a recognisable pattern: entry e, byte b = (e+1)*16 + b, so with hash size 1 // the entries are 0x10, 0x20, 0x30, ...; with size 2 entry 0 is 0x10 0x11. +// +// payload_len is clamped to the packet's real buffer: there is no packet the +// firmware could process with more payload than that, and a larger value reads +// past payload[] (which is what the probability hash used to do). inline mesh::Packet makePacket(uint8_t route, uint8_t type, uint16_t payload_len = 10, uint8_t hsz = 1, uint8_t hops = 0, int8_t snr_qdb = 0) { mesh::Packet p; p.header = (route & PH_ROUTE_MASK) | ((type & PH_TYPE_MASK) << PH_TYPE_SHIFT); + if (payload_len > MAX_PACKET_PAYLOAD) payload_len = MAX_PACKET_PAYLOAD; + if (hsz > MAX_PATH_SIZE) hsz = MAX_PATH_SIZE; + if (hops * hsz > MAX_PATH_SIZE) hops = hsz ? (uint8_t)(MAX_PATH_SIZE / hsz) : 0; p.setPathHashSizeAndCount(hsz, hops); p.payload_len = payload_len; p._snr = snr_qdb; + memset(p.payload, 0, sizeof(p.payload)); + memset(p.path, 0, sizeof(p.path)); + p.transport_codes[0] = p.transport_codes[1] = 0; for (uint8_t e = 0; e < hops && e * hsz < MAX_PATH_SIZE; e++) { for (uint8_t b = 0; b < hsz && e * hsz + b < MAX_PATH_SIZE; b++) { p.path[e * hsz + b] = (uint8_t)(((e + 1) << 4) | b); @@ -76,12 +90,23 @@ inline mesh::GroupChannel channelFromStore(FilterRules& filter, int idx) { } // Run one CLI command (with the "filter" prefix already stripped) and return -// the reply. `regions` may be null — the native RegionMap stub needs no -// instance state. +// the reply. The buffer is the real CLI_REPLY_MAX with a canary byte after it, +// so a reply that overruns the transport limit is caught here rather than +// silently passing. `regions` is a real RegionMap: the CLI calls members on it, +// and calling through a null pointer is undefined behaviour. inline std::string cli(FilterRules& filter, const char* command) { - char reply[MAX_PACKET_PAYLOAD + 1]; + static const uint8_t CANARY = 0xA5; + static TransportKeyStore store; + static RegionMap regions(store); + + uint8_t raw[CLI_REPLY_MAX + 1]; + memset(raw, CANARY, sizeof(raw)); + char* reply = (char*)raw; reply[0] = 0; - filterCLI(filter, command, reply, nullptr); + filterCLI(filter, command, reply, ®ions); + EXPECT_EQ(raw[CLI_REPLY_MAX], CANARY) << "reply overran " << CLI_REPLY_MAX << " bytes: " << command; + EXPECT_NE(memchr(reply, 0, CLI_REPLY_MAX), nullptr) + << "reply not NUL-terminated in " << CLI_REPLY_MAX << " bytes: " << command; return std::string(reply); } diff --git a/test/test_packet_filter/NativeShim.h b/test/test_packet_filter/NativeShim.h index b908afa3..6215dc6e 100644 --- a/test/test_packet_filter/NativeShim.h +++ b/test/test_packet_filter/NativeShim.h @@ -33,6 +33,10 @@ public: operator bool() const { return valid; } size_t read(uint8_t* buf, size_t len) { + // a zero-length or past-EOF read must not form a data pointer: an empty + // backing store has data() == nullptr, and memcpy() from it is UB even for + // n == 0 + if (backing == nullptr || pos >= backing->size() || len == 0) return 0; size_t n = len < (backing->size() - pos) ? len : (backing->size() - pos); memcpy(buf, backing->data() + pos, n); pos += n; @@ -40,10 +44,13 @@ public: } size_t write(const uint8_t* buf, size_t len) { + if (backing == nullptr) return 0; backing->insert(backing->end(), buf, buf + len); + pos = backing->size(); // append-only shim: the handle ends up at EOF return len; } + void flush() {} void close() {} }; @@ -63,7 +70,26 @@ public: return f; } - NativeFile open(const char* path, const char* mode) { return open(path); } + // Arduino (RP2040) flavour: "r" reads, "w" creates/truncates. Honouring the + // mode is what lets a test exercise the RP2040 open paths. + NativeFile open(const char* path, const char* mode) { + if (mode != nullptr && mode[0] == 'w') { + files[path].clear(); + NativeFile f; + f.backing = &files[path]; + f.valid = true; + return f; + } + return open(path); + } + + bool rename(const char* from, const char* to) { + auto it = files.find(from); + if (it == files.end()) return false; + files[to] = it->second; + files.erase(it); + return true; + } // Arduino (ESP32) flavour: open(..., "w", true) truncates/creates. NativeFile open(const char* path, const char* mode, bool truncate) { diff --git a/test/test_packet_filter/RegionMapStub.cpp b/test/test_packet_filter/RegionMapStub.cpp index 263babbd..a20b76a7 100644 --- a/test/test_packet_filter/RegionMapStub.cpp +++ b/test/test_packet_filter/RegionMapStub.cpp @@ -4,8 +4,9 @@ // RegionMap::findByNamePrefix() — used by the `region=` CLI predicate — is // resolved here, from a fixed table so tests are deterministic. // -// NOTE: the stub touches no RegionMap members, so tests may pass a null -// RegionMap* to filterCLI(). +// The real constructor is provided here too, so tests can hold an actual +// RegionMap instance: calling findByNamePrefix() through a null RegionMap* is +// undefined behaviour even when the callee never touches `this`. #include @@ -17,6 +18,14 @@ static RegionEntry g_test_regions[] = { { 3, 1, 0, "TestNorthEast" }, }; +RegionMap::RegionMap(TransportKeyStore& store) : _store(&store) { + next_id = 1; num_regions = 0; + default_id = home_id = 0; + wildcard.id = wildcard.parent = 0; + wildcard.flags = 0; + strcpy(wildcard.name, "*"); +} + RegionEntry* RegionMap::findByNamePrefix(const char* prefix) { for (auto& r : g_test_regions) { if (strncmp(r.name, prefix, strlen(prefix)) == 0) return &r; diff --git a/test/test_packet_filter/test_packet_filter.cpp b/test/test_packet_filter/test_packet_filter.cpp index 4b36148d..02409945 100644 --- a/test/test_packet_filter/test_packet_filter.cpp +++ b/test/test_packet_filter/test_packet_filter.cpp @@ -580,7 +580,9 @@ TEST_F(FilterTest, LenInterval) { expectOk(filter, "add len=[180,*]"); auto short_pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 20); auto edge = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 180); - auto long_pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 200); + // the largest payload the packet buffer can hold; there is no 200-byte + // packet the firmware could process + auto long_pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, MAX_PACKET_PAYLOAD); EXPECT_EQ(filter.checkPacket(&short_pkt, 0, nullptr), FILTER_ACT_ALLOW); EXPECT_EQ(filter.checkPacket(&edge, 0, nullptr), FILTER_ACT_DROP); EXPECT_EQ(filter.checkPacket(&long_pkt, 0, nullptr), FILTER_ACT_DROP); @@ -626,6 +628,9 @@ TEST_F(FilterTest, HashSizePredicate) { expectOk(filter, "add hsize=2,3"); auto h1 = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 10, 1, 2); auto h2 = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 10, 2, 2); + // hsize=4 is artificial: Packet::setPath rejects hash_size 4 as reserved for + // future use (Packet.cpp), so no such packet can arrive. This case only + // exercises the matcher's arithmetic — it is not on-air coverage. auto h4 = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 10, 4, 2); EXPECT_EQ(filter.checkPacket(&h1, 0, nullptr), FILTER_ACT_ALLOW); EXPECT_EQ(filter.checkPacket(&h2, 0, nullptr), FILTER_ACT_DROP);