Add owner-controlled personal room mailboxes and WiFi management
This commit is contained in:
1 parent
5165b6f490
commit
2c1c2c8e99
24 files changed
+3607
-24
No files matched your search
Vendored
+13
-1
@@ -7,6 +7,8 @@
|
||||
#include "filesystem.h"
|
||||
#include <Packet.h>
|
||||
#include <helpers/RoomAccessPolicy.h>
|
||||
#include <helpers/RoomMailProtocol.h>
|
||||
#include <helpers/RoomBoardProtocol.h>
|
||||
#include <helpers/RoomClientPathCommand.h>
|
||||
#include <helpers/RoomCatchUp.h>
|
||||
#include <helpers/ClientPathObservation.h>
|
||||
@@ -93,6 +95,7 @@ static uint32_t ticks = 100;
|
||||
static uint32_t millis() { return ticks; }
|
||||
struct Sent {
|
||||
mesh::Packet packet;
|
||||
uint8_t recipient[PUB_KEY_SIZE]{};
|
||||
uint8_t path[MAX_PATH_SIZE]{};
|
||||
uint8_t path_len = 0;
|
||||
unsigned long delay = 0;
|
||||
@@ -115,6 +118,7 @@ struct MyMesh {
|
||||
FakeRng rng;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD]{};
|
||||
mesh::Packet pool[64];
|
||||
mesh::Identity datagram_recipients[64]{};
|
||||
unsigned used = 0, allocations = 0, releases = 0, fail_allocation = UINT32_MAX;
|
||||
bool send_ok = true;
|
||||
unsigned general_commands = 0, post_count = 0, retry_replacements = 0, _num_post_pushes = 0;
|
||||
@@ -155,10 +159,12 @@ struct MyMesh {
|
||||
return &pool[used++];
|
||||
}
|
||||
void releasePacket(mesh::Packet* p) { assert(p != nullptr); ++releases; }
|
||||
mesh::Packet* createDatagram(uint8_t type, const mesh::Identity&, const uint8_t*,
|
||||
mesh::Packet* createDatagram(uint8_t type, const mesh::Identity& recipient, const uint8_t*,
|
||||
const uint8_t* data, size_t n) {
|
||||
auto p = obtainNewPacket();
|
||||
if (p) {
|
||||
assert(n <= sizeof(p->payload));
|
||||
datagram_recipients[p - pool] = recipient;
|
||||
p->header = type << PH_TYPE_SHIFT;
|
||||
p->payload_len = n;
|
||||
memcpy(p->payload, data, n);
|
||||
@@ -177,6 +183,7 @@ struct MyMesh {
|
||||
bool sendDirect(mesh::Packet* p, const uint8_t* path, uint8_t n, unsigned long delay = 0) {
|
||||
assert(p && mesh::Packet::isValidPathLen(n));
|
||||
Sent value; value.packet = *p; value.path_len = n; value.delay = delay;
|
||||
memcpy(value.recipient, datagram_recipients[p - pool].pub_key, PUB_KEY_SIZE);
|
||||
value.retry_enabled = _prefs.direct_retry_enabled != 0;
|
||||
memcpy(value.path, path, mesh::encodedClientPathByteLength(n));
|
||||
sent.push_back(value);
|
||||
@@ -184,6 +191,7 @@ struct MyMesh {
|
||||
}
|
||||
bool sendFloodReply(mesh::Packet* p, unsigned long delay, uint8_t hash_size) {
|
||||
Sent value; value.packet = *p; value.delay = delay; value.direct = false;
|
||||
memcpy(value.recipient, datagram_recipients[p - pool].pub_key, PUB_KEY_SIZE);
|
||||
value.path_len = (hash_size - 1) << 6;
|
||||
sent.push_back(value);
|
||||
return send_ok;
|
||||
@@ -210,6 +218,9 @@ struct MyMesh {
|
||||
int handleRequest(ClientInfo*, uint32_t, uint8_t*, size_t, size_t) { return 0; }
|
||||
static bool saveFilter(ClientInfo*);
|
||||
bool handleClientPathCommand(ClientInfo*, char*, char*);
|
||||
bool roomClientChatEnabled(ClientInfo*);
|
||||
bool handleRoomMailClientCommand(ClientInfo*, const char*, uint64_t, char*, size_t);
|
||||
bool handleRoomMailText(ClientInfo*, mesh::Packet*, const uint8_t*, uint8_t*, size_t);
|
||||
bool executeClientPathCommand(ClientInfo*, mesh::RoomClientPathCommand, const char*, char*);
|
||||
bool handleRoomCatchUpCommand(ClientInfo*, char*, char*);
|
||||
bool applyRoomCatchUpCommand(ClientInfo*, const char*, uint32_t, char*);
|
||||
@@ -220,6 +231,7 @@ struct MyMesh {
|
||||
void onPeerDataRecv(mesh::Packet*, uint8_t, int, const uint8_t*, uint8_t*, size_t);
|
||||
void command(const char* text, uint32_t timestamp = 100, unsigned sender = 0,
|
||||
uint32_t logical = 0, uint8_t flags = TXT_TYPE_CLI_COMMAND) {
|
||||
metadata_filesystem = &policy_fs;
|
||||
std::vector<uint8_t> data(5 + strlen(text) + mesh::RemoteCliRequest::EXTENSION_SIZE + 1);
|
||||
memcpy(data.data(), ×tamp, 4); data[4] = flags << 2;
|
||||
memcpy(data.data() + 5, text, strlen(text));
|
||||
|
||||
+43
-1
@@ -8,6 +8,7 @@
|
||||
#include <helpers/RoomAccessPolicy.h>
|
||||
#include <helpers/ClientPathPersistence.h>
|
||||
#include <helpers/RoomClientPathCommand.h>
|
||||
#include <helpers/RoomMailStore.h>
|
||||
|
||||
#define PUB_KEY_SIZE 32
|
||||
#define MAX_PATH_SIZE 64
|
||||
@@ -103,6 +104,9 @@ struct MyMesh {
|
||||
std::vector<Sent> sent;
|
||||
bool pool_available = true, queue_available = true, alternate_available = true;
|
||||
unsigned releases = 0;
|
||||
unsigned cancellations = 0;
|
||||
uint8_t retry_key[MAX_HASH_SIZE] = {};
|
||||
uint32_t retry_timestamp = 0;
|
||||
uint8_t reply_data[MAX_PACKET_PAYLOAD] = {};
|
||||
unsigned long next_push = 0, room_topic_ready_at = 0;
|
||||
bool room_topic_ready = true;
|
||||
@@ -158,7 +162,9 @@ struct MyMesh {
|
||||
memcpy(entry.path, path, mesh::encodedClientPathByteLength(length));
|
||||
return true;
|
||||
}
|
||||
void replaceActiveMessageRetries(mesh::Packet*, const uint8_t*, uint32_t) {}
|
||||
void replaceActiveMessageRetries(mesh::Packet*, const uint8_t* key, uint32_t timestamp) {
|
||||
memcpy(retry_key, key, sizeof(retry_key)); retry_timestamp = timestamp;
|
||||
}
|
||||
bool pushPostToClient(ClientInfo*, PostInfo&);
|
||||
bool sendClientReply(ClientInfo*, mesh::Packet*, unsigned long, uint8_t);
|
||||
bool pushRoomTextToClient(ClientInfo*, uint32_t, const mesh::Identity&, const char*, uint32_t = 0);
|
||||
@@ -166,6 +172,12 @@ struct MyMesh {
|
||||
void activateRoomTopic();
|
||||
bool handleRoomTopicCommand(const char*, char*);
|
||||
void serviceRoomPush();
|
||||
uint8_t getUnsyncedCount(ClientInfo*);
|
||||
bool roomClientChatEnabled(ClientInfo*);
|
||||
bool cancelActiveMessageRetries(const uint8_t* key, uint32_t timestamp) {
|
||||
assert(memcmp(key, retry_key, sizeof(retry_key)) == 0 && timestamp == retry_timestamp);
|
||||
++cancellations; return true;
|
||||
}
|
||||
void tick(uint32_t delta = 0) {
|
||||
ticks += delta + 1;
|
||||
next_push = uint32_t(ticks - 1);
|
||||
@@ -362,5 +374,35 @@ int main() {
|
||||
}
|
||||
assert(m._prefs.direct_retry_enabled == 1);
|
||||
}
|
||||
for (bool pending_topic : {false, true}) {
|
||||
MyMesh m; auto& client = m.acl.clients[0];
|
||||
m.topic("Public topic");
|
||||
if (!pending_topic) m.post(0, 900, "Public chat");
|
||||
m.tick(6000); assert(m.sent.size() == 1 && client.extra.room.pending_ack);
|
||||
const uint32_t old_ack = client.extra.room.pending_ack;
|
||||
mesh::RoomMailSettings settings; settings.mailbox_only = true;
|
||||
assert(mesh::saveRoomMailSettings(&m.policy_fs, client.id.pub_key, settings) == mesh::RoomMailResult::Success);
|
||||
assert(!m.roomClientChatEnabled(&client) && m.getUnsyncedCount(&client) == 0);
|
||||
m.tick(); assert(!client.extra.room.pending_ack && !client.extra.room.pending_topic_revision);
|
||||
assert(m.cancellations == 1 && !m.processAck(reinterpret_cast<const uint8_t*>(&old_ack)));
|
||||
for (int poll = 0; poll < 10; ++poll) m.tick(12000);
|
||||
assert(m.sent.size() == 1 && client.extra.room.sync_since == 0);
|
||||
settings.mailbox_only = false;
|
||||
assert(mesh::saveRoomMailSettings(&m.policy_fs, client.id.pub_key, settings) == mesh::RoomMailResult::Success);
|
||||
m.tick(); assert(m.sent.size() == 2); m.ack();
|
||||
}
|
||||
{
|
||||
// An intermittently connected mailbox subscriber never downloads chat or
|
||||
// the topic; corrupt saved policy remains closed to automatic delivery.
|
||||
MyMesh m; auto& client = m.acl.clients[0];
|
||||
mesh::RoomMailSettings settings; settings.mailbox_only = true;
|
||||
assert(mesh::saveRoomMailSettings(&m.policy_fs, client.id.pub_key, settings) == mesh::RoomMailResult::Success);
|
||||
m.topic("Public topic"); m.post(0, 900, "Public chat");
|
||||
for (int poll = 0; poll < 10; ++poll) m.tick(6000);
|
||||
assert(m.sent.empty() && !m.getUnsyncedCount(&client));
|
||||
m.policy_fs.put(mesh::ROOM_MAIL_PRIMARY_PATH, {'c','o','r','r','u','p','t'});
|
||||
for (int poll = 0; poll < 10; ++poll) m.tick(6000);
|
||||
assert(m.sent.empty() && !m.roomClientChatEnabled(&client));
|
||||
}
|
||||
puts("room topic delivery regressions passed");
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"status": {"name":"Test room","topic":"Topic <img src=x onerror=attack()>","boot":71,"role":2,"web_key":"5f5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a","persistent_history":false},
|
||||
"status": {"name":"Test room","topic":"Topic <img src=x onerror=attack()>","boot":71,"role":2,"web_key":"5f5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a","persistent_history":false,"mailbox_only":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=="}
|
||||
}
|
||||
+210
-4
@@ -24,6 +24,7 @@ static void* trackedRealloc(void* ptr, size_t size) {
|
||||
#undef free
|
||||
#undef realloc
|
||||
#include <helpers/RoomBoardStore.h>
|
||||
#include <helpers/RoomMailWeb.h>
|
||||
#include <helpers/RoomHistoryStore.h>
|
||||
#include <helpers/RoomAccessPolicy.h>
|
||||
#include <helpers/RoomLoginAuthorization.h>
|
||||
@@ -174,6 +175,7 @@ struct MyMesh {
|
||||
bool applyRoomCatchUpCommand(ClientInfo*, const char*, uint32_t, char*);
|
||||
static bool saveFilter(ClientInfo*);
|
||||
uint8_t getUnsyncedCount(ClientInfo*);
|
||||
bool roomClientChatEnabled(ClientInfo*);
|
||||
bool handleRoomHistoryCommand(const char*, char*);
|
||||
bool handleRoomTopicCommand(const char*, char*);
|
||||
void activateRoomTopic();
|
||||
@@ -237,7 +239,8 @@ static void seedClients(MyMesh& m, unsigned count = 5) {
|
||||
}
|
||||
static void adminAuthorizationCases() {
|
||||
const char* operations[] = {"admin.users", "admin.user", "admin.route", "admin.catchup",
|
||||
"admin.access", "admin.ban", "admin.settings", "admin.topic", "admin.history", "admin.rates"};
|
||||
"admin.access", "admin.ban", "admin.settings", "admin.topic", "admin.history", "admin.rates",
|
||||
"admin.mail.list", "admin.mail.settings", "admin.mail.policy", "admin.mail.delete"};
|
||||
unsigned denied = 0;
|
||||
for (const char* password : {"", "wrong-password", "write-secret"}) {
|
||||
for (const char* operation : operations) {
|
||||
@@ -554,7 +557,7 @@ static void adminInvalidAndSessionCases() {
|
||||
assert(m.room_access.postRate() == 0 && m.room_access.pollRate() == 0);
|
||||
}
|
||||
const char* writes[] = {"admin.route", "admin.catchup", "admin.access", "admin.ban",
|
||||
"admin.topic", "admin.history", "admin.rates"};
|
||||
"admin.topic", "admin.history", "admin.rates", "admin.mail.policy", "admin.mail.delete"};
|
||||
for (const char* operation : writes) {
|
||||
MyMesh m; enable(m); seedClients(m);
|
||||
error(m, adminClientRequest(operation, m.acl.clients[1], "", 70), 99, "restarted");
|
||||
@@ -581,7 +584,205 @@ static void adminInvalidAndSessionCases() {
|
||||
assert(banned.room_access.addBan(banned._fs, author) == mesh::RoomAccessPolicy::BanResult::Saved);
|
||||
error(banned, request("admin.settings", "admin-secret"), 1, "access denied");
|
||||
assert(floors(banned) == 0 && banned.acl.lookups == 0 && !banned.room_web_request_authenticated);
|
||||
printf("ADMIN_INVALID: %zu strict schemas, 21 boot guards, replay/auth floors, bounded sessions and banned browser passed\n", std::size(invalid));
|
||||
printf("ADMIN_INVALID: %zu strict schemas, %zu boot guards, replay/auth floors, bounded sessions and banned browser passed\n", std::size(invalid), std::size(writes) * 3);
|
||||
}
|
||||
static std::string browserKey(const MyMesh& m, uint8_t owner) {
|
||||
const auto identity = token(owner); uint8_t author[32]; char key[65];
|
||||
mesh::Utils::sha256(author, sizeof(author), identity.data(), identity.size(), m.self_id.pub_key, PUB_KEY_SIZE);
|
||||
mesh::Utils::toHex(key, author, sizeof(author)); return key;
|
||||
}
|
||||
static std::string quoted(const std::string& value) {
|
||||
JsonDocument json; json.set(value); std::string output; serializeJson(json, output); return output;
|
||||
}
|
||||
static std::string mailPolicyFields(const char* mode, uint32_t revision, bool only = false,
|
||||
const std::vector<std::string>& allowed = {}) {
|
||||
std::string fields = ",\"boot\":71,\"mode\":" + quoted(mode) + ",\"expected_revision\":" + std::to_string(revision)
|
||||
+ ",\"mailbox_only\":" + (only ? "true" : "false") + ",\"allowlist\":[";
|
||||
for (size_t i = 0; i < allowed.size(); ++i) { if (i) fields += ','; fields += quoted(allowed[i]); }
|
||||
return fields + ']';
|
||||
}
|
||||
static std::string mailSendRequest(const std::string& recipient, const std::string& text,
|
||||
const char* password = "write-secret") {
|
||||
return request("mail.send", password, ",\"boot\":71,\"recipient\":" + quoted(recipient) + ",\"text\":" + quoted(text));
|
||||
}
|
||||
static std::string mailListRequest(uint8_t cursor = 0, uint32_t revision = 0,
|
||||
const char* password = "") {
|
||||
return request("mail.list", password, ",\"cursor\":" + std::to_string(cursor) + ",\"revision\":" + std::to_string(revision));
|
||||
}
|
||||
static std::string mailOwnerRequest(const char* operation, const std::string& owner,
|
||||
const std::string& fields = "") {
|
||||
return request(operation, "admin-secret", ",\"owner\":" + quoted(owner) + fields);
|
||||
}
|
||||
static uint32_t mailRevision(MyMesh& m, uint32_t& sequence, uint8_t owner) {
|
||||
auto settings = result(m, request("mail.settings", ""), sequence++, owner);
|
||||
assert(!settings["error"] && settings["revision"].is<uint32_t>());
|
||||
return settings["revision"].as<uint32_t>();
|
||||
}
|
||||
static void mailAuthorizationAndPolicyCases() {
|
||||
MyMesh m; enable(m); uint32_t sequence = 1;
|
||||
const auto first = result(m, request("mail.settings", ""), sequence++, 1);
|
||||
const std::string owner = first["owner"].as<std::string>(), sender = browserKey(m, 2);
|
||||
assert(owner == browserKey(m, 1) && owner != sender);
|
||||
assert(first["mode"] == "closed" && first["revision"] == 0 && first["total"] == 0 && first["mailbox_only"] == false);
|
||||
const auto impersonated = result(m, request("mail.settings", "", ",\"owner\":" + quoted(owner)
|
||||
+ ",\"key\":" + quoted(clientKey(m.acl.radio_admin)) + ",\"permissions\":3"), sequence++, 2);
|
||||
assert(impersonated["owner"] == sender && m.acl.lookups == 0);
|
||||
auto policy = result(m, request("mail.policy", "", mailPolicyFields("public", 0, true)), sequence++, 1);
|
||||
assert(policy["mode"] == "public" && policy["revision"].as<uint32_t>() > 0 && policy["mailbox_only"] == true);
|
||||
const uint32_t initial_revision = policy["revision"];
|
||||
error(m, request("mail.policy", "", mailPolicyFields("closed", 0)), sequence++, "changed", 1);
|
||||
assert(result(m, request("mail.settings", ""), sequence++, 1)["mode"] == "public");
|
||||
assert(result(m, request("status", ""), sequence++, 1)["mailbox_only"] == true);
|
||||
assert(result(m, request("status", ""), sequence++, 2)["mailbox_only"] == false);
|
||||
error(m, mailSendRequest(owner, "reader cannot send", ""), sequence++, "read-only", 2);
|
||||
auto sent = result(m, mailSendRequest(owner, "public mail"), sequence++, 2);
|
||||
assert(sent["ok"] == true && sent["id"].as<uint32_t>() > initial_revision);
|
||||
const uint32_t id = sent["id"], revision = mailRevision(m, sequence, 1);
|
||||
error(m, request("mail.read", "", ",\"owner\":" + quoted(owner) + ",\"id\":" + std::to_string(id) + ",\"offset\":0"), sequence++, "not found", 2);
|
||||
error(m, request("mail.ack", "", ",\"boot\":71,\"owner\":" + quoted(owner) + ",\"id\":" + std::to_string(id)), sequence++, "not found", 2);
|
||||
assert(result(m, request("mail.check", ""), sequence++, 1)["unread"] == 1);
|
||||
policy = result(m, request("mail.policy", "", mailPolicyFields("private", revision, true, {sender})), sequence++, 1);
|
||||
assert(policy["allowlist"].size() == 1 && policy["allowlist"][0] == sender);
|
||||
error(m, mailSendRequest(owner, "unapproved mail"), sequence++, "not accepting", 3);
|
||||
assert(result(m, mailSendRequest(owner, "approved mail"), sequence++, 2)["ok"] == true);
|
||||
const uint32_t private_revision = mailRevision(m, sequence, 1);
|
||||
policy = result(m, request("mail.policy", "", mailPolicyFields("closed", private_revision)), sequence++, 1);
|
||||
assert(policy["mode"] == "closed");
|
||||
error(m, mailSendRequest(owner, "closed mail"), sequence++, "not accepting", 2);
|
||||
assert(result(m, request("mail.check", ""), sequence++, 1)["total"] == 2 && m._num_posted == 0);
|
||||
assert(result(m, request("status", ""), sequence++, 1)["mailbox_only"] == false);
|
||||
const auto before = m.storage.get(mesh::ROOM_MAIL_PRIMARY_PATH);
|
||||
const uint32_t closed_revision = mailRevision(m, sequence, 1);
|
||||
error(m, request("mail.policy", "", mailPolicyFields("private", closed_revision, false, {sender, sender})), sequence++, "invalid", 1);
|
||||
std::vector<std::string> too_many(9, sender);
|
||||
error(m, request("mail.policy", "", mailPolicyFields("private", closed_revision, false, too_many)), sequence++, "eight", 1);
|
||||
assert(m.storage.get(mesh::ROOM_MAIL_PRIMARY_PATH) == before && m.acl.lookups == 0);
|
||||
printf("MAIL_AUTH: browser token identity isolation, reader/writer gates, strict stale-zero policy, public/private/closed and sender limits passed\n");
|
||||
}
|
||||
static void mailDeliveryAndDurabilityCases() {
|
||||
MyMesh m; enable(m); const std::string recipient = browserKey(m, 2);
|
||||
assert(result(m, request("mail.policy", "", mailPolicyFields("public", 0, true)), 1, 2)["mode"] == "public");
|
||||
std::string text; for (unsigned i = 0; i < 128; ++i) text += "\xF0\x9F\x93\xA1";
|
||||
assert(text.size() == 512);
|
||||
const auto submission = mailSendRequest(recipient, text); auto sent = result(m, submission, 200, 1);
|
||||
assert(sent["ok"] == true); const uint32_t id = sent["id"];
|
||||
error(m, submission, 200, "completed", 1);
|
||||
error(m, mailSendRequest(recipient, text + "x"), 201, "1-512", 1);
|
||||
error(m, request("mail.send", "write-secret", ",\"boot\":71,\"recipient\":" + quoted(recipient) + ",\"text\":\"before\\u0000after\""), 202, "1-512", 1);
|
||||
error(m, mailSendRequest(recipient.substr(0, 12), "bad recipient"), 203, "complete", 1);
|
||||
MyMesh restored; restored.storage.files = m.storage.files; enable(restored);
|
||||
const auto duplicate = result(restored, submission, 200, 1);
|
||||
assert(duplicate["ok"] == true && duplicate["id"] == id && restored.storage.write_opens == 0);
|
||||
uint32_t sequence = 1;
|
||||
auto page = result(restored, mailListRequest(), sequence++, 2);
|
||||
assert(page["messages"].size() == 1 && page["messages"][0]["id"] == id && page["messages"][0]["sender"] == browserKey(restored, 1));
|
||||
assert(page["messages"][0]["length"] == 512 && page["messages"][0]["acked"] == false && page["next"].isNull());
|
||||
std::string assembled;
|
||||
for (unsigned offset = 0; offset < 512;) {
|
||||
auto chunk = result(restored, request("mail.read", "", ",\"id\":" + std::to_string(id) + ",\"offset\":" + std::to_string(offset)), sequence++, 2);
|
||||
uint8_t bytes[128]; size_t length = 0;
|
||||
assert(chunk["id"] == id && chunk["sender"] == browserKey(restored, 1) && chunk["length"] == 512 && chunk["created"] == 1000);
|
||||
assert(chunk["offset"] == offset && chunk["acked"] == false && mesh::roomDecodeBase64(chunk["data64"], bytes, sizeof(bytes), length));
|
||||
assert(length == 128 && chunk["count"] == length && chunk["next"] == offset + length);
|
||||
assembled.append(reinterpret_cast<const char*>(bytes), length); offset += length;
|
||||
}
|
||||
assert(assembled == text);
|
||||
auto count = result(restored, request("mail.check", ""), sequence++, 2);
|
||||
assert(count["total"] == 1 && count["unread"] == 1 && count["mailbox_only"] == true);
|
||||
const auto eof = result(restored, request("mail.read", "", ",\"id\":" + std::to_string(id) + ",\"offset\":512"), sequence++, 2);
|
||||
assert(eof["count"] == 0 && eof["next"] == 512 && eof["data64"] == "");
|
||||
assert(result(restored, request("mail.ack", "", ",\"boot\":71,\"id\":" + std::to_string(id)), sequence++, 2)["ok"] == true);
|
||||
assert(result(restored, request("mail.check", ""), sequence++, 2)["unread"] == 0);
|
||||
error(restored, request("mail.read", "", ",\"id\":" + std::to_string(id) + ",\"offset\":0"), sequence++, "not found", 2);
|
||||
MyMesh after_ack; after_ack.storage.files = restored.storage.files; enable(after_ack);
|
||||
const auto repeated = result(after_ack, submission, 200, 1);
|
||||
assert(repeated["ok"] == true && repeated["id"] == id);
|
||||
assert(result(after_ack, request("mail.check", ""), 1, 2)["total"] == 0);
|
||||
assert(result(after_ack, request("mail.ack", "", ",\"boot\":71,\"id\":" + std::to_string(id)), 2, 2)["ok"] == true);
|
||||
printf("MAIL_DELIVERY: 512-byte UTF-8, bounded chunks/EOF, read retains unread mail, explicit durable ACK and retry across reboot passed\n");
|
||||
}
|
||||
static void mailAdministratorCases() {
|
||||
MyMesh m; enable(m); uint32_t sequence = 1; const std::string target = browserKey(m, 2), sender = browserKey(m, 1);
|
||||
auto selected = result(m, mailOwnerRequest("admin.mail.settings", target), sequence++, 9);
|
||||
assert(selected["owner"] == target && selected["revision"] == 0 && selected["blocked"] == false);
|
||||
selected = result(m, mailOwnerRequest("admin.mail.policy", target, mailPolicyFields("private", 0, true, {sender})), sequence++, 9);
|
||||
assert(selected["owner"] == target && selected["allowlist"][0] == sender && selected["mailbox_only"] == true);
|
||||
const uint32_t revision = selected["revision"];
|
||||
error(m, mailOwnerRequest("admin.mail.policy", target, mailPolicyFields("closed", 0)), sequence++, "changed", 9);
|
||||
error(m, mailOwnerRequest("admin.mail.policy", target, mailPolicyFields("closed", revision - 1)), sequence++, "changed", 9);
|
||||
const auto sent = result(m, mailSendRequest(target, "recipient-only content"), sequence++, 1); assert(sent["ok"] == true);
|
||||
auto metadata = result(m, request("admin.mail.list", "admin-secret", ",\"cursor\":0,\"revision\":0"), sequence++, 9);
|
||||
assert(metadata["mailboxes"].size() == 1 && metadata["mailboxes"][0]["owner"] == target && metadata["mailboxes"][0]["total"] == 1);
|
||||
assert(!metadata["mailboxes"][0]["text"] && !metadata["mailboxes"][0]["data64"] && !metadata["mailboxes"][0]["allowlist"]);
|
||||
error(m, mailOwnerRequest("admin.mail.read", target, ",\"id\":" + std::to_string(sent["id"].as<uint32_t>()) + ",\"offset\":0"), sequence++, "unknown", 9);
|
||||
auto own = result(m, request("mail.list", "admin-secret", ",\"owner\":" + quoted(target) + ",\"cursor\":0,\"revision\":0"), sequence++, 9);
|
||||
assert(own["messages"].size() == 0);
|
||||
assert(result(m, request("admin.ban", "admin-secret", ",\"boot\":71,\"key\":" + quoted(target) + ",\"banned\":true"), sequence++, 9)["ok"] == true);
|
||||
selected = result(m, mailOwnerRequest("admin.mail.settings", target), sequence++, 9);
|
||||
assert(selected["blocked"] == true && selected["mode"] == "private" && selected["allowlist"][0] == sender);
|
||||
error(m, mailSendRequest(target, "blocked recipient"), sequence++, "blocked", 1);
|
||||
error(m, request("mail.check", ""), sequence++, "denied", 2);
|
||||
assert(result(m, mailOwnerRequest("admin.mail.delete", target, ",\"boot\":71,\"id\":0"), sequence++, 9)["ok"] == true);
|
||||
selected = result(m, mailOwnerRequest("admin.mail.settings", target), sequence++, 9);
|
||||
assert(selected["total"] == 0 && selected["mode"] == "private" && selected["blocked"] == true);
|
||||
assert(result(m, request("admin.ban", "admin-secret", ",\"boot\":71,\"key\":" + quoted(target) + ",\"banned\":false"), sequence++, 9)["ok"] == true);
|
||||
error(m, request("mail.delete", "", ",\"boot\":71,\"id\":0"), sequence++, "identifier", 2);
|
||||
printf("MAIL_ADMIN: selected full-key policies, metadata-only enumeration, blocked field/gates, owner-isolated admin reads and confirmed purge passed\n");
|
||||
}
|
||||
static void mailPagingAndStorageCases() {
|
||||
MyMesh m; enable(m); uint32_t sequence = 1; const std::string target = browserKey(m, 2);
|
||||
assert(result(m, request("mail.policy", "", mailPolicyFields("public", 0)), sequence++, 2)["mode"] == "public");
|
||||
std::vector<uint32_t> ids;
|
||||
for (unsigned i = 0; i < 3; ++i) { auto sent = result(m, mailSendRequest(target, "queued " + std::to_string(i)), sequence++, 1); assert(sent["ok"] == true); ids.push_back(sent["id"]); }
|
||||
auto page = result(m, mailListRequest(), sequence++, 2); assert(page["messages"].size() == 2 && page["next"] == 2);
|
||||
const uint32_t snapshot = page["revision"];
|
||||
assert(result(m, mailSendRequest(target, "arrival between pages"), sequence++, 1)["ok"] == true);
|
||||
error(m, mailListRequest(2, snapshot), sequence++, "changed", 2);
|
||||
page = result(m, mailListRequest(), sequence++, 2);
|
||||
const uint32_t newer = page["revision"];
|
||||
assert(result(m, request("mail.delete", "", ",\"boot\":71,\"id\":" + std::to_string(ids[0])), sequence++, 2)["ok"] == true);
|
||||
error(m, mailListRequest(2, newer), sequence++, "changed", 2);
|
||||
error(m, mailListRequest(2, 0), sequence++, "revision", 2);
|
||||
page = result(m, mailListRequest(), sequence++, 2);
|
||||
auto last = result(m, mailListRequest(2, page["revision"]), sequence++, 2);
|
||||
assert(last["messages"].size() == 1 && last["next"].isNull());
|
||||
for (uint8_t owner = 3; owner <= 4; ++owner) assert(result(m, mailOwnerRequest("admin.mail.policy", browserKey(m, owner), mailPolicyFields("public", 0)), sequence++, 9)["mode"] == "public");
|
||||
auto owners = result(m, request("admin.mail.list", "admin-secret", ",\"cursor\":0,\"revision\":0"), sequence++, 9);
|
||||
assert(owners["mailboxes"].size() == 2 && owners["next"] == 2); const uint32_t owner_snapshot = owners["revision"];
|
||||
assert(result(m, mailSendRequest(target, "admin snapshot mutation"), sequence++, 1)["ok"] == true);
|
||||
error(m, request("admin.mail.list", "admin-secret", ",\"cursor\":2,\"revision\":" + std::to_string(owner_snapshot)), sequence++, "changed", 9);
|
||||
owners = result(m, request("admin.mail.list", "admin-secret", ",\"cursor\":0,\"revision\":0"), sequence++, 9);
|
||||
auto owners_last = result(m, request("admin.mail.list", "admin-secret", ",\"cursor\":2,\"revision\":" + std::to_string(owners["revision"].as<uint32_t>())), sequence++, 9);
|
||||
assert(owners_last["mailboxes"].size() == 1 && owners_last["next"].isNull());
|
||||
error(m, mailSendRequest(target, "owner queue is full"), sequence++, "full", 1);
|
||||
const auto primary = m.storage.get(mesh::ROOM_MAIL_PRIMARY_PATH);
|
||||
m.storage.capacity = 0;
|
||||
error(m, request("mail.ack", "", ",\"boot\":71,\"id\":" + std::to_string(ids[1])), sequence++, "save failed", 2);
|
||||
assert(m.storage.get(mesh::ROOM_MAIL_PRIMARY_PATH) == primary); m.storage.reset();
|
||||
assert(result(m, request("mail.check", ""), sequence++, 2)["total"] == 4);
|
||||
uint8_t key[32]; assert(mesh::roomMailWebKey(key, sizeof(key), target.c_str()));
|
||||
mesh::room_mail_detail::Index index; mesh::room_mail_detail::Entry entry; mesh::room_mail_detail::Owner owner; bool found = false;
|
||||
assert(mesh::room_mail_detail::load(m._fs, key, index, entry, owner, found, false) == mesh::RoomMailResult::Success && found);
|
||||
char bank[24]; mesh::room_mail_detail::ownerPath(entry, bank);
|
||||
auto corrupt = m.storage.get(bank); corrupt.back() ^= 1; m.storage.put(bank, corrupt);
|
||||
auto denied = result(m, request("mail.read", "", ",\"id\":" + std::to_string(ids[1]) + ",\"offset\":0"), sequence++, 2);
|
||||
assert(denied.as<JsonObjectConst>().size() == 1 && strstr(denied["error"].as<const char*>(), "storage unavailable"));
|
||||
error(m, mailSendRequest(target, "preserve corrupt evidence"), sequence++, "storage unavailable", 1);
|
||||
assert(m.storage.get(bank) == corrupt && m.storage.get(mesh::ROOM_MAIL_PRIMARY_PATH) == primary);
|
||||
assert(result(m, request("status", ""), sequence++, 2)["mailbox_only"] == true);
|
||||
printf("MAIL_PAGING: explicit revisions reject message arrivals/deletions between pages and changed admin snapshots passed\n");
|
||||
printf("MAIL_STORAGE: full owner queue, failed ACK retention, corrupt-bank fail-closed reads/status and preserved evidence passed\n");
|
||||
}
|
||||
static void mailGlobalQueueCases() {
|
||||
MyMesh m; enable(m); uint32_t sequence = 1;
|
||||
for (uint8_t owner = 2; owner <= 6; ++owner) assert(result(m, mailOwnerRequest("admin.mail.policy", browserKey(m, owner), mailPolicyFields("public", 0)), sequence++, 9)["mode"] == "public");
|
||||
for (uint8_t owner = 2; owner <= 5; ++owner) for (unsigned i = 0; i < 4; ++i) assert(result(m, mailSendRequest(browserKey(m, owner), "bounded global queue"), sequence++, 1)["ok"] == true);
|
||||
error(m, mailSendRequest(browserKey(m, 6), "seventeenth message"), sequence++, "full", 1);
|
||||
const auto owners = result(m, request("admin.mail.list", "admin-secret", ",\"cursor\":0,\"revision\":0"), sequence++, 9);
|
||||
assert(owners["queued"] == 16);
|
||||
assert(result(m, mailOwnerRequest("admin.mail.delete", browserKey(m, 2), ",\"boot\":71,\"id\":0"), sequence++, 9)["ok"] == true);
|
||||
assert(result(m, mailSendRequest(browserKey(m, 6), "space released by purge"), sequence++, 1)["ok"] == true);
|
||||
printf("MAIL_GLOBAL: bounded 16-message server queue rejects without acceptance and recovers capacity after explicit purge passed\n");
|
||||
}
|
||||
int main() {
|
||||
unsigned scenarios = 0;
|
||||
@@ -714,11 +915,16 @@ int main() {
|
||||
adminListingCases();
|
||||
adminAccessAndSettingsCases();
|
||||
adminInvalidAndSessionCases();
|
||||
mailAuthorizationAndPolicyCases();
|
||||
mailDeliveryAndDurabilityCases();
|
||||
mailAdministratorCases();
|
||||
mailPagingAndStorageCases();
|
||||
mailGlobalQueueCases();
|
||||
// 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 base and 6 admin actual room web service authorization, storage, quota, JSON and boundary groups\n", scenarios);
|
||||
printf("PASS: %u base, 6 admin and 6 mail actual room web service authorization, storage, quota, JSON and boundary groups\n", scenarios);
|
||||
}
|
||||
@@ -37,6 +37,9 @@ def room_outputs(work, compiler):
|
||||
"bool MyMesh::pushPostToClient(", "bool MyMesh::pushRoomTextToClient(",
|
||||
"bool MyMesh::processAck(", "void MyMesh::activateRoomTopic(",
|
||||
"bool MyMesh::handleRoomTopicCommand(", "void MyMesh::serviceRoomPush("))
|
||||
definitions += "\n" + extract_braced(source, "bool MyMesh::roomClientChatEnabled(").replace(
|
||||
"getRoomMailboxOnly(_fs,", "getRoomMailboxOnly(&policy_fs,")
|
||||
definitions += "\n" + extract_braced(source, "uint8_t MyMesh::getUnsyncedCount(")
|
||||
packet = (ROOT / "src/Packet.cpp").read_text()
|
||||
definitions = "namespace mesh {\n" + extract_braced(
|
||||
packet, "bool Packet::isValidPathLen(") + "\n}\n" + definitions
|
||||
@@ -67,6 +70,7 @@ def room_outputs(work, compiler):
|
||||
checked([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-unused-parameter", "-Wno-missing-field-initializers", *SANITIZERS,
|
||||
f"-I{work}", f"-I{ROOT / 'src'}",
|
||||
f"-I{ROOT / 'test/mocks'}",
|
||||
f"-I{ROOT / 'test/fixtures/room_topic_delivery'}",
|
||||
str(FIXTURES / "room_messages.cpp"), "-o", str(binary)])
|
||||
records = []
|
||||
|
||||
@@ -404,6 +404,192 @@ static void catchupPolls() {
|
||||
puts("normal keep-alive echoes preserve selected catch-up while forward cursors and exact ACK retries work passed");
|
||||
}
|
||||
|
||||
static std::string mailKey(const MyMesh& mesh, unsigned index) {
|
||||
char key[65]; mesh::room_mail_protocol_detail::hex(mesh.acl.clients[index].id.pub_key, key); return key;
|
||||
}
|
||||
static mesh::RoomMailStatus mailStatus(MyMesh& mesh, unsigned index, bool provisioned = true) {
|
||||
metadata_filesystem = &mesh.policy_fs; mesh::RoomMailStatus status;
|
||||
const auto result = mesh::getRoomMailStatus(&mesh.policy_fs, mesh.acl.clients[index].id.pub_key, status);
|
||||
assert(result == (provisioned ? mesh::RoomMailResult::Success : mesh::RoomMailResult::NotFound));
|
||||
return status;
|
||||
}
|
||||
static uint32_t mailId(const std::string& reply) {
|
||||
unsigned long id = 0; assert(sscanf(reply.c_str(), "OK id=%lu", &id) == 1 && id <= UINT32_MAX && id);
|
||||
return uint32_t(id);
|
||||
}
|
||||
static void mailPlain(MyMesh& mesh, const std::string& command, uint32_t timestamp, unsigned sender = 0) {
|
||||
const size_t before = mesh.sent.size();
|
||||
mesh.command(command.c_str(), timestamp, sender, 0, TXT_TYPE_PLAIN);
|
||||
if (mesh.sent.size() > before && mesh.sent.back().packet.getPayloadType() == PAYLOAD_TYPE_TXT_MSG) {
|
||||
assert(mesh.sent.back().packet.payload[4] >> 2 == TXT_TYPE_PLAIN);
|
||||
assert(memcmp(mesh.sent.back().recipient, mesh.acl.clients[sender].id.pub_key, PUB_KEY_SIZE) == 0);
|
||||
}
|
||||
}
|
||||
static void mailPlainCommands() {
|
||||
MyMesh mesh; auto& reader = mesh.acl.clients[0]; reader.permissions = PERM_ACL_READ_ONLY;
|
||||
assert(mesh.roomClientChatEnabled(&reader));
|
||||
mailPlain(mesh, "!mail mode public", 100); assert(mesh.reply() == "OK");
|
||||
assert(mesh.sent.size() == 2 && mesh.sent[0].packet.getPayloadType() == PAYLOAD_TYPE_ACK);
|
||||
mailPlain(mesh, "!mail delivery mailbox", 101);
|
||||
assert(mailStatus(mesh, 0).settings.mailbox_only && !mesh.roomClientChatEnabled(&reader));
|
||||
assert(mesh.roomClientChatEnabled(&mesh.acl.clients[1]));
|
||||
mailPlain(mesh, "!mail settings", 102); assert(mesh.reply().find("delivery=mailbox") != std::string::npos);
|
||||
mailPlain(mesh, "!mail bogus", 103); assert(mesh.reply().find("Error ") == 0);
|
||||
mailPlain(mesh, "!mail", 104); assert(mesh.reply().find("Error ") == 0);
|
||||
mailPlain(mesh, "!mail read 0", 105); assert(mesh.reply().find("Error ") == 0);
|
||||
mesh.command("AB|mail delivery chat", 106);
|
||||
assert(mesh.reply() == "AB|OK" && mesh.sent.back().packet.payload[4] >> 2 == TXT_TYPE_CLI_DATA);
|
||||
assert(!mailStatus(mesh, 0).settings.mailbox_only && mesh.roomClientChatEnabled(&reader));
|
||||
assert(mesh.post_count == 0 && mesh.general_commands == 0 && mesh.acl.saves == 0);
|
||||
assert(reader.permissions == PERM_ACL_READ_ONLY && mesh.acl.clients[1].permissions == PERM_ACL_READ_WRITE);
|
||||
MyMesh ordinary;
|
||||
ordinary.command("dog lost: please call home", 100, 0, 0, TXT_TYPE_PLAIN);
|
||||
ordinary.command("!mailbox is just chat", 101, 0, 0, TXT_TYPE_PLAIN);
|
||||
assert(ordinary.post_count == 2 && ordinary.general_commands == 0);
|
||||
// A saved mailbox-only preference survives cache replacement and blocks
|
||||
// public unread counts without discarding retained chat.
|
||||
mailPlain(mesh, "!mail delivery mailbox", 107);
|
||||
mesh.remote_cli_reply_cache.clear(); assert(!mesh.roomClientChatEnabled(&reader));
|
||||
backlog(mesh); assert(mesh.getUnsyncedCount(&reader) == 0);
|
||||
assert(mesh.posts[0].post_timestamp != 0);
|
||||
auto corrupt = mesh.policy_fs.get(mesh::ROOM_MAIL_PRIMARY_PATH); corrupt[0] ^= 1;
|
||||
mesh.policy_fs.put(mesh::ROOM_MAIL_PRIMARY_PATH, corrupt);
|
||||
assert(!mesh.roomClientChatEnabled(&reader)); // Corrupt settings fail closed.
|
||||
puts("plain !mail commands privately reply, reserve unknown commands, preserve owner policy and mailbox-only chat admission passed");
|
||||
}
|
||||
static void mailOwnershipAndDog() {
|
||||
MyMesh mesh; mesh.acl.clients[0].permissions = PERM_ACL_READ_ONLY;
|
||||
mailPlain(mesh, "!mail mode public", 100);
|
||||
mailPlain(mesh, "!mail delivery mailbox", 101);
|
||||
const std::string dog = "dog lost: please call home; set password is ordinary text";
|
||||
mailPlain(mesh, "!mail send " + mailKey(mesh, 0) + " " + dog, 100, 1);
|
||||
const uint32_t id = mailId(mesh.reply()); assert(mailStatus(mesh, 0).count == 1);
|
||||
assert(mesh.post_count == 0 && mesh.general_commands == 0);
|
||||
mailPlain(mesh, "!mail inbox", 102); assert(mesh.reply().find(std::to_string(id) + "/") != std::string::npos);
|
||||
// A sleeping radio checks later; reading retains the item until explicit ACK.
|
||||
mesh.clock.now += 1800;
|
||||
mailPlain(mesh, "!mail read " + std::to_string(id), 103);
|
||||
assert(mesh.reply().find("text=" + dog) != std::string::npos && mailStatus(mesh, 0).count == 1);
|
||||
mailPlain(mesh, "!mail read " + std::to_string(id), 101, 1);
|
||||
assert(mesh.reply().find(dog) == std::string::npos && mesh.reply() == "Error not found");
|
||||
mailPlain(mesh, "!mail ack " + std::to_string(id), 102, 1);
|
||||
assert(mesh.reply() == "Error not found" && mailStatus(mesh, 0).count == 1);
|
||||
mailPlain(mesh, "!mail delete " + std::to_string(id), 103, 1);
|
||||
assert(mesh.reply() == "Error not found" && mailStatus(mesh, 0).count == 1);
|
||||
mailPlain(mesh, "!mail mode closed", 104);
|
||||
mailPlain(mesh, "!mail ack " + std::to_string(id), 105);
|
||||
assert(mailStatus(mesh, 0).count == 0);
|
||||
mailPlain(mesh, "!mail ack " + std::to_string(id), 105); assert(mailStatus(mesh, 0).count == 0);
|
||||
mailPlain(mesh, "!mail delete " + std::to_string(id), 106); assert(mesh.reply().find("OK id=") == 0);
|
||||
mailPlain(mesh, "!mail read " + std::to_string(id), 107); assert(mesh.reply() == "Error not found");
|
||||
assert(mesh.post_count == 0 && mesh.general_commands == 0 && mesh.acl.saves == 0);
|
||||
// Even administrators use their authenticated own inbox in these commands.
|
||||
mesh.acl.clients[1].permissions = PERM_ACL_ADMIN;
|
||||
mailPlain(mesh, "!mail settings", 104, 1); assert(mesh.reply().find("mode=closed") != std::string::npos);
|
||||
assert(mailStatus(mesh, 1, false).count == 0);
|
||||
puts("later dog-lost check and owner-only inbox read ACK delete keep bodies private and treat command-looking body as text passed");
|
||||
}
|
||||
static void mailModesRolesAndBans() {
|
||||
MyMesh policy; policy.acl.clients[0].permissions = PERM_ACL_READ_ONLY;
|
||||
mailPlain(policy, "!mail mode private", 100);
|
||||
mailPlain(policy, "!mail send " + mailKey(policy, 0) + " forbidden", 100, 1);
|
||||
assert(policy.reply() == "Error permission denied");
|
||||
mailPlain(policy, "!mail allow " + mailKey(policy, 1), 101);
|
||||
mailPlain(policy, "!mail send " + mailKey(policy, 0) + " allowed", 101, 1);
|
||||
assert(policy.reply().find("OK id=") == 0 && mailStatus(policy, 0).count == 1);
|
||||
mailPlain(policy, "!mail deny " + mailKey(policy, 1), 102);
|
||||
mailPlain(policy, "!mail send " + mailKey(policy, 0) + " denied", 102, 1);
|
||||
assert(policy.reply() == "Error permission denied" && mailStatus(policy, 0).count == 1);
|
||||
mailPlain(policy, "!mail mode public", 103);
|
||||
mailPlain(policy, "!mail send " + mailKey(policy, 0) + " public", 103, 1);
|
||||
assert(policy.reply().find("OK id=") == 0 && mailStatus(policy, 0).count == 2);
|
||||
mailPlain(policy, "!mail mode closed", 104);
|
||||
mailPlain(policy, "!mail send " + mailKey(policy, 0) + " closed", 104, 1);
|
||||
assert(policy.reply() == "Error permission denied" && mailStatus(policy, 0).count == 2);
|
||||
for (uint8_t role : {uint8_t(PERM_ACL_GUEST), uint8_t(PERM_ACL_READ_ONLY), uint8_t(PERM_ACL_READ_WRITE),
|
||||
uint8_t(PERM_ACL_ADMIN), uint8_t(PERM_ACL_FILTER_MGR), uint8_t(PERM_ACL_REGION_MGR)}) {
|
||||
for (bool active : {false, true}) {
|
||||
MyMesh mesh; mesh.acl.clients[0].permissions = role; mesh.acl.clients[0].last_activity = active ? 900 : 0;
|
||||
mailPlain(mesh, "!mail mode public", 100, 1); mesh.sent.clear();
|
||||
mailPlain(mesh, "!mail send " + mailKey(mesh, 1) + " role test", 100);
|
||||
const bool writer = role == PERM_ACL_READ_WRITE || role == PERM_ACL_ADMIN;
|
||||
assert(mailStatus(mesh, 1).count == (writer ? 1U : 0U));
|
||||
assert(mesh.post_count == 0 && mesh.general_commands == 0);
|
||||
mailPlain(mesh, "!mail mode private", 101);
|
||||
const bool own = writer || role == PERM_ACL_READ_ONLY || (role == PERM_ACL_GUEST && active);
|
||||
if (own) assert(mailStatus(mesh, 0).settings.mode == mesh::RoomMailMode::Private);
|
||||
else assert(mailStatus(mesh, 0, false).revision == 0);
|
||||
}
|
||||
}
|
||||
MyMesh blocked; mailPlain(blocked, "!mail mode public", 100, 1);
|
||||
assert(blocked.room_access.addBan(&blocked.policy_fs, blocked.acl.clients[1].id.pub_key)
|
||||
== mesh::RoomAccessPolicy::BanResult::Saved);
|
||||
mailPlain(blocked, "!mail send " + mailKey(blocked, 1) + " banned recipient", 100);
|
||||
assert(blocked.reply().find("recipient is blocked") != std::string::npos && mailStatus(blocked, 1).count == 0);
|
||||
assert(blocked.room_access.addBan(&blocked.policy_fs, blocked.acl.clients[0].id.pub_key)
|
||||
== mesh::RoomAccessPolicy::BanResult::Saved);
|
||||
const size_t replies = blocked.sent.size(); mailPlain(blocked, "!mail settings", 101);
|
||||
assert(blocked.sent.size() == replies && blocked.post_count == 0 && blocked.general_commands == 0);
|
||||
puts("private allow deny public closed policies honor writer reader guest roles and sender recipient bans passed");
|
||||
}
|
||||
static void mailTransportRetries() {
|
||||
MyMesh mesh; mailPlain(mesh, "!mail mode public", 100);
|
||||
const std::string submission = "!mail send " + mailKey(mesh, 0) + " dog lost";
|
||||
mailPlain(mesh, submission, 100, 1); const uint32_t id = mailId(mesh.reply()); const std::string original = mesh.reply();
|
||||
mailPlain(mesh, "!mail settings", 101, 1);
|
||||
mailPlain(mesh, submission, 100, 1);
|
||||
assert(mesh.reply() == original && mailStatus(mesh, 0).count == 1 && mesh.acl.clients[1].last_timestamp == 101);
|
||||
const size_t replies = mesh.sent.size(); mailPlain(mesh, submission + " changed", 100, 1);
|
||||
assert(mesh.sent.size() == replies && mailStatus(mesh, 0).count == 1);
|
||||
mesh.acl.clients[1].permissions = PERM_ACL_READ_ONLY;
|
||||
mailPlain(mesh, submission, 100, 1); assert(mesh.reply() == original && mailStatus(mesh, 0).count == 1);
|
||||
mailPlain(mesh, submission + " new", 102, 1);
|
||||
assert(mesh.reply() == "Error permission denied" && mailStatus(mesh, 0).count == 1);
|
||||
// Restore the same persisted files with a new transport cache and replay floor.
|
||||
MyMesh reboot;
|
||||
for (const auto& entry : mesh.policy_fs.files)
|
||||
reboot.policy_fs.put(entry.first.c_str(), *entry.second);
|
||||
mailPlain(reboot, submission, 100, 1);
|
||||
assert(mailId(reboot.reply()) == id && reboot.reply().find("duplicate") != std::string::npos);
|
||||
assert(mailStatus(reboot, 0).count == 1);
|
||||
mailPlain(reboot, "!mail read " + std::to_string(id), 100);
|
||||
assert(reboot.reply().find("text=dog lost") != std::string::npos);
|
||||
reboot.acl.clients[0].permissions = PERM_ACL_FILTER_MGR;
|
||||
const size_t before_revoke = reboot.sent.size(); mailPlain(reboot, "!mail read " + std::to_string(id), 100);
|
||||
assert(reboot.sent.size() == before_revoke || reboot.reply().find("dog lost") == std::string::npos);
|
||||
reboot.acl.clients[0].permissions = PERM_ACL_READ_ONLY;
|
||||
mailPlain(reboot, "!mail ack " + std::to_string(id), 101); assert(mailStatus(reboot, 0).count == 0);
|
||||
reboot.remote_cli_reply_cache.clear(); reboot.acl.clients[1].last_timestamp = 99;
|
||||
mailPlain(reboot, submission, 100, 1); assert(mailId(reboot.reply()) == id && mailStatus(reboot, 0).count == 0);
|
||||
assert(reboot.room_access.addBan(&reboot.policy_fs, reboot.acl.clients[1].id.pub_key)
|
||||
== mesh::RoomAccessPolicy::BanResult::Saved);
|
||||
const size_t before_ban = reboot.sent.size(); mailPlain(reboot, submission, 100, 1);
|
||||
assert(reboot.sent.size() == before_ban && reboot.post_count == 0 && reboot.general_commands == 0);
|
||||
puts("plain transport retries persist once across cache reboot ACK and role or ban changes without exposing revoked mail passed");
|
||||
}
|
||||
static void mailInputLengths() {
|
||||
MyMesh mesh; mailPlain(mesh, "!mail mode public", 100);
|
||||
const std::string prefix = "mail send " + mailKey(mesh, 0) + " ";
|
||||
const std::string longest = prefix + std::string(mesh::RemoteCliReplyCache::MAX_REPLY_TEXT - prefix.size(), 'x');
|
||||
char reply[180]{};
|
||||
assert(mesh.handleRoomMailClientCommand(&mesh.acl.clients[1], longest.c_str(), 800, reply, sizeof(reply)));
|
||||
const uint32_t id = mailId(reply); assert(mailStatus(mesh, 0).count == 1);
|
||||
mesh::RoomMailMessage message; uint8_t bytes[128]; size_t copied = 0;
|
||||
assert(mesh::readRoomMail(&mesh.policy_fs, mesh.acl.clients[0].id.pub_key, id, 0,
|
||||
bytes, sizeof(bytes), copied, message) == mesh::RoomMailResult::Success);
|
||||
assert(message.length == longest.size() - prefix.size() && copied == message.length);
|
||||
assert(std::string(reinterpret_cast<const char*>(bytes), copied) == longest.substr(prefix.size()));
|
||||
for (const std::string& input : {longest + "x", prefix + std::string(200, 'y'), prefix + std::string(512, 'z')}) {
|
||||
memset(reply, 0, sizeof(reply));
|
||||
assert(mesh.handleRoomMailClientCommand(&mesh.acl.clients[1], input.c_str(), 801, reply, sizeof(reply)));
|
||||
assert(strstr(reply, "Error command too long") && mailStatus(mesh, 0).count == 1);
|
||||
}
|
||||
mailPlain(mesh, "!" + longest + "x", 100, 1);
|
||||
assert(mesh.reply() == "Error command too long" && mailStatus(mesh, 0).count == 1);
|
||||
assert(mesh.post_count == 0 && mesh.general_commands == 0);
|
||||
puts("mail transport rejects oversized commands without truncating bodies while exact buffer boundary preserves complete text passed");
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "roles")) roleCases();
|
||||
@@ -417,6 +603,11 @@ int main(int argc, char** argv) {
|
||||
else if (!strcmp(argv[1], "catchup-retry")) catchupRetriesAndDenials();
|
||||
else if (!strcmp(argv[1], "admin-clients")) adminClients();
|
||||
else if (!strcmp(argv[1], "catchup-poll")) catchupPolls();
|
||||
else if (!strcmp(argv[1], "mail-plain")) mailPlainCommands();
|
||||
else if (!strcmp(argv[1], "mail-owner")) mailOwnershipAndDog();
|
||||
else if (!strcmp(argv[1], "mail-policies")) mailModesRolesAndBans();
|
||||
else if (!strcmp(argv[1], "mail-retries")) mailTransportRetries();
|
||||
else if (!strcmp(argv[1], "mail-lengths")) mailInputLengths();
|
||||
else assert(false);
|
||||
}
|
||||
'''
|
||||
@@ -444,6 +635,8 @@ def production_source():
|
||||
raise AssertionError("missing production constant " + name)
|
||||
constants += "\n" + found[0]
|
||||
methods = "\n".join(extract_braced(room, signature) for signature in (
|
||||
"bool MyMesh::roomClientChatEnabled(", "bool MyMesh::handleRoomMailClientCommand(",
|
||||
"bool MyMesh::handleRoomMailText(",
|
||||
"bool MyMesh::handleClientPathCommand(", "bool MyMesh::executeClientPathCommand(",
|
||||
"bool MyMesh::sendClientReply(",
|
||||
"bool MyMesh::handleRoomCatchUpCommand(", "bool MyMesh::applyRoomCatchUpCommand(",
|
||||
@@ -478,6 +671,7 @@ class RoomClientPathTests(unittest.TestCase):
|
||||
binary = work / name
|
||||
command = [cls.compiler, "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-I" + str(ROOT / "test/fixtures/room_history_store"), "-I" + str(ROOT / "src"),
|
||||
"-I" + str(ROOT / "test/mocks"),
|
||||
str(source), "-o", str(binary)]
|
||||
if sys.platform.startswith("linux"):
|
||||
command[1:1] = ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
@@ -543,6 +737,21 @@ class RoomClientPathTests(unittest.TestCase):
|
||||
def test_actual_keepalive_echo_cannot_undo_skip_and_exact_retries_still_ack(self):
|
||||
self.run_case("catchup-poll", "normal keep-alive echoes preserve selected catch-up while forward cursors and exact ACK retries work passed")
|
||||
|
||||
def test_actual_plain_mail_commands_are_reserved_private_and_save_delivery_policy(self):
|
||||
self.run_case("mail-plain", "plain !mail commands privately reply, reserve unknown commands, preserve owner policy and mailbox-only chat admission passed")
|
||||
|
||||
def test_actual_owner_only_mail_poll_read_and_durable_ack_for_later_dog_check(self):
|
||||
self.run_case("mail-owner", "later dog-lost check and owner-only inbox read ACK delete keep bodies private and treat command-looking body as text passed")
|
||||
|
||||
def test_actual_mail_sender_modes_reader_writer_roles_and_bans(self):
|
||||
self.run_case("mail-policies", "private allow deny public closed policies honor writer reader guest roles and sender recipient bans passed")
|
||||
|
||||
def test_actual_plain_mail_retries_reboot_receipts_and_current_authorization(self):
|
||||
self.run_case("mail-retries", "plain transport retries persist once across cache reboot ACK and role or ban changes without exposing revoked mail passed")
|
||||
|
||||
def test_actual_mail_input_length_rejection_preserves_complete_accepted_body(self):
|
||||
self.run_case("mail-lengths", "mail transport rejects oversized commands without truncating bodies while exact buffer boundary preserves complete text passed")
|
||||
|
||||
def test_negative_controls_detect_rollback_cache_authorization_and_retry_regressions(self):
|
||||
controls = (
|
||||
("rollback", "memcpy(selected, previous, sizeof(previous));",
|
||||
|
||||
@@ -29,6 +29,7 @@ HARNESS = r'''
|
||||
#include <helpers/ClientPathObservation.h>
|
||||
#include <helpers/RoomClientPathCommand.h>
|
||||
#include <helpers/RoomCatchUp.h>
|
||||
#include <helpers/RoomMailStore.h>
|
||||
#include <helpers/TxtDataHelpers.h>
|
||||
#include <Packet.h>
|
||||
#include <helpers/RoomLoginAuthorization.h>
|
||||
@@ -169,6 +170,7 @@ struct MyMesh {
|
||||
unsigned path_acks = 0;
|
||||
bool processAck(const uint8_t*) { ++path_acks; return true; }
|
||||
uint8_t getUnsyncedCount(ClientInfo*);
|
||||
bool roomClientChatEnabled(ClientInfo*);
|
||||
int getExtraAckTransmitCount() { return 0; }
|
||||
unsigned requests = 0;
|
||||
uint8_t last_request_type = 0;
|
||||
@@ -256,6 +258,8 @@ struct MyMesh {
|
||||
mesh::Packet packet; packet.header = ROUTE_TYPE_DIRECT;
|
||||
onPeerDataRecv(&packet, PAYLOAD_TYPE_REQ, 0, acl.client.shared_secret, data, sizeof(data));
|
||||
}
|
||||
bool handleRoomMailText(ClientInfo*, mesh::Packet*, const uint8_t*, uint8_t*, size_t) { return false; }
|
||||
bool handleRoomMailClientCommand(ClientInfo*, const char*, uint64_t, char*, size_t) { return false; }
|
||||
void onPeerDataRecv(mesh::Packet*, uint8_t, int, const uint8_t*, uint8_t*, size_t);
|
||||
bool onPeerPathRecv(mesh::Packet*, int, const uint8_t*, uint8_t*, uint8_t, uint8_t, uint8_t*, uint8_t);
|
||||
void onAnonDataRecv(mesh::Packet*, const uint8_t*, const mesh::Identity&,
|
||||
@@ -272,6 +276,7 @@ struct MyMesh {
|
||||
@ROOM_CATCHUP_HANDLER@
|
||||
@ROOM_CATCHUP_APPLY@
|
||||
@ROOM_UNSYNCED_COUNT@
|
||||
@ROOM_MAIL_STATUS@
|
||||
|
||||
static mesh::Identity identity(uint8_t n = 1) {
|
||||
mesh::Identity sender{};
|
||||
@@ -876,6 +881,7 @@ class RoomLoginIntegrationTests(unittest.TestCase):
|
||||
room, "bool MyMesh::applyRoomCatchUpCommand(")),
|
||||
"@ROOM_UNSYNCED_COUNT@": re.sub(r"\bposts\b", "retained_posts", extract_braced(
|
||||
room, "uint8_t MyMesh::getUnsyncedCount(")),
|
||||
"@ROOM_MAIL_STATUS@": extract_braced(room, "bool MyMesh::roomClientChatEnabled("),
|
||||
"@LOGIN_HANDLER@": extract_braced(room, "void MyMesh::onAnonDataRecv("),
|
||||
}
|
||||
generated = HARNESS
|
||||
@@ -889,6 +895,7 @@ class RoomLoginIntegrationTests(unittest.TestCase):
|
||||
cls.binary = work / "room-login"
|
||||
command = [compiler, "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-unused-parameter", "-I" + str(ROOT / "test/fixtures/room_history_store"), "-I" + str(ROOT / "src"),
|
||||
"-I" + str(ROOT / "test/mocks"),
|
||||
str(source), "-o", str(cls.binary)]
|
||||
if sys.platform.startswith("linux"):
|
||||
command[1:1] = ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Execute owner-bound room mail LoRa/CLI handlers against their real store."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_room_board_store import FILESYSTEM_HARNESS, LFS_MOCK, STAT_MOCK
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
TESTS = r'''
|
||||
#define FILE_O_WRITE 1
|
||||
#include <helpers/RoomMailProtocol.h>
|
||||
using Result = mesh::RoomMailResult;
|
||||
static unsigned scenarios = 0;
|
||||
static uint8_t a[32], b[32], c[32];
|
||||
static std::string key(const uint8_t* bytes) {
|
||||
char out[65]; mesh::room_mail_protocol_detail::hex(bytes, out); return out;
|
||||
}
|
||||
static std::map<std::string, std::vector<uint8_t>> snapshot(const MemoryFS& fs) {
|
||||
std::map<std::string, std::vector<uint8_t>> out;
|
||||
for (const auto& entry : fs.files) out[entry.first] = *entry.second;
|
||||
return out;
|
||||
}
|
||||
static std::vector<uint8_t> request(MemoryFS& fs, const uint8_t* owner,
|
||||
const std::vector<uint8_t>& input, size_t capacity = 160,
|
||||
bool can_send = true, uint64_t nonce = 1) {
|
||||
metadata_filesystem = &fs;
|
||||
std::vector<uint8_t> output(capacity + 2, 0x7f);
|
||||
const size_t used = mesh::handleRoomMailRequest(&fs, owner, can_send, nonce,
|
||||
input.data(), input.size(), output.data() + 1, capacity, 123456);
|
||||
assert(used <= capacity && output.front() == 0x7f && output.back() == 0x7f);
|
||||
++scenarios; return std::vector<uint8_t>(output.begin() + 1, output.begin() + 1 + used);
|
||||
}
|
||||
static std::string command(MemoryFS& fs, const uint8_t* owner,
|
||||
const std::string& text, size_t capacity = 160, bool can_send = true,
|
||||
uint64_t nonce = 1, bool handled = true) {
|
||||
metadata_filesystem = &fs;
|
||||
std::vector<char> output(capacity + 2, 0x7f);
|
||||
assert(mesh::handleRoomMailCommand(&fs, owner, can_send, nonce, text.c_str(),
|
||||
output.data() + 1, capacity, 123456) == handled);
|
||||
assert(output.front() == 0x7f && output.back() == 0x7f); ++scenarios;
|
||||
if (!capacity || !handled) return "";
|
||||
assert(memchr(output.data() + 1, 0, capacity)); return output.data() + 1;
|
||||
}
|
||||
static mesh::RoomMailStatus status(MemoryFS& fs, const uint8_t* owner) {
|
||||
metadata_filesystem = &fs; mesh::RoomMailStatus out;
|
||||
assert(mesh::getRoomMailStatus(&fs, owner, out) == Result::Success); return out;
|
||||
}
|
||||
static std::vector<uint8_t> edit(uint8_t op, uint32_t revision, uint8_t value) {
|
||||
std::vector<uint8_t> out(7); out[0] = 11; out[1] = op;
|
||||
mesh::room_mail_protocol_detail::put32(out.data() + 2, revision); out[6] = value; return out;
|
||||
}
|
||||
static std::vector<uint8_t> editKey(uint8_t op, uint32_t revision, const uint8_t* bytes) {
|
||||
std::vector<uint8_t> out(38); out[0] = 11; out[1] = op;
|
||||
mesh::room_mail_protocol_detail::put32(out.data() + 2, revision);
|
||||
memcpy(out.data() + 6, bytes, 32); return out;
|
||||
}
|
||||
static std::vector<uint8_t> indexRequest(uint32_t revision = 0, uint8_t cursor = 0) {
|
||||
std::vector<uint8_t> out(7); out[0] = 11; out[1] = 1;
|
||||
mesh::room_mail_protocol_detail::put32(out.data() + 2, revision); out[6] = cursor; return out;
|
||||
}
|
||||
static std::vector<uint8_t> settings(uint32_t revision = 0, uint8_t cursor = 0) {
|
||||
auto out = indexRequest(revision, cursor); out[1] = 0; return out;
|
||||
}
|
||||
static std::vector<uint8_t> read(uint32_t id, uint16_t offset = 0) {
|
||||
std::vector<uint8_t> out(8); out[0] = 11; out[1] = 2;
|
||||
mesh::room_mail_protocol_detail::put32(out.data() + 2, id);
|
||||
mesh::room_mail_protocol_detail::put16(out.data() + 6, offset); return out;
|
||||
}
|
||||
static std::vector<uint8_t> send(const uint8_t* recipient, const std::string& body) {
|
||||
std::vector<uint8_t> out(36 + body.size()); out[0] = 11; out[1] = 3;
|
||||
memcpy(out.data() + 2, recipient, 32);
|
||||
mesh::room_mail_protocol_detail::put16(out.data() + 34, uint16_t(body.size()));
|
||||
memcpy(out.data() + 36, body.data(), body.size()); return out;
|
||||
}
|
||||
static std::vector<uint8_t> remove(uint8_t op, uint32_t id) {
|
||||
std::vector<uint8_t> out(6); out[0] = 11; out[1] = op;
|
||||
mesh::room_mail_protocol_detail::put32(out.data() + 2, id); return out;
|
||||
}
|
||||
static std::vector<uint8_t> padded(std::vector<uint8_t> payload) {
|
||||
payload.resize(((payload.size() + 4 + 15) / 16) * 16 - 4, 0); return payload;
|
||||
}
|
||||
static uint32_t id(const std::vector<uint8_t>& response) {
|
||||
assert(response.size() == 7 && (response[2] == 0 || response[2] == 8));
|
||||
return mesh::room_mail_protocol_detail::get32(response.data() + 3);
|
||||
}
|
||||
int main() {
|
||||
memset(a, 0xa1, 32); memset(b, 0xb2, 32); memset(c, 0xc3, 32);
|
||||
MemoryFS fs;
|
||||
auto response = request(fs, a, settings());
|
||||
assert(response.size() == 13 && response[2] == 0 && response[7] == 0
|
||||
&& response[8] == 0 && response[9] == 0 && response[11] == 255 && response[12] == 0);
|
||||
assert(fs.files.empty());
|
||||
assert(request(fs, a, indexRequest())[9] == 255 && fs.files.empty());
|
||||
assert(command(fs, a, "mail settings").find("mode=closed delivery=chat queued=0") != std::string::npos);
|
||||
assert(command(fs, a, "mail mode public", 160, false) == "OK");
|
||||
assert(command(fs, a, "mail delivery mailbox", 160, false) == "OK");
|
||||
auto own = status(fs, a); assert(own.settings.mailbox_only);
|
||||
response = request(fs, a, editKey(6, own.revision, b)); assert(response[2] == 0);
|
||||
own = status(fs, a); assert(own.settings.allowed_count == 1);
|
||||
const uint32_t before_policy = own.revision;
|
||||
response = request(fs, a, edit(8, own.revision, 2), 7, false); assert(response[2] == 0);
|
||||
response = request(fs, a, edit(9, before_policy, 0)); assert(response[2] == 5);
|
||||
own = status(fs, a); assert(own.settings.mode == mesh::RoomMailMode::Private && own.settings.mailbox_only);
|
||||
response = request(fs, a, settings(), 45);
|
||||
assert(response.size() == 45 && response[9] == 1 && response[11] == 255
|
||||
&& memcmp(response.data() + 13, b, 32) == 0);
|
||||
assert(request(fs, b, settings())[9] == 0); // Another key cannot enumerate the allow list.
|
||||
assert(request(fs, c, send(a, "not authorized"))[2] == 6);
|
||||
assert(request(fs, b, send(a, "writer permission required"), 160, false)[2] == 6);
|
||||
assert(command(fs, b, "mail send " + key(a) + " blocked by role", 160, false) == "Error permission denied");
|
||||
assert(status(fs, a).count == 0);
|
||||
|
||||
const std::string full_body(512, 'p'); const uint64_t nonce = UINT64_C(0x1234567800000009);
|
||||
response = request(fs, b, send(a, full_body), 160, true, nonce); const uint32_t first = id(response);
|
||||
own = status(fs, a); assert(own.count == 1);
|
||||
response = request(fs, b, send(a, full_body), 160, true, nonce);
|
||||
assert(response[2] == 8 && id(response) == first && status(fs, a).count == 1);
|
||||
assert(request(fs, b, send(a, "changed"), 160, true, nonce)[2] == 9);
|
||||
assert(request(fs, b, send(a, "different nonce high bits"), 160, true, nonce + (UINT64_C(1) << 32))[2] == 0);
|
||||
assert(status(fs, a).count == 2);
|
||||
|
||||
const auto preserved = snapshot(fs);
|
||||
for (const uint8_t* stranger : {b, c}) {
|
||||
for (const auto& payload : {read(first), remove(4, first), remove(5, first)}) {
|
||||
response = request(fs, stranger, payload);
|
||||
assert(response[2] == 4 || response[2] == 6);
|
||||
assert(response.size() <= 7);
|
||||
}
|
||||
const std::string output = command(fs, stranger, "mail read " + std::to_string(first));
|
||||
assert(output == "Error not found" || output == "Error permission denied");
|
||||
}
|
||||
assert(snapshot(fs) == preserved && status(fs, a).count == 2);
|
||||
own = status(fs, a);
|
||||
response = request(fs, a, indexRequest());
|
||||
assert(response[2] == 0 && response[7] == 2 && response[9] == 255 && response[10] == 2);
|
||||
assert(response.size() == 87 && memcmp(response.data() + 15, b, 32) == 0);
|
||||
response = request(fs, a, indexRequest(own.revision, 1), 49);
|
||||
assert(response.size() == 49 && response[9] == 255 && response[10] == 1);
|
||||
assert(request(fs, a, indexRequest(own.revision - 1))[2] == 5);
|
||||
assert(request(fs, a, indexRequest(0, 1))[2] == 5);
|
||||
assert(request(fs, a, indexRequest(own.revision, 3))[2] == 1);
|
||||
|
||||
// Check every route reply capacity, including capacities too short for a
|
||||
// complete private header or entry. Response canaries prohibit overflows.
|
||||
for (size_t capacity = 0; capacity <= 200; ++capacity) {
|
||||
response = request(fs, a, indexRequest(), capacity);
|
||||
if (capacity < 3) assert(response.empty());
|
||||
else if (capacity < 49) assert(response.size() == 3 && response[2] == 1);
|
||||
else {
|
||||
assert(response[2] == 0 && response.size() == 11 + size_t(response[10]) * 38);
|
||||
assert(response[10] >= 1 && response[10] <= 2);
|
||||
}
|
||||
response = request(fs, a, read(first), capacity);
|
||||
if (capacity < 3) assert(response.empty());
|
||||
else if (capacity <= 44) assert(response.size() == 3 && response[2] == 1);
|
||||
else {
|
||||
assert(response[2] == 0 && response.size() == 44 + size_t(response[11]));
|
||||
assert(response[11] == std::min(size_t(128), capacity - 44));
|
||||
assert(memcmp(response.data() + 12, b, 32) == 0);
|
||||
}
|
||||
response = request(fs, a, settings(), capacity);
|
||||
if (capacity < 3) assert(response.empty());
|
||||
else if (capacity < 45) assert(response.size() == 3 && response[2] == 1);
|
||||
else assert(response.size() == 45 && response[2] == 0);
|
||||
}
|
||||
std::string assembled;
|
||||
for (uint16_t offset = 0; offset < 512;) {
|
||||
response = request(fs, a, read(first, offset), 90);
|
||||
assert(response[2] == 0 && response[11] && response[11] <= 46);
|
||||
assert(mesh::room_mail_protocol_detail::get16(response.data() + 7) == offset);
|
||||
assert(mesh::room_mail_protocol_detail::get16(response.data() + 9) == 512);
|
||||
assembled.append(reinterpret_cast<const char*>(response.data() + 44), response[11]); offset += response[11];
|
||||
}
|
||||
assert(assembled == full_body);
|
||||
response = request(fs, a, read(first, 512), 44); assert(response.size() == 44 && response[11] == 0);
|
||||
assert(request(fs, a, read(first, 513))[2] == 1);
|
||||
assembled.clear();
|
||||
for (size_t offset = 0; offset < 512;) {
|
||||
const std::string output = command(fs, a, "mail read " + std::to_string(first) + " " + std::to_string(offset), 157);
|
||||
const size_t data = output.find("text="); assert(data != std::string::npos);
|
||||
const std::string bytes = output.substr(data + 5); assert(!bytes.empty());
|
||||
assembled += bytes; offset += bytes.size();
|
||||
}
|
||||
assert(assembled == full_body);
|
||||
assert(command(fs, a, "mail read " + std::to_string(first) + " 512").find("next=512 total=512 text=") != std::string::npos);
|
||||
assert(command(fs, a, "mail inbox") == command(fs, a, "mail list"));
|
||||
assert(command(fs, a, "mail list", 80).find("..") != std::string::npos);
|
||||
{
|
||||
MemoryFS utf_fs;
|
||||
assert(command(utf_fs, a, "mail mode public") == "OK");
|
||||
std::string unicode;
|
||||
for (size_t i = 0; i < 128; ++i) unicode += "\xf0\x9f\x93\xa1";
|
||||
const uint32_t unicode_id = id(request(utf_fs, b, send(a, unicode), 160, true, 300));
|
||||
std::string text;
|
||||
for (size_t offset = 0; offset < unicode.size();) {
|
||||
const std::string output = command(utf_fs, a, "mail read " + std::to_string(unicode_id) + " " + std::to_string(offset), 83);
|
||||
const size_t marker = output.find("text="); assert(marker != std::string::npos);
|
||||
const std::string part = output.substr(marker + 5); assert(!part.empty() && part.size() % 4 == 0);
|
||||
assert(mesh::room_mail_detail::validBody(part.data(), part.size()));
|
||||
unsigned long got_id, got_offset, next; unsigned total;
|
||||
assert(sscanf(output.c_str(), "id=%lu off=%lu next=%lu total=%u text=", &got_id, &got_offset, &next, &total) == 4);
|
||||
assert(got_id == unicode_id && got_offset == offset && next == offset + part.size() && total == unicode.size());
|
||||
text += part; offset = next;
|
||||
}
|
||||
assert(text == unicode);
|
||||
for (unsigned offset = 1; offset <= 3; ++offset)
|
||||
assert(command(utf_fs, a, "mail read " + std::to_string(unicode_id) + " " + std::to_string(offset)) == "Error offset inside UTF-8 character");
|
||||
assert(request(utf_fs, a, read(unicode_id, 1))[2] == 0); // Binary reads retain arbitrary byte offsets.
|
||||
}
|
||||
for (size_t capacity = 0; capacity <= 160; ++capacity) {
|
||||
command(fs, a, "mail settings", capacity);
|
||||
command(fs, a, "mail list", capacity);
|
||||
command(fs, a, "mail read " + std::to_string(first), capacity);
|
||||
}
|
||||
|
||||
// No mutation is admitted if its complete confirmation cannot be returned.
|
||||
for (size_t capacity = 0; capacity < 7; ++capacity) {
|
||||
const auto before = snapshot(fs);
|
||||
for (const auto& payload : {send(a, "capacity"), remove(4, first), remove(5, first),
|
||||
edit(8, own.revision, 1), edit(9, own.revision, 0), editKey(6, own.revision, c), editKey(7, own.revision, b)})
|
||||
request(fs, a, payload, capacity, true, 500);
|
||||
assert(snapshot(fs) == before);
|
||||
}
|
||||
for (size_t capacity = 0; capacity < 32; ++capacity) {
|
||||
const auto before = snapshot(fs);
|
||||
command(fs, a, "mail mode public", capacity);
|
||||
command(fs, a, "mail ack " + std::to_string(first), capacity);
|
||||
command(fs, b, "mail send " + key(a) + " short confirmation", capacity, true, 501);
|
||||
assert(snapshot(fs) == before);
|
||||
}
|
||||
response = request(fs, a, remove(4, first)); assert(response[2] == 0);
|
||||
assert(status(fs, a).count == 1);
|
||||
response = request(fs, b, send(a, full_body), 160, true, nonce);
|
||||
assert(response[2] == 8 && id(response) == first && status(fs, a).count == 1);
|
||||
assert(request(fs, a, remove(4, first))[2] == 0);
|
||||
assert(request(fs, a, remove(5, first))[2] == 0);
|
||||
assert(request(fs, a, read(first))[2] == 4);
|
||||
{
|
||||
MemoryFS air;
|
||||
assert(request(air, a, padded(settings()))[2] == 0 && air.files.empty());
|
||||
assert(request(air, a, padded(edit(8, 0, 2)))[2] == 0);
|
||||
assert(request(air, a, padded(editKey(6, status(air, a).revision, b)))[2] == 0);
|
||||
assert(request(air, a, padded(edit(9, status(air, a).revision, 1)))[2] == 0);
|
||||
const std::string dog = "dog lost: please call home";
|
||||
response = request(air, b, padded(send(a, dog)), 160, true, 700);
|
||||
const uint32_t dog_id = id(response);
|
||||
assert(request(air, a, padded(indexRequest()))[7] == 1);
|
||||
response = request(air, a, padded(read(dog_id)));
|
||||
assert(response[11] == dog.size() && std::string(reinterpret_cast<const char*>(response.data() + 44), response[11]) == dog);
|
||||
assert(status(air, a).count == 1); // Reading on a later wake leaves queued mail intact.
|
||||
assert(request(air, a, padded(remove(4, dog_id)))[2] == 0 && status(air, a).count == 0);
|
||||
assert(request(air, a, padded(remove(5, dog_id)))[2] == 0);
|
||||
assert(request(air, a, padded(editKey(7, status(air, a).revision, b)))[2] == 0);
|
||||
const auto before = snapshot(air);
|
||||
for (auto input : {settings(), indexRequest(), read(dog_id), send(a, "changed padding"),
|
||||
remove(4, dog_id), remove(5, dog_id), edit(8, status(air, a).revision, 1),
|
||||
edit(9, status(air, a).revision, 0), editKey(6, status(air, a).revision, b), editKey(7, status(air, a).revision, b)}) {
|
||||
input.push_back(1); assert(request(air, a, input, 160, true, 701)[2] == 1);
|
||||
}
|
||||
assert(snapshot(air) == before);
|
||||
}
|
||||
|
||||
assert(command(fs, a, "mail deny " + key(b)) == "OK");
|
||||
assert(request(fs, b, send(a, "denied"), 160, true, 999)[2] == 6);
|
||||
assert(command(fs, a, "mail mode public") == "OK");
|
||||
response = request(fs, c, send(a, "public mode"), 160, true, 1000); const uint32_t public_id = id(response);
|
||||
assert(command(fs, a, "mail delete " + std::to_string(public_id)).find("OK id=") == 0);
|
||||
assert(command(fs, a, "mail delivery chat") == "OK" && !status(fs, a).settings.mailbox_only);
|
||||
for (uint8_t value = 1; value <= 8; ++value) {
|
||||
uint8_t allowed[32]; memset(allowed, value, 32);
|
||||
assert(command(fs, a, "mail allow " + key(allowed)) == "OK");
|
||||
}
|
||||
assert(command(fs, a, "mail allow " + key(b)) == "Error mailbox full");
|
||||
assert(command(fs, a, "mail settings").find("next=1") != std::string::npos);
|
||||
assert(command(fs, a, "mail settings 7").find("next=8") != std::string::npos);
|
||||
assert(request(fs, a, settings(status(fs, a).revision, 7), 45)[11] == 255);
|
||||
assert(command(fs, a, "mail check").find("allowed=8") != std::string::npos);
|
||||
assert(request(fs, c, send(a, std::string("bad\0body", 8)), 160, true, 1010)[2] == 1);
|
||||
assert(request(fs, c, send(a, std::string("\xed\xa0\x80", 3)), 160, true, 1011)[2] == 1);
|
||||
assert(request(fs, c, send(a, "cafe\xc3\xa9"), 160, true, 1012)[2] == 0);
|
||||
assert(request(fs, c, send(a, "third queued"), 160, true, 1013)[2] == 0);
|
||||
assert(request(fs, c, send(a, "fourth queued"), 160, true, 1014)[2] == 0);
|
||||
assert(status(fs, a).count == 4);
|
||||
assert(request(fs, c, send(a, "over quota"), 160, true, 1015)[2] == 7);
|
||||
response = request(fs, a, indexRequest());
|
||||
assert(response[7] == 4 && response[9] == 2 && response[10] == 2);
|
||||
response = request(fs, a, indexRequest(status(fs, a).revision, 2));
|
||||
assert(response[7] == 4 && response[9] == 255 && response[10] == 2);
|
||||
|
||||
for (const std::string& text : std::vector<std::string>{"mail", "mail bogus", "mail mode", "mail mode administrator",
|
||||
"mail mode public trailing", "mail delivery radio", "mail allow " + key(b).substr(0, 63),
|
||||
"mail deny " + std::string(64, '0'), "mail allow " + std::string(64, 'z'),
|
||||
"mail allow " + key(b) + " trailing", "mail send " + key(a),
|
||||
"mail send " + key(a) + " " + std::string(513, 'x'), "mail read 0", "mail read -1",
|
||||
"mail read 4294967296", "mail read 1 513", "mail read 1 0 trailing", "mail ack 0",
|
||||
"mail delete 1 trailing", "mail settings 9", "mail list 17"}) {
|
||||
const auto before = snapshot(fs);
|
||||
assert(command(fs, a, text).find("Error ") == 0); assert(snapshot(fs) == before);
|
||||
}
|
||||
command(fs, a, "mailbox settings", 160, true, 1, false);
|
||||
command(fs, a, "unrelated", 160, true, 1, false);
|
||||
const auto before_invalid = snapshot(fs);
|
||||
for (const std::vector<uint8_t>& payload : std::vector<std::vector<uint8_t>>{
|
||||
{}, {11}, {11, 255}, {11, 0}, {11, 0, 9}, {11, 0, 0, 1}, {11, 1}, {11, 2},
|
||||
{11, 3}, {11, 4}, {11, 5}, edit(8, status(fs, a).revision, 3), edit(9, status(fs, a).revision, 2),
|
||||
std::vector<uint8_t>(38, 0)}) {
|
||||
response = request(fs, a, payload); assert(response.empty() || response[2] == 1);
|
||||
}
|
||||
assert(snapshot(fs) == before_invalid);
|
||||
uint8_t zero[32] = {};
|
||||
assert(request(fs, zero, settings())[2] == 1);
|
||||
assert(command(fs, zero, "mail settings") == "Error invalid");
|
||||
printf("PASS: %u owner-bound room mail LoRa/CLI protocol, capacity and durable retry scenarios\n", scenarios);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class RoomMailProtocolTests(unittest.TestCase):
|
||||
def test_actual_protocol_and_store_all_backend_modes(self):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
self.skipTest("a host C++ compiler is required")
|
||||
candidates = [Path(os.environ["MESHCORE_CRYPTO_DIR"])] if os.environ.get("MESHCORE_CRYPTO_DIR") else []
|
||||
candidates += sorted((ROOT / ".pio/libdeps").glob("*/Crypto"))
|
||||
crypto = next((path for path in candidates if (path / "SHA256.cpp").is_file()), None)
|
||||
if crypto is None:
|
||||
raise RuntimeError("Install rweather/Crypto or set MESHCORE_CRYPTO_DIR (no hash mock fallback)")
|
||||
filesystem = FILESYSTEM_HARNESS.split("#define FILE_O_WRITE 1")[0]
|
||||
filesystem = filesystem.replace(" File() = default;", """#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
File() = delete;
|
||||
#else
|
||||
File() = default;
|
||||
#endif
|
||||
explicit File(MemoryFS* owner): fs(owner) {}""")
|
||||
filesystem = filesystem.replace("return {};", "return File(this);")
|
||||
filesystem = filesystem.replace(
|
||||
" void _lockFS() {}\n void _unlockFS() {}\n MemoryFS* _getFS() { return this; }\n", "", 1
|
||||
)
|
||||
filesystem = filesystem.replace(" void point(const std::string& event) {", """ int lock_depth = 0;
|
||||
void _lockFS() { assert(lock_depth++ == 0); }
|
||||
void _unlockFS() { assert(--lock_depth == 0); }
|
||||
MemoryFS* _getFS() { return this; }
|
||||
void point(const std::string& event) {""")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
if sys.platform.startswith("linux") else [])
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-room-mail-protocol-") as temporary:
|
||||
work = Path(temporary)
|
||||
(work / "sys").mkdir()
|
||||
(work / "sys/stat.h").write_text(STAT_MOCK)
|
||||
source = work / "protocol.cpp"
|
||||
for platform in (None, "NRF52_PLATFORM", "STM32_PLATFORM", "RP2040_PLATFORM", "ESP32_PLATFORM"):
|
||||
with self.subTest(platform=platform):
|
||||
source.write_text(filesystem + (LFS_MOCK if platform in ("NRF52_PLATFORM", "STM32_PLATFORM") else "") + TESTS)
|
||||
binary = work / (platform or "generic")
|
||||
defines = ["-D" + platform + "=1"] if platform else []
|
||||
built = subprocess.run(
|
||||
[compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", "-DHOST_BUILD", *sanitizers,
|
||||
*defines, "-I" + str(work), "-I" + str(ROOT / "src"), "-I" + str(crypto), str(source),
|
||||
str(crypto / "SHA256.cpp"), str(crypto / "Hash.cpp"), str(crypto / "Crypto.cpp"), "-o", str(binary)],
|
||||
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=60)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("owner-bound room mail LoRa/CLI protocol", checked.stdout)
|
||||
print(checked.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the actual owner-bound mailbox transaction under ASAN and storage faults."""
|
||||
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_room_topic_store import HARNESS as FILESYSTEM_HARNESS, STAT_MOCK
|
||||
from test_room_board_store import LFS_MOCK
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
# Host-only adapter supplies the same incremental SHA256 interface as Arduino
|
||||
# Crypto, using independently implemented OpenSSL for reproducible digests.
|
||||
SHA_MOCK = r'''
|
||||
#pragma once
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <openssl/evp.h>
|
||||
class SHA256 {
|
||||
EVP_MD_CTX* context;
|
||||
public:
|
||||
SHA256(): context(EVP_MD_CTX_new()) { assert(context && EVP_DigestInit_ex(context, EVP_sha256(), nullptr)); }
|
||||
~SHA256() { EVP_MD_CTX_free(context); }
|
||||
void update(const void* input, size_t length) { assert(EVP_DigestUpdate(context, input, length)); }
|
||||
void finalize(void* output, size_t length) {
|
||||
unsigned count = 0; unsigned char digest[32];
|
||||
assert(EVP_DigestFinal_ex(context, digest, &count) && count == 32 && length <= 32);
|
||||
memcpy(output, digest, length);
|
||||
}
|
||||
};
|
||||
'''
|
||||
|
||||
TESTS = r'''
|
||||
#define FILE_O_WRITE 1
|
||||
#include <helpers/RoomMailStore.h>
|
||||
using Result = mesh::RoomMailResult;
|
||||
using Settings = mesh::RoomMailSettings;
|
||||
using Mode = mesh::RoomMailMode;
|
||||
using Message = mesh::RoomMailMessage;
|
||||
using Status = mesh::RoomMailStatus;
|
||||
static const char* P = mesh::ROOM_MAIL_PRIMARY_PATH;
|
||||
static const char* T = mesh::ROOM_MAIL_TEMP_PATH;
|
||||
static const char* B = mesh::ROOM_MAIL_BACKUP_PATH;
|
||||
static unsigned scenarios = 0;
|
||||
static uint8_t OWNER[32] = {1}, OTHER[32] = {2}, SENDER[32] = {3};
|
||||
static const std::string OLD_BODY = "Existing private message";
|
||||
static const std::string NEW_BODY(512, 'n');
|
||||
static void use(MemoryFS& fs) { metadata_filesystem = &fs; }
|
||||
static MemoryFS clone(const MemoryFS& source) {
|
||||
MemoryFS fs; fs.directories = source.directories;
|
||||
for (const auto& file : source.files) fs.put(file.first.c_str(), *file.second);
|
||||
return fs;
|
||||
}
|
||||
static std::map<std::string, std::vector<uint8_t>> snapshot(const MemoryFS& fs) {
|
||||
std::map<std::string, std::vector<uint8_t>> result;
|
||||
for (const auto& file : fs.files) result[file.first] = *file.second;
|
||||
return result;
|
||||
}
|
||||
static Status status(MemoryFS& fs, const uint8_t* owner = OWNER) {
|
||||
use(fs); Status out;
|
||||
assert(mesh::getRoomMailStatus(&fs, owner, out) == Result::Success); return out;
|
||||
}
|
||||
static Result provision(MemoryFS& fs, const uint8_t* owner = OWNER, Mode mode = Mode::Public) {
|
||||
use(fs); Settings settings; settings.mode = mode;
|
||||
return mesh::saveRoomMailSettings(&fs, owner, settings);
|
||||
}
|
||||
static Result send(MemoryFS& fs, uint64_t nonce, const std::string& body, uint32_t& id,
|
||||
const uint8_t* owner = OWNER, const uint8_t* sender = SENDER, uint32_t created = 42) {
|
||||
use(fs); return mesh::sendRoomMail(&fs, sender, owner, nonce, body.data(), body.size(), id, created);
|
||||
}
|
||||
static void bodyIs(MemoryFS& fs, const uint8_t* owner, uint32_t id, const std::string& expected) {
|
||||
use(fs); std::string assembled; Message info;
|
||||
for (size_t offset = 0; offset <= expected.size();) {
|
||||
uint8_t output[39]; memset(output, 0x7f, sizeof(output)); size_t copied = 999;
|
||||
assert(mesh::readRoomMail(&fs, owner, id, offset, output + 1, 37, copied, info) == Result::Success);
|
||||
assert(output[0] == 0x7f && output[38] == 0x7f && copied <= 37 && info.length == expected.size());
|
||||
assembled.append(reinterpret_cast<const char*>(output + 1), copied); offset += copied;
|
||||
if (!copied) break;
|
||||
}
|
||||
assert(assembled == expected);
|
||||
}
|
||||
static void checksum(std::vector<uint8_t>& image) {
|
||||
const uint32_t value = mesh::room_mail_detail::crc(0xffffffffu, image.data(), image.size() - 4) ^ 0xffffffffu;
|
||||
mesh::room_mail_detail::put32(image.data() + image.size() - 4, value);
|
||||
}
|
||||
static uint32_t firstId(MemoryFS& fs) {
|
||||
use(fs); Message list[4]; size_t copied;
|
||||
assert(mesh::listRoomMail(&fs, OWNER, 0, 0, list, 4, copied) == Result::Success && copied == 1);
|
||||
return list[0].id;
|
||||
}
|
||||
static void preserveUnavailable(MemoryFS& fs) {
|
||||
use(fs); const auto before = snapshot(fs); const auto directories = fs.directories;
|
||||
Status out; out.count = 99; out.revision = 99;
|
||||
assert(mesh::getRoomMailStatus(&fs, OWNER, out) == Result::Unavailable && !out.count && !out.revision);
|
||||
uint32_t id = 123;
|
||||
assert(send(fs, 2, NEW_BODY, id) == Result::Unavailable && id == 0);
|
||||
assert(mesh::acknowledgeRoomMail(&fs, OWNER, 2) == Result::Unavailable);
|
||||
assert(provision(fs) == Result::Unavailable);
|
||||
assert(snapshot(fs) == before && fs.directories == directories && fs.write_opens == 0);
|
||||
++scenarios;
|
||||
}
|
||||
int main() {
|
||||
{ MemoryFS fs; use(fs); Status out;
|
||||
assert(mesh::getRoomMailStatus(&fs, OWNER, out) == Result::NotFound && out.settings.mode == Mode::Closed && !out.count);
|
||||
bool mailbox_only = true; assert(mesh::getRoomMailboxOnly(&fs, OWNER, mailbox_only) == Result::Success && !mailbox_only);
|
||||
uint32_t id; assert(send(fs, 1, "No mailbox", id) == Result::NotFound);
|
||||
assert(fs.files.empty() && fs.write_opens == 0);
|
||||
assert(provision(fs, OWNER, Mode::Closed) == Result::Success);
|
||||
Settings stale; stale.mode = Mode::Public;
|
||||
const auto before = snapshot(fs);
|
||||
assert(mesh::saveRoomMailSettings(&fs, OWNER, stale, 0) == Result::StaleVersion);
|
||||
assert(snapshot(fs) == before && status(fs).settings.mode == Mode::Closed);
|
||||
assert(send(fs, 1, "Denied", id) == Result::Forbidden);
|
||||
assert(send(fs, 1, "Owner always permitted", id, OWNER, OWNER) == Result::Success);
|
||||
assert(mesh::acknowledgeRoomMail(&fs, OWNER, id) == Result::Success);
|
||||
assert(mesh::acknowledgeRoomMail(&fs, OWNER, id) == Result::Success);
|
||||
assert(send(fs, 1, "Owner always permitted", id, OWNER, OWNER) == Result::Duplicate);
|
||||
assert(send(fs, 1, "Changed", id, OWNER, OWNER) == Result::Mismatch);
|
||||
++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; assert(provision(fs) == Result::Success); Settings settings;
|
||||
settings.mode = Mode::Private; settings.mailbox_only = true; settings.allowed_count = 2;
|
||||
memcpy(settings.allowed[0], SENDER, 32); memcpy(settings.allowed[1], OTHER, 32);
|
||||
assert(mesh::saveRoomMailSettings(&fs, OWNER, settings, 1) == Result::Success);
|
||||
Status own = status(fs); assert(own.settings.mailbox_only && own.settings.allowed_count == 2);
|
||||
assert(memcmp(own.settings.allowed[0], OTHER, 32) == 0); // Canonical full-key order.
|
||||
bool only = false; assert(mesh::getRoomMailboxOnly(&fs, OWNER, only) == Result::Success && only);
|
||||
uint32_t id; assert(send(fs, UINT64_C(0x100000001), u8"Caf\u00e9 \u5730\u56f3 \U0001f4e1", id) == Result::Success);
|
||||
assert(send(fs, UINT64_C(0x200000001), "Different high nonce bits", id) == Result::Success);
|
||||
uint8_t collision[32] = {3}; collision[31] = 1;
|
||||
assert(send(fs, 4, "Short key collision", id, OWNER, collision) == Result::Forbidden);
|
||||
assert(mesh::saveRoomMailSettings(&fs, OWNER, settings, 2) == Result::StaleVersion);
|
||||
assert(provision(fs, OTHER) == Result::Success);
|
||||
Message list[4]; size_t copied;
|
||||
assert(mesh::listRoomMail(&fs, OTHER, 0, 0, list, 4, copied) == Result::Success && copied == 0);
|
||||
uint8_t output[8]; Message info;
|
||||
assert(mesh::readRoomMail(&fs, OTHER, 3, 0, output, sizeof(output), copied, info) == Result::NotFound);
|
||||
assert(mesh::acknowledgeRoomMail(&fs, OTHER, 3) == Result::NotFound);
|
||||
assert(mesh::deleteRoomMail(&fs, OTHER, 3) == Result::NotFound);
|
||||
assert(status(fs).count == 2); ++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; assert(provision(fs) == Result::Success); uint32_t id;
|
||||
assert(send(fs, 1, NEW_BODY, id) == Result::Success); bodyIs(fs, OWNER, id, NEW_BODY);
|
||||
use(fs); Message info; uint8_t output[128]; size_t copied;
|
||||
assert(mesh::readRoomMail(&fs, OWNER, id, 512, output, 128, copied, info) == Result::Success && copied == 0);
|
||||
assert(mesh::readRoomMail(&fs, OWNER, id, 513, output, 128, copied, info) == Result::Invalid && !copied);
|
||||
assert(mesh::readRoomMail(&fs, OWNER, id, 0, output, 129, copied, info) == Result::Invalid && !copied);
|
||||
assert(send(fs, 1, NEW_BODY, id, OWNER, SENDER, 9876) == Result::Duplicate);
|
||||
++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; assert(provision(fs) == Result::Success); uint32_t id;
|
||||
use(fs); uint8_t zero[32] = {}; Settings bad; bad.allowed_count = 9;
|
||||
assert(mesh::saveRoomMailSettings(&fs, OWNER, bad) == Result::Invalid);
|
||||
bad.allowed_count = 1; assert(mesh::saveRoomMailSettings(&fs, OWNER, bad) == Result::Invalid);
|
||||
assert(mesh::saveRoomMailSettings(&fs, zero, Settings{}) == Result::Invalid);
|
||||
const auto before = snapshot(fs); fs.reset();
|
||||
for (const std::string& body : {std::string(), std::string(513, 'x'), std::string("a\0b", 3), std::string("\xc0\xaf"), std::string("\xed\xa0\x80"), std::string("\xf4\x90\x80\x80"), std::string("\xe2\x82")})
|
||||
assert(send(fs, 1, body, id) == Result::Invalid && !id);
|
||||
assert(send(fs, 0, "x", id) == Result::Invalid);
|
||||
assert(send(fs, 1, "x", id, OWNER, zero) == Result::Invalid);
|
||||
assert(snapshot(fs) == before && fs.write_opens == 0); ++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; uint32_t id;
|
||||
for (uint8_t owner = 1; owner <= 32; ++owner) {
|
||||
uint8_t key[32] = {owner}; assert(provision(fs, key) == Result::Success);
|
||||
if (owner <= 4) for (uint64_t nonce = 1; nonce <= 4; ++nonce) assert(send(fs, nonce, "Queue", id, key) == Result::Success);
|
||||
}
|
||||
uint8_t extra[32] = {33}; assert(provision(fs, extra) == Result::Full);
|
||||
assert(send(fs, 5, "Per owner full", id) == Result::Full);
|
||||
uint8_t fifth[32] = {5}; assert(send(fs, 1, "Global full", id, fifth) == Result::Full);
|
||||
use(fs); mesh::RoomMailStats stats; assert(mesh::getRoomMailStats(&fs, stats) == Result::Success && stats.owners == 32 && stats.messages == 16);
|
||||
uint8_t keys[3][32]; size_t copied;
|
||||
assert(mesh::listRoomMailOwners(&fs, stats.revision, 2, keys, 3, copied, stats) == Result::Success && copied == 3 && keys[0][0] == 3);
|
||||
assert(mesh::listRoomMailOwners(&fs, 1, 0, keys, 3, copied, stats) == Result::StaleVersion);
|
||||
assert(mesh::deleteRoomMail(&fs, OWNER, 0) == Result::Success);
|
||||
assert(mesh::getRoomMailStats(&fs, stats) == Result::Success && stats.messages == 12);
|
||||
assert(send(fs, 1, "Queue", id) == Result::Duplicate);
|
||||
assert(send(fs, 5, "Space reclaimed", id) == Result::Success); ++scenarios;
|
||||
}
|
||||
{ MemoryFS fs; assert(provision(fs) == Result::Success); uint32_t live, id;
|
||||
assert(send(fs, 100, "Keep this old queued message", live) == Result::Success);
|
||||
for (uint64_t nonce = 1; nonce <= 20; ++nonce) {
|
||||
assert(send(fs, nonce, "Retired", id) == Result::Success);
|
||||
assert(mesh::deleteRoomMail(&fs, OWNER, id) == Result::Success);
|
||||
assert(send(fs, nonce, "Retired", id) == Result::Duplicate);
|
||||
}
|
||||
bodyIs(fs, OWNER, live, "Keep this old queued message");
|
||||
assert(send(fs, 100, "Keep this old queued message", id) == Result::Duplicate && id == live);
|
||||
assert(mesh::deleteRoomMail(&fs, OWNER, 0) == Result::Success && !status(fs).count); ++scenarios;
|
||||
}
|
||||
|
||||
MemoryFS initial; assert(provision(initial) == Result::Success); uint32_t original_id;
|
||||
assert(send(initial, 1, OLD_BODY, original_id) == Result::Success); initial.reset();
|
||||
const auto old_primary = initial.get(P);
|
||||
const std::string old_path = "/room_mail_0.b", new_path = "/room_mail_0.a";
|
||||
|
||||
// Every byte of selected owner bank and registry is protected. A corrupt
|
||||
// primary cannot be replaced by backups or uncommitted temporary images.
|
||||
for (const std::string& path : {std::string(P), old_path}) {
|
||||
const auto original = initial.get(path.c_str());
|
||||
for (size_t position = 0; position < original.size(); ++position) {
|
||||
MemoryFS fs = clone(initial); auto corrupted = original; corrupted[position] ^= 1;
|
||||
fs.put(path.c_str(), corrupted); fs.put(B, old_primary); fs.put(T, old_primary);
|
||||
preserveUnavailable(fs);
|
||||
}
|
||||
}
|
||||
{ MemoryFS fs = clone(initial); auto future = fs.get(P); future[3] = 2; checksum(future); fs.put(P, future); preserveUnavailable(fs); }
|
||||
{ MemoryFS fs = clone(initial); auto invalid = fs.get(old_path.c_str()); invalid[42] = 5; checksum(invalid); fs.put(old_path.c_str(), invalid); preserveUnavailable(fs); }
|
||||
{ MemoryFS fs = clone(initial); auto invalid = fs.get(P); invalid[51] = 1; checksum(invalid); fs.put(P, invalid); preserveUnavailable(fs); }
|
||||
{ MemoryFS fs = clone(initial); fs.files.erase(P); fs.put(B, old_primary); fs.put(T, old_primary);
|
||||
bodyIs(fs, OWNER, original_id, OLD_BODY); assert(fs.files.count(P) && !fs.files.count(B)); ++scenarios; }
|
||||
{ MemoryFS fs = clone(initial); fs.files.erase(P); auto broken = old_primary; broken[0] ^= 1;
|
||||
fs.put(B, broken); fs.put(T, old_primary); preserveUnavailable(fs); }
|
||||
|
||||
// Faults before publication preserve the previous committed mailbox. The
|
||||
// inactive bank may contain an orphan; it is never selected without commit.
|
||||
for (const std::string& fault : {std::string("open:w:") + new_path, std::string("write:") + new_path,
|
||||
std::string("flush:") + new_path, std::string("close:w:") + new_path,
|
||||
std::string("open:r:") + new_path, std::string("directory:") + new_path,
|
||||
std::string("open:w:") + T, std::string("write:") + T, std::string("flush:") + T,
|
||||
std::string("close:w:") + T, std::string("open:r:") + T,
|
||||
std::string("rename:") + P + ":" + B, std::string("rename:") + T + ":" + P}) {
|
||||
MemoryFS fs = clone(initial); fs.faults.insert(fault); uint32_t id;
|
||||
assert(send(fs, 2, NEW_BODY, id) == Result::WriteFailure && !id);
|
||||
fs.reset(); assert(status(fs).count == 1 && firstId(fs) == original_id); bodyIs(fs, OWNER, original_id, OLD_BODY); ++scenarios;
|
||||
}
|
||||
{ MemoryFS fs = clone(initial); fs.short_write = true; uint32_t id;
|
||||
assert(send(fs, 2, NEW_BODY, id) == Result::WriteFailure && !id); fs.reset(); assert(status(fs).count == 1); ++scenarios; }
|
||||
{ MemoryFS fs = clone(initial); fs.short_read = true; uint32_t id;
|
||||
assert(send(fs, 2, NEW_BODY, id) == Result::Unavailable); fs.reset(); assert(status(fs).count == 1); ++scenarios; }
|
||||
for (size_t budget = 0; budget < 1800; ++budget) {
|
||||
MemoryFS fs = clone(initial); fs.write_budget = budget; uint32_t id;
|
||||
const Result result = send(fs, 2, NEW_BODY, id); fs.reset();
|
||||
assert(result == Result::Success || result == Result::WriteFailure);
|
||||
assert(status(fs).count == (result == Result::Success ? 2 : 1)); bodyIs(fs, OWNER, original_id, OLD_BODY); ++scenarios;
|
||||
}
|
||||
|
||||
// Reboot at every observable filesystem boundary of send, ACK, purge and
|
||||
// settings changes. Each recovered state is entirely old or entirely new.
|
||||
for (uint8_t operation = 0; operation < 4; ++operation) {
|
||||
auto mutate = [&](MemoryFS& fs) -> Result {
|
||||
use(fs); uint32_t id;
|
||||
if (operation == 0) return send(fs, 2, NEW_BODY, id);
|
||||
if (operation == 1) return mesh::acknowledgeRoomMail(&fs, OWNER, original_id);
|
||||
if (operation == 2) return mesh::deleteRoomMail(&fs, OWNER, 0);
|
||||
Settings settings; settings.mode = Mode::Private; settings.mailbox_only = true;
|
||||
return mesh::saveRoomMailSettings(&fs, OWNER, settings);
|
||||
};
|
||||
MemoryFS successful = clone(initial); assert(mutate(successful) == Result::Success);
|
||||
const size_t boundaries = successful.boundary;
|
||||
for (size_t cut = 1; cut <= boundaries; ++cut) {
|
||||
MemoryFS fs = clone(initial); fs.cut_at = cut;
|
||||
try { mutate(fs); } catch (const PowerCut&) {}
|
||||
fs.reset(); const Status restored = status(fs);
|
||||
if (operation == 0) {
|
||||
assert(restored.count == 1 || restored.count == 2); bodyIs(fs, OWNER, original_id, OLD_BODY);
|
||||
uint32_t id; const Result retry = send(fs, 2, NEW_BODY, id);
|
||||
assert(retry == Result::Success || retry == Result::Duplicate);
|
||||
assert(status(fs).count == 2); bodyIs(fs, OWNER, id, NEW_BODY);
|
||||
} else if (operation < 3) {
|
||||
assert(restored.count <= 1); assert(mutate(fs) == Result::Success && status(fs).count == 0);
|
||||
uint32_t id; assert(send(fs, 1, OLD_BODY, id) == Result::Duplicate && id == original_id);
|
||||
} else {
|
||||
assert(restored.count == 1 && (restored.settings.mode == Mode::Public || restored.settings.mode == Mode::Private));
|
||||
bodyIs(fs, OWNER, original_id, OLD_BODY);
|
||||
assert(mutate(fs) == Result::Success && status(fs).settings.mailbox_only);
|
||||
}
|
||||
++scenarios;
|
||||
}
|
||||
}
|
||||
printf("%u room mailbox ownership, policy, bounded storage, retry, fault and power-cut scenarios passed\n", scenarios);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class RoomMailStoreTest(unittest.TestCase):
|
||||
def test_actual_store_with_all_backend_modes_faults_and_powercuts(self):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
self.skipTest("a host C++ compiler is required")
|
||||
filesystem = FILESYSTEM_HARNESS.split("#define FILE_O_WRITE 1")[0]
|
||||
# Real Adafruit LittleFS files are filesystem-bound and have no default
|
||||
# constructor. A permissive mock must not hide unsupported handles.
|
||||
filesystem = filesystem.replace(" File() = default;", """#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
File() = delete;
|
||||
#else
|
||||
File() = default;
|
||||
#endif
|
||||
explicit File(MemoryFS* owner): fs(owner) {}""")
|
||||
filesystem = filesystem.replace("return {};", "return File(this);")
|
||||
filesystem = filesystem.replace(" void _lockFS() {}\n void _unlockFS() {}\n MemoryFS* _getFS() { return this; }\n", "", 1)
|
||||
filesystem = filesystem.replace(" void point(const std::string& event) {", """ int lock_depth = 0;
|
||||
void _lockFS() { assert(lock_depth++ == 0); }
|
||||
void _unlockFS() { assert(--lock_depth == 0); }
|
||||
MemoryFS* _getFS() { return this; }
|
||||
size_t write_budget = std::numeric_limits<size_t>::max();
|
||||
void point(const std::string& event) {""")
|
||||
filesystem = filesystem.replace(" bytes->insert(bytes->end(), data, data + length);", """ length = std::min(length, fs->write_budget);
|
||||
fs->write_budget -= length;
|
||||
bytes->insert(bytes->end(), data, data + length);""")
|
||||
filesystem = filesystem.replace("void reset() { trace.clear();", "void reset() { lock_depth = 0; write_budget = std::numeric_limits<size_t>::max(); trace.clear();")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
if sys.platform.startswith("linux") else [])
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-room-mail-") as temporary:
|
||||
work = Path(temporary)
|
||||
(work / "sys").mkdir()
|
||||
(work / "sys/stat.h").write_text(STAT_MOCK)
|
||||
(work / "SHA256.h").write_text(SHA_MOCK)
|
||||
source = work / "mail.cpp"
|
||||
for platform in (None, "NRF52_PLATFORM", "STM32_PLATFORM", "RP2040_PLATFORM", "ESP32_PLATFORM"):
|
||||
with self.subTest(platform=platform):
|
||||
source.write_text(filesystem + (LFS_MOCK if platform in ("NRF52_PLATFORM", "STM32_PLATFORM") else "") + TESTS)
|
||||
binary = work / (platform or "generic")
|
||||
defines = ["-D" + platform + "=1"] if platform else []
|
||||
built = subprocess.run([compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", *sanitizers,
|
||||
*defines, "-I" + str(work), "-I" + str(ROOT / "src"), str(source), "-lcrypto", "-o", str(binary)],
|
||||
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=120)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("room mailbox ownership, policy, bounded storage, retry, fault and power-cut scenarios passed", checked.stdout)
|
||||
print(checked.stdout.strip())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the actual personal mailbox page in Chromium, without hardware."""
|
||||
|
||||
import json
|
||||
import unittest
|
||||
|
||||
import test_room_web_ui as room_ui
|
||||
|
||||
|
||||
MAIL_COMMON = r'''
|
||||
const ownKey=boundary.status.web_key,senderKey='ab'.repeat(32),otherOwner='cd'.repeat(32);
|
||||
let serverRole=2,settingsRevision=0,serverMode='closed',serverOnly=false,serverAllow=[],inbox=[],chunks=[],confirmations=[];
|
||||
const settings=(owner=ownKey,extra={})=>Object.assign({owner:owner,revision:settingsRevision,mode:serverMode,mailbox_only:serverOnly,allowlist:serverAllow,blocked:false},extra);
|
||||
const mailBase=p=>{
|
||||
if(p.op==='status')return response(Object.assign({},boundary.status,{role:serverRole,mailbox_only:serverOnly}));
|
||||
if(p.op==='posts')return response({post:null});
|
||||
if(p.op==='board.index')return response({revision:0,articles:[],next:255});
|
||||
if(p.op==='mail.settings')return response(settings());
|
||||
if(p.op==='mail.check')return response({owner:ownKey,revision:settingsRevision,mailbox_only:serverOnly,total:inbox.length,unread:inbox.length});
|
||||
if(p.op==='mail.list')return response({messages:inbox,next:null,revision:settingsRevision});
|
||||
return null;
|
||||
};
|
||||
const joinedMailRoom=async()=>{submit('join');await until(()=>!$('room').hidden&&$('notices').textContent==='No notices published.')};
|
||||
const edit=id=>$(id).dispatchEvent(new Event(id.includes('allowlist')||id==='mail-text'||id==='mail-recipient'?'input':'change'));
|
||||
window.confirm=text=>{confirmations.push(text);return true};
|
||||
'''
|
||||
|
||||
|
||||
class RoomMailWebUiTest(unittest.TestCase):
|
||||
run_page = room_ui.RoomWebUiTest.run_page
|
||||
attribute = room_ui.RoomWebUiTest.attribute
|
||||
|
||||
def test_saved_mailbox_only_join_skips_chat_until_explicit_refresh(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
serverOnly=true;
|
||||
window.fetch=(url,options)=>{const p=record(url,options),result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op)};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();mark('initial-posts',calls.filter(c=>c.op==='posts').length);mark('initial-mail',calls.filter(c=>c.op.startsWith('mail.')).length);
|
||||
mark('hint',$('mail-summary').textContent);mark('hint-visible',!$('mail-summary').hidden);await refreshChat(true);mark('auto-posts',calls.filter(c=>c.op==='posts').length);
|
||||
await refreshChat();mark('manual-posts',calls.filter(c=>c.op==='posts').length);mark('lazy-panel',$('mail-panel').hidden);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertEqual(self.attribute(dom, "initial-posts"), "0")
|
||||
self.assertEqual(self.attribute(dom, "initial-mail"), "0")
|
||||
self.assertEqual(self.attribute(dom, "auto-posts"), "0")
|
||||
self.assertEqual(self.attribute(dom, "manual-posts"), "1")
|
||||
self.assertEqual(self.attribute(dom, "hint-visible"), "true")
|
||||
self.assertIn("automatic chat downloads are paused", self.attribute(dom, "hint"))
|
||||
self.assertEqual(self.attribute(dom, "lazy-panel"), "true")
|
||||
|
||||
def test_lazy_closed_mailbox_selective_safe_reads_resume_and_explicit_receipt(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
const text='<img src=x onerror=attack()> '+ 'x'.repeat(230),bytes=new TextEncoder().encode(text);
|
||||
const item={id:7,sender:senderKey,created:1001,length:bytes.length,acked:false};inbox=[item];let fail=true,acks=0;
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='mail.read'){
|
||||
chunks.push(p.offset);if(p.offset===128&&fail){fail=false;return response({error:'link lost'})}
|
||||
const part=bytes.slice(p.offset,p.offset+128);
|
||||
return response({id:7,sender:senderKey,created:1001,length:bytes.length,offset:p.offset,count:part.length,next:p.offset+part.length,data64:btoa(Array.from(part,b=>String.fromCharCode(b)).join('')),acked:false});
|
||||
}
|
||||
if(p.op==='mail.ack'){acks++;inbox=[];return response({ok:true})}
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();mark('initial-mail-requests',calls.filter(c=>c.op.startsWith('mail.')).length);
|
||||
await openMailbox();mark('default-mode',$('mail-mode').value);mark('address',$('mail-key').textContent);
|
||||
document.body.style.width='360px';document.body.style.boxSizing='border-box';const panel=$('mail-panel').getBoundingClientRect();mark('responsive-fit',Array.from($('mail-panel').querySelectorAll('fieldset')).every(field=>field.getBoundingClientRect().right<=panel.right+1));
|
||||
mark('before-body-reads',chunks.length);mark('sender',$('mail-rows').textContent);
|
||||
try{await openMail(item)}catch(error){}
|
||||
mark('partial',mailTransfers.get(7).next);mark('partial-ack-disabled',$('mail-ack').disabled);mark('before-acks',acks);
|
||||
await openMail(item);mark('body',$('mail-body').textContent);mark('images',document.querySelectorAll('img').length);
|
||||
mark('complete-ack-disabled',$('mail-ack').disabled);mark('read-acks',acks);await removeMail(true);
|
||||
mark('acks',acks);mark('offsets',JSON.stringify(chunks));mark('removed-body',$('mail-body').textContent);mark('removed-cache',mailTransfers.size);mark('receipt-confirmation',confirmations[0]);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertEqual(self.attribute(dom, "initial-mail-requests"), "0")
|
||||
self.assertEqual(self.attribute(dom, "default-mode"), "closed")
|
||||
self.assertEqual(self.attribute(dom, "responsive-fit"), "true")
|
||||
self.assertEqual(len(self.attribute(dom, "address")), 64)
|
||||
self.assertEqual(self.attribute(dom, "before-body-reads"), "0")
|
||||
self.assertIn("ab" * 32, self.attribute(dom, "sender"))
|
||||
self.assertEqual(self.attribute(dom, "partial"), "128")
|
||||
self.assertEqual(self.attribute(dom, "partial-ack-disabled"), "true")
|
||||
self.assertEqual(self.attribute(dom, "complete-ack-disabled"), "false")
|
||||
self.assertEqual(self.attribute(dom, "read-acks"), "0")
|
||||
self.assertEqual(self.attribute(dom, "acks"), "1")
|
||||
self.assertEqual(self.attribute(dom, "images"), "0")
|
||||
self.assertIn("<img src=x onerror=attack()>", self.attribute(dom, "body"))
|
||||
self.assertEqual(json.loads(self.attribute(dom, "offsets")), [0, 128, 128, 256])
|
||||
self.assertEqual(self.attribute(dom, "removed-body"), "")
|
||||
self.assertEqual(self.attribute(dom, "removed-cache"), "0")
|
||||
self.assertIn("Confirm receipt and remove", self.attribute(dom, "receipt-confirmation"))
|
||||
|
||||
def test_policy_stale_revision_retains_draft_key_limit_and_mailbox_only_poll(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
let writes=[];
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='mail.policy'){
|
||||
writes.push(p);if(p.expected_revision!==settingsRevision)return response({error:'mailbox policy changed; reload'});
|
||||
settingsRevision++;serverMode=p.mode;serverAllow=p.allowlist;serverOnly=p.mailbox_only;return response(settings());
|
||||
}
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await openMailbox();$('mail-mode').value='private';edit('mail-mode');$('mail-allowlist').value=senderKey;edit('mail-allowlist');$('mail-only').checked=true;edit('mail-only');
|
||||
settingsRevision=2;await loadMailSettings();mark('baseline-after-refresh',mailPolicy.revision);mark('draft-before-save',$('mail-allowlist').value);
|
||||
try{await saveMailPolicy()}catch(error){}mark('failed-draft',$('mail-allowlist').value);mark('failed-revision',writes[0].expected_revision);
|
||||
await loadMailSettings(true);$('mail-mode').value='private';edit('mail-mode');$('mail-allowlist').value=senderKey;edit('mail-allowlist');$('mail-only').checked=true;edit('mail-only');await saveMailPolicy();
|
||||
mark('success',$('mail-policy-result').textContent);mark('allowlist',JSON.stringify(writes[1].allowlist));mark('saved-revision',mailPolicy.revision);
|
||||
const before=calls.filter(c=>c.op==='posts').length;await refreshChat(true);mark('auto-chat',calls.filter(c=>c.op==='posts').length-before);await refreshChat();mark('manual-chat',calls.filter(c=>c.op==='posts').length-before);
|
||||
$('mail-allowlist').value=Array.from({length:9},(_,i)=>(i+1).toString(16).padStart(64,'0')).join('\n');edit('mail-allowlist');
|
||||
try{await saveMailPolicy()}catch(error){mark('limit-error',error.message)}mark('write-count',writes.length);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertEqual(self.attribute(dom, "baseline-after-refresh"), "0")
|
||||
self.assertEqual(self.attribute(dom, "failed-revision"), "0")
|
||||
self.assertEqual(self.attribute(dom, "failed-draft"), "ab" * 32)
|
||||
self.assertEqual(json.loads(self.attribute(dom, "allowlist")), ["ab" * 32])
|
||||
self.assertEqual(self.attribute(dom, "saved-revision"), "3")
|
||||
self.assertIn("saved and confirmed", self.attribute(dom, "success"))
|
||||
self.assertEqual(self.attribute(dom, "auto-chat"), "0")
|
||||
self.assertEqual(self.attribute(dom, "manual-chat"), "1")
|
||||
self.assertIn("up to 8", self.attribute(dom, "limit-error"))
|
||||
self.assertEqual(self.attribute(dom, "write-count"), "2")
|
||||
|
||||
def test_send_identical_http_retry_utf8_limit_failed_draft_and_reader_permission(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
let attempts=0,effects=0,first=null,pending=null;
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);if(url==='/api/room/result')return response(pending);
|
||||
if(p.op==='mail.send'){
|
||||
attempts++;if(attempts===1){first=calls[calls.length-1];effects++;pending={ok:true,id:11};return Promise.reject(Error('lost response'))}
|
||||
if(attempts===2){const current=calls[calls.length-1];mark('same-seq',current.seq===first.seq);mark('same-body',current.body===first.body);return response({},202)}
|
||||
return response({error:'recipient mailbox is full'});
|
||||
}
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await openMailbox();$('mail-recipient').value=senderKey;edit('mail-recipient');$('mail-text').value='\u{1f4e1}'.repeat(128);edit('mail-text');mark('max-disabled',$('mail-send').disabled);
|
||||
$('mail-text').value+='x';edit('mail-text');mark('over-disabled',$('mail-send').disabled);try{await sendMail()}catch(error){}mark('over-attempts',attempts);
|
||||
$('mail-text').value='hello';edit('mail-text');await sendMail();mark('confirmed-draft',$('mail-text').value);mark('confirmed-status',$('mail-send-result').textContent);
|
||||
$('mail-text').value='keep private draft';edit('mail-text');try{await sendMail()}catch(error){}mark('failed-draft',$('mail-text').value);mark('effects',effects);mark('attempts',attempts);
|
||||
serverRole=1;await status();$('mail-recipient').value=senderKey;$('mail-text').value='reader attempt';updateMailButtons();mark('reader-disabled',$('mail-send').disabled);
|
||||
try{await sendMail()}catch(error){mark('reader-error',error.message)}mark('reader-attempts',attempts);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertEqual(self.attribute(dom, "max-disabled"), "false")
|
||||
self.assertEqual(self.attribute(dom, "over-disabled"), "true")
|
||||
self.assertEqual(self.attribute(dom, "over-attempts"), "0")
|
||||
self.assertEqual(self.attribute(dom, "same-seq"), "true")
|
||||
self.assertEqual(self.attribute(dom, "same-body"), "true")
|
||||
self.assertEqual(self.attribute(dom, "effects"), "1")
|
||||
self.assertEqual(self.attribute(dom, "confirmed-draft"), "")
|
||||
self.assertIn("saved for", self.attribute(dom, "confirmed-status"))
|
||||
self.assertEqual(self.attribute(dom, "failed-draft"), "keep private draft")
|
||||
self.assertEqual(self.attribute(dom, "reader-disabled"), "true")
|
||||
self.assertEqual(self.attribute(dom, "reader-attempts"), self.attribute(dom, "attempts"))
|
||||
|
||||
def test_admin_metadata_only_pages_policy_purge_block_and_role_loss(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
serverRole=3;let changes=[],deletions=[],bans=[],acceptedConfirm=true;
|
||||
window.confirm=text=>{confirmations.push(text);return acceptedConfirm};
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='admin.mail.list')return response({mailboxes:[{owner:p.cursor===0?ownKey:otherOwner,mode:'private',revision:5,total:2,unread:2,blocked:false}],next:p.cursor===0?1:null,revision:5});
|
||||
if(p.op==='admin.mail.settings')return response(settings(p.owner,{revision:5,mode:'private',allowlist:[senderKey]}));
|
||||
if(p.op==='admin.mail.policy'){changes.push(p);return response({error:'mailbox policy changed; reload'})}
|
||||
if(p.op==='admin.mail.delete'){deletions.push(p);return response({ok:true})}
|
||||
if(p.op==='admin.ban'){bans.push(p);return response({ok:true})}
|
||||
if(p.op==='mail.read')throw Error('admin downloaded private mail');
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await loadAdminMail(0);mark('full-owner',$('admin-mail-rows').textContent);mark('next-enabled',!$('admin-mail-next').disabled);
|
||||
await loadAdminMail(1);mark('second-owner',$('admin-mail-rows').textContent);await selectAdminMail(otherOwner);mark('selected-address',$('admin-mail-key').textContent);mark('allowlist',$('admin-mail-allowlist').value);
|
||||
$('admin-mail-mode').value='public';edit('admin-mail-mode');try{await saveAdminMailPolicy()}catch(error){}mark('admin-failed-draft',$('admin-mail-mode').value);mark('policy-request',JSON.stringify(changes[0]));
|
||||
acceptedConfirm=false;await deleteAdminMail(true);mark('cancel-deletions',deletions.length);acceptedConfirm=true;await deleteAdminMail(true);mark('purge',JSON.stringify(deletions[0]));
|
||||
await blockAdminMail();mark('ban',JSON.stringify(bans[0]));mark('body-reads',calls.filter(c=>c.op==='mail.read').length);
|
||||
serverRole=2;await status();mark('cleared-key',$('admin-mail-key').textContent);mark('cleared-allowlist',$('admin-mail-allowlist').value);mark('hidden-policy',$('admin-mail-policy').hidden);mark('confirmations',JSON.stringify(confirmations));mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertIn("cd" * 32, self.attribute(dom, "second-owner"))
|
||||
self.assertEqual(self.attribute(dom, "next-enabled"), "true")
|
||||
self.assertEqual(self.attribute(dom, "selected-address"), "cd" * 32)
|
||||
self.assertEqual(self.attribute(dom, "allowlist"), "ab" * 32)
|
||||
self.assertEqual(self.attribute(dom, "admin-failed-draft"), "public")
|
||||
policy = json.loads(self.attribute(dom, "policy-request"))
|
||||
self.assertEqual((policy["owner"], policy["expected_revision"], policy["mode"]), ("cd" * 32, 5, "public"))
|
||||
self.assertEqual(self.attribute(dom, "cancel-deletions"), "0")
|
||||
purge = json.loads(self.attribute(dom, "purge"))
|
||||
self.assertEqual((purge["owner"], purge["id"]), ("cd" * 32, 0))
|
||||
ban = json.loads(self.attribute(dom, "ban"))
|
||||
self.assertEqual((ban["key"], ban["banned"]), ("cd" * 32, True))
|
||||
self.assertEqual(self.attribute(dom, "body-reads"), "0")
|
||||
self.assertEqual(self.attribute(dom, "cleared-key"), "")
|
||||
self.assertEqual(self.attribute(dom, "cleared-allowlist"), "")
|
||||
self.assertEqual(self.attribute(dom, "hidden-policy"), "true")
|
||||
|
||||
def test_admin_provisions_new_radio_mailbox_by_complete_address(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
serverRole=3;const radioOwner='ef'.repeat(32);let configured=false,loaded=[],policies=[];
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='admin.mail.settings'){loaded.push(p.owner);return response(settings(p.owner,{revision:0,mode:'closed',mailbox_only:false,allowlist:[]}))}
|
||||
if(p.op==='admin.mail.policy'){policies.push(p);if(p.owner!==radioOwner||p.expected_revision!==0)throw Error('incorrect new radio policy');configured=true;return response(settings(radioOwner,{revision:1,mode:p.mode,mailbox_only:p.mailbox_only,allowlist:p.allowlist}))}
|
||||
if(p.op==='admin.mail.list')return response({mailboxes:configured?[{owner:radioOwner,mode:'private',revision:1,unread:0,total:0,blocked:false}]:[],revision:configured?1:0,next:null});
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await loadAdminMail(0);$('admin-mail-owner').value='short-key';$('admin-mail-load-owner').click();await until(()=>$('error').textContent.includes('complete'));mark('invalid-loads',loaded.length);
|
||||
$('admin-mail-owner').value=radioOwner.toUpperCase();$('admin-mail-load-owner').click();await until(()=>!$('admin-mail-policy').hidden);mark('selected-address',$('admin-mail-key').textContent);mark('initial-mode',$('admin-mail-mode').value);mark('initial-revision',adminMailPolicy.revision);
|
||||
$('admin-mail-mode').value='private';edit('admin-mail-mode');$('admin-mail-allowlist').value=senderKey;edit('admin-mail-allowlist');$('admin-mail-only').checked=true;edit('admin-mail-only');await saveAdminMailPolicy();await loadAdminMail(0);
|
||||
mark('policy',JSON.stringify(policies[0]));mark('listed-owner',$('admin-mail-rows').textContent);mark('body-reads',calls.filter(c=>c.op==='mail.read').length);serverRole=2;await status();mark('cleared-entry',$('admin-mail-owner').value);mark('admin-hidden',$('admin-panel').hidden);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertEqual(self.attribute(dom, "invalid-loads"), "0")
|
||||
self.assertEqual(self.attribute(dom, "selected-address"), "ef" * 32)
|
||||
self.assertEqual(self.attribute(dom, "initial-mode"), "closed")
|
||||
self.assertEqual(self.attribute(dom, "initial-revision"), "0")
|
||||
policy = json.loads(self.attribute(dom, "policy"))
|
||||
self.assertEqual((policy["owner"], policy["expected_revision"], policy["mode"]), ("ef" * 32, 0, "private"))
|
||||
self.assertEqual(policy["allowlist"], ["ab" * 32])
|
||||
self.assertTrue(policy["mailbox_only"])
|
||||
self.assertIn("ef" * 32, self.attribute(dom, "listed-owner"))
|
||||
self.assertEqual(self.attribute(dom, "body-reads"), "0")
|
||||
self.assertEqual(self.attribute(dom, "cleared-entry"), "")
|
||||
self.assertEqual(self.attribute(dom, "admin-hidden"), "true")
|
||||
|
||||
def test_disconnect_rejects_late_private_response_and_clears_sensitive_drafts(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
const item={id:3,sender:senderKey,created:1001,length:6,acked:false};inbox=[item];let resolveRead;
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);if(p.op==='mail.read')return new Promise(resolve=>resolveRead=resolve);
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await openMailbox();$('mail-text').value='private draft';$('mail-allowlist').value=senderKey;
|
||||
const reading=openMail(item).catch(error=>error.message);await until(()=>resolveRead);$('disconnect').click();
|
||||
resolveRead({ok:true,status:200,json:()=>Promise.resolve({id:3,sender:senderKey,created:1001,length:6,offset:0,count:6,next:6,data64:btoa('secret')})});
|
||||
mark('late-error',await reading);mark('body',$('mail-body').textContent);mark('cache',mailTransfers.size);mark('draft',$('mail-text').value);mark('allowlist',$('mail-allowlist').value);mark('panel-hidden',$('mail-panel').hidden);mark('selected-hidden',$('mail-selected').hidden);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertIn("connection changed", self.attribute(dom, "late-error"))
|
||||
for field in ["body", "draft", "allowlist"]:
|
||||
self.assertEqual(self.attribute(dom, field), "")
|
||||
self.assertEqual(self.attribute(dom, "cache"), "0")
|
||||
self.assertEqual(self.attribute(dom, "panel-hidden"), "true")
|
||||
self.assertEqual(self.attribute(dom, "selected-hidden"), "true")
|
||||
|
||||
def test_mail_and_admin_pages_pin_revision_until_explicit_refresh(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
serverRole=3;settingsRevision=10;serverMode='public';let serverRevision=10,mailPagesAsked=[],adminPagesAsked=[];
|
||||
const entries=Array.from({length:3},(_,i)=>({id:i+1,sender:senderKey,created:1001+i,length:6,acked:false}));
|
||||
const owners=[ownKey,senderKey,otherOwner].map(owner=>({owner:owner,mode:'public',revision:10,unread:1,total:1,blocked:false}));
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='mail.list'||p.op==='admin.mail.list'){
|
||||
(p.op==='mail.list'?mailPagesAsked:adminPagesAsked).push(p);
|
||||
if(p.cursor&&p.revision!==serverRevision)return response({error:'mailbox changed; refresh before continuing'});
|
||||
const data=p.op==='mail.list'?{messages:entries.slice(p.cursor,p.cursor+2)}:{mailboxes:owners.slice(p.cursor,p.cursor+2)};
|
||||
return response(Object.assign(data,{next:p.cursor===0?2:null,revision:serverRevision}));
|
||||
}
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await openMailbox();serverRevision=11;
|
||||
try{await refreshMail(2)}catch(error){mark('mail-stale-error',error.message)}
|
||||
mark('retained-mail-rows',$('mail-rows').textContent);mark('mail-cursor-after-stale',mailCursor);mark('mail-stale-revision',mailPagesAsked[1].revision);
|
||||
mailPages=[];await refreshMail(0);await refreshMail(2);mark('mail-fresh-revision',mailPagesAsked[3].revision);mark('mail-last-page',$('mail-rows').textContent);
|
||||
await loadAdminMail(0);serverRevision=12;try{await loadAdminMail(2)}catch(error){mark('admin-stale-error',error.message)}
|
||||
mark('admin-cursor-after-stale',adminMailCursor);mark('admin-stale-revision',adminPagesAsked[1].revision);adminMailPages=[];await loadAdminMail(0);await loadAdminMail(2);
|
||||
mark('admin-fresh-revision',adminPagesAsked[3].revision);mark('admin-last-owner',$('admin-mail-rows').textContent);mark('body-requests',calls.filter(c=>c.op==='mail.read').length);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertIn("changed", self.attribute(dom, "mail-stale-error"))
|
||||
self.assertEqual(self.attribute(dom, "mail-cursor-after-stale"), "0")
|
||||
self.assertEqual(self.attribute(dom, "mail-stale-revision"), "10")
|
||||
self.assertEqual(self.attribute(dom, "mail-fresh-revision"), "11")
|
||||
self.assertIn("Read 3", self.attribute(dom, "mail-last-page"))
|
||||
self.assertIn("changed", self.attribute(dom, "admin-stale-error"))
|
||||
self.assertEqual(self.attribute(dom, "admin-cursor-after-stale"), "0")
|
||||
self.assertEqual(self.attribute(dom, "admin-stale-revision"), "11")
|
||||
self.assertEqual(self.attribute(dom, "admin-fresh-revision"), "12")
|
||||
self.assertIn("cd" * 32, self.attribute(dom, "admin-last-owner"))
|
||||
self.assertEqual(self.attribute(dom, "body-requests"), "0")
|
||||
|
||||
def test_invalid_chunk_cannot_enable_receipt_or_replace_saved_bytes(self):
|
||||
dom = self.run_page(MAIL_COMMON + r'''
|
||||
const item={id:3,sender:senderKey,created:1001,length:6,acked:false};inbox=[item];let acks=0;
|
||||
window.fetch=(url,options)=>{
|
||||
const p=record(url,options);
|
||||
if(p.op==='mail.read')return response({id:3,sender:otherOwner,created:1001,length:6,offset:0,count:6,next:6,data64:btoa('secret')});
|
||||
if(p.op==='mail.ack'){acks++;return response({ok:true})}
|
||||
const result=mailBase(p);if(result)return result;throw Error('unexpected '+p.op);
|
||||
};
|
||||
window.addEventListener('load',()=>{(async()=>{
|
||||
await joinedMailRoom();await openMailbox();try{await openMail(item)}catch(error){mark('read-error',error.message)}
|
||||
try{await removeMail(true)}catch(error){mark('receipt-error',error.message)}
|
||||
mark('offset',mailTransfers.get(3).next);mark('body',$('mail-body').textContent);mark('ack-disabled',$('mail-ack').disabled);mark('acks',acks);mark('done',true);
|
||||
})().catch(error=>mark('js-error',error.message))});
|
||||
''')
|
||||
self.assertIn("invalid", self.attribute(dom, "read-error"))
|
||||
self.assertIn("complete", self.attribute(dom, "receipt-error"))
|
||||
self.assertEqual(self.attribute(dom, "offset"), "0")
|
||||
self.assertEqual(self.attribute(dom, "body"), "")
|
||||
self.assertEqual(self.attribute(dom, "ack-disabled"), "true")
|
||||
self.assertEqual(self.attribute(dom, "acks"), "0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -30,7 +30,12 @@ class RoomTopicDeliveryTests(unittest.TestCase):
|
||||
"bool MyMesh::sendClientReply(",
|
||||
"bool MyMesh::pushPostToClient(", "bool MyMesh::pushRoomTextToClient(",
|
||||
"bool MyMesh::processAck(", "void MyMesh::activateRoomTopic(",
|
||||
"bool MyMesh::handleRoomTopicCommand(", "void MyMesh::serviceRoomPush("))
|
||||
"bool MyMesh::handleRoomTopicCommand(", "void MyMesh::serviceRoomPush(",
|
||||
"uint8_t MyMesh::getUnsyncedCount("))
|
||||
# The legacy topic fixture has a separate adapter for topic-only saves.
|
||||
# Mail policy uses its real filesystem, without replacing its handler.
|
||||
definitions += "\n" + extract_braced(source, "bool MyMesh::roomClientChatEnabled(").replace(
|
||||
"getRoomMailboxOnly(_fs,", "getRoomMailboxOnly(&policy_fs,")
|
||||
packet = (ROOT / "src/Packet.cpp").read_text()
|
||||
definitions = "namespace mesh {\n" + extract_braced(
|
||||
packet, "bool Packet::isValidPathLen(") + "\n}\n" + definitions
|
||||
@@ -41,6 +46,7 @@ class RoomTopicDeliveryTests(unittest.TestCase):
|
||||
binary = work / "delivery"
|
||||
command = [compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-unused-parameter", "-I" + str(work), "-I" + str(ROOT / "src"),
|
||||
"-I" + str(ROOT / "test/mocks"),
|
||||
str(FIXTURE), "-o", str(binary)]
|
||||
if sys.platform.startswith("linux"):
|
||||
command[1:1] = ["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
|
||||
@@ -34,7 +34,7 @@ class RoomWebServiceTest(unittest.TestCase):
|
||||
"bool MyMesh::executeClientPathCommand(", "bool MyMesh::setRoomClientPath(",
|
||||
"bool MyMesh::applyRoomCatchUpCommand(", "bool MyMesh::saveFilter(",
|
||||
"void MyMesh::writeRoomClientJson(",
|
||||
"uint8_t MyMesh::getUnsyncedCount(", "bool MyMesh::handleRoomHistoryCommand(",
|
||||
"bool MyMesh::roomClientChatEnabled(", "uint8_t MyMesh::getUnsyncedCount(", "bool MyMesh::handleRoomHistoryCommand(",
|
||||
"bool MyMesh::handleRoomTopicCommand(", "void MyMesh::activateRoomTopic("))
|
||||
packet = (ROOT / "src/Packet.cpp").read_text()
|
||||
production = "namespace mesh {\n" + extract_braced(
|
||||
@@ -73,6 +73,7 @@ class RoomWebServiceTest(unittest.TestCase):
|
||||
"-Wno-misleading-indentation", *sanitizers, "-DESP32_PLATFORM=1",
|
||||
"-DARDUINOJSON_POOL_CAPACITY=64",
|
||||
"-I" + str(work), "-I" + str(ROOT / "src"), "-I" + str(json_header.parent),
|
||||
"-I" + str(ROOT / "test/mocks"),
|
||||
str(FIXTURES / "service.cpp"), "-o", str(binary)],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
@@ -80,7 +81,8 @@ class RoomWebServiceTest(unittest.TestCase):
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("actual room web service", checked.stdout)
|
||||
for group in ("ADMIN_AUTH", "ADMIN_ROUTES", "ADMIN_CATCHUP", "ADMIN_USERS",
|
||||
"ADMIN_SETTINGS", "ADMIN_INVALID"):
|
||||
"ADMIN_SETTINGS", "ADMIN_INVALID", "MAIL_AUTH", "MAIL_DELIVERY",
|
||||
"MAIL_ADMIN", "MAIL_PAGING", "MAIL_STORAGE", "MAIL_GLOBAL"):
|
||||
self.assertRegex(checked.stdout, r"(?m)^" + group + ":")
|
||||
for kind in ("STATUS", "INDEX", "READ"):
|
||||
match = re.search(r"^BOUNDARY_" + kind + r" (.+)$", checked.stdout, re.M)
|
||||
|
||||
Reference in new issue
Block a user