diff --git a/FILTER.md b/FILTER.md index c757b17d..89251f4b 100644 --- a/FILTER.md +++ b/FILTER.md @@ -112,6 +112,7 @@ by spaces. Values containing spaces go in double quotes: `text="^RX in place"`. | `region` | region name(s), `unscoped` (comma-combine) | Flood region the packet arrived in (direct packets never match) | | `sender` | pattern | Sender name in group text, e.g. `SpamBot` from `SpamBot: hello` | | `text` | pattern | Message text in group text | +| `prob` | `1..100` | Match probability: the rule decides only that percentage of the packets its conditions match (see [prob examples](#prob)) | | `action` | `drop` (default) or `forward` | What to do on a match: `drop` discards the packet, `forward` stops the rule list and lets it through (see [shadow mode](#trying-a-rule-before-enforcing-it-shadow-mode)). Upgrading from firmware that called this `logonly`: such rules now read and behave as `forward` — the stored value is unchanged, only the keyword and display moved | `chan`, `sender`, and `text` are content conditions: they are checked after the @@ -515,6 +516,37 @@ Match the message only. For `SpamBot: BEACON 123`, the text is `BEACON 123`. The last pattern matches `ID:123` and `ID: 042`, but not `ID:12` or `ID:1234`. +### `prob` + +A rule with `prob=N` decides only about N% of the packets its conditions all +match. On a "failed roll" the rule steps aside and evaluation continues with +the next rule, exactly as if the conditions had not matched — when every +matching rule fails its roll, the packet passes. This is *dosing*: apply +pressure without a hard cutoff. + +- Omit `prob=` for the default: 100% (always decides). +- It works on both actions: a `drop` rule with `prob=75` drops 3 of 4 matching + packets; a `forward` probe with `prob=75` terminates the list on 3 of 4. +- A later static rule acts as the fallback for the packets a dosed rule + lets through — e.g. a `prob=80` drop followed by an unconditional rule + expresses "80% pressure, guaranteed floor". +- The roll is **deterministic per packet**: the same packet always gets the + same verdict from the same rule, so counters are stable and repeatable. + A retransmitted copy is a new packet and rolls again. +- `prob=0` is rejected — a 0% rule is a disabled rule; use + `filter disable ` instead. + +| Command | Effect | +|---|---| +| `filter add chan=#chat sender="^Bot" prob=50` | Halve the bot's delivered traffic on `#chat` without cutting its owner off | +| `filter add hsize=1 prob=75` | Degrade ambiguous 1-byte-hash relaying to 25% pass-through, nudging nodes to upgrade | +| `filter add chan=#auction prob=70` | Shed 70% of a busy event channel's load; users see degradation, not silence | +| `filter add type=advert action=forward prob=10` | Shadow-mode *sampling*: count a representative 10% of adverts without enforcing anything | + +Note: `hits` counts **decisions**, not condition matches — a packet the rule +matched but then passed on a failed roll is not counted (and not shown in +`filter get`). + ## Trying a rule before enforcing it (shadow mode) Not sure a rule is right? Add it with `action=forward`: matching packets are diff --git a/examples/simple_repeater/PacketFilter.cpp b/examples/simple_repeater/PacketFilter.cpp index 478e9922..2dcdcd38 100644 --- a/examples/simple_repeater/PacketFilter.cpp +++ b/examples/simple_repeater/PacketFilter.cpp @@ -26,9 +26,11 @@ static int filterDecodeHex(const char* in, size_t in_len, uint8_t* out) { // The well-known Public channel PSK (16 bytes); its sha256()[0] air hash is 0x11. #define FILTER_PUBLIC_PSK_HEX "8b3387e9c5cdea6ac9e5edbaa115cd72" #define FILTER_CFG_FILE "/filter_cfg" -#define FILTER_CFG_VERSION 4 // v4: region= predicate list on rules - // (a v3 rule record is a byte-prefix of a v4 - // record; v1/v2 configs discarded on upgrade) +#define FILTER_CFG_VERSION 5 // v5: prob= match probability on rules (stored + // in the tail padding after regions, so the + // record size is unchanged); a v4 record is a + // byte-identical prefix whose prob byte reads 0 + // (= always); v1/v2 configs discarded on upgrade #define FILTER_RULE_PERSIST_BYTES (offsetof(FilterRule, hits)) // config fields only; stats excluded // v3 record size: v3 ended each rule record at its offsetof(hits) — the config // bytes plus the tail padding that preceded the (then-next) uint32_t. With v4 @@ -250,6 +252,31 @@ bool FilterRules::advertRatelimitDrop(const mesh::Packet* pkt, uint32_t now_mill return false; } +// FNV-1a over the rule's predicate fields (a short display digest for `filter list`) +static uint32_t ruleDigest(const FilterRule* r) { + uint32_t h = 2166136261u; + const uint8_t* p = (const uint8_t*)&r->action; + const uint8_t* end = (const uint8_t*)&r->hits; + for (; p < end; p++) { + h ^= *p; + h *= 16777619u; + } + return h; +} + +// Deterministic per (packet, rule) match-probability roll: FNV-1a over the +// packet hash salted with the rule digest. rand() is never seeded anywhere, so +// it would replay the same sequence every boot; this roll is idempotent under +// the stash re-scan (same packet -> same verdict) and exact-testable. +static bool probDecides(const FilterRule* r, const mesh::Packet* pkt) { + if (r->prob == 0 || r->prob >= 100) return true; // unset = always (100 %) + uint8_t h[MAX_HASH_SIZE]; + pkt->calculatePacketHash(h); // same hash the stash guard uses + uint32_t x = ruleDigest(r) ^ 2166136261u; // per-rule salt + for (int i = 0; i < MAX_HASH_SIZE; i++) { x ^= h[i]; x *= 16777619u; } + return (x % 100) < r->prob; +} + // ---------------------------------------------------------------- matching static bool intervalMatches(const Interval& iv, int32_t v) { @@ -376,11 +403,11 @@ uint8_t FilterRules::checkPacket(const mesh::Packet* pkt, uint32_t now_millis, c for (int i = 0; i < num_rules; i++) { FilterRule* r = &rules[i]; if (!r->enabled || ruleIsDeferred(r)) continue; // deferred rules decide on decrypted content - if (ruleMatchesPacket(r, pkt, payload_type, region)) { - r->hits++; - action = r->action; - break; // first match wins - } + if (!ruleMatchesPacket(r, pkt, payload_type, region)) continue; + if (!probDecides(r, pkt)) continue; // failed roll: fall through as if not matched + r->hits++; + action = r->action; + break; // first match wins } if (action == FILTER_ACT_DROP) return FILTER_ACT_DROP; @@ -473,6 +500,7 @@ uint8_t FilterRules::checkContent(mesh::Packet* pkt, uint8_t type, const mesh::G if ((r->chan_flags & FILTER_CHANFLG_MASK_SET) && !channelMatchesStore(r, channel)) continue; if (r->sender[0] && (!parsed || !regexMatches(r->sender, sender))) continue; if (r->text[0] && (!parsed || !regexMatches(r->text, text))) continue; + if (!probDecides(r, pkt)) continue; // failed roll: fall through as if not matched r->hits++; verdict = r->action; break; // first match wins @@ -497,6 +525,7 @@ uint8_t FilterRules::checkContent(mesh::Packet* pkt, uint8_t type, const mesh::G // guards against layout drift. void FilterRules::load(FILESYSTEM* fs) { + memset(rules, 0, sizeof(rules)); // unpersisted tail bytes (padding, stats) stay deterministic num_rules = 0; num_channels = 0; enabled = true; @@ -511,17 +540,22 @@ void FilterRules::load(FILESYSTEM* fs) { uint8_t hdr[5]; // version, enabled, num_rules, num_channels, (spare) uint8_t ver; // version byte; hdr[] is reused for the remaining fields if (file.read(hdr, 1) == 1 && - ((ver = hdr[0]) == FILTER_CFG_VERSION || ver == FILTER_CFG_VERSION - 1) && + (ver = hdr[0], ver == FILTER_CFG_VERSION || ver == FILTER_CFG_VERSION - 1 || + ver == FILTER_CFG_VERSION - 2) && file.read(hdr, 4) == 4) { enabled = hdr[0] != 0; uint8_t nr = hdr[1] < FILTER_MAX_RULES ? hdr[1] : FILTER_MAX_RULES; uint8_t nc = hdr[2] < FILTER_MAX_CHANNELS ? hdr[2] : FILTER_MAX_CHANNELS; - size_t rule_bytes = (ver == FILTER_CFG_VERSION) ? FILTER_RULE_PERSIST_BYTES - : FILTER_RULE_V3_PERSIST_BYTES; + size_t rule_bytes = (ver >= FILTER_CFG_VERSION - 1) ? FILTER_RULE_PERSIST_BYTES + : FILTER_RULE_V3_PERSIST_BYTES; if (file.read((uint8_t*)&ratelimit_hours, 2) == 2) { bool ok = true; for (int i = 0; ok && i < nr; i++) { ok = (file.read((uint8_t*)&rules[i], rule_bytes) == rule_bytes); + if (ok && ver < FILTER_CFG_VERSION) { + // pre-v5 record: the prob byte (v4 tail padding) is not format-guaranteed + rules[i].prob = 0; + } if (ok && rule_bytes < FILTER_RULE_PERSIST_BYTES) { // v3 record: the read drags the old record's trailing padding bytes // into regions[0..1], so zero the whole regions field (predicate unset) @@ -698,18 +732,6 @@ static bool parsePath(const char* tok, FilterRule* r) { return true; } -// FNV-1a over the rule's predicate fields (a short display digest for `filter list`) -static uint32_t ruleDigest(const FilterRule* r) { - uint32_t h = 2166136261u; - const uint8_t* p = (const uint8_t*)&r->action; - const uint8_t* end = (const uint8_t*)&r->hits; - for (; p < end; p++) { - h ^= *p; - h *= 16777619u; - } - return h; -} - // ---------------------------------------------------------------- filter add static bool setPattern(char* dest, size_t dest_sz, const char* pattern) { @@ -856,6 +878,16 @@ static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions, else { strcpy(reply, "Err - action must be drop|forward"); return false; } return true; } + if (strcmp(key, "prob") == 0) { + char* end; + long v = strtol(val, &end, 10); + if (end == val || *end != 0 || v < 1 || v > 100) { + strcpy(reply, "Err - prob must be 1..100 (omit for 100%)"); + return false; + } + r->prob = (uint8_t)v; + return true; + } sprintf(reply, "Err - unknown param '%s'", key); return false; } @@ -1012,6 +1044,7 @@ static void cliGet(FilterRules& filter, int idx, char* reply) { if (strchr(r->text, ' ')) radd(&out, &remain, " text=\"%s\"", r->text); else radd(&out, &remain, " text=%s", r->text); } + if (r->prob) radd(&out, &remain, " prob=%u", r->prob); radd(&out, &remain, " hits=%lu", (unsigned long)r->hits); } diff --git a/examples/simple_repeater/PacketFilter.h b/examples/simple_repeater/PacketFilter.h index 8de927ab..50ff7094 100644 --- a/examples/simple_repeater/PacketFilter.h +++ b/examples/simple_repeater/PacketFilter.h @@ -106,6 +106,10 @@ struct FilterRule { char text[FILTER_TEXT_PATTERN_LEN]; // regex over message text; empty = wildcard char regions[FILTER_REGION_LIST_LEN]; // comma list of canonical region names // and/or "unscoped"; empty = wildcard + uint8_t prob; // match probability %; 0 = unset = always (100 %). + // Lands in the tail padding after regions, so the + // persisted record size is unchanged (v4 configs read + // back with prob == 0) uint32_t hits; // match counter (forward/drop telemetry + validation) }; diff --git a/test/test_packet_filter/test_packet_filter.cpp b/test/test_packet_filter/test_packet_filter.cpp index d093bc4b..6cd279cc 100644 --- a/test/test_packet_filter/test_packet_filter.cpp +++ b/test/test_packet_filter/test_packet_filter.cpp @@ -988,13 +988,15 @@ TEST_F(FilterTest, ForwardAdvertStillHitsLimiter) { #include "FilterTestHelpers.h" -// /filter_cfg layout constants (mirrors PacketFilter.cpp: the v4 record is -// the struct up to `hits`; the v3 record is the same struct with no `regions` -// field, padded to uint32_t alignment; the lazy-save delay is 3000 ms) +// /filter_cfg layout constants (mirrors PacketFilter.cpp: the v5 record is +// the struct up to `hits` (the prob byte slots into the former tail padding, +// so the v4 record is byte-identical in size); the v3 record is the same +// struct with no `regions` field, padded to uint32_t alignment; the lazy-save +// delay is 3000 ms) static constexpr size_t V4_RULE_BYTES = offsetof(FilterRule, hits); static constexpr size_t V3_RULE_BYTES = (offsetof(FilterRule, regions) + alignof(uint32_t) - 1) & ~(alignof(uint32_t) - 1); -static constexpr uint8_t CFG_VERSION = 4; +static constexpr uint8_t CFG_VERSION = 5; static constexpr unsigned long CFG_SAVE_DELAY_MS = 3000; static const char* CFG_FILE = "/filter_cfg"; @@ -1228,6 +1230,148 @@ TEST_F(FilterTest, LoopSavesOnceWhenClean) { EXPECT_EQ(fs.files[CFG_FILE], saved); } +// ============================================================ +// UNIT TESTS: match probability (prob=) +// ============================================================ + +// Native tests for the per-rule match probability: parse validation, the +// deterministic content-derived roll (same packet -> same verdict, no global +// RNG), fall-through on a failed roll, and the one-roll-per-decision stash +// contract on the content path. + +#include + +#include + +#include "FilterTestHelpers.h" + +static const uint8_t PROB_KEY[4] = { 0x11, 0x22, 0x33, 0x44 }; + +// distinct packets: same shape, varying first payload byte (the packet hash +// covers the payload, so each i rolls independently) +static mesh::Packet probAdvert(int i) { + mesh::Packet p = makeAdvert(PROB_KEY); + p.payload[0] = (uint8_t)i; // not one of the advert-limiter key offsets + return p; +} + +TEST_F(FilterTest, ProbParseRejectsInvalid) { + EXPECT_EQ(cli(filter, "add prob=0").substr(0, 5), "Err -"); + EXPECT_EQ(cli(filter, "add prob=101").substr(0, 5), "Err -"); + EXPECT_EQ(cli(filter, "add prob=abc").substr(0, 5), "Err -"); + EXPECT_EQ(cli(filter, "add prob=").substr(0, 5), "Err -"); + EXPECT_EQ(cli(filter, "add prob=5x").substr(0, 5), "Err -"); // full token required + EXPECT_EQ(filter.getNumRules(), 0); // no half-added rules +} + +TEST_F(FilterTest, ProbShownInGetAndChangesDigest) { + expectOk(filter, "add type=advert"); + expectOk(filter, "add type=advert prob=50"); + EXPECT_EQ(cli(filter, "get 0").find(" prob="), std::string::npos); + EXPECT_NE(cli(filter, "get 1").find(" prob=50"), std::string::npos); + + // digest covers the record through hits, so prob is part of it + std::string list = cli(filter, "list"); + size_t colon = list.find(':'); + size_t sp1 = list.find(' ', colon + 1), sp2 = list.find(' ', sp1 + 1); + ASSERT_NE(sp1, std::string::npos); + if (sp2 == std::string::npos) sp2 = list.size(); + std::string tok0 = list.substr(sp1 + 1, sp2 - sp1 - 1); + std::string tok1 = list.substr(sp2 + 1); + ASSERT_EQ(tok0.size(), 6u); + ASSERT_EQ(tok1.size(), 6u); + EXPECT_NE(tok0, tok1); +} + +TEST_F(FilterTest, ProbPersistsRoundtrip) { + expectOk(filter, "add type=advert prob=75"); + filter.save(&fs); + std::string digest_before = cli(filter, "list"); + + FilterRules restored; + restored.begin(&fs); + ASSERT_EQ(restored.getNumRules(), 1); + EXPECT_EQ(restored.getRule(0)->prob, 75); + std::string digest_after = cli(restored, "list"); + EXPECT_EQ(digest_after, digest_before); // padding canary: byte-identical record +} + +TEST_F(FilterTest, V4ConfigLoadsProbUnset) { + expectOk(filter, "add type=advert prob=50"); + filter.save(&fs); + auto& blob = fs.files[CFG_FILE]; + blob[0] = 4; // downgrade the header: a v4 record has no prob field + blob[7 + offsetof(FilterRule, prob)] = 0xFF; // old padding byte, not guaranteed + + FilterRules restored; + restored.begin(&fs); + ASSERT_EQ(restored.getNumRules(), 1); + EXPECT_EQ(restored.getRule(0)->prob, 0); // unset = always (100 %) + EXPECT_EQ(restored.getRule(0)->hits, 0u); // stats never persisted +} + +TEST_F(FilterTest, ProbAlwaysDecides) { + expectOk(filter, "add type=advert prob=100"); + for (int i = 0; i < 10; i++) { + mesh::Packet adv = probAdvert(i); + EXPECT_EQ(filter.checkPacket(&adv, 0, nullptr), FILTER_ACT_DROP); + } + EXPECT_EQ(filter.getRule(0)->hits, 10u); +} + +TEST_F(FilterTest, ProbRollStablePerPacket) { + // no global RNG: the same packet always gets the same verdict from the + // same rule, even across repeated scans (stash re-scan idempotence) + expectOk(filter, "add type=advert action=forward prob=50"); + for (int i = 0; i < 50; i++) { + mesh::Packet adv = probAdvert(i); + uint8_t v1 = filter.checkPacket(&adv, 0, nullptr); + uint8_t v2 = filter.checkPacket(&adv, 0, nullptr); + EXPECT_EQ(v1, v2) << "packet " << i; + } +} + +TEST_F(FilterTest, ProbRollDistribution) { + expectOk(filter, "add type=advert prob=50"); + int drops = 0; + for (int i = 0; i < 200; i++) { + mesh::Packet adv = probAdvert(i); + if (filter.checkPacket(&adv, 0, nullptr) == FILTER_ACT_DROP) drops++; + } + EXPECT_GE(drops, 80); // ~100 expected; wide bounds keep the test deterministic + EXPECT_LE(drops, 120); + EXPECT_EQ(filter.getRule(0)->hits, (uint32_t)drops); // hits count decisions +} + +TEST_F(FilterTest, ProbFailFallsThroughToLaterRule) { + expectOk(filter, "add type=advert prob=1"); // almost never decides + expectOk(filter, "add type=advert"); // unconditional fallback drop + for (int i = 0; i < 200; i++) { + mesh::Packet adv = probAdvert(i); + EXPECT_EQ(filter.checkPacket(&adv, 0, nullptr), FILTER_ACT_DROP); // either way + } + EXPECT_LE(filter.getRule(0)->hits, 20u); // dosed rule decides rarely + EXPECT_GE(filter.getRule(1)->hits, 180u); // fallback decides the rest +} + +TEST_F(FilterTest, ProbContentPathRollsOnce) { + expectOk(filter, "chan add #t"); + expectOk(filter, "add chan=#t prob=50"); + int b_idx = -1; + for (int i = 0; i < filter.getNumChannels(); i++) { + if (strcmp(filter.getChannel(i)->name, "#t") == 0) { b_idx = i; break; } + } + ASSERT_GE(b_idx, 0); + + mesh::Packet pkt; + uint8_t v = filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, channelFromStore(filter, b_idx), + nullptr, 0, nullptr); + // the stashed verdict is final: checkPacket consumes it without re-rolling + // or double-counting, whatever the roll said + EXPECT_EQ(filter.checkPacket(&pkt, 0, nullptr), v); + EXPECT_LE(filter.getRule(0)->hits, 1u); +} + // ============================================================ // UNIT TESTS: filter CLI surface // ============================================================ @@ -2016,7 +2160,7 @@ TEST_F(FilterTest, MovePersistsOrder) { filter.getRule(1)->hits = 42; // hits are RAM-only ASSERT_EQ(cli(filter, "move 1 0"), "OK - rule 1 moved to 0"); filter.save(&fs); - EXPECT_EQ(fs.files[CFG_FILE][0], 4); // config version byte unchanged + EXPECT_EQ(fs.files[CFG_FILE][0], CFG_VERSION); // config version byte unchanged FilterRules restored; restored.begin(&fs);