Add secure management reports and honor GPS off
This commit is contained in:
1 parent
ad0ea545d3
commit
4ba26ff4af
30 files changed
+2109
-76
No files matched your search
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
#include <Mesh.h>
|
||||
#include <vector>
|
||||
class NodePrefs { public: uint8_t path_hash_mode = 0; };
|
||||
class CommonCLI {
|
||||
uint8_t path[64] = {};
|
||||
public:
|
||||
uint8_t path_len = 0;
|
||||
bool scope_available = true;
|
||||
bool getDataTxPath(const uint8_t*& out, uint8_t& len) const {
|
||||
out = path; len = path_len;
|
||||
return path_len != 0xff && mesh::Packet::isValidPathLen(path_len);
|
||||
}
|
||||
bool resolveDataTxScope(TransportKey& scope, char* = nullptr,
|
||||
size_t = 0, bool* ambiguous = nullptr) const {
|
||||
if (ambiguous) *ambiguous = false;
|
||||
scope = TransportKey(); return scope_available;
|
||||
}
|
||||
bool adoptLegacyDataTxPath(const uint8_t*, uint8_t) { return true; }
|
||||
};
|
||||
class CommonCLICallbacks {
|
||||
public:
|
||||
const char* getFirmwareVer() { return "v1.17.1.5"; }
|
||||
const char* getRole() { return "repeater"; }
|
||||
};
|
||||
struct LocationProvider { bool isEnabled() { return false; } };
|
||||
class SensorManager {
|
||||
public:
|
||||
bool isGPSDetected() { return false; }
|
||||
LocationProvider* getLocationProvider() { return nullptr; }
|
||||
};
|
||||
struct ClientInfo { mesh::LocalIdentity id; bool admin = true; bool isAdmin() const { return admin; } };
|
||||
class ClientACL {
|
||||
public:
|
||||
std::vector<ClientInfo> clients;
|
||||
int getNumClients() { return clients.size(); }
|
||||
ClientInfo* getClientByIdx(int i) { return &clients[i]; }
|
||||
};
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
inline uint32_t test_millis = 0;
|
||||
inline uint32_t millis() { return test_millis; }
|
||||
#define MAX_PATH_SIZE 64
|
||||
#define OUT_PATH_UNKNOWN 0xff
|
||||
struct TransportKey {
|
||||
uint8_t key[16] = {1};
|
||||
bool isNull() const { for (auto b : key) if (b) return false; return true; }
|
||||
};
|
||||
namespace mesh {
|
||||
struct LocalIdentity { uint8_t pub_key[32] = {}; };
|
||||
struct Packet {
|
||||
uint8_t payload[184] = {}, payload_len = 0;
|
||||
bool flood = false;
|
||||
static bool isValidPathLen(uint8_t n) { return (n >> 6) < 3 && ((n & 63) * ((n >> 6) + 1)) <= 64; }
|
||||
static uint8_t copyPath(uint8_t* out, const uint8_t* in, uint8_t n) {
|
||||
const size_t bytes = (n & 63) * ((n >> 6) + 1);
|
||||
if (bytes) memcpy(out, in, bytes);
|
||||
return n;
|
||||
}
|
||||
};
|
||||
struct RTCClock { uint32_t time = 1789513200; uint32_t getCurrentTime() { return time; } };
|
||||
struct MainBoard {
|
||||
uint16_t voltage = 3740;
|
||||
float temperature = 24;
|
||||
uint16_t getBattMilliVolts() { return voltage; }
|
||||
float getMCUTemperature() { return temperature; }
|
||||
};
|
||||
struct Mesh {
|
||||
LocalIdentity self_id;
|
||||
RTCClock rtc;
|
||||
bool temp = false, outbound = false, fail_queue = false;
|
||||
unsigned budget = 60000;
|
||||
std::vector<Packet> packets;
|
||||
RTCClock* getRTCClock() { return &rtc; }
|
||||
bool isAnyTempRadioActive() { return temp; }
|
||||
bool hasOutbound() { return outbound; }
|
||||
unsigned getRemainingTxBudget() { return budget; }
|
||||
Packet* createRawData(const uint8_t* data, size_t n) { auto* p = new Packet; memcpy(p->payload, data, n); p->payload_len = n; return p; }
|
||||
bool sendManagementData(Packet* p, bool flood, const uint8_t*, uint8_t,
|
||||
uint8_t, const uint8_t* = nullptr) {
|
||||
p->flood = flood; if (!fail_queue) packets.push_back(*p); delete p; return !fail_queue;
|
||||
}
|
||||
};
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
#include <helpers/ManagementReport.h>
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
using namespace mesh::management;
|
||||
static std::vector<uint8_t> hex(const char* text) {
|
||||
std::vector<uint8_t> b;
|
||||
while (*text) { unsigned n; assert(sscanf(text, "%2x", &n) == 1); b.push_back(n); text += 2; }
|
||||
return b;
|
||||
}
|
||||
static void print(const uint8_t* p, size_t n) { while (n--) printf("%02x", *p++); puts(""); }
|
||||
int main() {
|
||||
// RFC 5297 Appendix A.1 (real AES, never the repository's no-op AES mock).
|
||||
auto k = hex("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");
|
||||
auto ad = hex("101112131415161718191a1b1c1d1e1f2021222324252627");
|
||||
auto plain = hex("112233445566778899aabbccddee"); auto p = plain;
|
||||
uint8_t tag[16]; assert(seal(k.data(), ad.data(), ad.size(), p.data(), p.size(), tag));
|
||||
assert(equal(tag, hex("85632d07c6e8f37f950acd320a2ecc93").data(), 16));
|
||||
assert(p == hex("40c02b9690c4dc04daef7f6afe5c"));
|
||||
assert(open(k.data(), ad.data(), ad.size(), p.data(), p.size(), tag)); assert(p == plain);
|
||||
for (size_t n : {size_t(0), size_t(1), size_t(15), size_t(16), size_t(17), size_t(78), size_t(177)}) {
|
||||
std::vector<uint8_t> b(n, 0x39), original = b;
|
||||
assert(seal(k.data(), ad.data(), ad.size(), b.data(), n, tag));
|
||||
assert(open(k.data(), ad.data(), ad.size(), b.data(), n, tag)); assert(b == original);
|
||||
assert(seal(k.data(), ad.data(), ad.size(), b.data(), n, tag)); tag[4] ^= 1;
|
||||
assert(!open(k.data(), ad.data(), ad.size(), b.data(), n, tag));
|
||||
for (uint8_t c : b) assert(c == 0);
|
||||
}
|
||||
assert(!seal(k.data(), ad.data(), ad.size(), p.data(), 178, tag));
|
||||
History history;
|
||||
history.sample(0, 3900, -4); history.sample(59, 3100, 98);
|
||||
assert(history.week().voltage == 3100 && history.week().high == temperature(98));
|
||||
history.sample(3600, 3800, 28);
|
||||
history.advance(169 * 3600);
|
||||
assert(history.week().voltage == 3800 && history.period.voltage == 3100);
|
||||
history.advance(400 * 3600); assert(history.week().voltage == 0);
|
||||
assert(temperature(NAN) == 0 && temperature(-51) == 252 && temperature(201) == 253);
|
||||
Schedule schedule;
|
||||
assert(Schedule::validDirect(5) && Schedule::validDirect(90));
|
||||
assert(!Schedule::validDirect(4) && !Schedule::validDirect(91));
|
||||
assert(Schedule::validFlood(21) && Schedule::validFlood(90));
|
||||
assert(!Schedule::validFlood(20) && !Schedule::validFlood(91));
|
||||
schedule.advance(5 * DAY); assert(schedule.flood == 16 * DAY);
|
||||
schedule.reserve(false, 5, 21, 0); assert(schedule.flood == 16 * DAY);
|
||||
schedule.advance(16 * DAY); assert(!schedule.direct && !schedule.flood);
|
||||
schedule.reserve(true, 5, 21, 0); assert(schedule.flood == 21 * DAY);
|
||||
assert(schedule.direct == 5 * DAY);
|
||||
schedule.direct = 4 * DAY; schedule.flood = 0;
|
||||
schedule.reserve(true, 5, 21, 0); assert(schedule.direct == 4 * DAY);
|
||||
schedule.reserve(true, 5, 90, 0); assert(schedule.flood == 90 * DAY);
|
||||
Schedule restored = schedule; restored.advance(90 * DAY); assert(!restored.flood);
|
||||
uint8_t root[32], radio[16] = {}, admin[32] = {}, token[12], other[12];
|
||||
passwordKey("management test password", root);
|
||||
fingerprint(root, radio, admin, token); radio[0] = 1;
|
||||
fingerprint(root, radio, admin, other); assert(!equal(token, other, 12));
|
||||
AclList acl; assert(acl.add(token, ADMIN)); assert(acl.add(token, OTA_SIGNER));
|
||||
assert(acl.count == 1 && acl.entries[0][12] == 3);
|
||||
for (uint8_t i = 1; i < MAX_KEYS; ++i) { token[0] = i; assert(acl.add(token, ADMIN)); }
|
||||
token[0] = 240; assert(!acl.add(token, ADMIN)); assert(acl.pages() == MAX_PAGES);
|
||||
// Emit cross-language packets with all header fields and maximum ACL pages.
|
||||
for (uint8_t page = 0; page < acl.pages(); ++page) {
|
||||
uint8_t raw[MAX_PAYLOAD] = {}, enc[32]; memcpy(raw, "MGR1", 4); memcpy(raw + 4, radio, 16);
|
||||
write32(raw + 20, 42); write32(raw + 28, 0x01110105); write16(raw + 76, FIRMWARE);
|
||||
raw[71] = 5; raw[78] = page; raw[79] = acl.pages(); raw[80] = acl.count;
|
||||
raw[81] = page * PER_PAGE; raw[82] = PER_PAGE;
|
||||
memcpy(raw + HEADER, acl.entries[page * PER_PAGE], PER_PAGE * ENTRY);
|
||||
deriveKey(root, "MeshCore-MGR1-SIV", radio, enc);
|
||||
assert(seal(enc, raw, HEADER, raw + HEADER, PER_PAGE * ENTRY, raw + MAX_PAYLOAD - TAG));
|
||||
assert(validPage(raw, sizeof(raw))); print(raw, sizeof(raw));
|
||||
raw[81]++; assert(!validPage(raw, sizeof(raw))); raw[81]--;
|
||||
assert(!validPage(raw, sizeof(raw) - 1)); raw[80] = 37; assert(!validPage(raw, sizeof(raw)));
|
||||
}
|
||||
for (size_t n = 0; n < HEADER + TAG; ++n) assert(!validPage(plain.data(), n));
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
#include "ManagementReporter.h"
|
||||
#include "CommonCLI.h"
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
using namespace mesh;
|
||||
using namespace mesh::management;
|
||||
struct Fixture {
|
||||
MemoryFS fs;
|
||||
Mesh mesh;
|
||||
MainBoard board;
|
||||
SensorManager sensors;
|
||||
ClientACL acl;
|
||||
NodePrefs prefs;
|
||||
CommonCLI cli;
|
||||
CommonCLICallbacks callbacks;
|
||||
std::unique_ptr<ManagementReporter> reporter;
|
||||
Fixture() { test_millis = 0; reboot(); }
|
||||
void reboot() { reporter.reset(); test_millis = 0; reporter.reset(new ManagementReporter(mesh, board, sensors, acl, prefs, callbacks, cli, &fs)); }
|
||||
std::string cmd(const char* text, bool ok = true) {
|
||||
char b[200], reply[160] = {}; strcpy(b, text);
|
||||
assert(reporter->command(b, reply, sizeof(reply)));
|
||||
if (!strncmp(text, "set ", 4) && ((!strncmp(reply, "OK", 2)) != ok)) {
|
||||
fprintf(stderr, "%s: %s\n", text, reply); assert(false);
|
||||
}
|
||||
if (!strncmp(text, "set mgmt.password ", 18) && strlen(text + 18) >= 12) assert(b[18] == 0);
|
||||
return reply;
|
||||
}
|
||||
void advance(uint32_t seconds) {
|
||||
while (seconds) { const uint32_t step = seconds < 60 ? seconds : 60; test_millis += step * 1000;
|
||||
reporter->loop(); seconds -= step;
|
||||
}
|
||||
}
|
||||
void configure(bool direct = true) {
|
||||
cmd("set mgmt.enabled on", false);
|
||||
cmd("set mgmt.password short", false);
|
||||
cmd("set mgmt.password management test password");
|
||||
if (direct) cmd("set mgmt.interval 5");
|
||||
cmd("set mgmt.enabled on");
|
||||
// Simulate a route becoming unavailable after enable so fallback-only
|
||||
// tests exercise the scoped 21-day safety report.
|
||||
if (!direct) cli.path_len = 0xff;
|
||||
const auto& file = fs.files["/management"];
|
||||
assert(std::string(file.begin(), file.end()).find("management test password") == std::string::npos);
|
||||
}
|
||||
};
|
||||
int main() {
|
||||
{
|
||||
Fixture f;
|
||||
assert(f.cmd("get mgmt").find("direct=5d") != std::string::npos);
|
||||
assert(f.cmd("get mgmt").find("flood=21d") != std::string::npos);
|
||||
f.advance(100 * DAY); assert(f.mesh.packets.empty());
|
||||
f.configure(); f.cmd("set mgmt.interval 91", false);
|
||||
f.advance(5 * DAY - 60); assert(f.mesh.packets.empty());
|
||||
// Changes to RTC in either direction have no effect on flood eligibility.
|
||||
f.mesh.rtc.time = 0; f.advance(60); assert(f.mesh.packets.size() == 1 && !f.mesh.packets[0].flood);
|
||||
f.mesh.rtc.time = 0xffffffff; f.reboot();
|
||||
f.advance(5 * DAY + 3600); assert(f.mesh.packets.size() == 2);
|
||||
for (const auto& p : f.mesh.packets) assert(!p.flood);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(); f.advance(21 * DAY + 601);
|
||||
assert(f.mesh.packets.size() == 5 && !f.mesh.packets[0].flood && f.mesh.packets.back().flood);
|
||||
const uint32_t seq = read32(f.mesh.packets.back().payload + 20); f.reboot(); f.advance(600);
|
||||
assert(f.mesh.packets.size() == 5);
|
||||
f.cmd("set mgmt.enabled off"); f.cmd("set mgmt.enabled on"); f.advance(600);
|
||||
assert(f.mesh.packets.size() == 5 && read32(f.mesh.packets.back().payload + 20) == seq);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(); f.cmd("set mgmt.flood off");
|
||||
f.advance(21 * DAY + 3600); assert(f.mesh.packets.size() == 4);
|
||||
for (const auto& p : f.mesh.packets) assert(!p.flood);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(); f.cmd("set mgmt.direct off");
|
||||
f.advance(21 * DAY + 60); assert(f.mesh.packets.size() == 1);
|
||||
assert(f.mesh.packets[0].flood);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(); f.cmd("set mgmt.direct 10");
|
||||
f.cmd("set mgmt.flood 30"); f.advance(30 * DAY + 60);
|
||||
assert(f.mesh.packets.size() == 3 && f.mesh.packets.back().flood);
|
||||
assert(!f.mesh.packets[0].flood && !f.mesh.packets[1].flood);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(false); f.advance(21 * DAY - 60); f.fs.fail_write = true; f.advance(120);
|
||||
assert(f.mesh.packets.empty()); assert(f.cmd("get mgmt").find("FAULT") != std::string::npos);
|
||||
// Last hourly checkpoint was one hour before the failed reservation.
|
||||
f.fs.fail_write = false; f.reboot(); f.advance(3600); assert(f.mesh.packets.size() == 1);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(false); f.fs.files["/management"][72] ^= 1; f.reboot(); f.advance(100 * DAY);
|
||||
assert(f.mesh.packets.empty()); assert(f.cmd("get mgmt").find("FAULT") != std::string::npos);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(false); f.fs.fail_read_open = true; f.reboot(); f.advance(100 * DAY);
|
||||
assert(f.mesh.packets.empty());
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
for (unsigned i = 0; i < 36; ++i) { ClientInfo c; c.id.pub_key[0] = i; f.acl.clients.push_back(c); }
|
||||
f.configure(false); f.advance(21 * DAY + 600); assert(f.mesh.packets.size() == 6);
|
||||
for (unsigned i = 0; i < 6; ++i) {
|
||||
const auto& p = f.mesh.packets[i]; assert(validPage(p.payload, p.payload_len));
|
||||
assert(p.payload[78] == i && p.payload[80] == 36 && p.flood);
|
||||
}
|
||||
}
|
||||
{
|
||||
Fixture f;
|
||||
for (unsigned i = 0; i < 7; ++i) { ClientInfo c; c.id.pub_key[0] = i; f.acl.clients.push_back(c); }
|
||||
f.configure(false); f.advance(21 * DAY); assert(f.mesh.packets.size() == 1);
|
||||
f.board.voltage = 2900; f.board.temperature = 60; f.advance(60);
|
||||
assert(f.mesh.packets.size() == 2);
|
||||
// The low reading was not in the first snapshot and must survive into the next one.
|
||||
f.board.voltage = 3740; f.board.temperature = 24; f.advance(21 * DAY + 3600);
|
||||
assert(f.mesh.packets.size() == 4);
|
||||
assert(read16(f.mesh.packets.back().payload + 66) == 2900);
|
||||
assert(f.mesh.packets.back().payload[69] == temperature(60));
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(false); f.mesh.temp = true; f.advance(22 * DAY); assert(f.mesh.packets.empty());
|
||||
f.mesh.temp = false; f.mesh.budget = 0; f.advance(60); assert(f.mesh.packets.empty());
|
||||
f.mesh.budget = 1000; f.advance(60); assert(f.mesh.packets.size() == 1);
|
||||
}
|
||||
{
|
||||
Fixture f; f.configure(false); f.cmd("set mgmt.flood 90"); f.advance(89 * DAY); assert(f.mesh.packets.empty());
|
||||
f.advance(DAY); assert(f.mesh.packets.size() == 1);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,10 @@ public:
|
||||
void setTransportAvailable(bool available) {
|
||||
setGpsTelemetryTransportAvailable(available);
|
||||
}
|
||||
void setLocationAccessAvailable(bool available) {
|
||||
setTelemetryLocationAccessAvailable(available);
|
||||
}
|
||||
void service(unsigned long now) { loopGpsTelemetry(now); }
|
||||
bool receiverRequired(unsigned long now) const {
|
||||
return gpsTelemetryReceiverRequired(now);
|
||||
}
|
||||
@@ -75,6 +79,30 @@ TEST(GpsTransportOwnership, UserPreferenceSurvivesBlockAndRestartsOnRelease) {
|
||||
EXPECT_EQ(2, sensors.starts);
|
||||
}
|
||||
|
||||
TEST(GpsTransportOwnership, UserOffCancelsTelemetryAcquisitionAndHold) {
|
||||
resetArduinoMock();
|
||||
TestGpsSensorManager sensors;
|
||||
CayenneLPP telemetry(64);
|
||||
|
||||
sensors.setLocationAccessAvailable(true);
|
||||
EXPECT_FALSE(sensors.queryLocation(telemetry));
|
||||
ASSERT_TRUE(sensors.active);
|
||||
ASSERT_TRUE(sensors.receiverRequired(millis()));
|
||||
|
||||
// This is the path used by `gps off`/`set gps off`. It must immediately
|
||||
// override a telemetry acquisition and the request's two-hour hold.
|
||||
sensors.setUserEnabled(false);
|
||||
EXPECT_FALSE(sensors.active);
|
||||
EXPECT_FALSE(sensors.receiverRequired(millis()));
|
||||
EXPECT_EQ(1, sensors.stops);
|
||||
|
||||
// Location-access policy may still be enabled, but the scheduled refresh
|
||||
// must not immediately turn the receiver back on in the next loop.
|
||||
sensors.service(millis());
|
||||
EXPECT_FALSE(sensors.active);
|
||||
EXPECT_EQ(1, sensors.starts);
|
||||
}
|
||||
|
||||
TEST(GpsTransportOwnership, LastGoodCacheSurvivesTemporaryUartOwnership) {
|
||||
resetArduinoMock();
|
||||
TestGpsSensorManager sensors;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Production crypto vs RFC vector + independent Python decoder, no AES mocks."""
|
||||
from pathlib import Path
|
||||
import importlib.util
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location("management", ROOT / "tools/management/report.py")
|
||||
report = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(report)
|
||||
|
||||
|
||||
class ManagementTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
candidates = [Path(os.environ.get("MESHCORE_CRYPTO_DIR", "/nonexistent"))]
|
||||
candidates += sorted((ROOT / ".pio/libdeps").glob("*/Crypto"))
|
||||
cls.crypto = next((p for p in candidates if (p / "AES128.cpp").is_file()), None)
|
||||
if cls.crypto is None:
|
||||
raise RuntimeError("Install rweather/Crypto 0.4.0 or set MESHCORE_CRYPTO_DIR (no mock fallback)")
|
||||
cls.work = tempfile.TemporaryDirectory()
|
||||
cls.exe = Path(cls.work.name) / "management-test"
|
||||
sources = ["AES128.cpp", "AESCommon.cpp", "BlockCipher.cpp", "Crypto.cpp", "SHA256.cpp", "Hash.cpp"]
|
||||
host_define = [] if os.name == "nt" else ["-DHOST_BUILD"]
|
||||
sanitizers = [] if os.name == "nt" else ["-fsanitize=address,undefined", "-fno-omit-frame-pointer"]
|
||||
cmd = [shutil.which("g++") or "g++", "-std=c++17", "-O1", "-g", "-Wall", "-Wextra"] + host_define + [
|
||||
*sanitizers, "-I", str(cls.crypto), "-I", str(ROOT / "src"),
|
||||
str(ROOT / "src/helpers/ManagementReport.cpp"),
|
||||
str(ROOT / "test/fixtures/management/protocol_test.cpp")]
|
||||
cmd += [str(cls.crypto / p) for p in sources] + ["-o", str(cls.exe)]
|
||||
subprocess.run(cmd, check=True, capture_output=True, text=True)
|
||||
result = subprocess.run([str(cls.exe)], check=True, capture_output=True, text=True)
|
||||
cls.pages = [bytes.fromhex(line) for line in result.stdout.splitlines()]
|
||||
# Compile the unchanged production runtime and transaction writer with
|
||||
# a memory filesystem/radio in place of the hardware-facing headers.
|
||||
fixture = ROOT / "test/fixtures/management"
|
||||
for name in ("ManagementReporter.cpp", "ManagementReporter.h", "FileRead.h", "ContactFileTransaction.h", "PersistentStoreFormat.h"):
|
||||
shutil.copyfile(ROOT / "src/helpers" / name, Path(cls.work.name) / name)
|
||||
for name in ("CommonCLI.h", "Mesh.h"):
|
||||
shutil.copyfile(fixture / name, Path(cls.work.name) / name)
|
||||
shutil.copyfile(ROOT / "test/fixtures/radio_profiles/mocks/helpers/IdentityStore.h", Path(cls.work.name) / "IdentityStore.h")
|
||||
runtime = Path(cls.work.name) / "runtime-test"
|
||||
runtime_cmd = [shutil.which("g++") or "g++", "-std=c++17", "-O1", "-g"] + host_define + ["-DRP2040_PLATFORM",
|
||||
*sanitizers, "-I", cls.work.name,
|
||||
"-I", str(cls.crypto), "-I", str(ROOT / "src/helpers"), "-I", str(ROOT / "src"),
|
||||
str(Path(cls.work.name) / "ManagementReporter.cpp"), str(ROOT / "src/helpers/ManagementReport.cpp"),
|
||||
str(fixture / "runtime_test.cpp")]
|
||||
runtime_cmd += [str(cls.crypto / p) for p in sources] + ["-o", str(runtime)]
|
||||
subprocess.run(runtime_cmd, check=True, capture_output=True, text=True)
|
||||
cls.runtime = runtime
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.work.cleanup()
|
||||
|
||||
def test_interoperable_full_report(self):
|
||||
decoded = report.decode_report(list(reversed(self.pages)), "management test password")
|
||||
self.assertEqual(decoded["sequence"], 42)
|
||||
self.assertEqual(len(decoded["acl"]), 36)
|
||||
self.assertEqual(decoded["firmware_version"], "1.17.1.5")
|
||||
self.assertNotIn("manifest_id", decoded)
|
||||
|
||||
def test_runtime_storage_scheduling_rollover_and_failures(self):
|
||||
subprocess.run([str(self.runtime)], check=True)
|
||||
|
||||
def test_tampering_and_wrong_password(self):
|
||||
for position in (4, 20, 28, 74, 76, 83, -1):
|
||||
changed = bytearray(self.pages[0]); changed[position] ^= 1
|
||||
with self.subTest(position=position), self.assertRaises(ValueError):
|
||||
report.decode_report([bytes(changed)] + self.pages[1:], "management test password")
|
||||
with self.assertRaises(ValueError):
|
||||
report.decode_report(self.pages, "incorrect management password")
|
||||
|
||||
def test_page_omission_duplicate_mixed(self):
|
||||
for pages in ([], self.pages[:-1], self.pages[1:] + [self.pages[1]], self.pages + [self.pages[0]]):
|
||||
with self.assertRaises(ValueError):
|
||||
report.decode_report(pages, "management test password")
|
||||
|
||||
def test_fingerprints_and_password_length(self):
|
||||
a = report.fingerprint("management test password", bytes(16), bytes(32))
|
||||
b = report.fingerprint("management test password", bytes([1]) + bytes(15), bytes(32))
|
||||
self.assertEqual(len(a), 12); self.assertNotEqual(a, b)
|
||||
for password in ("short", "x" * 97):
|
||||
with self.assertRaises(ValueError): report.password_key(password)
|
||||
|
||||
def test_companions_excluded(self):
|
||||
for role in ("simple_repeater/MyMesh", "simple_room_server/MyMesh", "simple_sensor/SensorMesh"):
|
||||
self.assertIn("_cli.beginManagement(*this, _fs)", (ROOT / "examples" / (role + ".cpp")).read_text())
|
||||
for path in (ROOT / "examples/companion_radio").glob("*.*"):
|
||||
if path.suffix in (".cpp", ".h"): self.assertNotIn("beginManagement", path.read_text())
|
||||
|
||||
def test_mqtt_paths_scopes_and_duplicate_uplinks(self):
|
||||
messages = []
|
||||
for route in range(4):
|
||||
for page in self.pages:
|
||||
wire = bytes([0x3c | route]) + (bytes(4) if route in (0, 3) else b"")
|
||||
wire += bytes([0x42]) + bytes.fromhex("1234abcd") + page
|
||||
message = dict(type="PACKET", direction="rx", raw=wire.hex())
|
||||
self.assertEqual(report.mqtt_payload(message), page)
|
||||
messages.extend([message, message])
|
||||
decoded = report.mqtt_reports(messages, "management test password")
|
||||
self.assertEqual(len(decoded), 1)
|
||||
self.assertEqual(len(decoded[0]["acl"]), 36)
|
||||
self.assertIsNone(report.mqtt_payload(dict(type="PACKET", direction="tx", raw=wire.hex())))
|
||||
self.assertIsNone(report.mqtt_payload(dict(type="PACKET", direction="rx", raw="3dc0")))
|
||||
self.assertEqual(report.mqtt_reports(messages[:2], "management test password"), [])
|
||||
for page in self.pages:
|
||||
padded = page + bytes(3 + ((len(page) - 3 + 15) // 16) * 16 - len(page))
|
||||
message = dict(type="PACKET", direction="rx", raw=(b"\x19\x00" + padded).hex())
|
||||
self.assertEqual(report.mqtt_payload(message), page)
|
||||
message["raw"] = (b"\x19\x00" + padded[:-1] + b"\x01").hex()
|
||||
self.assertIsNone(report.mqtt_payload(message))
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <helpers/FloodAdvertCLI.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <helpers/ota/OtaFormat.h>
|
||||
#include <helpers/ManagementReport.h>
|
||||
#include <vector>
|
||||
|
||||
class TraceTestClock : public mesh::MillisecondClock {
|
||||
@@ -166,6 +167,43 @@ static mesh::Packet makeFloodPacket(uint8_t payload_type) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
TEST(ManagementRouting, GroupDataForBothRoutesKeepsPublicHeaderAndLegacyLength) {
|
||||
TraceTestRadio radio; TraceTestClock clock; TraceTestRNG rng; TraceTestRTC rtc;
|
||||
TraceTestTables tables; StaticPoolPacketManager pool(8);
|
||||
TraceTestMesh mesh(radio, clock, rng, rtc, pool, tables);
|
||||
uint8_t raw[mesh::management::HEADER + mesh::management::TAG] = {};
|
||||
memcpy(raw, "MGR1", 4); raw[79] = 1;
|
||||
const uint8_t path[] = {0x12, 0xab};
|
||||
uint8_t scope_key[16]; memset(scope_key, 0x42, sizeof(scope_key));
|
||||
for (bool flood : {false, true}) {
|
||||
auto* p = mesh.createRawData(raw, sizeof(raw)); ASSERT_NE(nullptr, p);
|
||||
ASSERT_TRUE(mesh.sendManagementData(p, flood, path, 2, 2,
|
||||
flood ? scope_key : nullptr));
|
||||
EXPECT_EQ(PAYLOAD_TYPE_GRP_DATA, p->getPayloadType());
|
||||
EXPECT_EQ(flood, p->isRouteFlood());
|
||||
EXPECT_EQ(0, memcmp(p->payload, raw, sizeof(raw)));
|
||||
EXPECT_EQ(0u, (p->payload_len - 3u) % 16u);
|
||||
EXPECT_TRUE(mesh::management::validPage(p->payload, p->payload_len, true));
|
||||
EXPECT_EQ(flood ? 0 : 2, p->getPathHashCount());
|
||||
if (!flood) EXPECT_EQ(0, memcmp(p->path, path, 2));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(ManagementRouting, FloodForwardingDoesNotNeedAKeyAndStillHonorsFilters) {
|
||||
TraceTestRadio radio; TraceTestClock clock; TraceTestRNG rng; TraceTestRTC rtc;
|
||||
TraceTestTables tables; StaticPoolPacketManager pool(8);
|
||||
TraceTestMesh mesh(radio, clock, rng, rtc, pool, tables);
|
||||
mesh.forwardFloods = true;
|
||||
mesh::Packet p;
|
||||
p.header = (PAYLOAD_TYPE_GRP_DATA << PH_TYPE_SHIFT) | ROUTE_TYPE_FLOOD;
|
||||
p.setPathHashSizeAndCount(1, 0); memcpy(p.payload, "MGR1", 4); p.payload[79] = 1;
|
||||
p.payload_len = mesh::management::floodSize(mesh::management::HEADER + mesh::management::TAG);
|
||||
EXPECT_NE(ACTION_RELEASE, mesh.receivePacket(&p));
|
||||
EXPECT_FALSE(mesh.groupPacketObserved); // never delivered as decrypted channel data
|
||||
mesh.rejectFloods = true;
|
||||
EXPECT_EQ(ACTION_RELEASE, mesh.receivePacket(&p));
|
||||
}
|
||||
|
||||
class RetryCodingRateRadio : public TraceTestRadio {
|
||||
public:
|
||||
uint8_t cr = 5;
|
||||
|
||||
Reference in new issue
Block a user