Improve room retention, moderation and local browser access

Add opt-in bounded chat history, persist explicit room ACL roles, enforce full-key bans and per-user quotas, and provide versioned information-board reads plus an ESP32 local room page. Preserve stored evidence on faults and withhold room delivery acknowledgments when a Companion cannot retain the message.

Exercise production handlers and filesystem fault recovery, pinned official-app JavaScript, real Chromium interactions, and representative ESP32, nRF52, RP2040 and STM32 builds. Add regression suites and bounded browser-workspace RAM reservations to CI.
This commit is contained in:
mikecarper committed 2026-10-09 23:44:00 -07:00
1 parent b6b6b4eaaa
commit 74bc91bf69
61 files changed
+6993 -91

No files matched your search

@@ -3,6 +3,9 @@
#include <cstring>
#include <iostream>
#include <vector>
#include "filesystem.h"
#include <helpers/RoomAccessPolicy.h>
#include <helpers/LogicalMessageCache.h>
#include <helpers/ClientACLResponse.h>
#include <helpers/RoutingPolicy.h>
@@ -87,11 +90,13 @@ struct RegionMap {
struct ClientInfo {
mesh::Identity id;
uint8_t permissions = 3;
bool permissions_are_explicit = false;
uint8_t out_path_len = 0, out_path[MAX_PATH_SIZE] = {};
uint32_t last_timestamp = 0, last_activity = 0;
struct { struct {
uint32_t sync_since = 0, pending_ack = 0, pending_topic_revision = 0;
uint8_t push_failures = 0;
uint16_t poll_quota_used = 0, post_quota_used = 0;
} room; } extra;
bool isAdmin() const { return (permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_ADMIN; }
};
@@ -106,6 +111,7 @@ struct Clock : mesh::RTCClock {
};
#ifdef TEST_SENSOR
#define TARGET_CLASS SensorMesh
struct MetadataFixtureUse { MetadataFixtureUse() { (void)metadata_filesystem; } } metadata_fixture_use;
#else
#define TARGET_CLASS MyMesh
#endif
@@ -130,6 +136,12 @@ public:
int handleRequest(ClientInfo*, uint32_t, uint8_t*, size_t,
size_t = mesh::CLIENT_ACL_DIRECT_REPLY_CAPACITY);
int telemetryPrefix(uint8_t*, size_t);
MemoryFS fs;
mesh::RoomAccessPolicy room_access;
mesh::LogicalMessageCache<8> recent_room_polls;
TARGET_CLASS() { metadata_filesystem = &fs; assert(room_access.load(&fs)); }
static bool saveFilter(ClientInfo*);
void serviceRoomQuotas() { room_access.serviceQuotaWindow(0, [] {}); }
#endif
void receive(mesh::Packet*, uint8_t*, size_t);
bool admit(mesh::Packet* packet) {
@@ -16,7 +16,7 @@ struct WirePresentation {
int app_target_ver;
uint8_t out_frame[MAX_FRAME_SIZE] = {};
std::vector<uint8_t> frame;
void queueMessage(const RoomContact&, uint8_t, CompanionPacket*, uint32_t,
bool queueMessage(const RoomContact&, uint8_t, CompanionPacket*, uint32_t,
const uint8_t*, int, const char*, bool, uint32_t);
};
#include "presentation.inc"
+308
View File
@@ -0,0 +1,308 @@
// The production methods, plain-post gate, RTCClock and PostInfo are extracted
// unchanged. Only filesystem faults, radio ACK observation and identity hashing
// are host boundaries; the actual history store, quota and replay cache run here.
#include "../room_history_store/filesystem.h"
#include <helpers/RoomHistoryStore.h>
#include <helpers/RoomAccessPolicy.h>
#include <helpers/LogicalMessageCache.h>
#define PUB_KEY_SIZE 32
#define MAX_POST_TEXT_LEN 151
#define MAX_UNSYNCED_POSTS 32
#define MAX_HASH_SIZE 8
#define POST_SYNC_DELAY_SECS 6
#define PUSH_NOTIFY_DELAY_MILLIS 2000
#define TXT_TYPE_PLAIN 0
#undef MESH_DEBUG_PRINTLN
#define MESH_DEBUG_PRINTLN(...) ((void)0)
static uint32_t ticks = 100;
static unsigned long futureMillis(unsigned long delay) { return uint32_t(ticks + delay); }
namespace mesh {
struct Identity { uint8_t pub_key[32] = {}; };
struct Utils {
static void sha256(uint8_t* out, size_t size, const uint8_t* key, size_t key_size,
const uint8_t* text, size_t text_size) {
uint64_t value = UINT64_C(14695981039346656037);
for (size_t i = 0; i < key_size; ++i) value = (value ^ key[i]) * UINT64_C(1099511628211);
for (size_t i = 0; i < text_size; ++i) value = (value ^ text[i]) * UINT64_C(1099511628211);
for (size_t i = 0; i < size; ++i) out[i] = uint8_t(value >> (8 * (i % 8)));
}
};
}
#include "state.inc"
struct StrHelper { static void strncpy(char*, const char*, size_t); };
struct Clock : mesh::RTCClock {
uint32_t now = 1000;
unsigned set_calls = 0;
uint32_t getCurrentTime() override { return now; }
void setCurrentTime(uint32_t value) override { now = value; ++set_calls; }
};
struct ClientInfo {
mesh::Identity id;
uint8_t permissions = PERM_ACL_READ_WRITE;
struct { struct { uint32_t last_post_timestamp = 0; uint16_t post_quota_used = 0; } room; } extra;
ClientInfo() { id.pub_key[0] = 1; }
};
struct MyMesh {
MemoryFS* _fs;
Clock clock;
mesh::Identity self_id;
mesh::RoomAccessPolicy room_access;
mesh::LogicalMessageCache<8> recent_room_posts;
ClientInfo* active = nullptr;
PostInfo posts[MAX_UNSYNCED_POSTS] = {};
uint32_t post_ready_at[MAX_UNSYNCED_POSTS] = {}, post_ready_mask = UINT32_MAX;
uint32_t last_room_timestamp = 0;
mesh::RoomHistoryState room_history_state;
bool room_history_enabled = false, room_history_available = true;
int next_post_idx = 0;
unsigned long next_push = 0;
uint16_t _num_posted = 0;
unsigned acks = 0;
explicit MyMesh(MemoryFS* fs) : _fs(fs) {
metadata_filesystem = fs;
self_id.pub_key[0] = 77;
if (fs) assert(room_access.load(fs));
}
Clock* getRTCClock() { return &clock; }
bool addPost(ClientInfo*, const char*);
bool addSystemPost(const char*);
bool storePost(const mesh::Identity&, const char*);
bool snapshotRoomHistory();
void loadRoomHistory();
bool handleRoomHistoryCommand(const char*, char*);
void serviceRoomQuotas() {
room_access.serviceQuotaWindow(ticks, [this] { active->extra.room.post_quota_used = 0; });
}
void receive(ClientInfo* client, const char* text, uint32_t sender_timestamp) {
active = client;
const uint8_t flags = TXT_TYPE_PLAIN;
const size_t text_len = strlen(text);
bool send_ack = false;
#include "post_gate.inc"
if (send_ack) ++acks;
}
std::string command(const char* command) {
char reply[160] = {};
assert(handleRoomHistoryCommand(command, reply));
return reply;
}
std::vector<std::string> retained() const {
std::vector<std::string> result;
for (int k = 0, idx = next_post_idx; k < MAX_UNSYNCED_POSTS;
++k, idx = (idx + 1) % MAX_UNSYNCED_POSTS) {
if (posts[idx].post_timestamp) result.emplace_back(posts[idx].text);
}
return result;
}
};
#include "production.inc"
struct AdmissionState {
std::vector<std::string> text;
uint32_t floor, mask, ready[32], timestamps[32];
int index;
unsigned long next;
uint16_t stats, quota;
uint32_t replay;
unsigned acks;
AdmissionState(const MyMesh& m, const ClientInfo& c)
: text(m.retained()), floor(m.last_room_timestamp), mask(m.post_ready_mask),
index(m.next_post_idx), next(m.next_push), stats(m._num_posted),
quota(c.extra.room.post_quota_used), replay(c.extra.room.last_post_timestamp), acks(m.acks) {
memcpy(ready, m.post_ready_at, sizeof(ready));
for (unsigned i = 0; i < 32; ++i) timestamps[i] = m.posts[i].post_timestamp;
}
void unchanged(const MyMesh& m, const ClientInfo& c) const {
assert(text == m.retained() && floor == m.last_room_timestamp && mask == m.post_ready_mask);
assert(index == m.next_post_idx && next == m.next_push && stats == m._num_posted);
assert(quota == c.extra.room.post_quota_used && replay == c.extra.room.last_post_timestamp);
assert(acks == m.acks && memcmp(ready, m.post_ready_at, sizeof(ready)) == 0);
for (unsigned i = 0; i < 32; ++i) assert(timestamps[i] == m.posts[i].post_timestamp);
}
};
static void compareBoot(MemoryFS& fs, const MyMesh& running) {
const auto text = running.retained();
const uint32_t floor = running.last_room_timestamp;
MyMesh boot(&fs); boot.clock.now = 5; boot.loadRoomHistory();
assert(boot.room_history_available && boot.room_history_enabled);
assert(boot.retained() == text && boot.last_room_timestamp == floor);
assert(boot.clock.now == 5 && boot.clock.set_calls == 0 && boot.post_ready_mask == UINT32_MAX);
assert(boot._num_posted == 0);
}
int main() {
unsigned cases = 0;
{
MemoryFS fs; MyMesh m(&fs); m.loadRoomHistory();
assert(!m.room_history_enabled && m.room_history_available && m.retained().empty());
for (unsigned i = 0; i < 40; ++i) assert(m.addSystemPost(("volatile-" + std::to_string(i)).c_str()));
assert(!fs.files.count(mesh::ROOM_HISTORY_PATH) && fs.write_opens == 0);
assert(m.retained().size() == 32 && m.retained().front() == "volatile-8");
assert(m.command("set room.history on").find("enabled") != std::string::npos);
assert(m.room_history_enabled && m.room_history_state.count == 32 && m.room_history_state.total_records == 32);
compareBoot(fs, m);
for (unsigned i = 0; i < 180; ++i) {
assert(m.addSystemPost(("durable-" + std::to_string(i)).c_str()));
assert(m.room_history_state.count == 32 && m.room_history_state.total_records <= 64);
assert(fs.get(mesh::ROOM_HISTORY_PATH).size() <= mesh::ROOM_HISTORY_MAX_FILE_SIZE);
if (i % 13 == 0) compareBoot(fs, m);
++cases;
}
compareBoot(fs, m);
assert(m.retained().front() == "durable-148" && m.retained().back() == "durable-179");
assert(m.command("get room.history") == "> on; storage ready; retained 32/32");
++cases;
}
for (const std::string& text : {std::string(151, 'A'), std::string("x") + std::string(50, 'z')}) {
// Second text is replaced below with exactly fifty complete UTF-8 codepoints.
std::string exact = text;
if (exact.size() != 151) { exact = "x"; for (unsigned i = 0; i < 50; ++i) exact += "\xe2\x98\x83"; }
assert(exact.size() == 151);
MemoryFS fs; MyMesh m(&fs); assert(m.command("set room.history on").find("enabled") != std::string::npos);
ClientInfo client; m.receive(&client, exact.c_str(), 123);
assert(m.acks == 1 && m._num_posted == 1 && m.retained()[0] == exact);
assert(m.snapshotRoomHistory()); compareBoot(fs, m);
m.receive(&client, exact.c_str(), 123);
assert(m.acks == 2 && m._num_posted == 1);
AdmissionState before(m, client);
m.receive(&client, (exact + "!").c_str(), 124); before.unchanged(m, client);
assert(m.addSystemPost("short"));
for (unsigned i = 0; i < 31; ++i) assert(m.addSystemPost("tiny"));
assert(m.snapshotRoomHistory()); compareBoot(fs, m); // reused long slot has canonical padding
++cases;
}
for (const std::string failure : {"open:a:/room_history", "write:/room_history", "flush:/room_history",
"close:w:/room_history", "read:/room_history", "seek:/room_history"}) {
MemoryFS fs; MyMesh m(&fs); ClientInfo client;
assert(m.command("set room.history on").find("enabled") != std::string::npos);
m.receive(&client, "accepted", 100); assert(m.acks == 1 && m._num_posted == 1);
ticks = 100; fs.reset(); fs.faults.insert(failure);
AdmissionState before(m, client);
m.receive(&client, "not-yet-retained", 101); before.unchanged(m, client);
fs.reset(); m.receive(&client, "not-yet-retained", 101);
assert(m.acks == 2 && m._num_posted == 2 && m.retained().back() == "not-yet-retained");
assert(client.extra.room.last_post_timestamp == 101);
compareBoot(fs, m); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs); ClientInfo client;
assert(m.command("set room.history on").find("enabled") != std::string::npos);
m.receive(&client, "trusted", 100); fs.short_write = true;
AdmissionState before(m, client); m.receive(&client, "partial", 101); before.unchanged(m, client);
assert(m.room_history_state.needs_repair);
fs.reset();
MyMesh reboot(&fs); reboot.loadRoomHistory();
assert(reboot.room_history_state.needs_repair && reboot.retained() == m.retained());
m.receive(&client, "partial", 101);
assert(!m.room_history_state.needs_repair && m.acks == 2);
assert(m.retained() == std::vector<std::string>({"trusted", "partial"}));
compareBoot(fs, m); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs); ClientInfo client;
assert(m.command("set room.history on").find("enabled") != std::string::npos);
m.receive(&client, "durable-but-unconfirmed", 100); assert(m.acks == 1);
// Fail readback only after header+existing record validation. A whole disk
// append can survive without ACK, but trusted RAM repair must remove it.
fs.reset(); fs.fail_read_at = 3;
AdmissionState before(m, client); m.receive(&client, "readback-failed", 101); before.unchanged(m, client);
assert(m.room_history_state.needs_repair);
fs.reset(); m.receive(&client, "readback-failed", 101);
assert(m.acks == 2 && m._num_posted == 2 && m.retained().size() == 2);
compareBoot(fs, m); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs);
assert(m.command("set room.history on").find("enabled") != std::string::npos);
assert(m.addSystemPost("archived")); const auto archive = fs.get(mesh::ROOM_HISTORY_PATH);
assert(m.command("set room.history off").find("archive retained") != std::string::npos);
assert(fs.get(mesh::ROOM_HISTORY_PATH) == archive);
assert(m.addSystemPost("volatile")); assert(fs.get(mesh::ROOM_HISTORY_PATH) == archive);
MyMesh boot(&fs); boot.loadRoomHistory();
assert(!boot.room_history_enabled && boot.retained().empty() && fs.get(mesh::ROOM_HISTORY_PATH) == archive);
assert(m.command("set room.history 1").find("enabled") != std::string::npos);
compareBoot(fs, m);
const auto floor = m.last_room_timestamp;
assert(m.command("room.history.clear").find("cleared") != std::string::npos);
assert(m.retained().empty() && m.last_room_timestamp == floor);
MyMesh cleared(&fs); cleared.loadRoomHistory();
assert(cleared.room_history_available && cleared.retained().empty() && cleared.last_room_timestamp == 0);
++cases;
}
{
MemoryFS fs; MyMesh m(&fs); ClientInfo client;
assert(m.command("set room.history on").find("enabled") != std::string::npos);
assert(m.addSystemPost("before-clear")); const auto archive = fs.get(mesh::ROOM_HISTORY_PATH);
fs.faults.insert("rename:/room_history.tmp:/room_history"); AdmissionState before(m, client);
assert(m.command("room.history.clear").find("failed") != std::string::npos);
before.unchanged(m, client); fs.reset(); assert(fs.get(mesh::ROOM_HISTORY_PATH) == archive);
++cases;
}
{
MemoryFS fs; MyMesh m(&fs); ClientInfo client; assert(m.addSystemPost("volatile-before-enable"));
fs.faults.insert("rename:/room_hist_cfg.tmp:/room_hist_cfg");
assert(m.command("set room.history on").find("failed") != std::string::npos && !m.room_history_enabled);
fs.reset(); assert(m.command("set room.history on").find("enabled") != std::string::npos);
const auto config = fs.get(mesh::ROOM_HISTORY_CONFIG_PATH);
fs.faults.insert("rename:/room_hist_cfg.tmp:/room_hist_cfg");
assert(m.command("set room.history 0").find("failed") != std::string::npos && m.room_history_enabled);
fs.reset(); assert(fs.get(mesh::ROOM_HISTORY_CONFIG_PATH) == config);
for (const char* invalid : {"set room.history yes", "set room.history on ", "set room.history 2"}) {
assert(m.command(invalid).find("requires on/off") != std::string::npos);
}
char reply[160] = {}; assert(!m.handleRoomHistoryCommand("get room.history.extra", reply));
++cases;
}
{
MemoryFS fs; MyMesh m(&fs); m.clock.now = 2000;
assert(m.command("set room.history on").find("enabled") != std::string::npos);
assert(m.addSystemPost("first")); const auto floor = m.last_room_timestamp;
m.clock.now = 5; m.clock.resetUniqueTime(5);
assert(m.addSystemPost("backward")); assert(m.last_room_timestamp == floor + 1 && m.clock.now == 5);
assert(m.clock.set_calls == 0 && m.post_ready_at[1] == ticks + 6000);
MyMesh boot(&fs); boot.clock.now = 1; boot.loadRoomHistory(); const auto boot_floor = boot.last_room_timestamp;
assert(boot.addSystemPost("after-reboot") && boot.last_room_timestamp == boot_floor + 1);
assert(boot.clock.now == 1 && boot.clock.set_calls == 0); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs);
assert(m.command("set room.history on").find("enabled") != std::string::npos);
m.clock.now = UINT32_MAX; assert(m.addSystemPost("last representable"));
ClientInfo client; AdmissionState before(m, client); assert(!m.addSystemPost("overflow")); before.unchanged(m, client);
MyMesh boot(&fs); boot.loadRoomHistory(); assert(boot.last_room_timestamp == UINT32_MAX);
assert(!boot.addSystemPost("cannot wrap")); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs); ClientInfo client;
assert(!m.addSystemPost(nullptr) && !m.addSystemPost("") && !m.storePost(client.id, nullptr));
assert(!m.addSystemPost(std::string(152, 'x').c_str()) && m._num_posted == 0);
MyMesh unavailable(nullptr); unavailable.loadRoomHistory();
assert(!unavailable.room_history_available && !unavailable.addSystemPost("no fs"));
assert(unavailable.command("get room.history").find("unavailable") != std::string::npos);
assert(unavailable.command("set room.history on").find("failed") != std::string::npos);
assert(unavailable.command("room.history.clear").find("failed") != std::string::npos); ++cases;
}
{
MemoryFS fs; MyMesh m(&fs);
assert(m.command("set room.history on").find("enabled") != std::string::npos);
assert(m.addSystemPost("kept")); const auto original = fs.get(mesh::ROOM_HISTORY_PATH);
fs.faults.insert("open:r:/room_history"); MyMesh boot(&fs); boot.loadRoomHistory();
assert(!boot.room_history_available && boot.retained().empty() && fs.get(mesh::ROOM_HISTORY_PATH) == original);
assert(!boot.addSystemPost("must not overwrite")); fs.reset();
auto corrupt = original; corrupt[3] = 2; fs.put(mesh::ROOM_HISTORY_PATH, corrupt);
MyMesh future(&fs); future.loadRoomHistory();
assert(!future.room_history_available && !future.addSystemPost("must preserve future"));
assert(fs.get(mesh::ROOM_HISTORY_PATH) == corrupt); ++cases;
}
{
MemoryFS fs; mesh::RoomHistoryState state;
metadata_filesystem = &fs;
assert(mesh::saveRoomHistoryConfig(&fs, true));
assert(mesh::saveRoomHistorySnapshot(&fs, state, 2, [](uint8_t ordinal, mesh::RoomHistoryRecord& record) {
memset(&record, 0, sizeof(record)); record.author[0] = 1;
record.timestamp = ordinal == 0 ? 100 : 99; strcpy(record.text, "out of order"); return true;
}));
const auto original = fs.get(mesh::ROOM_HISTORY_PATH); MyMesh boot(&fs); boot.loadRoomHistory();
assert(!boot.room_history_available && boot.retained().empty() && boot.last_room_timestamp == 0);
assert(fs.get(mesh::ROOM_HISTORY_PATH) == original && !boot.addSystemPost("no rewrite")); ++cases;
}
printf("%u production room history integration scenarios passed\n", cases);
}
+155
View File
@@ -0,0 +1,155 @@
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
struct PowerCut {};
class MemoryFS;
static MemoryFS* metadata_filesystem = nullptr;
class File {
MemoryFS* fs = nullptr;
std::shared_ptr<std::vector<uint8_t>> bytes;
std::string path;
size_t cursor = 0, initial_size = 0;
bool writable = false, directory = false, valid = false;
public:
File() = default;
File(MemoryFS*, std::shared_ptr<std::vector<uint8_t>>, const char*, bool, bool);
operator bool() const { return valid; }
bool isDirectory() const { return directory; }
size_t size();
bool seek(uint32_t position);
int read(uint8_t*, size_t);
size_t write(const uint8_t*, size_t);
void flush();
void close();
};
class MemoryFS {
public:
void _lockFS() {}
void _unlockFS() {}
MemoryFS* _getFS() { return this; }
std::map<std::string, std::shared_ptr<std::vector<uint8_t>>> files;
std::set<std::string> faults, directories;
std::vector<std::string> trace;
size_t boundary = 0, cut_at = 0;
bool short_write = false, short_read = false;
std::vector<uint8_t> replacement_on_close;
unsigned write_opens = 0;
size_t capacity = std::numeric_limits<size_t>::max();
unsigned read_calls = 0, fail_read_at = 0;
std::string replacement_path;
void point(const std::string& event) {
trace.push_back(event);
if (++boundary == cut_at) throw PowerCut{};
}
bool begin(const std::string& op) { point("before:" + op); return !faults.count(op); }
void end(const std::string& op) { point("after:" + op); }
bool exists(const char* path) {
const std::string op = std::string("stat:") + path;
const bool okay = begin(op);
const bool present = files.count(path) || directories.count(path);
end(op);
return okay && present;
}
bool remove(const char* path) {
const std::string op = std::string("remove:") + path;
if (!begin(op)) return false;
const bool removed = files.erase(path) + directories.erase(path) != 0;
end(op); return removed;
}
bool rename(const char* from, const char* to) {
const std::string op = std::string("rename:") + from + ":" + to;
if (!begin(op) || !files.count(from) || files.count(to) || directories.count(to)) return false;
files[to] = files[from]; files.erase(from); end(op); return true;
}
File open(const char* path, const char* mode = "r", bool create = false) {
(void)create;
const bool append = mode[0] == 'a';
const bool write = mode[0] == 'w' || append;
const std::string op = std::string("open:") + (append ? "a:" : write ? "w:" : "r:") + path;
if (!begin(op)) return {};
if (write) {
++write_opens;
if (!append || !files.count(path)) files[path] = std::make_shared<std::vector<uint8_t>>();
if (faults.count(std::string("directory:") + path)) directories.insert(path);
}
if (!files.count(path) && !directories.count(path)) { end(op); return {}; }
if (!files.count(path)) files[path] = std::make_shared<std::vector<uint8_t>>();
File file(this, files[path], path, write, directories.count(path));
end(op); return file;
}
File open(const char* path, int mode) { assert(mode == 1); return open(path, "a"); }
void put(const char* path, const std::vector<uint8_t>& bytes) {
files[path] = std::make_shared<std::vector<uint8_t>>(bytes);
}
std::vector<uint8_t> get(const char* path) const { return *files.at(path); }
void reset() { trace.clear(); boundary = cut_at = 0; faults.clear(); short_write = short_read = false; write_opens = 0; read_calls = fail_read_at = 0; replacement_on_close.clear(); replacement_path.clear(); capacity = std::numeric_limits<size_t>::max(); }
};
File::File(MemoryFS* owner, std::shared_ptr<std::vector<uint8_t>> data,
const char* name, bool write, bool dir)
: fs(owner), bytes(data), path(name), writable(write), directory(dir), valid(true) {
initial_size = bytes->size(); cursor = write ? initial_size : 0;
}
size_t File::size() {
const std::string op = "size:" + path;
const bool okay = fs->begin(op); const size_t size = okay ? bytes->size() : 0;
fs->end(op); return size;
}
int File::read(uint8_t* output, size_t length) {
const std::string op = "read:" + path;
if (!valid || directory || !fs->begin(op)) return -1;
if (++fs->read_calls == fs->fail_read_at) return -1;
length = std::min(length, bytes->size() - cursor);
if (fs->short_read && length) --length;
if (length) memcpy(output, bytes->data() + cursor, length);
cursor += length; fs->end(op); return static_cast<int>(length);
}
size_t File::write(const uint8_t* data, size_t length) {
const std::string op = "write:" + path;
if (!valid || directory || !fs->begin(op)) return 0;
if (fs->short_write && length) --length;
size_t occupied = 0;
for (const auto& entry : fs->files) occupied += entry.second->size();
const size_t free = occupied < fs->capacity ? fs->capacity - occupied : 0;
length = std::min(length, free);
bytes->insert(bytes->end(), data, data + length); fs->end(op); return length;
}
void File::flush() {
const std::string op = "flush:" + path;
if (!fs->begin(op) && bytes->size() > initial_size) bytes->pop_back();
fs->end(op);
}
void File::close() {
const std::string op = std::string("close:") + (writable ? "w:" : "r:") + path;
if (!fs->begin(op) && writable && bytes->size() > initial_size) (*bytes)[initial_size] ^= 1;
if (writable && !fs->replacement_on_close.empty() && fs->replacement_path == path) *bytes = fs->replacement_on_close;
valid = false; fs->end(op);
}
bool File::seek(uint32_t position) {
const std::string op = "seek:" + path;
if (!valid || directory || !fs->begin(op) || position > bytes->size()) return false;
cursor = position; fs->end(op); return true;
}
#define FILE_O_WRITE 1
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
struct lfs_info {};
static constexpr int LFS_ERR_NOENT = -2;
static int lfs_stat(MemoryFS* fs, const char* path, lfs_info*) {
const std::string op = std::string("stat:") + path;
const bool okay = fs->begin(op);
const bool present = fs->files.count(path) || fs->directories.count(path);
fs->end(op);
return !okay ? -5 : present ? 0 : LFS_ERR_NOENT;
}
#endif
+385
View File
@@ -0,0 +1,385 @@
#include "filesystem.h"
#include <helpers/RoomHistoryStore.h>
#include "vectors.inc"
using Record = mesh::RoomHistoryRecord;
using State = mesh::RoomHistoryState;
static const char* P = mesh::ROOM_HISTORY_PATH;
static const char* T = mesh::ROOM_HISTORY_TEMP_PATH;
static const char* B = mesh::ROOM_HISTORY_BACKUP_PATH;
static const char* C = mesh::ROOM_HISTORY_CONFIG_PATH;
static const char* CT = mesh::ROOM_HISTORY_CONFIG_TEMP_PATH;
static const char* CB = mesh::ROOM_HISTORY_CONFIG_BACKUP_PATH;
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
static const char* WRITE_MODE = "a";
#else
static const char* WRITE_MODE = "w";
#endif
static unsigned scenarios = 0;
static Record record(unsigned number) {
Record result = {};
result.author[0] = 1; result.author[31] = uint8_t(number);
result.timestamp = 1000 + number;
snprintf(result.text, sizeof(result.text), "post %u", number);
return result;
}
static bool same(const Record& a, const Record& b) {
return a.timestamp == b.timestamp && strcmp(a.text, b.text) == 0
&& memcmp(a.author, b.author, sizeof(a.author)) == 0;
}
static bool sameState(const State& a, const State& b) {
return a.count == b.count && a.total_records == b.total_records
&& a.needs_repair == b.needs_repair && a.present == b.present;
}
static bool snapshot(MemoryFS& fs, State& state, const std::vector<Record>& records) {
metadata_filesystem = &fs;
return mesh::saveRoomHistorySnapshot(&fs, state, uint8_t(records.size()),
[&](uint8_t index, Record& output) {
if (index >= records.size()) return false;
output = records[index]; return true;
});
}
static bool append(MemoryFS& fs, State& state, const Record& input) {
metadata_filesystem = &fs;
return mesh::appendRoomHistory(&fs, state, input.author, input.timestamp, input.text);
}
static bool load(MemoryFS& fs, State& state, std::vector<Record>& records) {
metadata_filesystem = &fs; records.clear();
return mesh::loadRoomHistory(&fs, state,
[&](uint8_t index, const Record& input) {
assert(index == records.size()); records.push_back(input); return true;
});
}
static bool config(MemoryFS& fs, bool enabled) {
metadata_filesystem = &fs; return mesh::saveRoomHistoryConfig(&fs, enabled);
}
static bool loadConfig(MemoryFS& fs, bool& enabled) {
metadata_filesystem = &fs; return mesh::loadRoomHistoryConfig(&fs, enabled);
}
static void expect(MemoryFS& fs, const std::vector<Record>& expected, bool repair = false) {
State state; std::vector<Record> actual;
assert(load(fs, state, actual) && actual.size() == expected.size());
for (size_t index = 0; index < expected.size(); ++index) assert(same(actual[index], expected[index]));
assert(state.count == expected.size() && state.needs_repair == repair);
}
static std::vector<uint8_t> rendered(const Record& input) {
uint8_t image[mesh::ROOM_HISTORY_RECORD_SIZE];
assert(mesh::room_history_detail::encodeRecord(input, image));
return {image, image + sizeof(image)};
}
static void checkFailedSnapshot(MemoryFS& fs, State& state,
const std::vector<Record>& old) {
const State previous = state;
assert(!snapshot(fs, state, {record(10), record(11)}));
assert(sameState(state, previous)); fs.reset(); expect(fs, old);
assert(!fs.files.count(T) && !fs.files.count(B)); ++scenarios;
}
int main() {
const std::vector<Record> old = {record(1), record(2)};
{
MemoryFS fs; bool enabled = true; assert(loadConfig(fs, enabled) && !enabled);
assert(config(fs, true) && fs.get(C) == CONFIG_ON);
assert(loadConfig(fs, enabled) && enabled);
assert(config(fs, false) && fs.get(C) == CONFIG_OFF);
assert(loadConfig(fs, enabled) && !enabled); ++scenarios;
}
{
MemoryFS fs; State state; std::vector<Record> rows;
assert(load(fs, state, rows) && !state.present && rows.empty());
assert(append(fs, state, record(1)) && state.present);
const auto wire = fs.get(P);
assert(wire.size() == HEADER.size() + RECORD_ONE.size());
assert(std::equal(HEADER.begin(), HEADER.end(), wire.begin()));
assert(std::equal(RECORD_ONE.begin(), RECORD_ONE.end(), wire.begin() + HEADER.size()));
expect(fs, {record(1)}); ++scenarios;
}
{
MemoryFS fs; State loaded; assert(snapshot(fs, loaded, old));
const auto previous = fs.get(P); State uninitialized; fs.reset();
assert(!append(fs, uninitialized, record(3)) && uninitialized.needs_repair);
assert(fs.get(P) == previous && fs.write_opens == 0);
fs.files.erase(P); fs.put(B, previous); uninitialized = State{}; fs.reset();
assert(!append(fs, uninitialized, record(3)) && uninitialized.needs_repair);
assert(fs.get(P) == previous && fs.write_opens == 0); ++scenarios;
}
{
MemoryFS fs; State state; std::vector<Record> retained;
assert(snapshot(fs, state, {}));
for (unsigned number = 1; number <= 64; ++number) assert(append(fs, state, record(number)));
assert(state.count == 32 && state.total_records == 64);
assert(fs.get(P).size() == mesh::ROOM_HISTORY_MAX_FILE_SIZE);
for (unsigned number = 33; number <= 64; ++number) retained.push_back(record(number));
expect(fs, retained); const auto full = fs.get(P); fs.reset();
assert(!append(fs, state, record(65)) && fs.trace.empty() && fs.get(P) == full);
assert(snapshot(fs, state, retained) && state.total_records == 32);
assert(fs.get(P).size() == HEADER.size() + 32 * RECORD_ONE.size());
assert(append(fs, state, record(65))); retained.erase(retained.begin()); retained.push_back(record(65));
expect(fs, retained); metadata_filesystem = &fs;
assert(mesh::clearRoomHistory(&fs, state) && fs.get(P) == HEADER && state.count == 0);
expect(fs, {}); assert(!fs.files.count(T) && !fs.files.count(B)); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); const auto previous = fs.get(P);
Record maximum = record(3); memset(maximum.text, 'x', 151); maximum.text[151] = 0;
assert(append(fs, state, maximum)); expect(fs, {record(1), record(2), maximum});
fs.reset(); const auto accepted = fs.get(P);
Record bad = maximum; memset(bad.text, 'x', sizeof(bad.text));
assert(!append(fs, state, bad) && fs.trace.empty());
bad = record(4); bad.timestamp = 0; assert(!append(fs, state, bad) && fs.trace.empty());
bad = record(4); memset(bad.author, 0, sizeof(bad.author));
assert(!append(fs, state, bad) && fs.trace.empty() && fs.get(P) == accepted);
assert(previous.size() < accepted.size()); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); const auto previous = fs.get(P);
metadata_filesystem = &fs;
assert(!mesh::saveRoomHistorySnapshot(&fs, state, 33, mesh::room_history_detail::EmptyProvider{}));
assert(fs.get(P) == previous);
unsigned calls = 0;
assert(!mesh::saveRoomHistorySnapshot(&fs, state, 2, [&](uint8_t, Record& out) {
out = record(10); return ++calls == 1;
})); expect(fs, old);
calls = 0;
assert(!mesh::saveRoomHistorySnapshot(&fs, state, 2, [&](uint8_t index, Record& out) {
out = record(index + 10); return ++calls <= 2; // writer succeeds, verification provider fails
})); expect(fs, old); ++scenarios;
}
for (const std::string& fault : {std::string("open:") + WRITE_MODE + ":" + T,
std::string("write:") + T, std::string("flush:") + T,
std::string("close:w:") + T, std::string("open:r:") + T,
std::string("read:") + T, std::string("size:") + T,
std::string("directory:") + T, std::string("rename:") + P + ":" + B,
std::string("rename:") + T + ":" + P}) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset();
fs.faults.insert(fault); checkFailedSnapshot(fs, state, old);
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old));
fs.capacity = fs.get(P).size() + 100; checkFailedSnapshot(fs, state, old);
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old));
fs.replacement_path = T; fs.replacement_on_close = fs.get(P);
checkFailedSnapshot(fs, state, old); // valid CRC stale image is not intended contents
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old));
fs.faults.insert(std::string("rename:") + T + ":" + P);
fs.faults.insert(std::string("rename:") + B + ":" + P);
fs.faults.insert(std::string("remove:") + T);
assert(!snapshot(fs, state, {record(10)})); assert(!fs.files.count(P) && fs.files.count(B));
fs.reset(); expect(fs, old); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old));
fs.faults.insert(std::string("remove:") + B);
assert(snapshot(fs, state, {record(10)}) && fs.files.count(B));
const unsigned writes = fs.write_opens;
assert(!snapshot(fs, state, old) && fs.write_opens == writes);
assert(!append(fs, state, record(11)) && fs.write_opens == writes && state.needs_repair);
fs.reset(); expect(fs, {record(10)}); assert(snapshot(fs, state, {record(10)}));
assert(append(fs, state, record(11))); ++scenarios;
}
for (const std::string& fault : {std::string("open:a:") + P, std::string("write:") + P,
std::string("flush:") + P, std::string("close:w:") + P,
std::string("seek:") + P}) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset();
fs.faults.insert(fault); assert(!append(fs, state, record(3)) && state.needs_repair);
assert(state.count == 2 && state.total_records == 2);
const unsigned writes = fs.write_opens;
assert(!append(fs, state, record(3)) && fs.write_opens == writes);
fs.reset(); assert(snapshot(fs, state, old) && append(fs, state, record(3)));
expect(fs, {record(1), record(2), record(3)}); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset(); fs.short_write = true;
assert(!append(fs, state, record(3)) && state.needs_repair); fs.reset(); expect(fs, old, true);
assert(snapshot(fs, state, old) && append(fs, state, record(3))); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset();
fs.capacity = fs.get(P).size() + 100;
assert(!append(fs, state, record(3)) && state.needs_repair); fs.reset(); expect(fs, old, true); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset();
// Three old scan reads; the fourth, post-write verification header, fails.
fs.fail_read_at = 4;
assert(!append(fs, state, record(3)) && state.needs_repair && state.count == 2);
fs.reset(); expect(fs, {record(1), record(2), record(3)});
// Runtime repair uses unchanged trusted RAM, discarding the unACKed append.
assert(snapshot(fs, state, old) && append(fs, state, record(3)));
expect(fs, {record(1), record(2), record(3)}); ++scenarios;
}
for (size_t tail_length = 1; tail_length < RECORD_ONE.size(); ++tail_length) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); auto bytes = fs.get(P);
const auto tail = rendered(record(3)); bytes.insert(bytes.end(), tail.begin(), tail.begin() + tail_length);
fs.put(P, bytes); expect(fs, old, true); std::vector<Record> rows;
assert(load(fs, state, rows) && state.needs_repair);
fs.reset(); assert(!append(fs, state, record(3)) && fs.trace.empty() && fs.get(P) == bytes);
assert(snapshot(fs, state, old) && append(fs, state, record(3))); ++scenarios;
}
for (size_t position = 0; position < RECORD_ONE.size(); ++position) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); assert(append(fs, state, record(3)));
auto bytes = fs.get(P); bytes[HEADER.size() + 2 * RECORD_ONE.size() + position] ^= 1;
fs.put(P, bytes); expect(fs, old, true); assert(fs.get(P) == bytes); ++scenarios;
}
// Corruption before another complete accepted record is never a torn
// append. Do not expose a shortened RAM ring that could replace the intact
// later records on the next post, clear, or snapshot attempt.
for (size_t damaged_record = 0; damaged_record < 2; ++damaged_record) {
for (size_t position = 0; position < RECORD_ONE.size(); ++position) {
MemoryFS fs; State state;
assert(snapshot(fs, state, {record(1), record(2), record(3)}));
auto bytes = fs.get(P);
bytes[HEADER.size() + damaged_record * RECORD_ONE.size() + position] ^= 1;
fs.put(P, bytes); fs.reset();
const State previous = state;
std::vector<Record> rows;
assert(!load(fs, state, rows) && sameState(state, previous) && rows.empty());
assert(fs.get(P) == bytes && fs.write_opens == 0);
// Both a truncated boot destination and the old trusted live ring must
// fail closed; administrative clear cannot discard the evidence either.
assert(!snapshot(fs, state, {record(1)}));
assert(!snapshot(fs, state, {record(1), record(2), record(3)}));
assert(!mesh::clearRoomHistory(&fs, state));
assert(fs.get(P) == bytes && fs.write_opens == 0 && sameState(state, previous));
assert(!append(fs, state, record(4)) && state.needs_repair);
assert(fs.get(P) == bytes && fs.write_opens == 0);
assert(!fs.files.count(T) && !fs.files.count(B)); ++scenarios;
}
}
for (int malformed = 0; malformed < 4; ++malformed) {
MemoryFS fs; State state; assert(snapshot(fs, state, old));
auto bytes = fs.get(P); auto tail = rendered(record(3));
if (malformed == 0) std::fill(tail.begin(), tail.begin() + 32, 0);
if (malformed == 1) std::fill(tail.begin() + 32, tail.begin() + 36, 0);
if (malformed == 2) std::fill(tail.begin() + 36, tail.begin() + 188, 'x');
if (malformed == 3) tail[150] = 'x';
mesh::room_history_detail::put32(tail.data() + 188,
mesh::room_history_detail::crcBytes(tail.data(), 188));
bytes.insert(bytes.end(), tail.begin(), tail.end()); fs.put(P, bytes);
expect(fs, old, true); assert(fs.get(P) == bytes); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); fs.reset(); fs.fail_read_at = 2;
const State before = state; std::vector<Record> rows;
assert(!load(fs, state, rows) && sameState(state, before) && rows.empty());
fs.reset(); fs.fail_read_at = 6;
assert(!load(fs, state, rows) && sameState(state, before) && rows.size() == 1);
rows.clear(); fs.reset(); expect(fs, old); ++scenarios;
}
std::vector<std::vector<uint8_t>> invalid_headers = {{}, {1}, std::vector<uint8_t>(11), HEADER,
std::vector<uint8_t>(mesh::ROOM_HISTORY_MAX_FILE_SIZE + 1)};
invalid_headers[3][3] = 2;
mesh::room_history_detail::put32(invalid_headers[3].data() + 8,
mesh::room_history_detail::crcBytes(invalid_headers[3].data(), 8));
for (const auto& bytes : invalid_headers) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); const auto good = fs.get(P);
fs.put(P, bytes); fs.put(B, good); fs.put(T, good);
State before = state; std::vector<Record> rows;
assert(!load(fs, state, rows) && sameState(state, before));
assert(!snapshot(fs, state, {}) && fs.get(P) == bytes && fs.get(B) == good && fs.get(T) == good);
MemoryFS backup; backup.put(B, bytes); backup.put(T, good);
assert(!load(backup, state, rows) && backup.get(B) == bytes && backup.get(T) == good); ++scenarios;
}
for (size_t position = 0; position < HEADER.size(); ++position) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); auto bytes = fs.get(P);
bytes[position] ^= 1; fs.put(P, bytes); std::vector<Record> rows;
assert(!load(fs, state, rows) && !snapshot(fs, state, {}));
assert(fs.get(P) == bytes); ++scenarios;
}
for (size_t position : {size_t(4), size_t(6), size_t(7)}) {
MemoryFS fs; State state; assert(snapshot(fs, state, old)); auto bytes = fs.get(P);
++bytes[position]; mesh::room_history_detail::put32(bytes.data() + 8,
mesh::room_history_detail::crcBytes(bytes.data(), 8)); fs.put(P, bytes);
std::vector<Record> rows; assert(!load(fs, state, rows) && !snapshot(fs, state, {}));
assert(fs.get(P) == bytes); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old)); const auto bytes = fs.get(P);
fs.files.erase(P); fs.put(B, bytes); fs.put(T, HEADER); expect(fs, old);
assert(fs.get(P) == bytes && !fs.files.count(T) && !fs.files.count(B));
MemoryFS temp; temp.put(T, bytes); expect(temp, {}); assert(!temp.files.count(P)); ++scenarios;
}
{
MemoryFS fs; State state; assert(snapshot(fs, state, old));
fs.directories.insert(P); std::vector<Record> rows;
assert(!load(fs, state, rows) && !snapshot(fs, state, {}) && fs.files.count(P)); ++scenarios;
}
for (size_t position = 0; position < CONFIG_ON.size(); ++position) {
MemoryFS fs; auto image = CONFIG_ON; image[position] ^= 1;
fs.put(C, image); fs.put(CB, CONFIG_OFF); fs.put(CT, CONFIG_OFF);
bool enabled = false;
assert(!loadConfig(fs, enabled) && !enabled && !config(fs, false));
assert(fs.get(C) == image && fs.get(CB) == CONFIG_OFF && fs.get(CT) == CONFIG_OFF); ++scenarios;
}
{
MemoryFS fs; auto image = CONFIG_ON; image[3] = 2;
mesh::room_history_detail::put32(image.data() + 12, mesh::room_history_detail::crcBytes(image.data(), 12));
fs.put(C, image); bool enabled = true;
assert(!loadConfig(fs, enabled) && enabled && !config(fs, false) && fs.get(C) == image);
MemoryFS backup; backup.put(CB, CONFIG_ON); backup.put(CT, CONFIG_OFF);
assert(loadConfig(backup, enabled) && enabled && backup.get(C) == CONFIG_ON);
MemoryFS temp; temp.put(CT, CONFIG_ON); assert(loadConfig(temp, enabled) && !enabled && !temp.files.count(C)); ++scenarios;
}
for (size_t position : {size_t(4), size_t(5)}) {
MemoryFS fs; auto image = CONFIG_ON; image[position] = 2;
mesh::room_history_detail::put32(image.data() + 12,
mesh::room_history_detail::crcBytes(image.data(), 12)); fs.put(C, image);
bool enabled = false; assert(!loadConfig(fs, enabled) && !config(fs, false));
assert(fs.get(C) == image); ++scenarios;
}
for (const std::string& fault : {std::string("open:") + WRITE_MODE + ":" + CT,
std::string("write:") + CT, std::string("flush:") + CT,
std::string("close:w:") + CT, std::string("open:r:") + CT,
std::string("read:") + CT, std::string("size:") + CT,
std::string("directory:") + CT, std::string("rename:") + C + ":" + CB,
std::string("rename:") + CT + ":" + C}) {
MemoryFS fs; assert(config(fs, false)); fs.reset(); fs.faults.insert(fault);
assert(!config(fs, true)); fs.reset(); bool enabled = true;
assert(loadConfig(fs, enabled) && !enabled); ++scenarios;
}
#if defined(ESP32_PLATFORM) || defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
for (const char* path : {P, C}) {
MemoryFS fs; State state; assert(snapshot(fs, state, old) && config(fs, false)); fs.reset();
fs.faults.insert(std::string("stat:") + path); bool enabled = false; std::vector<Record> rows;
if (path == P) assert(!load(fs, state, rows) && !snapshot(fs, state, {}));
else assert(!loadConfig(fs, enabled) && !config(fs, true));
assert(fs.write_opens == 0); ++scenarios;
}
#endif
// Simulate interruption before/after every filesystem operation, including
// verification and publication. Only temp->primary publication changes the
// selected snapshot/config; journal appends may recover a complete new row.
for (int action = 0; action < 3; ++action) {
MemoryFS baseline; State state; assert(snapshot(baseline, state, old) && config(baseline, false));
baseline.reset();
if (action == 0) assert(snapshot(baseline, state, {record(10), record(11)}));
if (action == 1) assert(append(baseline, state, record(3)));
if (action == 2) assert(config(baseline, true));
const size_t boundaries = baseline.boundary;
for (size_t cut = 1; cut <= boundaries; ++cut) {
MemoryFS fs; State current; assert(snapshot(fs, current, old) && config(fs, false));
fs.reset(); fs.cut_at = cut;
try {
if (action == 0) snapshot(fs, current, {record(10), record(11)});
if (action == 1) append(fs, current, record(3));
if (action == 2) config(fs, true);
} catch (const PowerCut&) {}
const bool new_snapshot = fs.files.count(P) && fs.get(P).size() > HEADER.size()
&& fs.get(P)[HEADER.size() + 31] == 10;
const bool appended = action == 1 && fs.files.count(P)
&& fs.get(P).size() == HEADER.size() + 3 * RECORD_ONE.size();
const bool new_config = fs.files.count(C) && fs.get(C) == CONFIG_ON;
fs.reset();
if (action == 0) expect(fs, new_snapshot ? std::vector<Record>{record(10), record(11)} : old);
if (action == 1) expect(fs, appended ? std::vector<Record>{record(1), record(2), record(3)} : old);
if (action == 2) { bool enabled; assert(loadConfig(fs, enabled) && enabled == new_config); expect(fs, old); }
assert(!fs.files.count(T) && !fs.files.count(B) && !fs.files.count(CT) && !fs.files.count(CB)); ++scenarios;
}
}
printf("PASS: %u bounded room history fault and recovery scenarios\n", scenarios);
}
+237
View File
@@ -0,0 +1,237 @@
// Actual receive dispatcher and Companion queue/callbacks are extracted into
// production.inc. Radio, crypto, UI and persistent-store boundaries are mocks.
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include "helpers/CompanionFrameLimits.h"
#define PUB_KEY_SIZE 32
#define PRV_KEY_SIZE 64
#define MAX_CONTACTS 2
#define OFFLINE_QUEUE_SIZE 4
#define ADV_TYPE_NONE 0
#define ADV_TYPE_ROOM 3
#define OUT_PATH_UNKNOWN 255
#define PAYLOAD_TYPE_TXT_MSG 2
#define PAYLOAD_TYPE_REQ 0
#define PAYLOAD_TYPE_RESPONSE 1
#define PAYLOAD_TYPE_ACK 3
#define TXT_ACK_DELAY 200
#define CLI_REPLY_DELAY_MILLIS 200
#define SERVER_RESPONSE_DELAY 200
#define COMPANION_FEATURE_TEXT_TERMINAL 0
#define COMPANION_FEATURE_NOTIFICATIONS 1
#define MESH_ENABLE_ONE_KEY_DM 0
#define ONE_KEY_DM_SHARED_OFFLINE_QUEUE 0
#define DISPLAY_CLASS TestDisplay
#define MESH_DEBUG_PRINTLN(...) ((void)0)
#include "constants.inc"
static uint32_t millis() { return 100; }
static bool millisHasNowPassed(unsigned long deadline) { return millis() > deadline; }
namespace mesh {
struct Identity { uint8_t pub_key[PUB_KEY_SIZE] = {}; };
struct Packet {
bool flood = false;
uint8_t path[2] = {7, 8}, path_len = 2;
float getSNR() const { return 10.75f; }
bool isRouteFlood() const { return flood; }
};
struct Utils {
static void sha256(uint8_t* out, size_t size, const uint8_t*, size_t,
const uint8_t*, size_t) { memset(out, 0x55, size); }
};
}
struct ContactInfo {
mesh::Identity id;
uint8_t type = ADV_TYPE_ROOM, out_path_len = 0;
uint32_t sync_since = 50, lastmod = 99;
char name[16] = "room";
const uint8_t* getPath() const { return id.pub_key; }
};
struct Clock {
uint32_t now = 1200;
uint32_t getCurrentTime() const { return now; }
uint32_t getCurrentTimeUnique() { return now++; }
};
struct Rng { void random(uint8_t* out, size_t length) { memset(out, 0, length); } };
struct BaseChatMesh {
ContactInfo contacts[MAX_CONTACTS];
int matching_peer_indexes[1] = {0}, num_contacts = MAX_CONTACTS;
bool mutable_contacts = true;
Clock clock;
Rng rng;
mesh::Identity self_id;
mesh::Packet response;
unsigned direct_acks = 0, flood_acks = 0;
std::vector<uint8_t> ack;
uint8_t temp_buf[184] = {};
bool canMutateContacts() const { return mutable_contacts; }
Clock* getRTCClock() { return &clock; }
Rng* getRNG() { return &rng; }
virtual bool onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*) = 0;
virtual void onMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) = 0;
void onCommandDataRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) {}
void onCLICommandRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*, char*) {}
uint8_t onContactRequest(const ContactInfo&, uint32_t, const uint8_t*, size_t, uint8_t*) { return 0; }
void onContactResponse(const ContactInfo&, const uint8_t*, size_t) {}
void handleReturnPathRetry(const ContactInfo&, const uint8_t*, uint8_t) {}
mesh::Packet* createDatagram(uint8_t, const mesh::Identity&, const uint8_t*, const uint8_t*, size_t) { return &response; }
mesh::Packet* createPathReturn(const mesh::Identity&, const uint8_t*, const uint8_t*, uint8_t,
uint8_t type, const uint8_t* bytes, size_t length) {
if (type == PAYLOAD_TYPE_ACK) { ++flood_acks; ack.assign(bytes, bytes + length); }
return &response;
}
void sendAckTo(const ContactInfo&, const uint8_t* bytes, size_t length = 4) {
++direct_acks; ack.assign(bytes, bytes + length);
}
void sendFloodScoped(const ContactInfo&, mesh::Packet*, unsigned long = 0) {}
void sendDirect(mesh::Packet*, const uint8_t*, uint8_t, unsigned long = 0) {}
void onPeerDataRecv(mesh::Packet*, uint8_t, int, const uint8_t*, uint8_t*, size_t);
};
enum class UIEventType { contactMessage };
struct UI {
unsigned queue_changes = 0, messages = 0, notifications = 0, overrides = 0;
void syncMessageQueue(int, int = -1) { ++queue_changes; }
void setMessageNotificationOverride(bool, bool = false) { ++overrides; }
template<typename... Args> void newMsg(Args...) { ++messages; }
void notify(UIEventType) { ++notifications; }
};
struct Notifications {
unsigned remote = 0, ordinary = 0;
bool remoteMessage(const uint8_t*, const char*, uint32_t, uint32_t) { ++remote; return false; }
bool message(const uint8_t*, const uint8_t*, bool, uint32_t) { ++ordinary; return false; }
bool overridesScreen() const { return false; }
};
struct Serial {
bool connected = false;
unsigned writes = 0;
bool isConnected() const { return connected; }
bool isReplyRouteAvailable(void*) const { return true; }
size_t writeFrameToRoute(void*, const uint8_t*, size_t length) { ++writes; return length; }
size_t writeFrame(const uint8_t*, size_t length) { ++writes; return length; }
};
struct MyMesh : BaseChatMesh {
#include "frame.inc"
Frame offline_queue[OFFLINE_QUEUE_SIZE] = {};
int offline_queue_len = 0, offline_queue_head = 0;
uint8_t out_frame[MAX_FRAME_SIZE + 1] = {};
uint8_t app_target_ver = 3;
UI ui, *_ui = &ui;
Serial serial, *_serial = &serial;
Notifications _notifications;
void* private_key_backup_route = nullptr;
unsigned long private_key_backup_deadline = 1000;
uint8_t private_key_backup_sender[6] = {};
char private_key_backup_nonce[17] = {};
unsigned active = 0;
std::vector<std::pair<uint32_t, uint32_t>> saved;
MyMesh() { contacts[0].id.pub_key[0] = 77; contacts[1].id.pub_key[0] = 77; contacts[1].id.pub_key[31] = 1; }
void markConnectionActive(const ContactInfo&) { ++active; }
bool scheduleContactWrite(const ContactInfo& from) { saved.emplace_back(from.sync_since, from.lastmod); return true; }
int getOfflineQueueCapacity() const;
Frame& offlineQueueFrameAt(int);
bool addToOfflineQueue(const uint8_t*, int);
void popOfflineQueue();
bool queueMessage(const ContactInfo&, uint8_t, mesh::Packet*, uint32_t, const uint8_t*, int, const char*, bool = false, uint32_t = 0);
bool onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*) override;
void onMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*) override;
void receive(mesh::Packet& packet, uint32_t timestamp, const char* text, uint8_t type = TXT_TYPE_SIGNED_PLAIN, int sender = 0) {
std::vector<uint8_t> payload(10 + strlen(text), 0);
memcpy(payload.data(), &timestamp, 4); payload[4] = uint8_t(type << 2);
const size_t offset = type == TXT_TYPE_SIGNED_PLAIN ? 9 : 5;
if (offset == 9) { payload[5] = 1; payload[6] = 2; payload[7] = 3; payload[8] = 4; }
memcpy(payload.data() + offset, text, strlen(text));
matching_peer_indexes[0] = sender;
const uint8_t secret[32] = {};
onPeerDataRecv(&packet, PAYLOAD_TYPE_TXT_MSG, 0, secret, payload.data(), offset + strlen(text));
}
void fill(bool channel = false) {
for (int at = 0; at < OFFLINE_QUEUE_SIZE; ++at) {
const uint8_t frame[] = {uint8_t(channel && at == 1 ? RESP_CODE_CHANNEL_MSG_RECV : RESP_CODE_CONTACT_MSG_RECV), uint8_t(at)};
assert(addToOfflineQueue(frame, sizeof(frame)));
}
}
};
#include "production.inc"
static unsigned effects(const MyMesh& m) {
return m.ui.messages + m.ui.notifications + m.ui.overrides + m.serial.writes
+ m._notifications.remote + m._notifications.ordinary + m.active + unsigned(m.saved.size());
}
int main() {
unsigned cases = 0;
for (int version : {2, 3}) for (bool flood : {false, true}) for (bool connected : {false, true}) {
MyMesh m; m.app_target_ver = version; m.serial.connected = connected; m.fill();
mesh::Packet packet; packet.flood = flood;
const unsigned before = effects(m);
m.receive(packet, 100, "retained-before-ack");
assert(m.contacts[0].sync_since == 50 && m.contacts[0].lastmod == 99);
assert(m.direct_acks == 0 && m.flood_acks == 0 && m.saved.empty());
assert(effects(m) == before && m.offline_queue_len == OFFLINE_QUEUE_SIZE);
m.popOfflineQueue(); m.receive(packet, 100, "retained-before-ack");
assert(m.contacts[0].sync_since == 100 && m.contacts[0].lastmod == 1200);
assert(m.saved.size() == 1 && m.saved[0] == std::make_pair(100U, 1200U));
assert(m.direct_acks == unsigned(!flood) && m.flood_acks == unsigned(flood));
assert(m.ack.size() == 4 && m.ui.messages == 1 && m._notifications.ordinary == 1);
const auto& frame = m.offlineQueueFrameAt(OFFLINE_QUEUE_SIZE - 1);
const size_t timestamp_offset = version >= 3 ? 12 : 9;
uint32_t stored; memcpy(&stored, frame.buf + timestamp_offset, 4); assert(stored == 100);
assert(frame.buf[timestamp_offset - 1] == TXT_TYPE_SIGNED_PLAIN);
assert(memcmp(frame.buf + timestamp_offset + 4, "\x01\x02\x03\x04", 4) == 0);
// Lost ACK with a now-full queue must not claim retention of another copy.
const unsigned accepted_effects = effects(m);
m.receive(packet, 100, "retained-before-ack");
assert(effects(m) == accepted_effects && m.saved.size() == 1);
assert(m.direct_acks + m.flood_acks == 1 && m.contacts[0].sync_since == 100);
// Once the app drains capacity, normal retry admission and ACK resume.
m.popOfflineQueue(); m.receive(packet, 100, "retained-before-ack");
assert(m.direct_acks + m.flood_acks == 2 && m.saved.size() == 2);
assert(m.contacts[0].sync_since == 100 && m.offline_queue_len == OFFLINE_QUEUE_SIZE);
++cases;
}
{
MyMesh m; m.fill(true); mesh::Packet packet;
m.receive(packet, 100, "replace-channel");
assert(m.offline_queue_len == OFFLINE_QUEUE_SIZE && m.direct_acks == 1);
assert(m.contacts[0].sync_since == 100 && m.saved.size() == 1); ++cases;
}
{
MyMesh m; mesh::Packet packet; m.mutable_contacts = false;
m.receive(packet, 100, "immutable-contact");
assert(m.contacts[0].sync_since == 50 && m.contacts[0].lastmod == 99);
assert(m.direct_acks == 1 && m.offline_queue_len == 1); ++cases;
}
{
MyMesh m; mesh::Packet packet;
m.receive(packet, 40, "earlier-topic");
assert(m.contacts[0].sync_since == 50 && m.direct_acks == 1);
m.receive(packet, 100, "same-text", TXT_TYPE_SIGNED_PLAIN, 0);
m.receive(packet, 100, "same-text", TXT_TYPE_SIGNED_PLAIN, 1);
assert(m.contacts[1].sync_since == 100 && m.offline_queue_len == 3);
// Distinct full room keys sharing the serialized prefix are both retained.
++cases;
}
{
MyMesh m; m.fill(); mesh::Packet packet;
m.receive(packet, 100, "direct-message", TXT_TYPE_PLAIN);
assert(m.direct_acks == 1 && m.ack.size() == 6);
assert(m.contacts[0].sync_since == 50 && m.saved.size() == 1);
assert(m.ui.messages == 1 && m.offline_queue_len == OFFLINE_QUEUE_SIZE); ++cases;
}
for (size_t length : {6U, 7U, 8U}) {
MyMesh m; mesh::Packet packet; std::vector<uint8_t> malformed(length + 1, 0);
malformed[4] = TXT_TYPE_SIGNED_PLAIN << 2;
const uint8_t secret[32] = {};
m.onPeerDataRecv(&packet, PAYLOAD_TYPE_TXT_MSG, 0, secret, malformed.data(), length);
assert(m.direct_acks == 0 && m.offline_queue_len == 0 && effects(m) == 0);
assert(m.contacts[0].sync_since == 50 && m.contacts[0].lastmod == 99); ++cases;
}
assert(cases == 15);
printf("PASS: production room receive admission (%u cases, direct/flood, legacy/V3, both app states)\n", cases);
return 0;
}
+36 -3
View File
@@ -4,6 +4,8 @@
#include <cstring>
#include <string>
#include <vector>
#include "../room_history_store/filesystem.h"
#include <helpers/RoomAccessPolicy.h>
#define PUB_KEY_SIZE 32
#define MAX_PATH_SIZE 64
@@ -55,7 +57,7 @@ static bool saveRoomTopic(Store* store, const char* text) {
}
}
#include "state.inc"
static_assert(sizeof(((ClientInfo*)0)->extra.room) <= sizeof(((ClientInfo*)0)->extra.sensor),
static_assert(sizeof(void*) != 4 || sizeof(((ClientInfo*)0)->extra.room) <= sizeof(((ClientInfo*)0)->extra.sensor),
"topic state must fit the existing shared union");
struct Clock : mesh::RTCClock {
uint32_t now = 1000;
@@ -79,6 +81,8 @@ struct Sent {
};
struct MyMesh {
ACL acl;
MemoryFS policy_fs;
mesh::RoomAccessPolicy room_access;
Clock clock;
Random rng;
mesh::Identity self_id;
@@ -95,9 +99,13 @@ struct MyMesh {
uint16_t _num_post_pushes = 0;
char room_topic[MAX_POST_TEXT_LEN + 1] = {};
PostInfo posts[MAX_UNSYNCED_POSTS] = {};
uint32_t post_ready_at[MAX_UNSYNCED_POSTS] = {};
uint32_t post_ready_mask = UINT32_MAX;
struct { uint8_t path_hash_mode = 0; } _prefs;
int default_scope = 0;
MyMesh() {
metadata_filesystem = &policy_fs;
assert(room_access.load(&policy_fs));
self_id.pub_key[0] = 77;
acl.clients[0].id.pub_key[0] = 1;
acl.clients[0].last_activity = 1000;
@@ -200,9 +208,10 @@ int main() {
}
{
MyMesh m; m.topic("topic"); m.clock.now = 1003;
m.post(0, 1000, "unaged"); m.tick(6000);
m.post(0, 1000, "unaged"); m.post_ready_mask &= ~UINT32_C(1);
m.post_ready_at[0] = futureMillis(10000); m.tick(6000);
assert(m.sent.empty()); // Unaged older posts still protect app forceSince.
m.clock.now = 1007; m.tick(); assert(m.sent.back().text == "unaged");
m.tick(4000); assert(m.sent.back().text == "unaged");
m.ack(); m.tick(); assert(m.sent.back().text == "topic");
}
for (bool flood : {false, true}) for (bool pool : {false, true}) {
@@ -266,5 +275,29 @@ int main() {
m.tick(UINT32_C(0x80000000));
assert(m.sent.size() == 2); m.ack();
}
{
MyMesh m; m.topic("banned topic"); m.post(0, 900, "banned post");
assert(m.room_access.addBan(&m.policy_fs, m.acl.clients[0].id.pub_key) == mesh::RoomAccessPolicy::BanResult::Saved);
m.tick(6000); assert(m.sent.empty());
assert(m.acl.clients[0].extra.room.pending_ack == 0);
assert(m.room_access.removeBan(&m.policy_fs, m.acl.clients[0].id.pub_key) == mesh::RoomAccessPolicy::BanResult::Saved);
m.tick(); assert(m.sent.back().text == "banned post"); m.ack();
m.tick(); assert(m.sent.back().text == "banned topic"); m.ack();
}
{
// A banned first slot cannot swallow an ACK for a later allowed identity.
MyMesh m; m.acl.count = 2;
auto& banned = m.acl.clients[0]; auto& allowed = m.acl.clients[1];
allowed.id.pub_key[0] = 2;
banned.extra.room.pending_ack = allowed.extra.room.pending_ack = 0x12345678;
banned.extra.room.push_post_timestamp = 200;
allowed.extra.room.push_post_timestamp = 300;
assert(m.room_access.addBan(&m.policy_fs, banned.id.pub_key) == mesh::RoomAccessPolicy::BanResult::Saved);
const auto ban_before = banned;
const uint32_t ack = 0x12345678;
assert(m.processAck(reinterpret_cast<const uint8_t*>(&ack)));
assert(memcmp(&ban_before, &banned, sizeof(banned)) == 0);
assert(allowed.extra.room.pending_ack == 0 && allowed.extra.room.sync_since == 300);
}
puts("room topic delivery regressions passed");
}
+5
View File
@@ -0,0 +1,5 @@
{
"status": {"name":"Test room","topic":"Topic <img src=x onerror=attack()>","boot":71,"role":2,"web_key":"5f5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a","persistent_history":false},
"index": {"revision":1,"articles":[{"id":1,"version":1,"length":22,"title":"Instructions"}],"next":255},
"read": {"version":1,"offset":0,"next":22,"total":22,"data64":"UmVhZCBvbmx5IHRoaXMgYXJ0aWNsZQ=="}
}
+279
View File
@@ -0,0 +1,279 @@
#include "filesystem.h"
#include <cstdlib>
#include <new>
#include <array>
#include <ArduinoJson.h>
static bool deny_json_allocation = false;
static unsigned json_allocations = 0;
static void* trackedMalloc(size_t size) {
if (deny_json_allocation) return nullptr;
void* result = std::malloc(size); if (result) ++json_allocations; return result;
}
static void trackedFree(void* ptr) {
if (ptr) { assert(json_allocations != 0); --json_allocations; } std::free(ptr);
}
static void* trackedRealloc(void* ptr, size_t size) {
if (deny_json_allocation) return nullptr;
return std::realloc(ptr, size);
}
#define malloc trackedMalloc
#define free trackedFree
#define realloc trackedRealloc
#include <helpers/RoomWebJson.h>
#undef malloc
#undef free
#undef realloc
#include <helpers/RoomBoardStore.h>
#include <helpers/RoomHistoryStore.h>
#include <helpers/RoomAccessPolicy.h>
#include <helpers/RoomLoginAuthorization.h>
#define WITH_WEBCONFIG 1
#define PUB_KEY_SIZE 32
#define MAX_POST_TEXT_LEN 151
#define MAX_UNSYNCED_POSTS 32
#define POST_SYNC_DELAY_SECS 2
#define PUSH_NOTIFY_DELAY_MILLIS 200
#define MESH_DEBUG_PRINTLN(...) ((void)0)
#include "roles.inc"
static uint32_t ticks = 100;
static uint32_t millis() { return ticks; }
static uint32_t futureMillis(uint32_t duration) { return millis() + duration; }
namespace mesh {
struct Identity {
uint8_t pub_key[32] = {};
bool matches(const Identity& other) const { return memcmp(pub_key, other.pub_key, 32) == 0; }
};
struct Utils {
// Cryptography is a boundary mock: every fixture token has a distinct key.
static void sha256(uint8_t* out, size_t length, const uint8_t* token, size_t token_length,
const uint8_t* server, size_t server_length) {
assert(length == 32 && token_length == 32 && server_length == 32);
for (size_t i = 0; i < length; ++i) out[i] = token[i] ^ server[i] ^ 0x5a;
}
static void toHex(char* output, const uint8_t* key, size_t length) {
static const char digits[] = "0123456789abcdef";
for (size_t i = 0; i < length; ++i) { output[2 * i] = digits[key[i] >> 4]; output[2 * i + 1] = digits[key[i] & 15]; }
output[length * 2] = 0;
}
};
}
struct StrHelper {
static void strncpy(char* out, const char* text, size_t capacity) { std::snprintf(out, capacity, "%s", text); }
};
struct Preferences {
static bool value, fail_open, fail_write;
bool begin(const char* name, bool readonly) { assert(strcmp(name, "mesh-room") == 0 && !readonly); return !fail_open; }
size_t putBool(const char* key, bool next) { assert(strcmp(key, "web") == 0); if (fail_write) return 0; value = next; return sizeof(bool); }
bool getBool(const char* key, bool fallback) { (void)fallback; assert(strcmp(key, "web") == 0); return value; }
void end() {}
};
bool Preferences::value = false, Preferences::fail_open = false, Preferences::fail_write = false;
struct ClientInfo {
mesh::Identity id;
uint8_t permissions = PERM_ACL_ADMIN;
struct { struct { uint16_t post_quota_used = 0, poll_quota_used = 0; uint32_t last_post_timestamp = 0; } room; } extra;
};
struct ACL {
ClientInfo radio_admin;
unsigned lookups = 0;
int getNumClients() const { return 1; }
ClientInfo* getClientByIdx(int i) { assert(i == 0); return &radio_admin; }
ClientInfo* getClient(const mesh::Identity&) { ++lookups; return &radio_admin; }
};
struct Clock { uint32_t now = 1000; uint32_t getCurrentTimeUnique() { return now++; } };
#include "post.inc"
struct MyMesh {
MemoryFS storage; MemoryFS* _fs = &storage;
mesh::RoomAccessPolicy room_access;
mesh::Identity self_id;
struct { char password[65] = "admin-secret", guest_password[65] = "write-secret", node_name[64] = "Test room"; bool allow_read_only = true; } _prefs;
bool room_web_enabled = false;
bool room_web_request_authenticated = false;
uint32_t room_web_boot_id = 71;
#include "web_user.inc"
ACL acl;
Clock clock;
PostInfo posts[MAX_UNSYNCED_POSTS] = {};
int next_post_idx = 0;
uint32_t last_room_timestamp = 0, post_ready_at[MAX_UNSYNCED_POSTS] = {}, post_ready_mask = UINT32_MAX, next_push = 0;
uint16_t _num_posted = 0;
mesh::RoomHistoryState room_history_state;
bool room_history_enabled = false, room_history_available = true;
char room_topic[152] = "Topic <img src=x onerror=attack()>";
MyMesh() { self_id.pub_key[0] = 4; metadata_filesystem = &storage; assert(room_access.load(_fs)); }
Clock* getRTCClock() { return &clock; }
bool handleRoomWebCommand(const char*, char*);
void processRoomRequest(const uint8_t*, uint32_t, char*, char*, size_t);
void serviceRoomQuotas();
bool storePost(const mesh::Identity&, const char*);
bool snapshotRoomHistory();
};
#include "production.inc"
static std::array<uint8_t, 32> token(uint8_t id = 1) { std::array<uint8_t, 32> value = {}; value[0] = id; return value; }
static std::string execute(MyMesh& m, const std::string& input, uint32_t sequence,
uint8_t owner = 1, size_t capacity = 2048) {
metadata_filesystem = &m.storage;
std::vector<char> request(input.begin(), input.end()); request.push_back(0);
std::vector<char> reply(capacity + 2, 0x7f);
const auto key = token(owner);
m.processRoomRequest(key.data(), sequence, request.data(), reply.data() + 1, capacity);
assert(reply.front() == 0x7f && reply.back() == 0x7f && json_allocations == 0);
if (!capacity) return "";
assert(memchr(reply.data() + 1, 0, capacity)); return reply.data() + 1;
}
static JsonDocument result(MyMesh& m, const std::string& input, uint32_t sequence, uint8_t owner = 1) {
const auto text = execute(m, input, sequence, owner);
JsonDocument json; assert(deserializeJson(json, text) == DeserializationError::Ok); return json;
}
static std::string request(const char* op, const char* password = "write-secret", const std::string& fields = "") {
return std::string("{\"op\":\"") + op + "\",\"password\":\"" + password + "\"" + fields + "}";
}
static void error(MyMesh& m, const std::string& input, uint32_t sequence, const char* fragment, uint8_t owner = 1) {
const auto json = result(m, input, sequence, owner); const char* text = json["error"];
if (!text || !strstr(text, fragment)) fprintf(stderr, "Expected %s, got %s for %.120s\n", fragment, text ? text : "no error", input.c_str());
assert(text && strstr(text, fragment));
}
static std::string encoded(const std::string& body) {
std::vector<char> out(4 * ((body.size() + 2) / 3) + 1);
mesh::roomEncodeBase64(reinterpret_cast<const uint8_t*>(body.data()), body.size(), out.data()); return out.data();
}
static std::string saveRequest(uint8_t id, uint32_t version, const std::string& title, const std::string& body, const char* password = "admin-secret") {
return request("board.save", password, ",\"boot\":71,\"id\":" + std::to_string(id) + ",\"version\":" + std::to_string(version)
+ ",\"title\":\"" + title + "\",\"body64\":\"" + encoded(body) + "\"");
}
static void enable(MyMesh& m) { char reply[160]; assert(m.handleRoomWebCommand("set room.web on", reply)); assert(m.room_web_enabled); }
static unsigned floors(const MyMesh& m) { unsigned total = 0; for (const auto& user : m.room_web_users) total += user.last_sequence; return total; }
int main() {
unsigned scenarios = 0;
{
MyMesh m; assert(!m.room_web_enabled);
error(m, request("status"), 1, "disabled"); assert(floors(m) == 0);
char reply[160]; assert(m.handleRoomWebCommand("get room.web", reply) && strstr(reply, "off"));
Preferences::fail_write = true; assert(m.handleRoomWebCommand("set room.web on", reply) && !m.room_web_enabled);
Preferences::fail_write = false; enable(m);
assert(!m.handleRoomWebCommand("get room.webx", reply));
auto status = result(m, request("status"), 1); assert(status["role"] == PERM_ACL_READ_WRITE && status["boot"] == 71);
assert(strcmp(status["topic"], m.room_topic) == 0 && status["persistent_history"] == false);
status = result(m, request("status", "bad-password", ",\"key\":\"radio-admin\",\"permissions\":3"), 2);
assert(status["role"] == PERM_ACL_GUEST && m.acl.lookups == 0);
const std::string web_key = status["web_key"].as<std::string>(); assert(web_key.size() == 64);
error(m, request("post", "bad-password", ",\"boot\":71,\"name\":\"A\",\"text\":\"denied\""), 500, "read-only");
assert(floors(m) == 2 && m.last_room_timestamp == 0 && m._num_posted == 0);
assert(result(m, request("status", "admin-secret"), 3)["role"] == PERM_ACL_ADMIN); ++scenarios;
}
{
MyMesh m; enable(m); m._prefs.allow_read_only = false;
error(m, request("status", "wrong"), 100, "incorrect"); assert(floors(m) == 0 && !m.room_web_request_authenticated);
error(m, request("status"), 100, "invalid browser", 0); assert(floors(m) == 0 && !m.room_web_request_authenticated);
assert(result(m, request("status"), 1)["role"] == PERM_ACL_READ_WRITE);
error(m, request("post", "write-secret", ",\"boot\":70,\"name\":\"A\",\"text\":\"no\""), 200, "restarted");
assert(floors(m) == 1 && m._num_posted == 0);
error(m, saveRequest(1, 0, "Title", "body", "write-secret"), 300, "admin"); assert(floors(m) == 1);
const auto okay = result(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"one\""), 2);
assert(okay["ok"] == true && m.last_room_timestamp == 1000 && m._num_posted == 1);
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"one\""), 2, "completed");
assert(m._num_posted == 1 && m.acl.radio_admin.extra.room.last_post_timestamp == 0);
auto post = result(m, request("posts", "write-secret", ",\"after\":0"), 3);
assert(strcmp(post["post"]["text"], "A: one") == 0 && post["post"]["timestamp"] == 1000);
post = result(m, request("posts", "write-secret", ",\"after\":1000"), 4); assert(post["post"].isNull()); ++scenarios;
}
{
MyMesh m; enable(m); m.room_history_enabled = true;
const std::string text(148, 'x');
assert(result(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"" + text + "\""), 1)["ok"] == true);
assert(strlen(m.posts[0].text) == 151 && m.room_history_state.count == 1);
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"" + text + "x\""), 2, "151");
assert(m._num_posted == 1 && m.last_room_timestamp == 1000);
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A:B\",\"text\":\"x\""), 3, "display name");
m.storage.capacity = 0;
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"retain\""), 4, "not retained");
assert(m._num_posted == 1 && m.last_room_timestamp == 1000 && m.room_history_state.count == 1);
m.storage.reset(); m.clock.now = 2;
assert(result(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"retry with new sequence\""), 5)["timestamp"] == 1001);
assert(m._num_posted == 2 && m.room_history_state.count == 2); ++scenarios;
}
{
MyMesh m; enable(m); assert(m.room_access.setRates(m._fs, 1, 2));
assert(result(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"one\""), 1)["ok"] == true);
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"two\""), 2, "rate limit");
assert(m._num_posted == 1 && m.last_room_timestamp == 1000);
result(m, request("status"), 3); result(m, request("status"), 4); error(m, request("status"), 5, "rate limit");
ticks += 60000; result(m, request("status"), 6);
const auto key = token(); uint8_t author[32]; mesh::Utils::sha256(author, 32, key.data(), 32, m.self_id.pub_key, 32);
assert(m.room_access.addBan(m._fs, author) == mesh::RoomAccessPolicy::BanResult::Saved);
const unsigned floor = floors(m); error(m, request("status"), 1000, "denied"); assert(floors(m) == floor);
assert(m.room_access.removeBan(m._fs, author) == mesh::RoomAccessPolicy::BanResult::Saved);
result(m, request("status"), 7); ++scenarios;
}
{
MyMesh m; enable(m); const std::string title = u8"Café 地図 📡"; const std::string body(2048, 'b');
const auto saved = result(m, saveRequest(1, 0, title, body), 1);
if (saved["ok"] != true) fprintf(stderr, "Full board save error: %s\n", saved["error"].as<const char*>());
assert(saved["ok"] == true);
assert(saved["version"] == 1);
auto page = result(m, request("board.index", "", ",\"revision\":0,\"cursor\":0"), 2);
assert(page["revision"] == 1 && page["articles"].size() == 1 && page["next"] == 255);
assert(page["articles"][0]["length"] == 2048 && strcmp(page["articles"][0]["title"], title.c_str()) == 0);
std::string assembled;
for (unsigned offset = 0, sequence = 3; offset < 2048; ++sequence) {
auto chunk = result(m, request("board.read", "", ",\"id\":1,\"version\":1,\"offset\":" + std::to_string(offset)), sequence);
assert(chunk["version"] == 1 && chunk["offset"] == offset && chunk["total"] == 2048);
uint8_t bytes[128]; size_t length; assert(mesh::roomDecodeBase64(chunk["data64"], bytes, sizeof(bytes), length) && length > 0 && length <= 128);
assembled.append(reinterpret_cast<const char*>(bytes), length); offset += length; assert(chunk["next"] == offset);
}
assert(assembled == body);
const auto updated = result(m, saveRequest(1, 1, "Updated", "new body"), 30);
assert(updated["ok"] == true && updated["version"] == 2);
error(m, request("board.index", "", ",\"revision\":1,\"cursor\":0"), 31, "board changed");
error(m, request("board.read", "", ",\"id\":1,\"version\":1,\"offset\":128"), 32, "article changed");
error(m, saveRequest(1, 1, "Stale", "old"), 33, "article changed");
error(m, request("board.delete", "admin-secret", ",\"boot\":71,\"id\":1,\"version\":0"), 34, "current article version");
assert(result(m, request("board.delete", "admin-secret", ",\"boot\":71,\"id\":1,\"version\":2"), 35)["ok"] == true);
assert(result(m, saveRequest(1, 0, "Reused", "new"), 36)["ok"] == true);
error(m, request("board.read", "", ",\"id\":1,\"version\":2,\"offset\":0"), 37, "article changed"); ++scenarios;
}
{
MyMesh m; enable(m); uint32_t sequence = 1;
for (const std::string& input : {std::string("{"), std::string("[]"), std::string("null"), std::string("{\"op\":{\"a\":{\"b\":{\"c\":{\"d\":1}}}}}"),
std::string("{\"op\":\"status\",\"password\":\"write-secret\\u0000ignored\"}"), std::string("{\"op\":\"status\\u0000ignored\",\"password\":\"write-secret\"}"),
std::string("{\"op\":3,\"password\":[]}")}) {
const auto json = result(m, input, sequence++); assert(json["error"].is<const char*>() && floors(m) == 0);
}
error(m, std::string(4097, ' '), sequence++, "invalid request");
for (const std::string text : {"A===", "====", "Zg=A", "Zg==Zg==", "Zh==", "Zm9=", "*m9v", "Zg", "Zg== "}) {
error(m, request("board.save", "admin-secret", ",\"boot\":71,\"id\":1,\"version\":0,\"title\":\"T\",\"body64\":\"" + text + "\""), sequence++, "encoding");
}
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"before\\u0000after\""), sequence++, "name and message");
error(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\\u0000B\",\"text\":\"body\""), sequence++, "name and message");
error(m, request("board.save", "admin-secret", ",\"boot\":71,\"id\":1,\"version\":0,\"title\":\"T\\u0000X\",\"body64\":\"Zg==\""), sequence++, "article changed");
error(m, request("board.save", "admin-secret", ",\"boot\":71,\"id\":1,\"version\":0,\"title\":\"T\",\"body64\":\"Zg==\\u0000Zg==\""), sequence++, "article changed");
assert(m._num_posted == 0 && m.last_room_timestamp == 0);
error(m, saveRequest(1, 0, std::string(64, 't'), "body"), sequence++, "article changed");
error(m, saveRequest(1, 0, "Title", std::string(2049, 'b')), sequence++, "encoding");
assert(!m.storage.files.count(mesh::ROOM_BOARD_PRIMARY_PATH));
deny_json_allocation = true; error(m, request("status"), sequence++, "invalid JSON"); deny_json_allocation = false;
result(m, request("status"), sequence++);
// Excess unknown array members exhaust the actual bounded allocator.
std::string huge = "{\"op\":\"status\",\"password\":\"write-secret\",\"extra\":[";
for (unsigned i = 0; i < 1000; ++i) { if (i) huge += ','; huge += '0'; } huge += "]}";
error(m, huge, sequence++, "invalid JSON"); assert(json_allocations == 0); ++scenarios;
}
{
MyMesh m; enable(m);
for (uint8_t owner = 1; owner <= 8; ++owner) result(m, request("status"), 1, owner);
error(m, request("status"), 1, "busy", 9); ticks += 1200000;
result(m, request("status"), 1, 9);
// Every small response capacity stays within its provided buffer.
for (size_t capacity = 0; capacity < 200; ++capacity) execute(m, request("status"), uint32_t(capacity + 2), 9, capacity);
for (unsigned i = 0; i < 40; ++i) assert(result(m, request("post", "write-secret", ",\"boot\":71,\"name\":\"A\",\"text\":\"bounded ring\""), 300 + i, 9)["ok"] == true);
assert(m._num_posted == 40 && m.next_post_idx == 8 && m.last_room_timestamp == 1039); ++scenarios;
}
// Deliver concrete backend responses for the browser boundary fixture.
MyMesh boundary; enable(boundary);
printf("BOUNDARY_STATUS %s\n", execute(boundary, request("status"), 1).c_str());
assert(result(boundary, saveRequest(1, 0, "Instructions", "Read only this article"), 2)["ok"] == true);
printf("BOUNDARY_INDEX %s\n", execute(boundary, request("board.index", "write-secret", ",\"revision\":0,\"cursor\":0"), 3).c_str());
printf("BOUNDARY_READ %s\n", execute(boundary, request("board.read", "write-secret", ",\"id\":1,\"version\":1,\"offset\":0"), 4).c_str());
printf("PASS: %u actual room web service authorization, storage, quota, JSON and boundary scenarios\n", scenarios);
}
@@ -7,6 +7,8 @@
#include <vector>
#include <helpers/ClientACLResponse.h>
#include <helpers/sensors/LPPDataHelpers.h>
#include "../room_history_store/filesystem.h"
#include <helpers/RoomBoardProtocol.h>
#include "telemetry_capacity.inc"
#include "telemetry_access.inc"
@@ -127,7 +129,12 @@ public:
};
class MyMesh : public SensorMesh {
public:
MyMesh() { telemetry.max_len = ROOM_TELEMETRY_CAPACITY; telemetry.data.reserve(telemetry.max_len); }
MemoryFS room_fs;
MemoryFS* _fs = &room_fs;
MyMesh() {
telemetry.max_len = ROOM_TELEMETRY_CAPACITY; telemetry.data.reserve(telemetry.max_len);
metadata_filesystem = _fs;
}
int handleRequest(ClientInfo*, uint32_t, uint8_t*, size_t,
size_t = mesh::CLIENT_ACL_DIRECT_REPLY_CAPACITY);
};
@@ -245,6 +252,30 @@ static void room_telemetry_checks() {
assert(target.handleRequest(nullptr, 51, query, sizeof(query)) == 0);
}
static void room_board_dispatch_checks() {
ClientInfo client;
uint8_t malformed[] = {mesh::ROOM_BOARD_REQUEST_SUBTYPE, 0};
for (size_t capacity = 0; capacity <= MAX_PACKET_PAYLOAD; ++capacity) {
MyMesh target;
memset(target.reply_data, 0xee, sizeof(target.reply_data));
const int length = target.handleRequest(&client, 51, malformed, sizeof(malformed), capacity);
assert(length == (capacity < 7 ? 0 : 7));
assert(size_t(length) <= capacity);
for (size_t i = capacity; i < sizeof(target.reply_data); ++i) assert(target.reply_data[i] == 0xee);
if (length) {
uint32_t tag = 0; memcpy(&tag, target.reply_data, sizeof(tag));
assert(tag == 51 && target.reply_data[4] == mesh::ROOM_BOARD_REQUEST_SUBTYPE);
assert(target.reply_data[5] == 0 && target.reply_data[6] == 1);
}
}
uint8_t index[] = {mesh::ROOM_BOARD_REQUEST_SUBTYPE, 0, 0, 0, 0, 0, 0};
MyMesh target;
assert(target.handleRequest(&client, 51, index, sizeof(index), 13) == 7);
assert(target.reply_data[6] == 1);
assert(target.handleRequest(&client, 51, index, sizeof(index), 14) == 14);
assert(target.reply_data[6] == 0);
}
static void history_checks() {
ClientInfo client;
uint8_t query[10] = {};
@@ -313,6 +344,7 @@ static void history_checks() {
int main(int argc, char** argv) {
assert(argc == 2);
if (!strcmp(argv[1], "room")) room_telemetry_checks();
else if (!strcmp(argv[1], "room.board")) room_board_dispatch_checks();
else if (!strcmp(argv[1], "telemetry")) telemetry_checks();
else if (!strcmp(argv[1], "history")) history_checks();
else if (!strcmp(argv[1], "empty")) {
+5
View File
@@ -4,6 +4,7 @@
#include <cstdint>
#include <cstring>
#include <initializer_list>
#include <helpers/RoomWebMailbox.h>
static uint32_t millis() { return 123; }
struct WebConfigBatch {
@@ -34,6 +35,7 @@ struct WebConfigServer {
DNS* _dns = nullptr;
Callbacks callbacks;
Callbacks* _cb = &callbacks;
mesh::RoomWebMailbox* _room_mailbox = new mesh::RoomWebMailbox;
Mode _mode = MODE_LAN;
bool _stopping = false, _keep_wifi_on_stop = false, _was_setup_ap = false;
bool _owns_wifi = true, _stop_warned = false, _initial_setup = false;
@@ -54,6 +56,7 @@ struct WebConfigServer {
void requestStop();
bool stopForOTA(char*);
void finalizeTeardown();
~WebConfigServer() { delete _room_mailbox; }
};
@METHODS@
@@ -79,6 +82,7 @@ int main() {
WiFi.ap = true;
portal.requestStop(); // A duplicate stop cannot revoke the handoff.
portal.finalizeTeardown(); // Existing requests have finally drained.
assert(portal._room_mailbox == nullptr);
assert(WiFi.ap && WiFi.sta && WiFi.stops == 0);
assert(WiFi.ap_stops == unsigned(setup));
assert(portal.callbacks.stops == 1 && !portal._keep_wifi_on_stop);
@@ -88,6 +92,7 @@ int main() {
WiFi = WiFiFake{};
ordinary.requestStop();
ordinary.finalizeTeardown();
assert(ordinary._room_mailbox == nullptr);
assert(WiFi.stops == 1 && !WiFi.sta); // Normal stop keeps its old behavior.
WebConfigServer failed;
failed._was_setup_ap = true;
+5 -1
View File
@@ -2,7 +2,9 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <new>
#include <string>
#include <helpers/RoomWebMailbox.h>
#include <helpers/WiFiReconnectPolicy.h>
static uint32_t clock_ms = 1000;
uint32_t millis() { return clock_ms; }
@@ -77,7 +79,7 @@ struct DNS { void stop() {} };
class WebConfigServer {
public:
enum Mode { MODE_OFF, MODE_SETUP, MODE_CONNECTING, MODE_LAN };
struct Callbacks {};
struct Callbacks { bool supportsRoomService() const { return false; } };
Callbacks* _cb;
void* _mqtt_prefs;
bool _owns_wifi;
@@ -86,6 +88,7 @@ public:
const uint8_t* _pub_key;
const char *_fw_ver, *_build_date, *_role, *_board_name;
void* _mux = nullptr;
mesh::RoomWebMailbox* _room_mailbox = nullptr;
bool _cli_enabled = false;
char _wifi_ssid[32] = {}, _wifi_password[65] = {};
uint8_t _wifi_power_save = 0;
@@ -130,6 +133,7 @@ public:
void createServer() { ++server_starts; }
void probeBoardCommands() { _board_cmds_probed = true; }
void serviceTerminal(uint32_t) {}
void serviceRoom(uint32_t) {}
bool bluetoothWiFiCoexistenceRequired() { return false; }
bool acceptWiFi(Entry& e, const char* value) {
@CREDENTIAL_BATCH@