Fix USB radio stalls and add durable replay timestamp recovery
This commit is contained in:
1 parent
b199ba27bf
commit
e36b092aa3
44 files changed
+4339
-148
No files matched your search
@@ -21,8 +21,17 @@ python3 test/test_color_theme.py # shared color-display dark-pale
|
||||
python3 test/test_indicator_font_recovery.py # Indicator TLS/SD font recovery contract
|
||||
python3 test/test_companion_terminal_profile.py # Companion CLI capability gates
|
||||
python3 test/test_client_login_profile_contract.py # ACL login ordering/role contract
|
||||
python3 test/test_client_acl_spiffs.py # Actual ACL: first login, replay/reboot, failed storage
|
||||
python3 test/test_replay_reset_command.py # Strict full keys and one-use recovery confirmations
|
||||
python3 test/test_replay_reset_integration.py # Actual repeater handler: USB/LoRa permissions and persistence ordering
|
||||
python3 test/test_regular_file_reads.py # SPIFFS phantom directories, listings, log HTTP status
|
||||
python3 test/test_esp32_full_partition.py # Full partition-preservation policy
|
||||
python3 test/test_esp32_usb_serial_hygiene.py # Single-TTY diagnostics/NVS contract
|
||||
python3 test/test_esp32_tinyusb_role_hygiene.py # G2/room USB write coverage and bounded-list contracts
|
||||
python3 test/test_esp32_tinyusb_cooperative_output.py # Real role dump/list pumps with host C++ stubs
|
||||
python3 test/test_esp32_tinyusb_nonblocking.py # Native CDC stalled-host/64-byte-FIFO simulation (C++17 compiler)
|
||||
python3 test/test_esp32_tinyusb_role_hygiene.py # Repeater/room nonblocking console and paced large replies
|
||||
python3 test/test_esp32_tinyusb_cooperative_output.py # Real role pumps: large logs/listings, EOF, backpressure
|
||||
python3 test/test_temp_radio_reply_delivery_contract.py # TempRadio ACK path/barrier integration
|
||||
python3 test/test_tls_download_clock_gates.py # Fresh-NTP/TLS download integration contract
|
||||
```
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
#pragma once
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#define MESH_DEBUG_PRINTLN(...) ((void)0)
|
||||
|
||||
class FakeFilesystem;
|
||||
struct FakeFileHandle {
|
||||
FakeFilesystem* fs;
|
||||
std::string path;
|
||||
bool directory;
|
||||
bool writable;
|
||||
bool open = true;
|
||||
size_t position = 0;
|
||||
};
|
||||
|
||||
class File {
|
||||
std::shared_ptr<FakeFileHandle> handle;
|
||||
public:
|
||||
File() = default;
|
||||
File(FakeFilesystem* fs, const std::string& path, bool directory, bool writable)
|
||||
: handle(std::make_shared<FakeFileHandle>(FakeFileHandle{fs, path, directory, writable})) {}
|
||||
explicit operator bool() const { return handle && handle->open; }
|
||||
bool isDirectory() const { return *this && handle->directory; }
|
||||
size_t size() const;
|
||||
int read(uint8_t* output, size_t length);
|
||||
size_t write(const uint8_t* input, size_t length);
|
||||
void close();
|
||||
};
|
||||
|
||||
class FakeFilesystem {
|
||||
public:
|
||||
std::map<std::string, std::vector<uint8_t>> files;
|
||||
std::set<std::string> unreadable;
|
||||
std::set<std::string> directories_on_read;
|
||||
std::set<std::string> directories_on_write;
|
||||
std::map<std::string, size_t> read_open_count;
|
||||
std::string truncate_path;
|
||||
size_t truncate_on_read_open = 0;
|
||||
std::string fail_rename_from;
|
||||
std::set<std::string> fail_rename_from_paths;
|
||||
std::string fail_remove;
|
||||
std::string fail_open_write;
|
||||
std::string corrupt_on_close;
|
||||
size_t write_budget = std::numeric_limits<size_t>::max();
|
||||
size_t bytes_written = 0;
|
||||
size_t directory_closes = 0;
|
||||
size_t missing_read_opens = 0;
|
||||
|
||||
bool exists(const char* path) const { return files.count(path) != 0; }
|
||||
File open(const char* path, const char* mode = "r", bool = false) {
|
||||
const std::string name(path);
|
||||
if (mode[0] == 'r') {
|
||||
++read_open_count[name];
|
||||
if (unreadable.count(name)) return File();
|
||||
if (!exists(path)) {
|
||||
++missing_read_opens;
|
||||
// The real Arduino-ESP32 SPIFFS opendir fallback for missing paths.
|
||||
return File(this, name, true, false);
|
||||
}
|
||||
if (truncate_path == name && read_open_count[name] == truncate_on_read_open)
|
||||
files[name].resize(1);
|
||||
return File(this, name, directories_on_read.count(name) != 0, false);
|
||||
}
|
||||
if (fail_open_write == name) return File();
|
||||
if (directories_on_write.count(name)) return File(this, name, true, true);
|
||||
files[name].clear();
|
||||
return File(this, name, false, true);
|
||||
}
|
||||
bool remove(const char* path) {
|
||||
return fail_remove != path && files.erase(path) != 0;
|
||||
}
|
||||
bool rename(const char* from, const char* to) {
|
||||
if (fail_rename_from == from || fail_rename_from_paths.count(from)
|
||||
|| !exists(from) || exists(to)) return false;
|
||||
files[to] = files[from];
|
||||
files.erase(from);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
inline size_t File::size() const {
|
||||
if (!*this || handle->directory) return 0;
|
||||
auto found = handle->fs->files.find(handle->path);
|
||||
return found == handle->fs->files.end() ? 0 : found->second.size();
|
||||
}
|
||||
inline int File::read(uint8_t* output, size_t length) {
|
||||
if (!*this || handle->directory) return 0;
|
||||
auto found = handle->fs->files.find(handle->path);
|
||||
if (found == handle->fs->files.end() || handle->position >= found->second.size()) return 0;
|
||||
length = std::min(length, found->second.size() - handle->position);
|
||||
std::memcpy(output, found->second.data() + handle->position, length);
|
||||
handle->position += length;
|
||||
return static_cast<int>(length);
|
||||
}
|
||||
inline size_t File::write(const uint8_t* input, size_t length) {
|
||||
if (!*this || handle->directory || !handle->writable) return 0;
|
||||
auto& fs = *handle->fs;
|
||||
length = std::min(length, fs.write_budget);
|
||||
if (length == 0) return 0;
|
||||
fs.write_budget -= length;
|
||||
fs.bytes_written += length;
|
||||
auto& data = fs.files[handle->path];
|
||||
data.resize(handle->position + length);
|
||||
std::memcpy(data.data() + handle->position, input, length);
|
||||
handle->position += length;
|
||||
return length;
|
||||
}
|
||||
inline void File::close() {
|
||||
if (!*this) return;
|
||||
if (handle->directory) ++handle->fs->directory_closes;
|
||||
if (handle->writable && handle->fs->corrupt_on_close == handle->path) {
|
||||
auto& data = handle->fs->files[handle->path];
|
||||
if (!data.empty()) data.back() ^= 0x80;
|
||||
}
|
||||
handle->open = false;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include "Arduino.h"
|
||||
#define PUB_KEY_SIZE 32
|
||||
#define MAX_PATH_SIZE 64
|
||||
namespace mesh {
|
||||
struct Identity {
|
||||
uint8_t pub_key[PUB_KEY_SIZE];
|
||||
Identity() { std::memset(pub_key, 0, sizeof(pub_key)); }
|
||||
explicit Identity(const uint8_t* key) { std::memcpy(pub_key, key, sizeof(pub_key)); }
|
||||
bool matches(const Identity& other) const { return std::memcmp(pub_key, other.pub_key, sizeof(pub_key)) == 0; }
|
||||
};
|
||||
struct LocalIdentity : Identity {
|
||||
void calcSharedSecret(uint8_t* output, const uint8_t* key) const {
|
||||
std::memcpy(output, key, PUB_KEY_SIZE);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#define FILESYSTEM FakeFilesystem
|
||||
@@ -0,0 +1,482 @@
|
||||
// Include the production implementation so its static validators and the full
|
||||
// ClientACL load/admission/publication path execute against the SPIFFS model.
|
||||
#include "../../../src/helpers/ClientACL.cpp"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <initializer_list>
|
||||
#include <utility>
|
||||
|
||||
#define CHECK(condition) do { if (!(condition)) { \
|
||||
std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #condition); std::exit(1); \
|
||||
} } while (0)
|
||||
|
||||
static const uint8_t KEY[PUB_KEY_SIZE] = {0x12, 0x57, 0xae, 0xe5};
|
||||
static const char* PRIMARY = mesh::CLIENT_LOGIN_REPLAY_PRIMARY_PATH;
|
||||
static const char* TEMP = mesh::CLIENT_LOGIN_REPLAY_TEMP_PATH;
|
||||
static mesh::LocalIdentity SELF;
|
||||
static const uint8_t SECOND_KEY[PUB_KEY_SIZE] = {0x12, 0x57, 0xae, 0xe5, 0x02};
|
||||
static const uint8_t ARCHIVED_KEY[PUB_KEY_SIZE] = {0x77, 0x03};
|
||||
|
||||
static std::vector<uint8_t> replay_records(
|
||||
std::initializer_list<std::pair<const uint8_t*, uint32_t>> records) {
|
||||
std::vector<uint8_t> image;
|
||||
for (const auto& record : records) {
|
||||
image.insert(image.end(), record.first, record.first + PUB_KEY_SIZE);
|
||||
const auto* value = reinterpret_cast<const uint8_t*>(&record.second);
|
||||
image.insert(image.end(), value, value + sizeof(record.second));
|
||||
}
|
||||
const uint32_t crc = mesh::updateClientLoginReplayCRC(
|
||||
0xffffffffu, image.data(), image.size()) ^ 0xffffffffu;
|
||||
image.insert(image.end(), mesh::CLIENT_LOGIN_REPLAY_MAGIC,
|
||||
mesh::CLIENT_LOGIN_REPLAY_MAGIC + 4);
|
||||
const auto* value = reinterpret_cast<const uint8_t*>(&crc);
|
||||
image.insert(image.end(), value, value + sizeof(crc));
|
||||
return image;
|
||||
}
|
||||
|
||||
static void check_empty_result(const ClientLoginReplayClampResult& result) {
|
||||
CHECK(result.stored_matched == 0 && result.stored_changed == 0
|
||||
&& result.live_matched == 0 && result.live_changed == 0);
|
||||
}
|
||||
|
||||
static std::vector<uint8_t> replay(uint32_t ceiling) {
|
||||
std::vector<uint8_t> image(KEY, KEY + PUB_KEY_SIZE);
|
||||
const auto* bytes = reinterpret_cast<const uint8_t*>(&ceiling);
|
||||
image.insert(image.end(), bytes, bytes + sizeof(ceiling));
|
||||
const uint32_t crc = mesh::updateClientLoginReplayCRC(0xffffffffu, image.data(), image.size()) ^ 0xffffffffu;
|
||||
image.insert(image.end(), mesh::CLIENT_LOGIN_REPLAY_MAGIC, mesh::CLIENT_LOGIN_REPLAY_MAGIC + 4);
|
||||
bytes = reinterpret_cast<const uint8_t*>(&crc);
|
||||
image.insert(image.end(), bytes, bytes + sizeof(crc));
|
||||
return image;
|
||||
}
|
||||
|
||||
static void missing_read_is_not_empty_file() {
|
||||
FakeFilesystem fs;
|
||||
auto raw = fs.open(PRIMARY);
|
||||
CHECK(raw && raw.isDirectory() && raw.size() == 0);
|
||||
raw.close();
|
||||
auto checked = mesh::openFileRead(&fs, PRIMARY);
|
||||
CHECK(!checked && fs.missing_read_opens == 1);
|
||||
CHECK(!validateContactsFileIntegrity(&fs, "/s_contacts"));
|
||||
CHECK(!validateLoginReplayFileIntegrity(&fs, PRIMARY));
|
||||
CHECK(!mesh::openFileRead(static_cast<FakeFilesystem*>(nullptr), PRIMARY));
|
||||
CHECK(!mesh::openFileRead(&fs, nullptr));
|
||||
}
|
||||
|
||||
static void first_admin_and_retries() {
|
||||
FakeFilesystem fs;
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 100, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(160));
|
||||
CHECK(fs.files[PRIMARY].size() == 44 && !fs.exists(TEMP));
|
||||
CHECK(fs.missing_read_opens == 0);
|
||||
const auto writes = fs.bytes_written;
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 101, 100, PERM_ACL_ADMIN));
|
||||
CHECK(fs.bytes_written == writes);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 101, 101, PERM_ACL_ADMIN));
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 0, 101, PERM_ACL_ADMIN));
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 161, 101, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(221));
|
||||
}
|
||||
|
||||
static void reboot_preserves_ceiling() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 160, 0, PERM_ACL_ADMIN));
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 161, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(221));
|
||||
}
|
||||
|
||||
static void corrupt_state_is_preserved() {
|
||||
for (size_t length : {size_t(0), size_t(1), size_t(7), size_t(9), size_t(43)}) {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = std::vector<uint8_t>(length, 0x99);
|
||||
const auto original = fs.files[PRIMARY];
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 1000, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == original && fs.bytes_written == 0);
|
||||
}
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
fs.files[PRIMARY].back() ^= 1;
|
||||
const auto original = fs.files[PRIMARY];
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 1000, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == original);
|
||||
}
|
||||
|
||||
static void write_failures_keep_boundary() {
|
||||
for (int failure = 0; failure < 5; ++failure) {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
if (failure == 0) fs.write_budget = 12;
|
||||
if (failure == 1) fs.fail_open_write = TEMP;
|
||||
if (failure == 2) fs.fail_rename_from = TEMP;
|
||||
if (failure == 3) fs.corrupt_on_close = TEMP;
|
||||
if (failure == 4) fs.directories_on_write.insert(TEMP);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 200, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(160));
|
||||
CHECK(!fs.exists(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH));
|
||||
}
|
||||
}
|
||||
|
||||
static void first_write_failure_is_retriable() {
|
||||
FakeFilesystem fs;
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
fs.write_budget = 5;
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 100, 0, PERM_ACL_ADMIN));
|
||||
CHECK(!fs.exists(PRIMARY) && !fs.exists(TEMP));
|
||||
fs.write_budget = std::numeric_limits<size_t>::max();
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 101, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(161));
|
||||
}
|
||||
|
||||
static void directory_reads_are_rejected() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
fs.directories_on_read.insert(PRIMARY);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 1000, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.directory_closes > 0 && fs.files[PRIMARY] == replay(160));
|
||||
fs.files["/s_contacts"] = {};
|
||||
fs.directories_on_read.insert("/s_contacts");
|
||||
CHECK(!validateContactsFileIntegrity(&fs, "/s_contacts"));
|
||||
}
|
||||
|
||||
static void regular_empty_contacts_remain_valid() {
|
||||
FakeFilesystem fs;
|
||||
fs.files["/s_contacts"] = {};
|
||||
CHECK(validateContactsFileIntegrity(&fs, "/s_contacts"));
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(acl.getNumClients() == 0);
|
||||
CHECK(acl.authorizeLoginTimestamp(KEY, 100, 0, PERM_ACL_ADMIN));
|
||||
}
|
||||
|
||||
static void contacts_save_load_uses_regular_files() {
|
||||
FakeFilesystem fs;
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(acl.applyPermissions(SELF, KEY, PUB_KEY_SIZE, PERM_ACL_ADMIN));
|
||||
CHECK(acl.save(&fs));
|
||||
CHECK(fs.files["/s_contacts"].size() == 209);
|
||||
ClientACL reloaded;
|
||||
reloaded.load(&fs, SELF);
|
||||
CHECK(reloaded.getNumClients() == 1);
|
||||
CHECK(reloaded.getClient(KEY, PUB_KEY_SIZE)->isAdmin());
|
||||
CHECK(reloaded.authorizeLoginTimestamp(KEY, 100, 0, PERM_ACL_ADMIN));
|
||||
}
|
||||
|
||||
static void replay_source_reopen_failure_is_not_missing() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
fs.truncate_path = PRIMARY;
|
||||
fs.truncate_on_read_open = 2; // validation succeeds, source reopened truncated
|
||||
CHECK(!writeClientLoginReplayCeiling(&fs, KEY, 260,
|
||||
mesh::ClientLoginReplayReservationAction::UpdateExisting));
|
||||
CHECK(fs.bytes_written == 0 && !fs.exists(TEMP));
|
||||
}
|
||||
|
||||
static void unreadable_primary_is_not_first_login() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(160);
|
||||
fs.unreadable.insert(PRIMARY);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 1000, 0, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(160) && fs.bytes_written == 0);
|
||||
}
|
||||
|
||||
static void null_load_fails_closed() {
|
||||
ClientACL acl;
|
||||
acl.load(nullptr, SELF);
|
||||
CHECK(!acl.authorizeLoginTimestamp(KEY, 100, 0, PERM_ACL_ADMIN));
|
||||
}
|
||||
|
||||
static void clamp_exact_key_preserves_other_state() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay_records({{KEY, 900}, {SECOND_KEY, 800}});
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
client->last_activity = 777;
|
||||
client->out_path_len = 1;
|
||||
client->out_path[0] = 0x77;
|
||||
client->alt_path_len = 1;
|
||||
client->alt_path[0] = 0x12;
|
||||
client->shared_secret[3] = 0x88;
|
||||
client->extra.room.sync_since = 600;
|
||||
ClientInfo* other = acl.putClient(mesh::Identity(SECOND_KEY), PERM_ACL_REGION_MGR);
|
||||
other->last_timestamp = 800;
|
||||
CHECK(acl.save(&fs));
|
||||
const auto saved_contacts = fs.files["/s_contacts"];
|
||||
ClientInfo expected = *client;
|
||||
expected.last_timestamp = 500;
|
||||
const ClientInfo expected_other = *other;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
CHECK(result.stored_matched == 1 && result.stored_changed == 1);
|
||||
CHECK(result.live_matched == 1 && result.live_changed == 1);
|
||||
CHECK(fs.files[PRIMARY] == replay_records({{KEY, 500}, {SECOND_KEY, 800}}));
|
||||
CHECK(fs.files["/s_contacts"] == saved_contacts);
|
||||
CHECK(std::memcmp(client, &expected, sizeof(expected)) == 0);
|
||||
CHECK(std::memcmp(other, &expected_other, sizeof(expected_other)) == 0);
|
||||
}
|
||||
|
||||
static void clamp_all_keeps_duplicates_and_tombstones() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay_records(
|
||||
{{KEY, 100}, {ARCHIVED_KEY, 900}, {KEY, 700}, {SECOND_KEY, 500}});
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
ClientInfo* other = acl.putClient(mesh::Identity(SECOND_KEY), PERM_ACL_READ_ONLY);
|
||||
other->last_timestamp = 400;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(nullptr, 500, result));
|
||||
CHECK(result.stored_matched == 4 && result.stored_changed == 2);
|
||||
CHECK(result.live_matched == 2 && result.live_changed == 1);
|
||||
CHECK(fs.files[PRIMARY] == replay_records(
|
||||
{{KEY, 100}, {ARCHIVED_KEY, 500}, {KEY, 500}, {SECOND_KEY, 500}}));
|
||||
CHECK(acl.getNumClients() == 2 && acl.getClient(ARCHIVED_KEY, PUB_KEY_SIZE) == nullptr);
|
||||
CHECK(client->last_timestamp == 500 && other->last_timestamp == 400);
|
||||
CHECK(validateLoginReplayFileIntegrity(&fs, PRIMARY));
|
||||
}
|
||||
|
||||
static void clamp_missing_key_or_store_never_creates() {
|
||||
FakeFilesystem fs;
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files.empty() && fs.bytes_written == 0 && acl.getNumClients() == 0);
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
const auto before = fs.files;
|
||||
CHECK(acl.clampLoginReplayTimestamps(SECOND_KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files == before && fs.bytes_written == 0 && acl.getNumClients() == 0);
|
||||
fs.files[PRIMARY] = replay_records({});
|
||||
CHECK(acl.clampLoginReplayTimestamps(nullptr, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files[PRIMARY] == replay_records({}) && fs.bytes_written == 0);
|
||||
}
|
||||
|
||||
static void clamp_noop_never_writes_or_raises() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay_records({{KEY, 100}, {SECOND_KEY, 500}});
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 100;
|
||||
const auto before = fs.files;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(nullptr, 500, result));
|
||||
CHECK(result.stored_matched == 2 && result.stored_changed == 0);
|
||||
CHECK(result.live_matched == 1 && result.live_changed == 0);
|
||||
CHECK(acl.clampLoginReplayTimestamps(nullptr, UINT32_MAX, result));
|
||||
CHECK(result.stored_changed == 0 && result.live_changed == 0);
|
||||
CHECK(fs.files == before && fs.bytes_written == 0 && client->last_timestamp == 100);
|
||||
}
|
||||
|
||||
static void clamp_live_only_does_not_create_or_raise_store() {
|
||||
for (bool has_store : {false, true}) {
|
||||
FakeFilesystem fs;
|
||||
if (has_store) fs.files[PRIMARY] = replay(100);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 900;
|
||||
const auto before = fs.files;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
CHECK(result.stored_matched == (has_store ? 1 : 0) && result.stored_changed == 0);
|
||||
CHECK(result.live_matched == 1 && result.live_changed == 1);
|
||||
CHECK(fs.files == before && fs.bytes_written == 0 && client->last_timestamp == 500);
|
||||
}
|
||||
}
|
||||
|
||||
static void clamp_stored_only_does_not_raise_live() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 100;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
CHECK(result.stored_changed == 1 && result.live_changed == 0);
|
||||
CHECK(fs.files[PRIMARY] == replay(500) && client->last_timestamp == 100);
|
||||
const auto writes = fs.bytes_written;
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
CHECK(result.stored_changed == 0 && result.live_changed == 0);
|
||||
CHECK(fs.bytes_written == writes);
|
||||
}
|
||||
|
||||
static void clamp_invalid_clock_or_unavailable_fails_closed() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
ClientLoginReplayClampResult result = {9, 9, 9, 9};
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 900;
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 0, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files[PRIMARY] == replay(900) && fs.bytes_written == 0);
|
||||
CHECK(client->last_timestamp == 900);
|
||||
}
|
||||
|
||||
static void clamp_write_failures_leave_live_and_store_unchanged() {
|
||||
for (int failure = 0; failure < 6; ++failure) {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
if (failure == 0) fs.write_budget = 12;
|
||||
if (failure == 1) fs.fail_open_write = TEMP;
|
||||
if (failure == 2) fs.fail_rename_from = TEMP;
|
||||
if (failure == 3) fs.corrupt_on_close = TEMP;
|
||||
if (failure == 4) fs.directories_on_write.insert(TEMP);
|
||||
if (failure == 5) fs.fail_rename_from = PRIMARY;
|
||||
ClientLoginReplayClampResult result = {9, 9, 9, 9};
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files[PRIMARY] == replay(900) && client->last_timestamp == 1000);
|
||||
}
|
||||
}
|
||||
|
||||
static void clamp_corrupt_or_unreadable_source_never_repairs() {
|
||||
for (int failure = 0; failure < 5; ++failure) {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
if (failure == 0) fs.files[PRIMARY].back() ^= 1;
|
||||
if (failure == 1) fs.files[PRIMARY].resize(1);
|
||||
if (failure == 2) fs.unreadable.insert(PRIMARY);
|
||||
if (failure == 3) fs.directories_on_read.insert(PRIMARY);
|
||||
if (failure == 4) {
|
||||
fs.files[mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH] = replay(900);
|
||||
fs.files.erase(PRIMARY);
|
||||
}
|
||||
const auto before = fs.files;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files == before && fs.bytes_written == 0 && client->last_timestamp == 1000);
|
||||
CHECK(!acl.authorizeLoginTimestamp(SECOND_KEY, 2000, 0, PERM_ACL_ADMIN));
|
||||
}
|
||||
}
|
||||
|
||||
static void clamp_reopen_and_rollback_failures_block_new_admission() {
|
||||
for (bool rollback_failure : {false, true}) {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
if (rollback_failure) {
|
||||
fs.fail_rename_from_paths.insert(TEMP);
|
||||
fs.fail_rename_from_paths.insert(mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH);
|
||||
} else {
|
||||
fs.truncate_path = PRIMARY;
|
||||
fs.truncate_on_read_open = fs.read_open_count[PRIMARY] + 2;
|
||||
}
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(client->last_timestamp == 1000);
|
||||
CHECK(!acl.authorizeLoginTimestamp(SECOND_KEY, 2000, 0, PERM_ACL_ADMIN));
|
||||
if (rollback_failure) {
|
||||
CHECK(!fs.exists(PRIMARY));
|
||||
CHECK(fs.files[mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH] == replay(900));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void clamp_reboot_keeps_lowered_boundary() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
CHECK(acl.save(&fs));
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
ClientACL rebooted;
|
||||
rebooted.load(&fs, SELF);
|
||||
CHECK(rebooted.getClient(KEY, PUB_KEY_SIZE)->last_timestamp == 500);
|
||||
CHECK(!rebooted.authorizeLoginTimestamp(KEY, 500, 500, PERM_ACL_ADMIN));
|
||||
CHECK(rebooted.authorizeLoginTimestamp(KEY, 501, 500, PERM_ACL_ADMIN));
|
||||
CHECK(fs.files[PRIMARY] == replay(561));
|
||||
}
|
||||
|
||||
static void clamp_backup_cleanup_failure_does_not_mutate_live() {
|
||||
FakeFilesystem fs;
|
||||
fs.files[PRIMARY] = replay(900);
|
||||
ClientACL acl;
|
||||
acl.load(&fs, SELF);
|
||||
ClientInfo* client = acl.putClient(mesh::Identity(KEY), PERM_ACL_ADMIN);
|
||||
client->last_timestamp = 1000;
|
||||
fs.files[mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH] = replay(950);
|
||||
fs.fail_remove = mesh::CLIENT_LOGIN_REPLAY_BACKUP_PATH;
|
||||
const auto before = fs.files;
|
||||
ClientLoginReplayClampResult result = {};
|
||||
CHECK(!acl.clampLoginReplayTimestamps(KEY, 500, result));
|
||||
check_empty_result(result);
|
||||
CHECK(fs.files == before && fs.bytes_written == 0 && client->last_timestamp == 1000);
|
||||
}
|
||||
|
||||
int main() {
|
||||
const struct { const char* name; void (*run)(); } tests[] = {
|
||||
{"missing read differs from empty file", missing_read_is_not_empty_file},
|
||||
{"first admin and monotonic retries", first_admin_and_retries},
|
||||
{"reboot preserves ceiling", reboot_preserves_ceiling},
|
||||
{"corrupt state retained", corrupt_state_is_preserved},
|
||||
{"write failures retain boundary", write_failures_keep_boundary},
|
||||
{"failed first write can retry", first_write_failure_is_retriable},
|
||||
{"truthy directories rejected", directory_reads_are_rejected},
|
||||
{"regular empty legacy ACL accepted", regular_empty_contacts_remain_valid},
|
||||
{"contacts save and reload", contacts_save_load_uses_regular_files},
|
||||
{"reopen truncation fails closed", replay_source_reopen_failure_is_not_missing},
|
||||
{"unreadable history preserved", unreadable_primary_is_not_first_login},
|
||||
{"uninitialized storage fails closed", null_load_fails_closed},
|
||||
{"clamp exact key preserves all other state", clamp_exact_key_preserves_other_state},
|
||||
{"clamp all preserves duplicate and historical records", clamp_all_keeps_duplicates_and_tombstones},
|
||||
{"clamp missing selection creates nothing", clamp_missing_key_or_store_never_creates},
|
||||
{"clamp noop never writes or raises", clamp_noop_never_writes_or_raises},
|
||||
{"clamp live only leaves storage alone", clamp_live_only_does_not_create_or_raise_store},
|
||||
{"clamp stored only never raises live", clamp_stored_only_does_not_raise_live},
|
||||
{"clamp zero clock and unavailable fail closed", clamp_invalid_clock_or_unavailable_fails_closed},
|
||||
{"clamp write errors preserve live and disk", clamp_write_failures_leave_live_and_store_unchanged},
|
||||
{"clamp corrupt source is not a repair", clamp_corrupt_or_unreadable_source_never_repairs},
|
||||
{"clamp reopen and rollback failures fail closed", clamp_reopen_and_rollback_failures_block_new_admission},
|
||||
{"clamp survives reboot", clamp_reboot_keeps_lowered_boundary},
|
||||
{"clamp backup cleanup failure preserves state", clamp_backup_cleanup_failure_does_not_mutate_live},
|
||||
};
|
||||
for (const auto& test : tests) {
|
||||
test.run();
|
||||
std::printf("PASS: %s\n", test.name);
|
||||
}
|
||||
std::puts("24 ClientACL SPIFFS checks passed");
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include "../../../mocks/Arduino.h"
|
||||
#include <cassert>
|
||||
|
||||
using esp_event_base_t = const char*;
|
||||
using esp_event_handler_t = void (*)(void*, esp_event_base_t, int32_t, void*);
|
||||
constexpr int ARDUINO_USB_CDC_ANY_EVENT = -1;
|
||||
constexpr int ARDUINO_USB_CDC_DISCONNECTED_EVENT = 1;
|
||||
constexpr int ARDUINO_USB_CDC_LINE_STATE_EVENT = 2;
|
||||
struct arduino_usb_cdc_event_data_t {
|
||||
struct { bool dtr; bool rts; } line_state{};
|
||||
};
|
||||
|
||||
inline bool mock_isr = false;
|
||||
inline bool xPortInIsrContext() { return mock_isr; }
|
||||
|
||||
class MockSerial : public Stream {
|
||||
public:
|
||||
int available() override { return rx_count; }
|
||||
int read() override { return rx_count > 0 ? (--rx_count, 'v') : -1; }
|
||||
int peek() override { return rx_count > 0 ? 'v' : -1; }
|
||||
int availableForWrite() override {
|
||||
++blocking_calls;
|
||||
assert(false && "mode0 must not acquire the USBCDC TX mutex");
|
||||
return 0;
|
||||
}
|
||||
size_t write(const uint8_t*, size_t) override {
|
||||
++blocking_calls;
|
||||
assert(false && "mode0 must never call USBCDC::write");
|
||||
return 0;
|
||||
}
|
||||
void flush() override {
|
||||
++blocking_calls;
|
||||
assert(false && "mode0 must never call USBCDC::flush");
|
||||
}
|
||||
void setDebugOutput(bool enabled) { debug_enabled = enabled; }
|
||||
void onEvent(int event, esp_event_handler_t handler) {
|
||||
assert(event == ARDUINO_USB_CDC_ANY_EVENT);
|
||||
callback = handler;
|
||||
++registrations;
|
||||
}
|
||||
int blocking_calls = 0;
|
||||
int rx_count = 0;
|
||||
int registrations = 0;
|
||||
bool debug_enabled = true;
|
||||
esp_event_handler_t callback = nullptr;
|
||||
};
|
||||
|
||||
extern MockSerial Serial;
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
bool tud_cdc_n_connected(uint8_t instance);
|
||||
uint32_t tud_cdc_n_write_available(uint8_t instance);
|
||||
uint32_t tud_cdc_n_write(uint8_t instance, const void* data, uint32_t size);
|
||||
uint32_t tud_cdc_n_write_flush(uint8_t instance);
|
||||
bool tud_cdc_n_write_clear(uint8_t instance);
|
||||
@@ -0,0 +1,232 @@
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include "helpers/UsbLogging.h"
|
||||
#include "MeshCore.h"
|
||||
|
||||
MockSerial Serial;
|
||||
static bool connected = true;
|
||||
static bool auto_drain = false;
|
||||
static std::string fifo;
|
||||
static std::string host;
|
||||
static unsigned write_calls = 0;
|
||||
static unsigned flush_calls = 0;
|
||||
static unsigned clear_calls = 0;
|
||||
static void (*during_write)() = nullptr;
|
||||
|
||||
bool tud_cdc_n_connected(uint8_t instance) {
|
||||
assert(!mock_isr);
|
||||
assert(instance == 0);
|
||||
return connected;
|
||||
}
|
||||
uint32_t tud_cdc_n_write_available(uint8_t instance) {
|
||||
assert(!mock_isr);
|
||||
assert(instance == 0);
|
||||
return 64 - fifo.size();
|
||||
}
|
||||
uint32_t tud_cdc_n_write(uint8_t instance, const void* data, uint32_t size) {
|
||||
assert(!mock_isr);
|
||||
assert(instance == 0);
|
||||
assert(size <= 64 - fifo.size());
|
||||
++write_calls;
|
||||
if (during_write) during_write();
|
||||
fifo.append(static_cast<const char*>(data), size);
|
||||
return size;
|
||||
}
|
||||
uint32_t tud_cdc_n_write_flush(uint8_t instance) {
|
||||
assert(!mock_isr);
|
||||
assert(instance == 0);
|
||||
++flush_calls;
|
||||
if (!auto_drain) return 0;
|
||||
const auto size = fifo.size();
|
||||
host += fifo;
|
||||
fifo.clear();
|
||||
return size;
|
||||
}
|
||||
bool tud_cdc_n_write_clear(uint8_t instance) {
|
||||
assert(!mock_isr);
|
||||
assert(instance == 0);
|
||||
++clear_calls;
|
||||
fifo.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
static size_t put(Stream& port, const std::string& value) {
|
||||
return port.write(reinterpret_cast<const uint8_t*>(value.data()), value.size());
|
||||
}
|
||||
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
static void drain_all() {
|
||||
for (unsigned turn = 0; turn != 200; ++turn) {
|
||||
host += fifo;
|
||||
fifo.clear();
|
||||
mesh::serviceUsbTerminalPort();
|
||||
if (fifo.empty() && !mesh::hasPendingUsbTerminalOutput()) return;
|
||||
}
|
||||
assert(false && "finite queue should drain in bounded service calls");
|
||||
}
|
||||
|
||||
static void fresh_session() {
|
||||
connected = false;
|
||||
arduino_usb_cdc_event_data_t event;
|
||||
event.line_state.dtr = false;
|
||||
Serial.callback(nullptr, nullptr, ARDUINO_USB_CDC_LINE_STATE_EVENT, &event);
|
||||
connected = true; // fast close/reopen, without an intervening service poll
|
||||
mesh::serviceUsbLoggingPort();
|
||||
assert(mesh::takeUsbTerminalSessionReset());
|
||||
assert(!mesh::takeUsbTerminalSessionReset());
|
||||
assert(mesh::tryCompleteUsbTerminalSessionReset());
|
||||
fifo.clear();
|
||||
host.clear();
|
||||
auto_drain = false;
|
||||
}
|
||||
|
||||
static void check_native_short_writes_and_mota() {
|
||||
const unsigned before = write_calls;
|
||||
assert(put(mesh::usbCompanionPort(), std::string(200, 'B')) == 64);
|
||||
assert(write_calls == before + 1);
|
||||
assert(put(mesh::usbCompanionPort(), "more") == 0);
|
||||
const unsigned flushed = flush_calls;
|
||||
mesh::usbCompanionPort().flush();
|
||||
assert(flush_calls == flushed);
|
||||
fifo.resize(59); // only 5 bytes free: an 11-byte mOTA record must not split
|
||||
assert(put(mesh::usbMotaPort(), std::string(11, 'M')) == 0);
|
||||
assert(write_calls == before + 1);
|
||||
fifo.resize(50);
|
||||
assert(put(mesh::usbMotaPort(), std::string(11, 'M')) == 11);
|
||||
assert(write_calls == before + 2);
|
||||
fresh_session();
|
||||
}
|
||||
|
||||
static void check_ordered_text_and_functional_reserve() {
|
||||
const std::string log = "RAW: " + std::string(545, 'L') + "\r\n";
|
||||
const std::string reply = " -> " + std::string(2177, 'R') + "\r\n";
|
||||
assert(put(mesh::usbLoggingPort(), log) == log.size());
|
||||
assert(fifo.size() == 64);
|
||||
assert(mesh::hasPendingUsbTerminalOutput());
|
||||
assert(mesh::canAcceptUsbConsoleCommand()); // logs cannot starve CLI input
|
||||
assert(put(mesh::usbConsolePort(), reply) == reply.size());
|
||||
assert(!mesh::canAcceptUsbConsoleCommand()); // previous reply needs draining
|
||||
assert(mesh::usbLoggingPort().availableForWrite() == 0);
|
||||
assert(put(mesh::usbLoggingPort(), std::string(900, 'X')) == 0);
|
||||
drain_all();
|
||||
assert(host == log + reply); // no 64-byte log/reply interleaving
|
||||
assert(mesh::canAcceptUsbConsoleCommand());
|
||||
assert(mesh::usbTerminalDroppedBytes() == 0);
|
||||
fresh_session();
|
||||
}
|
||||
|
||||
static void check_stalled_host_and_visible_overflow() {
|
||||
const std::string fill(4096, 'F');
|
||||
assert(put(mesh::usbConsolePort(), fill) == fill.size());
|
||||
assert(put(mesh::usbConsolePort(), std::string(64, 'T')) == 64);
|
||||
assert(!mesh::canAcceptUsbConsoleCommand());
|
||||
const unsigned before = write_calls;
|
||||
for (unsigned i = 0; i != 1000; ++i) mesh::serviceUsbLoggingPort();
|
||||
assert(write_calls == before); // no retry loop enters a full USB FIFO
|
||||
assert(put(mesh::usbConsolePort(), "!") == 0);
|
||||
assert(mesh::usbTerminalDroppedBytes() == 1);
|
||||
drain_all();
|
||||
assert(host.find(fill + std::string(64, 'T')) == 0);
|
||||
assert(host.find("[USB terminal output dropped 1 bytes]") != std::string::npos);
|
||||
fresh_session();
|
||||
}
|
||||
|
||||
static void check_disconnect_cleanup_keeps_new_host_input() {
|
||||
assert(put(mesh::usbConsolePort(), std::string(1000, 'O')) == 1000);
|
||||
const auto before = clear_calls;
|
||||
Serial.rx_count = 4;
|
||||
fresh_session();
|
||||
assert(clear_calls > before);
|
||||
assert(!mesh::hasPendingUsbTerminalOutput());
|
||||
assert(mesh::usbConsolePort().available() == 4);
|
||||
assert(mesh::usbConsolePort().peek() == 'v');
|
||||
assert(mesh::usbConsolePort().read() == 'v');
|
||||
assert(put(mesh::usbConsolePort(), "new\r\n") == 5);
|
||||
drain_all();
|
||||
assert(host == "new\r\n");
|
||||
fresh_session();
|
||||
}
|
||||
|
||||
static void check_debug_formatter_and_reentrancy() {
|
||||
auto_drain = true;
|
||||
const std::string long_text(1000, 'D');
|
||||
assert(mesh::nrf52DebugPrintf("%s\n", long_text.c_str()) == 255);
|
||||
drain_all();
|
||||
assert(host.size() == 255);
|
||||
assert(host.substr(host.size() - 4) == "...\n");
|
||||
host.clear();
|
||||
during_write = [] {
|
||||
assert(mesh::nrf52DebugPrintf("must not recurse\n") == 0);
|
||||
};
|
||||
assert(mesh::nrf52DebugPrintf("outer\n") == 6);
|
||||
during_write = nullptr;
|
||||
drain_all();
|
||||
assert(host == "outer\n");
|
||||
fresh_session();
|
||||
}
|
||||
|
||||
static void check_cached_logging_gate_and_isr() {
|
||||
Stream& cached = mesh::usbLoggingPort();
|
||||
mesh::setUsbLoggingEnabled(false);
|
||||
assert(put(cached, "off") == 0);
|
||||
mesh::setUsbLoggingEnabled(true);
|
||||
mock_isr = true;
|
||||
const auto before = write_calls;
|
||||
assert(put(mesh::usbCompanionPort(), "isr") == 0);
|
||||
assert(put(mesh::usbConsolePort(), "isr") == 0);
|
||||
mesh::serviceUsbTerminalPort();
|
||||
assert(write_calls == before);
|
||||
mock_isr = false;
|
||||
}
|
||||
|
||||
static void check_protocol_switch_cancels_text_and_overflow_marker() {
|
||||
fresh_session();
|
||||
assert(put(mesh::usbConsolePort(), std::string(5000, 'X')) == 0);
|
||||
assert(put(mesh::usbLoggingPort(), std::string(550, 'L')) == 550);
|
||||
mesh::setUsbLoggingEnabled(false);
|
||||
assert(!mesh::hasPendingUsbTerminalOutput());
|
||||
// A protocol owner may discard application text without resetting USB. The
|
||||
// already accepted FIFO prefix stays ordered before the new binary frame.
|
||||
mesh::discardUsbTerminalOutput();
|
||||
host += fifo;
|
||||
fifo.clear();
|
||||
assert(put(mesh::usbCompanionPort(), "binary") == 6);
|
||||
drain_all();
|
||||
assert(host == std::string(64, 'L') + "binary");
|
||||
// In particular, service must not inject a delayed ASCII overflow notice
|
||||
// into Binary or mOTA after the owner has discarded the terminal epoch.
|
||||
host.clear();
|
||||
assert(put(mesh::usbMotaPort(), std::string(11, 'M')) == 11);
|
||||
drain_all();
|
||||
assert(host == std::string(11, 'M'));
|
||||
mesh::setUsbLoggingEnabled(true);
|
||||
fresh_session();
|
||||
}
|
||||
#endif
|
||||
|
||||
int main() {
|
||||
#if MESH_ESP32_TINYUSB_NONBLOCKING
|
||||
mesh::beginUsbLoggingPort();
|
||||
mesh::beginUsbLoggingPort();
|
||||
mesh::setUsbLoggingEnabled(true);
|
||||
assert(Serial.registrations == 1);
|
||||
assert(!Serial.debug_enabled);
|
||||
mesh::serviceUsbLoggingPort();
|
||||
assert(&mesh::usbConsolePort() == &mesh::usbTerminalPort());
|
||||
check_native_short_writes_and_mota();
|
||||
check_ordered_text_and_functional_reserve();
|
||||
check_stalled_host_and_visible_overflow();
|
||||
check_disconnect_cleanup_keeps_new_host_input();
|
||||
check_debug_formatter_and_reentrancy();
|
||||
check_cached_logging_gate_and_isr();
|
||||
check_protocol_switch_cancels_text_and_overflow_marker();
|
||||
assert(Serial.blocking_calls == 0);
|
||||
#else
|
||||
assert(&mesh::usbConsolePort() == &Serial);
|
||||
assert(mesh::canAcceptUsbConsoleCommand());
|
||||
assert(mesh::usbTerminalDroppedBytes() == 0);
|
||||
#endif
|
||||
std::cout << "ESP32 TinyUSB transport checks passed\n";
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
// The production helper only needs a valid owner for a closed LittleFS file.
|
||||
// The harness defines this object without any filesystem or hardware access.
|
||||
struct FakeFS;
|
||||
extern FakeFS InternalFS;
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
#include <helpers/ReplayResetCommand.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
using mesh::ReplayResetKind;
|
||||
using mesh::ReplayResetNonce;
|
||||
using mesh::ReplayResetRequest;
|
||||
using Result = mesh::ReplayResetNonce::IssueResult;
|
||||
|
||||
static void check(bool condition, const char* message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
static ReplayResetKind parse(const std::string& command) {
|
||||
ReplayResetRequest request;
|
||||
const auto result = mesh::parseReplayResetCommand(command.c_str(), request);
|
||||
check(result == request.kind, "parser result disagrees with request");
|
||||
return result;
|
||||
}
|
||||
|
||||
static void parserTests() {
|
||||
const std::string key =
|
||||
"0123456789abcdef0123456789ABCDEF0123456789abcdef0123456789ABCDEF";
|
||||
const std::string token = "0123456789abcdefFEDCBA9876543210";
|
||||
const std::string base = "replay reset " + key;
|
||||
check(parse(base) == ReplayResetKind::ExactKey, "exact key");
|
||||
check(parse(base + " " + token) == ReplayResetKind::ExactKeyConfirm, "exact confirmation");
|
||||
check(parse(" \tQ7| RePlAy\tRESET\t" + key + "\r\n") == ReplayResetKind::ExactKey,
|
||||
"normalization and companion prefix");
|
||||
check(parse("ab|replay reset " + key + " " + token + " \t\r\n")
|
||||
== ReplayResetKind::ExactKeyConfirm, "prefixed confirmation");
|
||||
check(parse("replay reset all CONFIRM") == ReplayResetKind::AllConfirm, "all confirmation");
|
||||
check(parse(" REPLAY reset ALL confirm\r\n") == ReplayResetKind::AllConfirm, "all case fold");
|
||||
|
||||
ReplayResetRequest request;
|
||||
memset(&request, 0xff, sizeof(request));
|
||||
check(mesh::parseReplayResetCommand(nullptr, request) == ReplayResetKind::NotReplay,
|
||||
"null command");
|
||||
for (size_t i = 0; i < sizeof(request.key); ++i) check(request.key[i] == 0, "request key initialized");
|
||||
for (size_t i = 0; i < sizeof(request.token); ++i) check(request.token[i] == 0, "request token initialized");
|
||||
mesh::parseReplayResetCommand((base + " " + token).c_str(), request);
|
||||
check(request.key[0] == 0x01 && request.key[7] == 0xef && request.key[31] == 0xef,
|
||||
"decoded exact full key");
|
||||
check(request.token[0] == 0x01 && request.token[8] == 0xfe && request.token[15] == 0x10,
|
||||
"decoded full nonce");
|
||||
|
||||
const std::string invalid[] = {
|
||||
"replay", "replay ", "replay reset", "replay reset all", "replay reset all 123",
|
||||
"replay reset all CONFIRM extra", "replay RESET " + key.substr(2),
|
||||
"replay reset " + key + "00", "replay reset g" + key.substr(1),
|
||||
"replay reset " + key.substr(0, 20) + " " + key.substr(20),
|
||||
base + " " + token.substr(2), base + " " + token + "00",
|
||||
base + " " + token + " extra", base + " g" + token.substr(1),
|
||||
base + " CONFIRM", "replay reset0 " + key, "replay bogus", "replay.reset " + key,
|
||||
" ab|replay reset all", "replay reset all\nCONFIRM extra",
|
||||
};
|
||||
for (const auto& command : invalid) {
|
||||
check(parse(command) == ReplayResetKind::Invalid, command.c_str());
|
||||
}
|
||||
const std::string unrelated[] = {"", " ", "a", "ab", "ab|", "replayx", "replay-reset", "get replay", "reboot"};
|
||||
for (const auto& command : unrelated) {
|
||||
check(parse(command) == ReplayResetKind::NotReplay, command.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
struct Identities {
|
||||
uint8_t issuer[32] = {1};
|
||||
uint8_t target[32] = {2};
|
||||
uint8_t other[32] = {3};
|
||||
uint8_t random[16] = {4};
|
||||
uint8_t later_random[16] = {5};
|
||||
uint8_t zero[16] = {};
|
||||
};
|
||||
|
||||
static void lifecycleTests() {
|
||||
Identities ids;
|
||||
ReplayResetNonce nonce;
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 100, 2000000000), "unissued nonce");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, 100, 2000000000) == Result::Issued,
|
||||
"issue nonce");
|
||||
check(memcmp(nonce.token(), ids.random, 16) == 0, "exposes original token");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 1100, 2000000001), "matches issuer and target");
|
||||
check(!nonce.matches(ids.other, ids.target, ids.random, 1100, 2000000001), "different issuer");
|
||||
check(!nonce.matches(ids.issuer, ids.other, ids.random, 1100, 2000000001), "different target");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 1100, 2000000001), "wrong token");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 20100, 2000000020) == Result::Reused,
|
||||
"prepare retry reuses existing token");
|
||||
check(memcmp(nonce.token(), ids.random, 16) == 0, "retry cannot replace token");
|
||||
check(nonce.issue(ids.other, ids.target, ids.later_random, 20100, 2000000020) == Result::Busy,
|
||||
"other issuer cannot replace challenge");
|
||||
check(nonce.issue(ids.issuer, ids.other, ids.later_random, 20100, 2000000020) == Result::Busy,
|
||||
"other target cannot replace challenge");
|
||||
check(!nonce.consume(ids.issuer, ids.target, ids.later_random, 20100, 2000000020),
|
||||
"bad token does not consume challenge");
|
||||
check(nonce.consume(ids.issuer, ids.target, ids.random, 20100, 2000000020), "valid token consumed");
|
||||
check(!nonce.consume(ids.issuer, ids.target, ids.random, 20100, 2000000020), "cannot consume twice");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 21100, 2000000021), "captured confirmation rejected");
|
||||
for (size_t i = 0; i < 16; ++i) check(nonce.token()[i] == 0, "consumption clears token");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 21100, 2000000021) == Result::Issued,
|
||||
"reissue after consumption");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 21100, 2000000021), "old token rejected after reissue");
|
||||
nonce.clear();
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 21100, 2000000021), "USB invalidation");
|
||||
ReplayResetNonce rebooted;
|
||||
check(!rebooted.matches(ids.issuer, ids.target, ids.random, 100, 2000000000), "reboot invalidates captured token");
|
||||
check(rebooted.issue(ids.issuer, ids.issuer, ids.random, 100, 2000000000) == Result::Issued,
|
||||
"self reset allowed by nonce layer");
|
||||
check(rebooted.consume(ids.issuer, ids.issuer, ids.random, 100, 2000000000), "self reset consumed once");
|
||||
}
|
||||
|
||||
static void timeTests() {
|
||||
Identities ids;
|
||||
ReplayResetNonce nonce;
|
||||
check(ReplayResetNonce::RESEND_WINDOW_MILLIS == 120000, "resend window is exactly 120 seconds");
|
||||
check(ReplayResetNonce::LIFETIME_MILLIS == 300000, "confirmation expires at exactly 300 seconds");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, 100, 2000000000) == Result::Issued, "time fixture");
|
||||
check(nonce.remainingSeconds(100, 2000000000) == 300, "initial TTL is 300 seconds");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 120099, 2000000119) == Result::Reused,
|
||||
"119999ms remains in the resend window");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 120099, 2000000119), "119999ms original token valid");
|
||||
check(nonce.remainingSeconds(120099, 2000000119) == 180, "last resend advertises original 180-second TTL");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 120100, 2000000120)
|
||||
== Result::AwaitingConfirmation, "120000ms starts confirmation-only window");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 120100, 2000000120), "120000ms token still valid");
|
||||
check(nonce.remainingSeconds(120100, 2000000120) == 180, "confirmation-only boundary retains original TTL");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 300099, 2000000299)
|
||||
== Result::AwaitingConfirmation, "299999ms cannot reissue or resend original token");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 300099, 2000000299), "299999ms original token valid");
|
||||
check(nonce.remainingSeconds(300099, 2000000299) == 0, "TTL rounds down during valid final subsecond");
|
||||
check(memcmp(nonce.token(), ids.random, 16) == 0, "confirmation-only retries cannot replace token");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 300100, 2000000300), "300000ms expiration boundary");
|
||||
check(nonce.remainingSeconds(300100, 2000000300) == 0, "expired TTL is zero");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 300100, 2000000300) == Result::Issued,
|
||||
"expired challenge replaceable");
|
||||
check(memcmp(nonce.token(), ids.later_random, 16) == 0, "new lifetime uses fresh token");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.later_random, 301100, 2000000306), "positive clock tolerance");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.later_random, 301100, 2000000296), "negative clock tolerance");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 301100, 2000000307), "forward clock jump");
|
||||
check(nonce.remainingSeconds(301100, 2000000307) == 0, "clock-invalid TTL is zero");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 301100, 2000000295), "backward clock jump");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 301100, 0), "zero clock invalid");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.later_random, 300099, 2000000300), "monotonic backwards fails closed");
|
||||
|
||||
nonce.clear();
|
||||
nonce.issue(ids.issuer, ids.target, ids.random, 0, 2000000000);
|
||||
for (uint32_t age : {119999U, 120000U, 299999U}) {
|
||||
check(nonce.issue(ids.other, ids.target, ids.later_random, age, 2000000000 + age / 1000)
|
||||
== Result::Busy, "another issuer stays blocked through confirmation-only window");
|
||||
check(nonce.issue(ids.issuer, ids.other, ids.later_random, age, 2000000000 + age / 1000)
|
||||
== Result::Busy, "another target stays blocked through confirmation-only window");
|
||||
}
|
||||
check(nonce.issue(ids.other, ids.target, ids.later_random, 300000, 2000000300)
|
||||
== Result::Issued, "another identity can start only after 300000ms");
|
||||
|
||||
nonce.clear();
|
||||
const uint32_t started = UINT32_MAX - 500;
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, started, 2000000000) == Result::Issued, "rollover issue");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 499, 2000000001), "millis rollover valid");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, started + 119999U, 2000000119)
|
||||
== Result::Reused, "rollover 119999ms resend");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, started + 120000U, 2000000120)
|
||||
== Result::AwaitingConfirmation, "rollover 120000ms confirmation-only");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, started + 299999U, 2000000299),
|
||||
"rollover 299999ms original confirmation valid");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, started + 300000U, 2000000300),
|
||||
"rollover 300000ms expiration");
|
||||
|
||||
nonce.clear();
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, 0, UINT32_MAX) == Result::Issued, "epoch boundary issue");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 1000, UINT32_MAX), "epoch overflow rejected");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 1000, 1), "epoch wrap rejected");
|
||||
|
||||
nonce.clear();
|
||||
nonce.issue(ids.issuer, ids.target, ids.random, 0, 2000000000);
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, 119999, 2000000119) == Result::Reused,
|
||||
"last possible resend still reuses");
|
||||
check(nonce.consume(ids.issuer, ids.target, ids.random, 299999, 2000000299),
|
||||
"original confirmation works exactly 180 seconds after last possible resend");
|
||||
check(nonce.remainingSeconds(299999, 2000000299) == 0, "consumed token TTL is zero");
|
||||
nonce.issue(ids.issuer, ids.target, ids.random, 0, 2000000000);
|
||||
for (uint32_t age : {119000U, 119999U, 120000U, 200000U, 299999U}) {
|
||||
const auto expected = age < 120000 ? Result::Reused : Result::AwaitingConfirmation;
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.later_random, age, 2000000000 + age / 1000)
|
||||
== expected, "repeated requests obey original window");
|
||||
}
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 300000, 2000000300), "retries never extend lifetime");
|
||||
|
||||
nonce.clear();
|
||||
nonce.issue(ids.issuer, ids.target, ids.random, 0, 2000000000);
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 180000, 2000000185),
|
||||
"confirmation-only phase allows positive clock tolerance");
|
||||
check(nonce.matches(ids.issuer, ids.target, ids.random, 180000, 2000000175),
|
||||
"confirmation-only phase allows negative clock tolerance");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 180000, 2000000186),
|
||||
"forward correction invalidates confirmation-only token");
|
||||
check(!nonce.matches(ids.issuer, ids.target, ids.random, 180000, 2000000174),
|
||||
"backward correction invalidates confirmation-only token");
|
||||
}
|
||||
|
||||
static void invalidTests() {
|
||||
Identities ids;
|
||||
ReplayResetNonce nonce;
|
||||
check(nonce.issue(nullptr, ids.target, ids.random, 0, 1) == Result::Invalid, "null issuer");
|
||||
check(nonce.issue(ids.issuer, nullptr, ids.random, 0, 1) == Result::Invalid, "null target");
|
||||
check(nonce.issue(ids.issuer, ids.target, nullptr, 0, 1) == Result::Invalid, "null random");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.zero, 0, 1) == Result::Invalid, "zero random");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, 0, 0) == Result::Invalid, "zero epoch");
|
||||
check(nonce.issue(ids.issuer, ids.target, ids.random, 0, 2000000000) == Result::Issued, "valid after invalid attempts");
|
||||
check(!nonce.matches(nullptr, ids.target, ids.random, 0, 2000000000), "null matching issuer");
|
||||
check(!nonce.matches(ids.issuer, nullptr, ids.random, 0, 2000000000), "null matching target");
|
||||
check(!nonce.matches(ids.issuer, ids.target, nullptr, 0, 2000000000), "null matching token");
|
||||
check(nonce.issue(ids.issuer, ids.target, nullptr, 0, 2000000000) == Result::Reused,
|
||||
"existing challenge does not require replacement randomness");
|
||||
check(nonce.issue(ids.issuer, ids.target, nullptr, 120000, 2000000120)
|
||||
== Result::AwaitingConfirmation, "confirmation-only phase needs no replacement randomness");
|
||||
for (size_t i = 0; i < 32; ++i) {
|
||||
uint8_t changed[32];
|
||||
memcpy(changed, ids.issuer, 32);
|
||||
changed[i] ^= 1;
|
||||
check(!nonce.matches(changed, ids.target, ids.random, 0, 2000000000), "every issuer byte bound");
|
||||
memcpy(changed, ids.target, 32);
|
||||
changed[i] ^= 1;
|
||||
check(!nonce.matches(ids.issuer, changed, ids.random, 0, 2000000000), "every target byte bound");
|
||||
}
|
||||
for (size_t i = 0; i < 16; ++i) {
|
||||
uint8_t changed[16];
|
||||
memcpy(changed, ids.random, 16);
|
||||
changed[i] ^= 1;
|
||||
check(!nonce.matches(ids.issuer, ids.target, changed, 0, 2000000000), "every token byte bound");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
try {
|
||||
if (argc != 2) throw std::runtime_error("expected test case");
|
||||
const std::string test = argv[1];
|
||||
if (test == "parser") parserTests();
|
||||
else if (test == "lifecycle") lifecycleTests();
|
||||
else if (test == "time") timeTests();
|
||||
else if (test == "invalid") invalidTests();
|
||||
else throw std::runtime_error("unknown test case");
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << std::endl;
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
#include <helpers/ReplayResetCommand.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static constexpr size_t PUB_KEY_SIZE = 32;
|
||||
static constexpr uint32_t NOW = 1760000000;
|
||||
static constexpr int CLOCK_SYNC_MESH_SUPPRESS_NONE = 0;
|
||||
static constexpr int CLOCK_SYNC_RESULT_WITHIN_DRIFT = 5;
|
||||
static constexpr int CLOCK_SYNC_RESULT_CORRECTED_BACKWARD = 7;
|
||||
static uint32_t fake_millis = 1000;
|
||||
uint32_t millis() { return fake_millis; }
|
||||
static uint32_t clockSyncMinimumValidEpoch() { return 1700000000; }
|
||||
static uint32_t clockSyncMaximumValidEpoch() { return 1900000000; }
|
||||
|
||||
#define CHECK(expression) do { if (!(expression)) { \
|
||||
std::fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #expression); std::exit(1); \
|
||||
} } while (0)
|
||||
|
||||
namespace mesh {
|
||||
struct Utils {
|
||||
static void toHex(char* out, const uint8_t* data, size_t length) {
|
||||
const char digits[] = "0123456789ABCDEF";
|
||||
for (size_t i = 0; i < length; ++i) {
|
||||
out[i * 2] = digits[data[i] >> 4];
|
||||
out[i * 2 + 1] = digits[data[i] & 15];
|
||||
}
|
||||
out[length * 2] = 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
struct ClientInfo {
|
||||
struct { uint8_t pub_key[PUB_KEY_SIZE]; } id{};
|
||||
bool admin = false;
|
||||
bool observed_path_pending = true;
|
||||
uint32_t last_timestamp = NOW + 10000;
|
||||
bool isAdmin() const { return admin; }
|
||||
};
|
||||
|
||||
struct ClientLoginReplayClampResult {
|
||||
uint16_t stored_matched, stored_changed, live_matched, live_changed;
|
||||
};
|
||||
|
||||
struct FakeACL {
|
||||
std::vector<ClientInfo> clients;
|
||||
std::vector<ClientInfo> stored;
|
||||
bool fail_persist = false;
|
||||
int calls = 0;
|
||||
bool selected_all = false;
|
||||
std::array<uint8_t, 32> selected_key{};
|
||||
uint32_t selected_now = 0;
|
||||
|
||||
int getNumClients() const { return static_cast<int>(clients.size()); }
|
||||
ClientInfo* getClientByIdx(int index) { return &clients.at(index); }
|
||||
bool clampLoginReplayTimestamps(const uint8_t* key, uint32_t now,
|
||||
ClientLoginReplayClampResult& result) {
|
||||
++calls;
|
||||
selected_all = key == nullptr;
|
||||
if (key) std::copy(key, key + 32, selected_key.begin());
|
||||
selected_now = now;
|
||||
result = {};
|
||||
if (fail_persist) return false;
|
||||
for (auto& record : stored) {
|
||||
if (!key || std::memcmp(key, record.id.pub_key, 32) == 0) {
|
||||
++result.stored_matched;
|
||||
if (record.last_timestamp > now) { record.last_timestamp = now; ++result.stored_changed; }
|
||||
}
|
||||
}
|
||||
for (auto& client : clients) {
|
||||
if (!key || std::memcmp(key, client.id.pub_key, 32) == 0) {
|
||||
++result.live_matched;
|
||||
if (client.last_timestamp > now) { client.last_timestamp = now; ++result.live_changed; }
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
struct FakeClock { uint32_t now = NOW; uint32_t getCurrentTime() const { return now; } };
|
||||
struct FakeRNG {
|
||||
uint8_t next = 1;
|
||||
int calls = 0;
|
||||
void random(uint8_t* output, size_t length) { ++calls; std::memset(output, next++, length); }
|
||||
};
|
||||
|
||||
struct CountingReplyCache {
|
||||
bool hit;
|
||||
int& calls;
|
||||
bool lookup(const uint8_t*, uint32_t, uint32_t, const char**) {
|
||||
++calls;
|
||||
return hit;
|
||||
}
|
||||
};
|
||||
|
||||
class MyMesh {
|
||||
public:
|
||||
FakeACL acl;
|
||||
FakeClock clock;
|
||||
FakeRNG rng;
|
||||
bool replay_clock_set = true;
|
||||
int clock_sync_mesh_suppressed_by = CLOCK_SYNC_MESH_SUPPRESS_NONE;
|
||||
int clock_sync_last_result = 0;
|
||||
mesh::ReplayResetNonce replay_reset_nonce;
|
||||
struct { bool pending = false; int client_index = -1; } deferred_cli_command;
|
||||
int mailbox_clears = 0;
|
||||
|
||||
FakeClock* getRTCClock() { return &clock; }
|
||||
FakeRNG* getRNG() { return &rng; }
|
||||
void clearDeferredCliCommand() { deferred_cli_command.pending = false; ++mailbox_clears; }
|
||||
bool handleReplayResetCommand(ClientInfo*, const char*, char*, bool);
|
||||
};
|
||||
|
||||
#include "production_handler.inc"
|
||||
|
||||
static ClientInfo client(uint8_t key_byte, bool admin = false) {
|
||||
ClientInfo value;
|
||||
std::memset(value.id.pub_key, key_byte, sizeof(value.id.pub_key));
|
||||
value.admin = admin;
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::string key(const ClientInfo& value) {
|
||||
char output[65];
|
||||
mesh::Utils::toHex(output, value.id.pub_key, 32);
|
||||
return output;
|
||||
}
|
||||
|
||||
static MyMesh populated() {
|
||||
fake_millis = 1000;
|
||||
MyMesh value;
|
||||
value.acl.clients = {client(0x12, true), client(0x77), client(0x99)};
|
||||
value.acl.stored = value.acl.clients;
|
||||
value.acl.stored.push_back(client(0x88)); // Historical identity, no live ACL entry.
|
||||
return value;
|
||||
}
|
||||
|
||||
static std::string run(MyMesh& value, ClientInfo* sender, const std::string& command,
|
||||
bool usb = false, bool expected_handled = true) {
|
||||
std::array<char, 168> guarded;
|
||||
guarded.fill('#');
|
||||
guarded[4] = 0;
|
||||
CHECK(value.handleReplayResetCommand(sender, command.c_str(), guarded.data() + 4, usb)
|
||||
== expected_handled);
|
||||
for (size_t i = 0; i < 4; ++i) CHECK(guarded[i] == '#');
|
||||
for (size_t i = 164; i < guarded.size(); ++i) CHECK(guarded[i] == '#');
|
||||
return std::string(guarded.data() + 4);
|
||||
}
|
||||
|
||||
static std::string request(const ClientInfo& target) { return "replay reset " + key(target); }
|
||||
static bool contains(const std::string& text, const char* part) { return text.find(part) != std::string::npos; }
|
||||
static std::string challenge(MyMesh& value, ClientInfo* admin, const ClientInfo& target,
|
||||
std::string* full_reply = nullptr) {
|
||||
const std::string response = run(value, admin, request(target));
|
||||
if (full_reply) *full_reply = response;
|
||||
const auto where = response.find("confirm: ");
|
||||
CHECK(where != std::string::npos);
|
||||
return response.substr(where + std::strlen("confirm: "));
|
||||
}
|
||||
|
||||
static void authorization() {
|
||||
auto value = populated();
|
||||
const auto command = request(value.acl.clients[1]);
|
||||
CHECK(contains(run(value, nullptr, command), "requires USB or LoRa admin"));
|
||||
CHECK(contains(run(value, &value.acl.clients[1], command), "requires USB or LoRa admin"));
|
||||
CHECK(contains(run(value, &value.acl.clients[1], command, true), "requires USB or LoRa admin"));
|
||||
CHECK(value.acl.calls == 0 && value.rng.calls == 0);
|
||||
CHECK(run(value, nullptr, "get name", false, false).empty());
|
||||
}
|
||||
|
||||
static void usb_exact_and_all() {
|
||||
auto value = populated();
|
||||
CHECK(contains(run(value, nullptr, request(value.acl.clients[1]), true), "OK - clamped"));
|
||||
CHECK(value.acl.calls == 1 && !value.acl.selected_all && value.acl.selected_now == NOW);
|
||||
CHECK(value.acl.clients[1].last_timestamp == NOW);
|
||||
CHECK(value.acl.clients[0].last_timestamp > NOW);
|
||||
CHECK(!value.acl.clients[1].observed_path_pending && value.acl.clients[0].observed_path_pending);
|
||||
CHECK(contains(run(value, nullptr, "replay reset all CONFIRM", true), "stored=3 live=2"));
|
||||
CHECK(value.acl.selected_all && value.acl.stored[3].last_timestamp == NOW);
|
||||
CHECK(value.acl.clients.size() == 3 && value.acl.stored.size() == 4);
|
||||
}
|
||||
|
||||
static void all_usb_only() {
|
||||
auto value = populated();
|
||||
CHECK(contains(run(value, &value.acl.clients[0], "replay reset all CONFIRM"), "USB-only"));
|
||||
CHECK(contains(run(value, nullptr, "replay reset all CONFIRM"), "requires USB"));
|
||||
CHECK(contains(run(value, nullptr, "replay reset all", true), "64-hex"));
|
||||
CHECK(value.acl.calls == 0 && value.rng.calls == 0);
|
||||
}
|
||||
|
||||
static void strict_full_key() {
|
||||
auto value = populated();
|
||||
const std::string full = key(value.acl.clients[1]);
|
||||
for (size_t size : {size_t(2), size_t(4), size_t(6), size_t(63)}) {
|
||||
CHECK(contains(run(value, nullptr, "replay reset " + full.substr(0, size), true), "64-hex"));
|
||||
}
|
||||
CHECK(contains(run(value, nullptr, "replay reset " + full + "00", true), "64-hex"));
|
||||
CHECK(contains(run(value, nullptr, "replay reset " + full + " trailing", true), "64-hex"));
|
||||
CHECK(value.acl.calls == 0);
|
||||
}
|
||||
|
||||
static void clock_must_be_observed() {
|
||||
auto value = populated();
|
||||
value.replay_clock_set = false;
|
||||
CHECK(contains(run(value, nullptr, request(value.acl.clients[1]), true), "set/sync"));
|
||||
CHECK(value.acl.calls == 0);
|
||||
value.clock_sync_last_result = CLOCK_SYNC_RESULT_WITHIN_DRIFT;
|
||||
CHECK(contains(run(value, nullptr, request(value.acl.clients[1]), true), "OK"));
|
||||
value.clock_sync_last_result = 0;
|
||||
value.clock_sync_mesh_suppressed_by = 1;
|
||||
CHECK(contains(run(value, nullptr, request(value.acl.clients[2]), true), "OK"));
|
||||
}
|
||||
|
||||
static void clock_must_be_sane() {
|
||||
auto value = populated();
|
||||
for (uint32_t now : {0U, clockSyncMinimumValidEpoch() - 1, clockSyncMaximumValidEpoch() + 1}) {
|
||||
value.clock.now = now;
|
||||
CHECK(contains(run(value, nullptr, request(value.acl.clients[1]), true), "set/sync"));
|
||||
}
|
||||
CHECK(value.acl.calls == 0 && value.rng.calls == 0);
|
||||
}
|
||||
|
||||
static void remote_challenge_then_commit() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto confirm = challenge(value, admin, value.acl.clients[1]);
|
||||
CHECK(value.acl.calls == 0 && value.acl.clients[1].last_timestamp > NOW);
|
||||
CHECK(challenge(value, admin, value.acl.clients[1]) == confirm);
|
||||
CHECK(contains(run(value, admin, confirm), "OK - clamped"));
|
||||
CHECK(value.acl.calls == 1 && value.acl.clients[1].last_timestamp == NOW);
|
||||
}
|
||||
|
||||
static void nonce_binds_sender_and_target() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
value.acl.clients[2].admin = true;
|
||||
const auto confirm = challenge(value, admin, value.acl.clients[1]);
|
||||
CHECK(contains(run(value, &value.acl.clients[2], confirm), "expired/used"));
|
||||
std::string swapped = confirm;
|
||||
swapped.replace(std::strlen("replay reset "), 64, key(value.acl.clients[2]));
|
||||
CHECK(contains(run(value, admin, swapped), "expired/used"));
|
||||
CHECK(value.acl.calls == 0);
|
||||
CHECK(contains(run(value, admin, confirm), "OK"));
|
||||
}
|
||||
|
||||
static void failure_is_not_live_and_token_is_consumed() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto confirm = challenge(value, admin, value.acl.clients[1]);
|
||||
value.acl.fail_persist = true;
|
||||
value.deferred_cli_command = {true, 1};
|
||||
CHECK(contains(run(value, admin, confirm), "no live timestamps changed"));
|
||||
CHECK(value.acl.calls == 1 && value.acl.clients[1].last_timestamp > NOW);
|
||||
CHECK(value.acl.clients[1].observed_path_pending && value.deferred_cli_command.pending);
|
||||
value.acl.fail_persist = false;
|
||||
CHECK(contains(run(value, admin, confirm), "expired/used"));
|
||||
CHECK(value.acl.calls == 1);
|
||||
}
|
||||
|
||||
static void self_reset_replay_never_reexecutes_or_raises_floor() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto confirm = challenge(value, admin, *admin);
|
||||
CHECK(contains(run(value, admin, confirm), "OK"));
|
||||
CHECK(admin->last_timestamp == NOW && value.acl.calls == 1);
|
||||
apply_actual_receive_guard(admin, confirm.c_str(), NOW + 100000);
|
||||
CHECK(admin->last_timestamp == NOW);
|
||||
CHECK(contains(run(value, admin, confirm), "expired/used"));
|
||||
CHECK(value.acl.calls == 1 && admin->last_timestamp == NOW);
|
||||
}
|
||||
|
||||
static void every_replay_family_preserves_receive_floor() {
|
||||
auto value = populated();
|
||||
auto* sender = &value.acl.clients[0];
|
||||
sender->last_timestamp = NOW;
|
||||
std::vector<std::string> commands = {"replay", "replay anything", "replay.reset", "REPLAY RESET 12",
|
||||
"replay reset all", "replay reset all CONFIRM", request(*sender),
|
||||
"aa| REPLAY RESET " + key(*sender) + " " + std::string(32, 'a'),
|
||||
"\tRePlAy\treset\tbad", "replay reset " + key(*sender) + " bad"};
|
||||
for (const auto& command : commands) {
|
||||
apply_actual_receive_guard(sender, command.c_str(), NOW + 10000);
|
||||
CHECK(sender->last_timestamp == NOW);
|
||||
}
|
||||
apply_actual_receive_guard(sender, "get name", NOW + 10);
|
||||
CHECK(sender->last_timestamp == NOW + 10);
|
||||
apply_actual_receive_guard(sender, "replayable", NOW + 20);
|
||||
CHECK(sender->last_timestamp == NOW + 20);
|
||||
}
|
||||
|
||||
static void pending_usb_affected_and_unrelated_mailboxes() {
|
||||
auto value = populated();
|
||||
value.deferred_cli_command = {true, 2};
|
||||
run(value, nullptr, request(value.acl.clients[1]), true);
|
||||
CHECK(value.deferred_cli_command.pending && value.mailbox_clears == 0);
|
||||
value.deferred_cli_command = {true, 1};
|
||||
run(value, nullptr, request(value.acl.clients[1]), true);
|
||||
CHECK(!value.deferred_cli_command.pending && value.mailbox_clears == 1);
|
||||
value.deferred_cli_command = {true, -1};
|
||||
run(value, nullptr, "replay reset all CONFIRM", true);
|
||||
CHECK(!value.deferred_cli_command.pending && value.mailbox_clears == 2);
|
||||
}
|
||||
|
||||
static void remote_keeps_its_executing_mailbox() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto confirm = challenge(value, admin, *admin);
|
||||
value.deferred_cli_command = {true, 0};
|
||||
CHECK(contains(run(value, admin, confirm), "OK"));
|
||||
CHECK(value.deferred_cli_command.pending && value.mailbox_clears == 0);
|
||||
}
|
||||
|
||||
static void expiry_clock_change_and_usb_token_rejected() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
auto confirm = challenge(value, admin, value.acl.clients[1]);
|
||||
CHECK(contains(run(value, nullptr, confirm, true), "no token"));
|
||||
fake_millis += mesh::ReplayResetNonce::LIFETIME_MILLIS;
|
||||
value.clock.now += 300;
|
||||
CHECK(contains(run(value, admin, confirm), "expired/used"));
|
||||
confirm = challenge(value, admin, value.acl.clients[1]);
|
||||
value.clock.now += 60;
|
||||
CHECK(contains(run(value, admin, confirm), "expired/used"));
|
||||
CHECK(value.acl.calls == 0);
|
||||
}
|
||||
|
||||
static void missing_identity_does_not_create_records() {
|
||||
auto value = populated();
|
||||
const auto unknown = client(0xee);
|
||||
CHECK(contains(run(value, nullptr, request(unknown), true), "nothing created"));
|
||||
CHECK(value.acl.clients.size() == 3 && value.acl.stored.size() == 4);
|
||||
CHECK(value.acl.calls == 1);
|
||||
for (const auto& entry : value.acl.clients) CHECK(entry.last_timestamp > NOW);
|
||||
}
|
||||
|
||||
static void confirmation_only_window_preserves_last_resend() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto prepare = request(value.acl.clients[1]);
|
||||
std::string first_reply;
|
||||
const auto original = challenge(value, admin, value.acl.clients[1], &first_reply);
|
||||
CHECK(contains(first_reply, "ttl=300s; confirm:"));
|
||||
const auto token = original.substr(original.rfind(' ') + 1);
|
||||
fake_millis = 1000 + 119999;
|
||||
value.clock.now = NOW + 119;
|
||||
std::string last_resend_reply;
|
||||
CHECK(challenge(value, admin, value.acl.clients[1], &last_resend_reply) == original);
|
||||
CHECK(contains(last_resend_reply, "ttl=180s; confirm:"));
|
||||
|
||||
for (uint32_t age : {120000U, 180000U, 299999U}) {
|
||||
fake_millis = 1000 + age;
|
||||
value.clock.now = NOW + age / 1000;
|
||||
const auto response = run(value, admin, prepare);
|
||||
CHECK(contains(response, "confirmation-only"));
|
||||
CHECK(!contains(response, "confirm: "));
|
||||
CHECK(response.find(token) == std::string::npos);
|
||||
CHECK(response.find(key(value.acl.clients[1])) == std::string::npos);
|
||||
CHECK(value.acl.calls == 0);
|
||||
CHECK(contains(run(value, admin, request(value.acl.clients[2])), "another replay confirmation"));
|
||||
CHECK(contains(run(value, &value.acl.clients[1], original), "requires USB or LoRa admin"));
|
||||
}
|
||||
// This is exactly 180000ms after the last allowed token resend at119999ms.
|
||||
CHECK(contains(run(value, admin, original), "OK - clamped"));
|
||||
CHECK(value.acl.calls == 1 && value.acl.clients[1].last_timestamp == NOW + 299);
|
||||
CHECK(contains(run(value, admin, original), "expired/used"));
|
||||
CHECK(value.acl.calls == 1);
|
||||
}
|
||||
|
||||
static void repeated_requests_cannot_extend_original_deadline() {
|
||||
auto value = populated();
|
||||
auto* admin = &value.acl.clients[0];
|
||||
const auto original = challenge(value, admin, value.acl.clients[1]);
|
||||
for (uint32_t age : {119999U, 120000U, 200000U, 299999U}) {
|
||||
fake_millis = 1000 + age;
|
||||
value.clock.now = NOW + age / 1000;
|
||||
run(value, admin, request(value.acl.clients[1]));
|
||||
}
|
||||
fake_millis = 1000 + 300000;
|
||||
value.clock.now = NOW + 300;
|
||||
CHECK(contains(run(value, admin, original), "expired/used"));
|
||||
CHECK(value.acl.calls == 0);
|
||||
const auto next = challenge(value, admin, value.acl.clients[1]);
|
||||
CHECK(next != original);
|
||||
CHECK(contains(run(value, admin, original), "expired/used"));
|
||||
CHECK(contains(run(value, admin, next), "OK"));
|
||||
CHECK(value.acl.calls == 1);
|
||||
}
|
||||
|
||||
static void preparation_never_uses_cached_token_reply() {
|
||||
auto value = populated();
|
||||
const auto prepare = request(value.acl.clients[1]);
|
||||
const auto confirm = prepare + " " + std::string(32, 'a');
|
||||
for (const auto& command : {prepare, "aa| " + prepare, "\tREPLAY RESET " + key(value.acl.clients[1])}) {
|
||||
int calls = 0;
|
||||
CHECK(!apply_actual_receive_cache_gate(command.c_str(), true, calls));
|
||||
CHECK(calls == 0);
|
||||
}
|
||||
for (const auto& command : {confirm, std::string("get name"), std::string("replay reset 12")}) {
|
||||
int calls = 0;
|
||||
CHECK(apply_actual_receive_cache_gate(command.c_str(), true, calls));
|
||||
CHECK(calls == 1);
|
||||
CHECK(!apply_actual_receive_cache_gate(command.c_str(), false, calls));
|
||||
CHECK(calls == 2);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
#define RUN(test) do { test(); std::printf("PASS: %s\n", #test); } while (0)
|
||||
RUN(authorization);
|
||||
RUN(usb_exact_and_all);
|
||||
RUN(all_usb_only);
|
||||
RUN(strict_full_key);
|
||||
RUN(clock_must_be_observed);
|
||||
RUN(clock_must_be_sane);
|
||||
RUN(remote_challenge_then_commit);
|
||||
RUN(nonce_binds_sender_and_target);
|
||||
RUN(failure_is_not_live_and_token_is_consumed);
|
||||
RUN(self_reset_replay_never_reexecutes_or_raises_floor);
|
||||
RUN(every_replay_family_preserves_receive_floor);
|
||||
RUN(pending_usb_affected_and_unrelated_mailboxes);
|
||||
RUN(remote_keeps_its_executing_mailbox);
|
||||
RUN(expiry_clock_change_and_usb_token_rejected);
|
||||
RUN(missing_identity_does_not_create_records);
|
||||
RUN(confirmation_only_window_preserves_last_resend);
|
||||
RUN(repeated_requests_cannot_extend_original_deadline);
|
||||
RUN(preparation_never_uses_cached_token_reply);
|
||||
std::puts("18 replay-reset integration checks passed");
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run real ClientACL persistence against ESP32's missing-file directory quirk."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / "test/fixtures/client_acl_spiffs"
|
||||
|
||||
|
||||
class ClientAclSpiffsTest(unittest.TestCase):
|
||||
def test_real_acl_with_spiffs_file_semantics(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
self.skipTest("a host C++17 compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix=".tmp-client-acl-", dir=ROOT) as directory:
|
||||
binary = Path(directory) / "client-acl-spiffs.exe"
|
||||
compiled = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-DESP32=1",
|
||||
"-DESP32_PLATFORM=1", f"-I{FIXTURE / 'mocks'}", f"-I{ROOT / 'src'}",
|
||||
str(FIXTURE / "test_client_acl_spiffs.cpp"), "-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
|
||||
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("24 ClientACL SPIFFS checks passed", checked.stdout)
|
||||
self.assertEqual(checked.stdout.count("PASS:"), 24)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Execute the real native-TinyUSB role output pumps with small host stubs."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
#include <helpers/FileRead.h>
|
||||
#define MESH_ESP32_TINYUSB_NONBLOCKING 1
|
||||
#define MAX_ROUTE_HASH_BYTES 3
|
||||
#define PACKET_LOG_FILE "/packet_log"
|
||||
static void require(bool ok, const char* what) {
|
||||
if (!ok) throw std::runtime_error(what);
|
||||
}
|
||||
struct FileData { std::string text; size_t reads = 0; bool exists = true; };
|
||||
struct File {
|
||||
std::shared_ptr<FileData> data;
|
||||
size_t pos = 0;
|
||||
bool closed = false;
|
||||
bool directory = false;
|
||||
explicit operator bool() const { return data && (data->exists || directory) && !closed; }
|
||||
bool isDirectory() const { return directory; }
|
||||
size_t size() const { return data ? data->text.size() : 0; }
|
||||
int read() {
|
||||
if (!static_cast<bool>(*this) || pos >= data->text.size()) return -1;
|
||||
++data->reads;
|
||||
return static_cast<unsigned char>(data->text[pos++]);
|
||||
}
|
||||
void close() { closed = true; }
|
||||
};
|
||||
struct FakeFS {
|
||||
std::shared_ptr<FileData> data = std::make_shared<FileData>();
|
||||
bool exists(const char*) const { return data->exists; }
|
||||
// ESP32 SPIFFS can return a truthy directory for a missing regular file.
|
||||
File open(const char*) { return File{data, 0, false, !data->exists}; }
|
||||
} fs;
|
||||
struct Stream {
|
||||
std::string output;
|
||||
std::vector<std::string> records;
|
||||
size_t capacity = 4096;
|
||||
size_t short_limit = 0;
|
||||
bool fail_once = false;
|
||||
int availableForWrite() const { return static_cast<int>(capacity); }
|
||||
size_t write(const uint8_t* data, size_t len) {
|
||||
if (fail_once) { fail_once = false; return 0; }
|
||||
if (len > capacity) return 0;
|
||||
if (short_limit != 0) len = std::min(len, short_limit);
|
||||
output.append(reinterpret_cast<const char*>(data), len);
|
||||
records.emplace_back(reinterpret_cast<const char*>(data), len);
|
||||
capacity -= len;
|
||||
return len;
|
||||
}
|
||||
size_t printf(const char* format, ...) {
|
||||
char record[1024];
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int len = vsnprintf(record, sizeof(record), format, args);
|
||||
va_end(args);
|
||||
return len > 0 ? write(reinterpret_cast<const uint8_t*>(record), len) : 0;
|
||||
}
|
||||
} console;
|
||||
namespace mesh {
|
||||
Stream& usbConsolePort() { return console; }
|
||||
namespace Utils {
|
||||
void toHex(char* dest, const uint8_t* src, size_t len) {
|
||||
static const char digits[] = "0123456789ABCDEF";
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
*dest++ = digits[src[i] >> 4];
|
||||
*dest++ = digits[src[i] & 15];
|
||||
}
|
||||
*dest = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
struct SimpleMeshTables {
|
||||
struct RecentRepeaterInfo {
|
||||
uint8_t prefix[3];
|
||||
uint8_t prefix_len;
|
||||
int8_t snr_x4;
|
||||
};
|
||||
std::vector<RecentRepeaterInfo> rows;
|
||||
int getRecentRepeaterCount() const { return static_cast<int>(rows.size()); }
|
||||
const RecentRepeaterInfo* getNextRecentRepeaterBySortKey(
|
||||
const RecentRepeaterInfo*, int previous, int& result) const {
|
||||
result = previous + 1;
|
||||
return result < static_cast<int>(rows.size()) ? &rows[result] : nullptr;
|
||||
}
|
||||
};
|
||||
class MyMesh {
|
||||
public:
|
||||
FakeFS* _fs = &fs;
|
||||
File serial_log_dump;
|
||||
size_t serial_log_remaining = 0;
|
||||
size_t serial_log_pending_size = 0;
|
||||
char serial_log_pending[640];
|
||||
bool serial_log_active = false;
|
||||
bool serial_log_eof_pending = false;
|
||||
bool serial_log_skip_line = false;
|
||||
int serial_recent_next = -1;
|
||||
int serial_recent_count = 0;
|
||||
bool serial_recent_header = false;
|
||||
bool serial_recent_has_cursor = false;
|
||||
SimpleMeshTables::RecentRepeaterInfo serial_recent_cursor{};
|
||||
int serial_recent_cursor_index = -1;
|
||||
SimpleMeshTables tables;
|
||||
const SimpleMeshTables* getTables() const { return &tables; }
|
||||
void dumpLogFile();
|
||||
bool hasPendingSerialOutput() const;
|
||||
void servicePendingSerialOutput();
|
||||
void cancelPendingSerialOutput();
|
||||
void printRecentRepeatersSerial();
|
||||
};
|
||||
@METHODS@
|
||||
static void setupFile(const std::string& text, bool exists = true) {
|
||||
fs.data = std::make_shared<FileData>();
|
||||
fs.data->text = text;
|
||||
fs.data->exists = exists;
|
||||
console = Stream();
|
||||
}
|
||||
static void drain(MyMesh& radio, size_t capacity = 4096) {
|
||||
int passes = 0;
|
||||
while (radio.hasPendingSerialOutput() && passes++ < 10000) {
|
||||
console.capacity = capacity;
|
||||
const size_t reads = fs.data->reads;
|
||||
radio.servicePendingSerialOutput();
|
||||
require(fs.data->reads - reads <= 640, "unbounded file read pass");
|
||||
}
|
||||
require(!radio.hasPendingSerialOutput(), "output pump failed to finish");
|
||||
}
|
||||
int main() {
|
||||
try {
|
||||
const std::string eof = " -> EOF\r\n";
|
||||
for (bool exists : {false, true}) {
|
||||
setupFile("", exists);
|
||||
MyMesh radio;
|
||||
radio.dumpLogFile();
|
||||
require(exists || !radio.serial_log_active, "missing log accepted as a directory");
|
||||
require(console.output.empty(), "synchronous premature EOF");
|
||||
drain(radio);
|
||||
require(console.output == eof, "missing or duplicate empty-file EOF");
|
||||
}
|
||||
setupFile("hello\nworld\n");
|
||||
{
|
||||
MyMesh radio;
|
||||
radio.dumpLogFile();
|
||||
console.capacity = 0;
|
||||
radio.servicePendingSerialOutput();
|
||||
const size_t reads = fs.data->reads;
|
||||
radio.servicePendingSerialOutput();
|
||||
require(reads == fs.data->reads, "backpressure lost pending line");
|
||||
require(console.output.empty(), "wrote without capacity");
|
||||
console.short_limit = 3;
|
||||
console.capacity = 4096;
|
||||
radio.servicePendingSerialOutput();
|
||||
console.short_limit = 0;
|
||||
drain(radio);
|
||||
require(console.output == "hello\nworld\n" + eof, "short-write suffix lost");
|
||||
}
|
||||
std::string large;
|
||||
for (int i = 0; i < 1000; ++i) large += "stored packet\n";
|
||||
setupFile(large);
|
||||
{
|
||||
MyMesh radio;
|
||||
radio.dumpLogFile();
|
||||
fs.data->text += "arrived later\n";
|
||||
drain(radio);
|
||||
require(console.output == large + eof, "large dump lost bytes or ignored snapshot");
|
||||
for (const auto& record : console.records)
|
||||
require(!record.empty() && record.back() == '\n', "split stored record");
|
||||
}
|
||||
const std::string boundary(639, 'a');
|
||||
const std::string too_long(640, 'b');
|
||||
setupFile(boundary + "\n" + too_long + "\nend\ntail");
|
||||
{
|
||||
MyMesh radio;
|
||||
radio.dumpLogFile();
|
||||
drain(radio);
|
||||
require(console.output == boundary + "\n"
|
||||
"[USB log line omitted: exceeds 640 bytes]\r\nend\ntail\n" + eof,
|
||||
"long line boundary or final partial line is wrong");
|
||||
}
|
||||
setupFile(std::string(2000, 'x') + "\n");
|
||||
{
|
||||
MyMesh radio;
|
||||
radio.dumpLogFile();
|
||||
radio.servicePendingSerialOutput();
|
||||
require(radio.hasPendingSerialOutput(), "overlong line not pending");
|
||||
radio.cancelPendingSerialOutput();
|
||||
drain(radio);
|
||||
require(console.output.empty(), "canceled old-session output leaked");
|
||||
}
|
||||
@RECENT_TEST@
|
||||
std::cout << "cooperative output checks passed\n";
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << "\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
RECENT_TEST = r'''
|
||||
setupFile("");
|
||||
{
|
||||
MyMesh radio;
|
||||
for (int i = 0; i < 2048; ++i) {
|
||||
radio.tables.rows.push_back({{0, static_cast<uint8_t>(i >> 8),
|
||||
static_cast<uint8_t>(i)}, 3, -127});
|
||||
}
|
||||
console.fail_once = true;
|
||||
radio.printRecentRepeatersSerial();
|
||||
require(radio.serial_recent_header, "failed header write advanced cursor");
|
||||
drain(radio, 64);
|
||||
require(console.output.find("Recent repeaters (2048):\n") == 0, "missing header");
|
||||
require(std::count(console.output.begin(), console.output.end(), '\n') == 2049,
|
||||
"2048-row listing truncated");
|
||||
require(console.output.substr(console.output.size() - 14) == "0007FF,-31.75\n",
|
||||
"last recent repeater missing");
|
||||
for (const auto& record : console.records)
|
||||
require(!record.empty() && record.back() == '\n', "split recent row");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class CooperativeOutputTest(unittest.TestCase):
|
||||
def test_real_role_pumps(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("A host C++ compiler is required for pump execution")
|
||||
for role in ("simple_repeater", "simple_room_server"):
|
||||
with self.subTest(role=role), tempfile.TemporaryDirectory() as temporary:
|
||||
text = (ROOT / f"examples/{role}/MyMesh.cpp").read_text()
|
||||
dump_start = text.index("void MyMesh::dumpLogFile()")
|
||||
dump_end = text.index("\n#if MESH_ESP32_TINYUSB_NONBLOCKING\nbool MyMesh::hasPendingSerialOutput", dump_start)
|
||||
pump_start = text.index("bool MyMesh::hasPendingSerialOutput()", dump_end)
|
||||
pump_end = text.index("\n#endif", pump_start)
|
||||
methods = text[dump_start:dump_end] + "\n" + text[pump_start:pump_end]
|
||||
if role == "simple_repeater":
|
||||
format_start = text.index("static void formatLocalSnrX4(")
|
||||
format_end = text.index("\nvoid MyMesh::formatRecentRepeatersReply", format_start)
|
||||
recent_start = text.index("void MyMesh::printRecentRepeatersSerial()")
|
||||
recent_end = text.index("\nbool MyMesh::setRecentRepeater(", recent_start)
|
||||
methods = text[format_start:format_end] + "\n" + text[recent_start:recent_end] + "\n" + methods
|
||||
program = HARNESS.replace("@METHODS@", methods).replace(
|
||||
"@RECENT_TEST@", RECENT_TEST if role == "simple_repeater" else ""
|
||||
)
|
||||
executable = Path(temporary) / ("pump.exe" if os.name == "nt" else "pump")
|
||||
build = subprocess.run(
|
||||
[compiler, "-std=c++17", "-O0", "-I", str(ROOT / "src"),
|
||||
"-x", "c++", "-", "-o", str(executable)],
|
||||
input=program, text=True, capture_output=True, timeout=60,
|
||||
)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
run = subprocess.run(
|
||||
[str(executable)], text=True, capture_output=True, timeout=30,
|
||||
)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the real USB facade against a stalled, 64-byte ESP32 CDC FIFO."""
|
||||
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / "test/fixtures/esp32_tinyusb_nonblocking"
|
||||
|
||||
|
||||
class Esp32TinyUsbNonblockingTest(unittest.TestCase):
|
||||
def test_native_fifo_and_other_role_fallback(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
self.skipTest("a host C++17 compiler is required")
|
||||
with tempfile.TemporaryDirectory(prefix=".tmp-usb-mode0-", dir=ROOT) as temporary:
|
||||
for mode, companion in ((0, False), (0, True), (1, False)):
|
||||
with self.subTest(usb_mode=mode, companion=companion):
|
||||
binary = Path(temporary) / f"usb-mode-{mode}-{companion}.exe"
|
||||
command = [
|
||||
compiler, "-std=c++17", "-DARDUINO=1", "-DESP32=1",
|
||||
"-DESP32_PLATFORM=1", "-DMESH_DEBUG=1",
|
||||
"-DARDUINO_USB_CDC_ON_BOOT=1", f"-DARDUINO_USB_MODE={mode}",
|
||||
f"-I{FIXTURE / 'mocks'}", f"-I{ROOT / 'src'}",
|
||||
str(FIXTURE / "test_esp32_tinyusb_nonblocking.cpp"),
|
||||
str(ROOT / "src/helpers/UsbLogging.cpp"),
|
||||
"-o", str(binary),
|
||||
]
|
||||
if companion:
|
||||
command.insert(1, "-DENABLE_USB_INTERFACE=1")
|
||||
built = subprocess.run(command, capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("transport checks passed", checked.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Keep native-TinyUSB repeater/room output away from blocking Arduino writes."""
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ROLES = ("simple_repeater", "simple_room_server")
|
||||
|
||||
|
||||
def source(relative: str) -> str:
|
||||
return (ROOT / relative).read_text()
|
||||
|
||||
|
||||
class Esp32TinyUsbRoleHygieneTest(unittest.TestCase):
|
||||
def test_console_helper_preserves_other_platform_semantics(self):
|
||||
text = source("src/helpers/UsbLogging.cpp")
|
||||
self.assertRegex(
|
||||
text,
|
||||
r"Stream& usbConsolePort\(\)\s*\{\s*"
|
||||
r"#if MESH_ESP32_TINYUSB_NONBLOCKING\s+"
|
||||
r"return buffered_esp32_tinyusb_terminal_port;\s+"
|
||||
r"#else\s+return Serial;\s+#endif",
|
||||
)
|
||||
|
||||
def test_role_output_never_bypasses_the_usb_facade(self):
|
||||
# A capacity check outside Serial.write() cannot make Arduino's
|
||||
# native USBCDC writer bounded. Cover direct writes and Print/Stream
|
||||
# references, including printHex's less obvious indirect writes.
|
||||
for role in ROLES:
|
||||
for filename in ("main.cpp", "MyMesh.cpp", "UITask.cpp"):
|
||||
relative = f"examples/{role}/{filename}"
|
||||
with self.subTest(path=relative):
|
||||
text = source(relative)
|
||||
self.assertNotRegex(
|
||||
text,
|
||||
r"\bSerial\s*\.\s*(?:print|println|printf|write|flush)\s*\(",
|
||||
)
|
||||
self.assertNotRegex(text, r"\bprintHex\s*\(\s*Serial\b")
|
||||
self.assertNotRegex(
|
||||
text,
|
||||
r"\b(?:Print|Stream)\s*&\s*\w+\s*=\s*Serial\b",
|
||||
)
|
||||
self.assertIn("mesh::usbConsolePort()", text)
|
||||
|
||||
def test_functional_replies_do_not_use_the_logging_gate(self):
|
||||
for role in ROLES:
|
||||
with self.subTest(role=role):
|
||||
text = source(f"examples/{role}/MyMesh.cpp")
|
||||
self.assertIn('mesh::usbConsolePort().printf("ACL:\\r\\n");', text)
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("%02X %s\\n", '
|
||||
"c->permissions, public_key);",
|
||||
text,
|
||||
)
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("OTA: starting update\\r\\n");',
|
||||
text,
|
||||
)
|
||||
self.assertIn('mesh::usbConsolePort().printf("%s\\r\\n", wc_reply);', text)
|
||||
start = text.index("void MyMesh::dumpLogFile()")
|
||||
end = text.index("bool MyMesh::setTxPower(", start)
|
||||
dump = text[start:end]
|
||||
self.assertIn("mesh::usbConsolePort().print((char)c);", dump)
|
||||
self.assertNotIn("isUsbLoggingEnabled", dump)
|
||||
self.assertNotIn("usbLoggingPort", dump)
|
||||
|
||||
repeater = source("examples/simple_repeater/MyMesh.cpp")
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("Recent repeaters (%d):\\n", count);',
|
||||
repeater,
|
||||
)
|
||||
self.assertIn('mesh::usbConsolePort().printf("%s\\r\\n", record);', repeater)
|
||||
|
||||
def test_unconditional_display_diagnostics_keep_their_visibility(self):
|
||||
for role in ROLES:
|
||||
with self.subTest(role=role):
|
||||
text = source(f"examples/{role}/UITask.cpp")
|
||||
self.assertIn("#include <helpers/UsbLogging.h>", text)
|
||||
self.assertIn("// Logged unconditionally:", text)
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("Display: flip %s\\n",',
|
||||
text,
|
||||
)
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("Display: %s -> %s\\n",',
|
||||
text,
|
||||
)
|
||||
self.assertIn(
|
||||
'mesh::usbConsolePort().printf("Powering Off\\r\\n");', text
|
||||
)
|
||||
|
||||
def test_both_roles_initialize_and_service_queued_terminal_output(self):
|
||||
for role in ROLES:
|
||||
with self.subTest(role=role):
|
||||
text = source(f"examples/{role}/main.cpp")
|
||||
setup = text[text.index("void setup()") : text.index("void loop()")]
|
||||
loop = text[text.index("void loop()") :]
|
||||
self.assertIn("mesh::beginUsbLoggingPort();", setup)
|
||||
self.assertIn("mesh::serviceUsbTerminalPort();", loop)
|
||||
|
||||
def test_sleep_keeps_raw_flush_only_for_other_esp32_transports(self):
|
||||
text = source("src/helpers/ESP32Board.cpp")
|
||||
sleep = text[text.index("void ESP32Board::enterDeepSleep(") :]
|
||||
guard = re.search(
|
||||
r"#if MESH_ESP32_TINYUSB_NONBLOCKING\s+"
|
||||
r"mesh::serviceUsbTerminalPort\(\);\s+"
|
||||
r"#else\s+Serial\.flush\(\);\s+#endif",
|
||||
sleep,
|
||||
)
|
||||
self.assertIsNotNone(guard)
|
||||
self.assertEqual(sleep.count("Serial.flush();"), 1)
|
||||
|
||||
def test_large_file_dumps_are_bounded_and_cancelable(self):
|
||||
for role in ROLES:
|
||||
with self.subTest(role=role):
|
||||
text = source(f"examples/{role}/MyMesh.cpp")
|
||||
header = source(f"examples/{role}/MyMesh.h")
|
||||
self.assertIn("char serial_log_pending[640];", header)
|
||||
self.assertIn("serial_log_active ? serial_log_dump.size() : 0", text)
|
||||
start = text.index("void MyMesh::servicePendingSerialOutput()")
|
||||
end = text.index("bool MyMesh::setTxPower(", start)
|
||||
service = text[start:end]
|
||||
self.assertIn("serial_log_pending_size < sizeof(serial_log_pending)", service)
|
||||
self.assertIn("--serial_log_remaining;", service)
|
||||
self.assertIn("serial_log_pending_size -= written;", service)
|
||||
self.assertIn("memmove(serial_log_pending", service)
|
||||
self.assertNotIn("delay(", service)
|
||||
self.assertNotIn("flush(", service)
|
||||
cancel = text[
|
||||
text.index("void MyMesh::cancelPendingSerialOutput()") : start
|
||||
]
|
||||
self.assertIn("serial_log_dump.close();", cancel)
|
||||
self.assertIn("serial_log_pending_size = 0;", cancel)
|
||||
loop = text[text.index("void MyMesh::loop()") :]
|
||||
self.assertLess(
|
||||
loop.index("mesh::Mesh::loop();"),
|
||||
loop.index("servicePendingSerialOutput();"),
|
||||
)
|
||||
|
||||
def test_recent_list_advances_only_after_whole_row_admission(self):
|
||||
text = source("examples/simple_repeater/MyMesh.cpp")
|
||||
start = text.index("void MyMesh::servicePendingSerialOutput()")
|
||||
service = text[start : text.index("if (!serial_log_active)", start)]
|
||||
self.assertIn("char record[64];", service)
|
||||
self.assertIn("serial_recent_next < serial_recent_count", service)
|
||||
self.assertIn("getNextRecentRepeaterBySortKey", service)
|
||||
self.assertNotIn("getRecentRepeaterBySortedIdx", service)
|
||||
self.assertNotRegex(service, r"\b(?:while|for)\s*\(")
|
||||
self.assertLess(
|
||||
service.index("console.availableForWrite() < length"),
|
||||
service.index("++serial_recent_next"),
|
||||
)
|
||||
self.assertIn("!= static_cast<size_t>(length)) return;", service)
|
||||
|
||||
def test_functional_reserve_fits_default_full_acl_plus_command_echo(self):
|
||||
logging = source("src/helpers/UsbLogging.cpp")
|
||||
reserve = int(re.search(
|
||||
r"esp32_tinyusb_functional_reserve\s*=\s*(\d+)", logging
|
||||
).group(1))
|
||||
acl = source("src/helpers/ClientACL.h")
|
||||
clients = int(re.search(r"#define MAX_CLIENTS\s+(\d+)", acl).group(1))
|
||||
acl_bytes = len("ACL:\r\n") + clients * (2 + 1 + 64 + 1)
|
||||
self.assertGreaterEqual(reserve, acl_bytes + len("get acl\r\n") + 160)
|
||||
|
||||
def test_file_eof_and_malformed_line_marker_are_deferred(self):
|
||||
for role in ROLES:
|
||||
with self.subTest(role=role):
|
||||
text = source(f"examples/{role}/MyMesh.cpp")
|
||||
self.assertIn('strcmp(reply, " EOF") == 0) reply[0] = 0;', text)
|
||||
self.assertIn('static const char eof[] = " -> EOF\\r\\n";', text)
|
||||
self.assertIn("if (!serial_log_active) {", text)
|
||||
self.assertIn("serial_log_eof_pending = false;", text)
|
||||
self.assertIn("while (budget-- > 0 && serial_log_remaining > 0)", text)
|
||||
self.assertIn("[USB log line omitted: exceeds 640 bytes]", text)
|
||||
self.assertIn("if (serial_log_skip_line) return;", text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -347,6 +347,76 @@ TEST(SimpleMeshTables, ExpirationKeepsOccupiedEntriesPacked) {
|
||||
EXPECT_EQ(0, storage[3].prefix_len);
|
||||
}
|
||||
|
||||
TEST(SimpleMeshTables, CooperativeRecentCursorMatchesUnchangedRankOrder) {
|
||||
SimpleMeshTables::RecentRepeaterInfo storage[8];
|
||||
SimpleMeshTables t(storage, 8);
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
const uint8_t prefix[] = {static_cast<uint8_t>(0x10 + i), 0x22, 0x33};
|
||||
ASSERT_TRUE(t.setRecentRepeater(prefix, 1 + i % 3, (i / 2) * 4));
|
||||
}
|
||||
SimpleMeshTables::RecentRepeaterInfo cursor{};
|
||||
int cursor_index = -1;
|
||||
for (int rank = 0; rank < 8; ++rank) {
|
||||
int found_index = -1;
|
||||
const auto* found = t.getNextRecentRepeaterBySortKey(
|
||||
rank == 0 ? nullptr : &cursor, cursor_index, found_index);
|
||||
ASSERT_NE(nullptr, found);
|
||||
EXPECT_EQ(t.getRecentRepeaterBySortedIdx(rank), found);
|
||||
cursor = *found;
|
||||
cursor_index = found_index;
|
||||
}
|
||||
int found_index = 123;
|
||||
EXPECT_EQ(nullptr, t.getNextRecentRepeaterBySortKey(&cursor, cursor_index, found_index));
|
||||
EXPECT_EQ(-1, found_index);
|
||||
}
|
||||
|
||||
TEST(SimpleMeshTables, CooperativeRecentCursorSurvivesLiveStorageCompaction) {
|
||||
SimpleMeshTables::RecentRepeaterInfo storage[3];
|
||||
SimpleMeshTables t(storage, 3);
|
||||
const uint8_t first[] = {0x10};
|
||||
const uint8_t second[] = {0x20};
|
||||
const uint8_t third[] = {0x30};
|
||||
ASSERT_TRUE(t.setRecentRepeater(first, 1, 12));
|
||||
ASSERT_TRUE(t.setRecentRepeater(second, 1, 8));
|
||||
ASSERT_TRUE(t.setRecentRepeater(third, 1, 4));
|
||||
int cursor_index = -1;
|
||||
const auto* first_row = t.getNextRecentRepeaterBySortKey(nullptr, -1, cursor_index);
|
||||
ASSERT_NE(nullptr, first_row);
|
||||
const auto cursor = *first_row;
|
||||
storage[0].last_heard_millis = 0;
|
||||
storage[1].last_heard_millis = 100;
|
||||
storage[2].last_heard_millis = 100;
|
||||
ASSERT_EQ(1, t.expireRecentRepeaters(101, 50));
|
||||
int next_index = -1;
|
||||
const auto* next = t.getNextRecentRepeaterBySortKey(&cursor, cursor_index, next_index);
|
||||
ASSERT_NE(nullptr, next);
|
||||
EXPECT_EQ(0x20, next->prefix[0]);
|
||||
EXPECT_EQ(0x10, cursor.prefix[0]);
|
||||
}
|
||||
|
||||
TEST(SimpleMeshTables, CooperativeRecentCursorTraverses2048Rows) {
|
||||
SimpleMeshTables::RecentRepeaterInfo storage[2048];
|
||||
SimpleMeshTables t(storage, 2048);
|
||||
for (int i = 0; i < 2048; ++i) {
|
||||
const uint8_t prefix[] = {0x80, static_cast<uint8_t>(i >> 8),
|
||||
static_cast<uint8_t>(i)};
|
||||
ASSERT_TRUE(t.setRecentRepeater(prefix, 3, 4));
|
||||
}
|
||||
SimpleMeshTables::RecentRepeaterInfo cursor{};
|
||||
int cursor_index = -1;
|
||||
for (int i = 0; i < 2048; ++i) {
|
||||
int found_index = -1;
|
||||
const auto* found = t.getNextRecentRepeaterBySortKey(
|
||||
i == 0 ? nullptr : &cursor, cursor_index, found_index);
|
||||
ASSERT_NE(nullptr, found);
|
||||
EXPECT_EQ(static_cast<uint8_t>(i >> 8), found->prefix[1]);
|
||||
EXPECT_EQ(static_cast<uint8_t>(i), found->prefix[2]);
|
||||
cursor = *found;
|
||||
cursor_index = found_index;
|
||||
}
|
||||
EXPECT_EQ(nullptr, t.getNextRecentRepeaterBySortKey(&cursor, cursor_index, cursor_index));
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Execute production file readers against SPIFFS-style phantom directories."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def section(path, start, end):
|
||||
text = (ROOT / path).read_text(encoding="utf-8")
|
||||
begin = text.index(start)
|
||||
return text[begin:text.index(end, begin)]
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <helpers/FileRead.h>
|
||||
#define FILE_O_READ 0
|
||||
static void check(bool ok, const char* why) {
|
||||
if (!ok) throw std::runtime_error(why);
|
||||
}
|
||||
struct Entry { std::string text; bool directory = false; };
|
||||
struct FakeFS;
|
||||
struct File {
|
||||
std::shared_ptr<Entry> entry;
|
||||
size_t position = 0;
|
||||
FakeFS* owner = nullptr;
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
// Actual Adafruit LittleFS requires an owner even for a closed File.
|
||||
File() = delete;
|
||||
#else
|
||||
File() = default;
|
||||
#endif
|
||||
explicit File(FakeFS& fs) : owner(&fs) {}
|
||||
File(FakeFS& fs, std::shared_ptr<Entry> data) : entry(data), owner(&fs) {}
|
||||
explicit operator bool() const { return bool(entry); }
|
||||
bool isDirectory() const { return entry && entry->directory; }
|
||||
size_t size() const { return entry && !isDirectory() ? entry->text.size() : 0; }
|
||||
size_t available() const { return size() - position; }
|
||||
size_t read(uint8_t* dest, size_t count) {
|
||||
if (!entry || isDirectory()) return 0;
|
||||
count = std::min(count, available());
|
||||
memcpy(dest, entry->text.data() + position, count);
|
||||
position += count;
|
||||
return count;
|
||||
}
|
||||
void close() { entry.reset(); }
|
||||
};
|
||||
struct FakeFS {
|
||||
std::map<std::string, std::shared_ptr<Entry>> entries;
|
||||
bool fail_open = false;
|
||||
bool report_directory_exists = false;
|
||||
unsigned missing_opens = 0;
|
||||
unsigned open_calls = 0;
|
||||
bool exists(const char* path) {
|
||||
auto it = entries.find(path);
|
||||
return it != entries.end() &&
|
||||
(!it->second->directory || report_directory_exists);
|
||||
}
|
||||
File fixtureOpen(const char* path) {
|
||||
++open_calls;
|
||||
if (fail_open) return File(*this);
|
||||
auto it = entries.find(path);
|
||||
if (it != entries.end()) return File(*this, it->second);
|
||||
++missing_opens;
|
||||
return File(*this, std::make_shared<Entry>(Entry{"", true}));
|
||||
}
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
File open(const char* path, uint8_t = FILE_O_READ) { return fixtureOpen(path); }
|
||||
#elif defined(RP2040_PLATFORM)
|
||||
// Philhower FS requires the mode argument, unlike Arduino ESP32.
|
||||
File open(const char* path, const char*) { return fixtureOpen(path); }
|
||||
#else
|
||||
File open(const char* path, const char* = "r", bool = false) { return fixtureOpen(path); }
|
||||
#endif
|
||||
void put(const char* path, const std::string& content, bool directory = false) {
|
||||
entries[path] = std::make_shared<Entry>(Entry{content, directory});
|
||||
}
|
||||
} SPIFFS;
|
||||
FakeFS InternalFS;
|
||||
using FILESYSTEM = FakeFS;
|
||||
class DataStore {
|
||||
public:
|
||||
FILESYSTEM* _fs;
|
||||
explicit DataStore(FILESYSTEM* fs) : _fs(fs) {}
|
||||
File openRead(const char*);
|
||||
File openRead(FILESYSTEM*, const char*);
|
||||
File openDirectory(const char*);
|
||||
File openDirectory(FILESYSTEM*, const char*);
|
||||
};
|
||||
@DATASTORE@
|
||||
struct WiFiClient {
|
||||
std::string output;
|
||||
bool connected() const { return true; }
|
||||
size_t write(const uint8_t* data, size_t size) {
|
||||
output.append(reinterpret_cast<const char*>(data), size);
|
||||
return size;
|
||||
}
|
||||
void printf(const char* format, ...) {
|
||||
char buffer[512];
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
int size = vsnprintf(buffer, sizeof(buffer), format, args);
|
||||
va_end(args);
|
||||
check(size >= 0 && static_cast<size_t>(size) < sizeof(buffer), "HTTP overflow");
|
||||
output.append(buffer, size);
|
||||
}
|
||||
};
|
||||
struct LogServer {
|
||||
bool running = true;
|
||||
@RESPONSE@
|
||||
@SENDLOG@
|
||||
};
|
||||
@FLOOD_VERIFY@
|
||||
int main() {
|
||||
try {
|
||||
FakeFS fs;
|
||||
DataStore store(&fs);
|
||||
File unopened = mesh::emptyFile(&fs);
|
||||
File unavailable = mesh::emptyFile(static_cast<FILESYSTEM*>(nullptr));
|
||||
check(!unopened && !unavailable, "empty helper returned an open file");
|
||||
check(fs.open_calls == 0 && InternalFS.open_calls == 0,
|
||||
"closed file construction must never access either filesystem");
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
check(unopened.owner == &fs, "closed LittleFS file lost its selected owner");
|
||||
check(unavailable.owner == &InternalFS, "null filesystem lacks a valid fallback owner");
|
||||
#endif
|
||||
File phantom = fs.fixtureOpen("/missing");
|
||||
check(bool(phantom) && phantom.isDirectory(), "fixture must reproduce SPIFFS");
|
||||
unsigned before = fs.missing_opens;
|
||||
check(!store.openRead("/missing"), "missing file accepted");
|
||||
check(fs.missing_opens == before, "missing regular file should not be opened");
|
||||
check(!store.openRead(nullptr, "/file"), "unavailable FS accepted");
|
||||
check(!store.openRead(nullptr), "null path accepted");
|
||||
check(!store.openDirectory(nullptr, "/"), "unavailable directory FS accepted");
|
||||
check(!store.openDirectory(nullptr), "null directory path accepted");
|
||||
fs.put("/empty", "");
|
||||
fs.put("/real", "data");
|
||||
check(bool(store.openRead("/empty")), "real empty file rejected");
|
||||
File real = store.openRead("/real");
|
||||
uint8_t bytes[4];
|
||||
check(real.read(bytes, sizeof(bytes)) == 4 && memcmp(bytes, "data", 4) == 0,
|
||||
"real file changed");
|
||||
check(!store.openDirectory("/real"), "regular file accepted as directory");
|
||||
check(store.openDirectory("/").isDirectory(), "SPIFFS root listing broken");
|
||||
fs.put("/directory", "", true);
|
||||
fs.report_directory_exists = true;
|
||||
check(!store.openRead("/directory"), "directory accepted when exists is true");
|
||||
check(store.openDirectory("/directory").isDirectory(), "real listing broken");
|
||||
fs.fail_open = true;
|
||||
check(!store.openRead("/real"), "failed read-open accepted");
|
||||
fs.fail_open = false;
|
||||
// Empty expected images must not validate a missing file/directory as data.
|
||||
check(!verifyFloodSettingsWrite(&fs, "/missing", 0, 2166136261UL),
|
||||
"missing flood file passed empty verification");
|
||||
check(!verifyFloodSettingsWrite(&fs, "/directory", 0, 2166136261UL),
|
||||
"directory passed empty verification");
|
||||
check(verifyFloodSettingsWrite(&fs, "/empty", 0, 2166136261UL),
|
||||
"real empty image should verify");
|
||||
check(verifyFloodSettingsWrite(&fs, "/real", 4,
|
||||
updateFloodSettingsHash(2166136261UL, reinterpret_cast<const uint8_t*>("data"), 4)),
|
||||
"valid flood image rejected");
|
||||
LogServer server;
|
||||
WiFiClient missing;
|
||||
server.sendLog(missing);
|
||||
check(missing.output.find("HTTP/1.1 404 Not Found\r\n") == 0,
|
||||
"missing packet log must return HTTP404");
|
||||
SPIFFS.put("/packet_log", "");
|
||||
WiFiClient empty;
|
||||
server.sendLog(empty);
|
||||
check(empty.output.find("HTTP/1.1 200 OK\r\n") == 0 &&
|
||||
empty.output.find("Content-Length: 0\r\n") != std::string::npos,
|
||||
"existing empty packet log must remain HTTP200");
|
||||
SPIFFS.put("/packet_log", "packet\n");
|
||||
WiFiClient log;
|
||||
server.sendLog(log);
|
||||
check(log.output.find("Content-Length: 7\r\n") != std::string::npos &&
|
||||
log.output.substr(log.output.size() - 7) == "packet\n", "log download changed");
|
||||
SPIFFS.put("/packet_log", "", true);
|
||||
SPIFFS.report_directory_exists = true;
|
||||
WiFiClient directory;
|
||||
server.sendLog(directory);
|
||||
check(directory.output.find("HTTP/1.1 404 Not Found\r\n") == 0,
|
||||
"directory log must return HTTP404");
|
||||
std::cout << "regular-file readers: PASS\n";
|
||||
return 0;
|
||||
} catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class RegularFileReadTest(unittest.TestCase):
|
||||
def test_production_readers(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
self.skipTest("A host C++ compiler is required")
|
||||
program = HARNESS.replace("@DATASTORE@", section(
|
||||
"examples/companion_radio/DataStore.cpp", "File DataStore::openRead(",
|
||||
"bool DataStore::removeFile("))
|
||||
program = program.replace("@RESPONSE@", section(
|
||||
"src/helpers/ESP32Board.cpp", " static void sendResponse(", " bool readLine("))
|
||||
program = program.replace("@SENDLOG@", section(
|
||||
"src/helpers/ESP32Board.cpp", " void sendLog(", " void sendUpdateError("))
|
||||
read_helper = section("examples/simple_repeater/MyMesh.cpp",
|
||||
"static File openFloodSettingsRead(",
|
||||
"static File openFloodSettingsWrite(")
|
||||
verification = section("examples/simple_repeater/MyMesh.cpp",
|
||||
"static uint32_t updateFloodSettingsHash(",
|
||||
"static uint8_t batteryPercentFromMilliVolts(")
|
||||
program = program.replace("@FLOOD_VERIFY@", read_helper + verification)
|
||||
for platform in ("ESP32_PLATFORM", "NRF52_PLATFORM", "RP2040_PLATFORM", "STM32_PLATFORM"):
|
||||
with self.subTest(platform=platform), tempfile.TemporaryDirectory() as tmp:
|
||||
executable = Path(tmp) / ("readers.exe" if os.name == "nt" else "readers")
|
||||
built = subprocess.run(
|
||||
[compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", "-O0",
|
||||
f"-D{platform}", "-I", str(ROOT / "test/fixtures/regular_file_reads"),
|
||||
"-I", str(ROOT / "src"), "-x", "c++", "-",
|
||||
"-o", str(executable)],
|
||||
input=program, text=True, capture_output=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
run = subprocess.run([str(executable)], capture_output=True, text=True, timeout=15)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
def test_directory_listing_uses_explicit_directory_api(self):
|
||||
cli = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
self.assertIn("File root = _store->openDirectory(path);", cli)
|
||||
self.assertIn("File root2 = _store->openDirectory(_store->getSecondaryFS(), path);", cli)
|
||||
self.assertIn("File file = _store->openRead(selected_fs, path);", cli)
|
||||
|
||||
def test_audited_read_helpers_remain_regular_file_only(self):
|
||||
for path, marker, end in (
|
||||
("src/helpers/ClientACL.cpp", "static File openRead(", "#if !defined(NRF52_PLATFORM)"),
|
||||
("examples/simple_room_server/FloodRuleEngine.cpp", "static File openRead(", "static File openWrite("),
|
||||
):
|
||||
with self.subTest(path=path):
|
||||
self.assertIn("mesh::openFileRead(", section(path, marker, end))
|
||||
for role in ("simple_repeater", "simple_room_server"):
|
||||
dump = section(f"examples/{role}/MyMesh.cpp", "void MyMesh::dumpLogFile()",
|
||||
"bool MyMesh::hasPendingSerialOutput()")
|
||||
self.assertEqual(dump.count("mesh::openFileRead(_fs, PACKET_LOG_FILE)"), 2)
|
||||
self.assertNotIn("_fs->open(", dump)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Native, hardware-free tests of replay-reset parsing and one-use challenges."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ReplayResetCommandTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest("a host C++ compiler is required")
|
||||
cls.directory = tempfile.TemporaryDirectory(prefix="mesh-replay-reset-")
|
||||
cls.addClassCleanup(cls.directory.cleanup)
|
||||
cls.executable = Path(cls.directory.name) / (
|
||||
"replay-reset.exe" if os.name == "nt" else "replay-reset"
|
||||
)
|
||||
subprocess.run(
|
||||
[compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", "-pedantic",
|
||||
"-I", str(ROOT / "src"),
|
||||
str(ROOT / "test/fixtures/replay_reset_command/main.cpp"),
|
||||
"-o", str(cls.executable)],
|
||||
check=True,
|
||||
)
|
||||
|
||||
def run_case(self, name):
|
||||
subprocess.run([str(self.executable), name], check=True)
|
||||
|
||||
def test_strict_parser_and_family_classification(self):
|
||||
self.run_case("parser")
|
||||
|
||||
def test_one_use_identity_bound_lifecycle(self):
|
||||
self.run_case("lifecycle")
|
||||
|
||||
def test_expiration_rollover_and_clock_changes(self):
|
||||
self.run_case("time")
|
||||
|
||||
def test_invalid_arguments_and_complete_binding(self):
|
||||
self.run_case("invalid")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the production replay-reset handler and verify its transport wiring."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
FIXTURE = ROOT / "test/fixtures/replay_reset_integration"
|
||||
SOURCE = ROOT / "examples/simple_repeater/MyMesh.cpp"
|
||||
HEADER = ROOT / "examples/simple_repeater/MyMesh.h"
|
||||
MAIN = ROOT / "examples/simple_repeater/main.cpp"
|
||||
|
||||
|
||||
def extract_braced(source, signature):
|
||||
"""Return an actual C++ definition/block, ignoring quoted/comment braces."""
|
||||
start = source.index(signature)
|
||||
opening = source.index("{", start)
|
||||
depth = 0
|
||||
token = re.compile(r'//[^\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|[{}]')
|
||||
for match in token.finditer(source, opening):
|
||||
if match.group() == "{":
|
||||
depth += 1
|
||||
elif match.group() == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start:match.end()]
|
||||
raise AssertionError(f"unterminated C++ block: {signature}")
|
||||
|
||||
|
||||
class ReplayResetIntegrationTest(unittest.TestCase):
|
||||
def test_executable_production_handler(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
self.skipTest("a host C++17 compiler is required")
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
handler = extract_braced(source, "bool MyMesh::handleReplayResetCommand(")
|
||||
epoch_check = extract_braced(source, "static bool clockSyncEpochIsValid(")
|
||||
guard = extract_braced(source, "if (!replay_command && sender_timestamp > client->last_timestamp)")
|
||||
prepare = re.search(r"const bool replay_prepare\s*=[\s\S]*?;", source).group()
|
||||
cache_gate = re.search(r"const bool cached_retry\s*=\s*!replay_prepare[\s\S]*?;", source).group()
|
||||
generated = epoch_check + "\n" + handler + "\n" + """
|
||||
static void apply_actual_receive_guard(ClientInfo* client, const char* command,
|
||||
uint32_t sender_timestamp) {
|
||||
mesh::ReplayResetRequest replay_request;
|
||||
const bool replay_command = mesh::parseReplayResetCommand(command, replay_request)
|
||||
!= mesh::ReplayResetKind::NotReplay;
|
||||
""" + guard + "\n}\n" + """
|
||||
static bool apply_actual_receive_cache_gate(const char* command, bool cache_hit,
|
||||
int& lookup_calls) {
|
||||
mesh::ReplayResetRequest replay_request;
|
||||
mesh::parseReplayResetCommand(command, replay_request);
|
||||
ClientInfo sender;
|
||||
ClientInfo* client = &sender;
|
||||
uint32_t request_id = 1, command_fingerprint = 2;
|
||||
const char* cached_response = nullptr;
|
||||
CountingReplyCache remote_cli_reply_cache{cache_hit, lookup_calls};
|
||||
""" + prepare + "\n" + cache_gate + "\nreturn cached_retry;\n}\n"
|
||||
with tempfile.TemporaryDirectory(prefix=".tmp-replay-integration-", dir=ROOT) as directory:
|
||||
work = Path(directory)
|
||||
(work / "production_handler.inc").write_text(generated, encoding="utf-8")
|
||||
binary = work / "replay-reset-integration.exe"
|
||||
compiled = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
f"-I{work}", f"-I{ROOT / 'src'}",
|
||||
str(FIXTURE / "test_replay_reset_integration.cpp"), "-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(compiled.returncode, 0, compiled.stdout + compiled.stderr)
|
||||
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("18 replay-reset integration checks passed", checked.stdout)
|
||||
self.assertEqual(checked.stdout.count("PASS:"), 18)
|
||||
|
||||
def test_only_physical_console_grants_usb_origin(self):
|
||||
header = HEADER.read_text(encoding="utf-8")
|
||||
main = MAIN.read_text(encoding="utf-8")
|
||||
self.assertIn("bool usb_origin = false", header)
|
||||
usb = extract_braced(header, "void handleUsbCommand(")
|
||||
self.assertIn("handleCommand(0, NULL, command, reply, -1, 1, true)", usb)
|
||||
null_sender = extract_braced(header, "void handleCommand(uint32_t sender_timestamp, char* command, char* reply)")
|
||||
self.assertIn("handleCommand(sender_timestamp, NULL, command, reply)", null_sender)
|
||||
console_start = main.index("if (line_complete)")
|
||||
ethernet_start = main.index("if (ethernet_read_line(", console_start)
|
||||
self.assertIn("the_mesh.handleUsbCommand(command, reply)", main[console_start:ethernet_start])
|
||||
ethernet = extract_braced(main, "if (ethernet_read_line(")
|
||||
self.assertNotIn("handleUsbCommand", ethernet)
|
||||
self.assertIn("the_mesh.handleCommand(0, ethernet_command, reply)", ethernet)
|
||||
# No web/internal callback is allowed to adopt the physical entry point.
|
||||
cpp = SOURCE.read_text(encoding="utf-8")
|
||||
self.assertNotIn("handleUsbCommand(", cpp)
|
||||
|
||||
def test_receiver_keeps_authentication_and_blocks_replay_floor_mutation(self):
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
cli_start = source.index("else if (type == PAYLOAD_TYPE_TXT_MSG && len > 5")
|
||||
cli_end = source.index("void MyMesh::", cli_start)
|
||||
cli = source[cli_start:cli_end]
|
||||
self.assertIn("client->isAdmin() || client->isRegionMgr() || client->isFilterMgr()", cli)
|
||||
parser = cli.index("mesh::parseReplayResetCommand(command, replay_request)")
|
||||
stale = cli.index("sender_timestamp < client->last_timestamp && !cached_retry")
|
||||
assignment = cli.index("client->last_timestamp = sender_timestamp;")
|
||||
self.assertLess(parser, stale)
|
||||
self.assertLess(stale, assignment)
|
||||
guarded = extract_braced(cli, "if (!replay_command && sender_timestamp > client->last_timestamp)")
|
||||
self.assertIn("client->last_timestamp = sender_timestamp;", guarded)
|
||||
self.assertEqual(cli.count("client->last_timestamp = sender_timestamp;"), 1)
|
||||
self.assertIn("const bool replay_prepare = replay_request.kind == mesh::ReplayResetKind::ExactKey;", cli)
|
||||
self.assertRegex(cli, r"const bool cached_retry\s*=\s*!replay_prepare\s*&&\s*remote_cli_reply_cache\.lookup\(")
|
||||
self.assertLess(cli.index("const bool cached_retry"), stale)
|
||||
handler = extract_braced(source, "bool MyMesh::handleReplayResetCommand(")
|
||||
self.assertNotIn("remote_cli_reply_cache.clear", handler)
|
||||
self.assertLess(handler.index("replay_reset_nonce.consume("),
|
||||
handler.index("acl.clampLoginReplayTimestamps("))
|
||||
|
||||
def test_recovery_dispatch_precedes_other_command_handlers(self):
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
handler = extract_braced(source, "void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender,")
|
||||
recovery = handler.index("handleReplayResetCommand(sender, command, reply, usb_origin)")
|
||||
self.assertLess(recovery, handler.index("_cli.handleCommand("))
|
||||
self.assertNotIn("sender_timestamp == 0", handler[:recovery])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user