Extend flood policy and harden message retries

This commit is contained in:
mikecarper committed 2026-08-07 14:26:31 -07:00
1 parent 687e114828
commit 7f56da7a34
34 files changed
+5297 -1338

No files matched your search

+4 -1
View File
@@ -39,7 +39,10 @@ does not reflect the GoogleTest count -- run the built binary directly
| `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 |
| `test_telemetry_history` | `src/helpers/TelemetryHistory.h` | 30-minute rings; seven-day temperature/voltage and dynamically sized GPS retention; exact 1 C temperature/status encoding; separate Base64 series payloads; 14-bit GPS differentials; resize preservation, heap budgets, and 1-based paging bounds |
| `test_flood_filter_policy` | `src/helpers/FloodFilterPolicy.h` | unordered 3-byte and 2-byte-prefix path matching; match thresholds; repeated path-entry semantics; blacklist and bridge-bucket channel-scope selection; `require=region` and per-channel scope-gate truth tables; fast/slow scope timing; adding, replacing, and preserving packet scope |
| `test_flood_filter_policy` | `src/helpers/FloodFilterPolicy.h` | unordered blacklist matching; ordered 1/2/3-byte pbyte rule prefixes; original incoming scope classes and canonical region-name identity; channel-authentication cache key comparison; priority ordering and terminal stop masks; bridge-bucket and regionless channel-target selector encoding; `require=region` and per-channel scope-gate truth tables; fast/slow timing; adding, replacing, and preserving packet scope |
| `test_logical_message_cache` | `src/helpers/LogicalMessageCache.h` | bounded logical-message mapping; stable retry timestamps; exact older retries after newer messages; stale and same-timestamp mismatch rejection |
| `test_remote_cli_reply_cache` | `src/helpers/RemoteCliReplyCache.h` | authenticated sender/timestamp/command matching; owned response storage; empty-response completion; on-air truncation; replacement and clearing |
| `test_companion_frame_queue` | `src/helpers/CompanionFrameQueue.h` | reserved reply capacity; response priority; push eviction under saturation; response preservation |
| `test_utils` | `src/Utils.cpp` | `Utils::toHex` (upstream) |
## Conventions (and how to add a suite)
@@ -0,0 +1,78 @@
#include <gtest/gtest.h>
#include <helpers/CompanionFrameQueue.h>
namespace {
struct TestFrame {
size_t len;
uint8_t buf[8];
};
static bool enqueue(TestFrame queue[], size_t& count, size_t capacity,
uint8_t code) {
return mesh::enqueueCompanionFrame(queue, count, capacity, &code, 1);
}
TEST(CompanionFrameQueue, PushTrafficLeavesOneResponseSlot) {
TestFrame queue[4] = {};
size_t count = 0;
EXPECT_TRUE(enqueue(queue, count, 4, 0x88));
EXPECT_TRUE(enqueue(queue, count, 4, 0x84));
EXPECT_TRUE(enqueue(queue, count, 4, 0x81));
EXPECT_FALSE(enqueue(queue, count, 4, 0x8A));
ASSERT_EQ(3U, count);
EXPECT_TRUE(enqueue(queue, count, 4, 0x00));
ASSERT_EQ(4U, count);
EXPECT_EQ(0x00, queue[0].buf[0]);
}
TEST(CompanionFrameQueue, ResponsesRunBeforeQueuedPushesAndRemainFifo) {
TestFrame queue[5] = {};
size_t count = 0;
ASSERT_TRUE(enqueue(queue, count, 5, 0x88));
ASSERT_TRUE(enqueue(queue, count, 5, 0x06));
ASSERT_TRUE(enqueue(queue, count, 5, 0x84));
ASSERT_TRUE(enqueue(queue, count, 5, 0x00));
ASSERT_EQ(4U, count);
EXPECT_EQ(0x06, queue[0].buf[0]);
EXPECT_EQ(0x00, queue[1].buf[0]);
EXPECT_EQ(0x88, queue[2].buf[0]);
EXPECT_EQ(0x84, queue[3].buf[0]);
}
TEST(CompanionFrameQueue, ResponseEvictsNewestPushFromAnAlreadyFullQueue) {
TestFrame queue[4] = {
{1, {0x06}}, {1, {0x88}}, {1, {0x00}}, {1, {0x84}}};
size_t count = 4;
ASSERT_TRUE(enqueue(queue, count, 4, 0x01));
ASSERT_EQ(4U, count);
EXPECT_EQ(0x06, queue[0].buf[0]);
EXPECT_EQ(0x00, queue[1].buf[0]);
EXPECT_EQ(0x01, queue[2].buf[0]);
EXPECT_EQ(0x88, queue[3].buf[0]);
}
TEST(CompanionFrameQueue, ResponseDoesNotEvictAnotherResponse) {
TestFrame queue[3] = {
{1, {0x00}}, {1, {0x01}}, {1, {0x06}}};
size_t count = 3;
EXPECT_FALSE(enqueue(queue, count, 3, 0x02));
EXPECT_EQ(3U, count);
EXPECT_EQ(0x00, queue[0].buf[0]);
EXPECT_EQ(0x01, queue[1].buf[0]);
EXPECT_EQ(0x06, queue[2].buf[0]);
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -1,6 +1,7 @@
#include <gtest/gtest.h>
#include <helpers/FloodFilterPolicy.h>
#include <helpers/RegionNameUtils.h>
static mesh::Packet makeFloodPacket(uint8_t hash_size,
const uint8_t* path,
@@ -127,6 +128,161 @@ TEST(FloodFilterBlacklist, ConfiguredBucketStopsAtEmptyTrailingIds) {
&packet, &bucket[0][0], 17));
}
TEST(FloodRulePrefix, SupportsOneTwoAndThreeBytePathPrefixes) {
const uint8_t one_byte_path[] = {0x11, 0x22, 0x33};
const uint8_t two_byte_path[] = {0x11, 0x22, 0x33, 0x44};
const uint8_t three_byte_path[] = {
0x11, 0x22, 0x33,
0x44, 0x55, 0x66,
};
mesh::Packet one = makeFloodPacket(1, one_byte_path, 3);
mesh::Packet two = makeFloodPacket(2, two_byte_path, 2);
mesh::Packet three = makeFloodPacket(3, three_byte_path, 2);
EXPECT_TRUE(FloodFilterPolicy::pathStartsWith(
&one, 1, 2, one_byte_path));
EXPECT_TRUE(FloodFilterPolicy::pathStartsWith(
&two, 2, 2, two_byte_path));
EXPECT_TRUE(FloodFilterPolicy::pathStartsWith(
&three, 3, 2, three_byte_path));
}
TEST(FloodRulePrefix, RequiresTheExactPathWidthAndStartingSequence) {
const uint8_t path[] = {
0x11, 0x22,
0x33, 0x44,
};
const uint8_t wrong_start[] = {0x33, 0x44};
mesh::Packet packet = makeFloodPacket(2, path, 2);
EXPECT_FALSE(FloodFilterPolicy::pathStartsWith(
&packet, 1, 1, path));
EXPECT_FALSE(FloodFilterPolicy::pathStartsWith(
&packet, 2, 1, wrong_start));
EXPECT_FALSE(FloodFilterPolicy::pathStartsWith(
&packet, 2, 3, path));
}
TEST(FloodRuleIncomingScope, MatchesOriginalScopeClasses) {
using namespace FloodFilterPolicy;
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_ANY, false, 0, false, 0));
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_NONE, false, 0, true, 0));
EXPECT_FALSE(ruleIncomingScopeMatches(
RULE_IN_NONE, true, 0x1234, true, 0));
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_SCOPED, true, 0x1234, false, 0));
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_ALLOWED, true, 0x1234, true, 0));
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_UNKNOWN, true, 0x1234, false, 0));
}
TEST(FloodRuleIncomingScope, ExactScopeDoesNotCrossMatch) {
using namespace FloodFilterPolicy;
EXPECT_TRUE(ruleIncomingScopeMatches(
RULE_IN_SCOPE, true, 0x1234, true, 0x1234));
EXPECT_FALSE(ruleIncomingScopeMatches(
RULE_IN_SCOPE, true, 0x1235, true, 0x1234));
EXPECT_FALSE(ruleIncomingScopeMatches(
RULE_IN_REGION, true, 0x1234, true, 0));
}
TEST(FloodRuleIncomingScope, RegionIdentityUsesCanonicalNames) {
EXPECT_TRUE(RegionNameUtils::equivalent("usa", "#usa"));
EXPECT_TRUE(RegionNameUtils::equivalent("BlackHole86", "BlackHole86"));
EXPECT_FALSE(RegionNameUtils::equivalent("usa", "BlackHole86"));
}
TEST(FloodRuleRate, BlocksAtTheConfiguredPerMinuteLimit) {
EXPECT_FALSE(FloodFilterPolicy::rateLimitReached(
false, 1000, 0, 500, 2));
EXPECT_FALSE(FloodFilterPolicy::rateLimitReached(
true, 2000, 1000, 1, 2));
EXPECT_TRUE(FloodFilterPolicy::rateLimitReached(
true, 2000, 1000, 2, 2));
EXPECT_TRUE(FloodFilterPolicy::rateLimitReached(
true, 2000, 1000, 0, 0));
}
TEST(FloodRuleRate, StartsANewWindowAfterSixtySeconds) {
EXPECT_FALSE(FloodFilterPolicy::rateLimitReached(
true, 61000, 1000, 2, 2));
EXPECT_TRUE(FloodFilterPolicy::rateLimitReached(
true, 999, 0xFFFFFF00U, 2, 2));
EXPECT_FALSE(FloodFilterPolicy::rateLimitReached(
true, 60000, 0xFFFFFF00U, 2, 2));
}
TEST(FloodRuleAuthentication, CacheKeysCompareOnlyTheirActiveBytes) {
uint8_t first[32] = {0};
uint8_t same[32] = {0};
uint8_t different[32] = {0};
first[0] = same[0] = different[0] = 0xA5;
first[15] = same[15] = different[15] = 0x5A;
first[31] = 0x11;
same[31] = 0x22;
different[15] = 0x5B;
EXPECT_TRUE(FloodFilterPolicy::sameChannelKey(16, first, 16, same));
EXPECT_FALSE(FloodFilterPolicy::sameChannelKey(
16, first, 16, different));
EXPECT_FALSE(FloodFilterPolicy::sameChannelKey(16, first, 32, first));
EXPECT_FALSE(FloodFilterPolicy::sameChannelKey(0, first, 0, same));
}
TEST(FloodRuleOrder, HighestPriorityWinsAndSlotBreaksTies) {
const uint8_t priorities[] = {10, 30, 30, 5};
uint32_t matches = 0x0F;
uint32_t visited = 0;
int first = FloodFilterPolicy::nextOrderedRule(
matches, visited, priorities, 4);
ASSERT_EQ(1, first);
visited |= (uint32_t)1U << first;
EXPECT_EQ(2, FloodFilterPolicy::nextOrderedRule(
matches, visited, priorities, 4));
}
TEST(FloodRuleOrder, StopRemovesOnlyLowerOrderedMatches) {
const uint8_t priorities[] = {10, 30, 20, 5};
const uint8_t stop_flags[] = {0, 0, 1, 0};
EXPECT_EQ(0x06U, FloodFilterPolicy::truncateRulesAtStop(
0x0F, priorities, stop_flags, 4));
}
TEST(FloodRuleOrder, StopAtEqualPriorityUsesLowerSlotFirst) {
const uint8_t priorities[] = {40, 40, 50};
const uint8_t stop_flags[] = {1, 0, 0};
EXPECT_EQ(0x05U, FloodFilterPolicy::truncateRulesAtStop(
0x07, priorities, stop_flags, 3));
}
TEST(FloodRuleOrder, NoStopPreservesEveryMatch) {
const uint8_t priorities[] = {1, 200, 3, 99};
const uint8_t stop_flags[] = {0, 0, 0, 0};
EXPECT_EQ(0x0BU, FloodFilterPolicy::truncateRulesAtStop(
0x0B, priorities, stop_flags, 4));
}
TEST(FloodRuleOrder, ThirtyOneSlotTableIncludesTheLastSlot) {
uint8_t priorities[31] = {0};
uint8_t stop_flags[31] = {0};
priorities[30] = 200;
stop_flags[30] = 1;
const uint32_t matches = ((uint32_t)1U << 30) | 1U;
EXPECT_EQ(30, FloodFilterPolicy::nextOrderedRule(
matches, 0, priorities, 31));
EXPECT_EQ((uint32_t)1U << 30,
FloodFilterPolicy::truncateRulesAtStop(
matches, priorities, stop_flags, 31));
}
TEST(FloodFilterScope, RegionRequirementHasTheExpectedTruthTable) {
EXPECT_TRUE(FloodFilterPolicy::scopeRuleAllowed(false, false));
EXPECT_TRUE(FloodFilterPolicy::scopeRuleAllowed(false, true));
@@ -193,6 +349,42 @@ TEST(FloodFilterScope, EveryBridgeBucketRoundTripsWithoutChangingSelector) {
}
}
TEST(FloodFilterScope, DirectChannelTargetsRoundTripEveryMatcherClass) {
const uint8_t selectors[] = {0, 1, 2, 16, 32};
for (uint8_t selector : selectors) {
uint8_t direct = FloodFilterPolicy::encodeChannelScopeTargetSelector(
selector, true);
uint8_t stored = FloodFilterPolicy::encodeScopeSelector(
direct, true, FloodFilterPolicy::SCOPE_PATH_BRIDGE_BUCKET_BASE + 5);
EXPECT_NE(FloodFilterPolicy::CHANNEL_SCOPE_INVALID_SELECTOR, direct);
EXPECT_TRUE(FloodFilterPolicy::channelScopeUsesDirectTarget(stored));
EXPECT_EQ(selector,
FloodFilterPolicy::channelScopeMatchSelectorValue(stored));
EXPECT_TRUE(FloodFilterPolicy::scopeUsesSlowTiming(stored));
EXPECT_EQ(FloodFilterPolicy::SCOPE_PATH_BRIDGE_BUCKET_BASE + 5,
FloodFilterPolicy::scopePathSelectorValue(stored));
}
}
TEST(FloodFilterScope, RegionChannelTargetsKeepLegacySelectorValues) {
const uint8_t selectors[] = {0, 1, 2, 16, 32};
for (uint8_t selector : selectors) {
uint8_t region = FloodFilterPolicy::encodeChannelScopeTargetSelector(
selector, false);
EXPECT_EQ(selector, region);
EXPECT_FALSE(FloodFilterPolicy::channelScopeUsesDirectTarget(region));
EXPECT_EQ(selector,
FloodFilterPolicy::channelScopeMatchSelectorValue(region));
}
}
TEST(FloodFilterScope, DirectChannelTargetRejectsUnknownMatcher) {
EXPECT_EQ(FloodFilterPolicy::CHANNEL_SCOPE_INVALID_SELECTOR,
FloodFilterPolicy::encodeChannelScopeTargetSelector(7, true));
}
TEST(FloodFilterScope, OnlyChangedFastRulesReceiveFastTrackTreatment) {
EXPECT_TRUE(FloodFilterPolicy::fastTrackScopeChange(true, false));
EXPECT_FALSE(FloodFilterPolicy::fastTrackScopeChange(true, true));
@@ -0,0 +1,111 @@
#include <gtest/gtest.h>
#include <helpers/LogicalMessageCache.h>
static void makeFingerprint(uint8_t fingerprint[MAX_HASH_SIZE], uint8_t value) {
memset(fingerprint, value, MAX_HASH_SIZE);
}
TEST(LogicalMessageCache, MatchesFingerprintAndSourceTimestamp) {
mesh::LogicalMessageCache<4> cache;
uint8_t first[MAX_HASH_SIZE];
uint8_t second[MAX_HASH_SIZE];
makeFingerprint(first, 0x11);
makeFingerprint(second, 0x22);
ASSERT_TRUE(cache.remember(first, 100U, 500U));
uint32_t mapped = 0;
EXPECT_TRUE(cache.find(first, 100U, &mapped));
EXPECT_EQ(500U, mapped);
EXPECT_FALSE(cache.find(first, 101U));
EXPECT_FALSE(cache.find(second, 100U));
}
TEST(LogicalMessageCache, RepeatedRememberUpdatesMappedTimestamp) {
mesh::LogicalMessageCache<2> cache;
uint8_t fingerprint[MAX_HASH_SIZE];
makeFingerprint(fingerprint, 0x33);
ASSERT_TRUE(cache.remember(fingerprint, 7U, 70U));
ASSERT_TRUE(cache.remember(fingerprint, 7U, 71U));
uint32_t mapped = 0;
EXPECT_TRUE(cache.find(fingerprint, 7U, &mapped));
EXPECT_EQ(71U, mapped);
}
TEST(LogicalMessageCache, RoundRobinReplacementIsBounded) {
mesh::LogicalMessageCache<2> cache;
uint8_t first[MAX_HASH_SIZE];
uint8_t second[MAX_HASH_SIZE];
uint8_t third[MAX_HASH_SIZE];
makeFingerprint(first, 0x41);
makeFingerprint(second, 0x42);
makeFingerprint(third, 0x43);
ASSERT_TRUE(cache.remember(first, 1U));
ASSERT_TRUE(cache.remember(second, 2U));
ASSERT_TRUE(cache.remember(third, 3U));
EXPECT_FALSE(cache.find(first, 1U));
EXPECT_TRUE(cache.find(second, 2U));
EXPECT_TRUE(cache.find(third, 3U));
}
TEST(LogicalMessageCache, ClearForgetsAllEntries) {
mesh::LogicalMessageCache<2> cache;
uint8_t fingerprint[MAX_HASH_SIZE];
makeFingerprint(fingerprint, 0x55);
ASSERT_TRUE(cache.remember(fingerprint, 9U, 90U));
cache.clear();
EXPECT_FALSE(cache.find(fingerprint, 9U));
}
TEST(LogicalMessageCache, ExactOlderRetrySurvivesNewerMessages) {
mesh::LogicalMessageCache<4> cache;
uint8_t first[MAX_HASH_SIZE];
uint8_t second[MAX_HASH_SIZE];
makeFingerprint(first, 0x61);
makeFingerprint(second, 0x62);
uint32_t latest = 0;
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::NewMessage,
cache.classifyAndRemember(first, 100U, latest));
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::NewMessage,
cache.classifyAndRemember(second, 101U, latest));
EXPECT_EQ(101U, latest);
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::ExactRetry,
cache.classifyAndRemember(first, 100U, latest));
EXPECT_EQ(101U, latest);
}
TEST(LogicalMessageCache, RejectsOldUnseenAndSameTimestampMismatches) {
mesh::LogicalMessageCache<4> cache;
uint8_t accepted[MAX_HASH_SIZE];
uint8_t mismatched[MAX_HASH_SIZE];
makeFingerprint(accepted, 0x71);
makeFingerprint(mismatched, 0x72);
uint32_t latest = 200U;
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::StaleOrMismatched,
cache.classifyAndRemember(mismatched, 199U, latest));
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::StaleOrMismatched,
cache.classifyAndRemember(mismatched, 200U, latest));
EXPECT_EQ(mesh::LogicalMessageCache<4>::ReplayDecision::NewMessage,
cache.classifyAndRemember(accepted, 201U, latest));
}
TEST(LogicalMessageCache, RejectsNullFingerprint) {
mesh::LogicalMessageCache<2> cache;
EXPECT_FALSE(cache.remember(NULL, 1U, 2U));
EXPECT_FALSE(cache.find(NULL, 1U));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,85 @@
#include <gtest/gtest.h>
#include <helpers/RemoteCliReplyCache.h>
TEST(RemoteCliReplyCache, ReplaysOnlyTheSameAuthenticatedRequest) {
mesh::RemoteCliReplyCache cache;
uint8_t alice[PUB_KEY_SIZE] = {};
uint8_t bob[PUB_KEY_SIZE] = {};
alice[0] = 0xA1;
bob[0] = 0xB2;
const char command[] = "set repeat off";
const uint32_t fingerprint =
mesh::RemoteCliReplyCache::fingerprint(command, strlen(command));
EXPECT_FALSE(cache.matches(alice, 123U, fingerprint));
ASSERT_TRUE(cache.remember(alice, 123U, fingerprint, "OK"));
EXPECT_TRUE(cache.matches(alice, 123U, fingerprint));
EXPECT_STREQ("OK", cache.response());
EXPECT_TRUE(cache.hasResponse());
EXPECT_FALSE(cache.matches(bob, 123U, fingerprint));
EXPECT_FALSE(cache.matches(alice, 124U, fingerprint));
EXPECT_FALSE(cache.matches(
alice, 123U,
mesh::RemoteCliReplyCache::fingerprint("set repeat on", 13)));
}
TEST(RemoteCliReplyCache, OwnsAndReplacesTheRememberedResponse) {
mesh::RemoteCliReplyCache cache;
uint8_t first_sender[PUB_KEY_SIZE] = {};
uint8_t sender[PUB_KEY_SIZE] = {};
first_sender[0] = 0x11;
memcpy(sender, first_sender, sizeof(sender));
char response[] = "first";
ASSERT_TRUE(cache.remember(sender, 1U, 10U, response));
response[0] = 'X';
sender[0] = 0x22;
EXPECT_STREQ("first", cache.response());
ASSERT_TRUE(cache.remember(sender, 2U, 20U, "second"));
EXPECT_FALSE(cache.matches(first_sender, 1U, 10U));
EXPECT_TRUE(cache.matches(sender, 2U, 20U));
EXPECT_STREQ("second", cache.response());
}
TEST(RemoteCliReplyCache, EmptyResponseStillMarksRequestComplete) {
mesh::RemoteCliReplyCache cache;
uint8_t sender[PUB_KEY_SIZE] = {};
ASSERT_TRUE(cache.remember(sender, 9U, 99U, ""));
EXPECT_TRUE(cache.matches(sender, 9U, 99U));
EXPECT_TRUE(cache.isValid());
EXPECT_FALSE(cache.hasResponse());
EXPECT_STREQ("", cache.response());
}
TEST(RemoteCliReplyCache, TruncatesToTheOnAirReplyLimit) {
mesh::RemoteCliReplyCache cache;
uint8_t sender[PUB_KEY_SIZE] = {};
char response[mesh::RemoteCliReplyCache::MAX_REPLY_TEXT + 20];
memset(response, 'x', sizeof(response));
response[sizeof(response) - 1] = 0;
ASSERT_TRUE(cache.remember(sender, 7U, 77U, response));
EXPECT_EQ(mesh::RemoteCliReplyCache::MAX_REPLY_TEXT,
strlen(cache.response()));
}
TEST(RemoteCliReplyCache, ClearForgetsTheRequestAndResponse) {
mesh::RemoteCliReplyCache cache;
uint8_t sender[PUB_KEY_SIZE] = {};
ASSERT_TRUE(cache.remember(sender, 1U, 2U, "OK"));
cache.clear();
EXPECT_FALSE(cache.isValid());
EXPECT_FALSE(cache.matches(sender, 1U, 2U));
EXPECT_STREQ("", cache.response());
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}