Allow local CLI maintenance across direct connections
This commit is contained in:
1 parent
001b4985f7
commit
06c51fdef5
39 files changed
+3338
-2312
No files matched your search
@@ -78,6 +78,10 @@ class FirmwareRamTest(unittest.TestCase):
|
||||
self.assertEqual(ram.requirements("ESP32_PLATFORM", wifi_only, "v4_companion"), plain)
|
||||
repeater = ram.requirements("ESP32_PLATFORM", defines, "v4_repeater")
|
||||
self.assertNotIn("browser_terminal_session", repeater["components"])
|
||||
for role in ("v4_repeater", "v4_room_server"):
|
||||
local = ram.requirements("ESP32_PLATFORM", {**defines, "ADMIN_PASSWORD": "test"}, role)
|
||||
self.assertEqual(local["components"]["browser_terminal_session"], 2048)
|
||||
self.assertEqual(local["components"]["browser_terminal_scrollback"], 4096)
|
||||
|
||||
def test_longer_display_previews_reserve_heap_and_contiguous_history(self):
|
||||
defines = {"DISPLAY_CLASS": "SSD1306Display", "UI_SMALL_MESSAGE_FONT": 0}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
"""Compile real Companion command dispatch with local and LoRa callers."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
PREAMBLE = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#define ESP32 1
|
||||
#define WIFI_SSID "test"
|
||||
#define WITH_MQTT_BRIDGE 1
|
||||
#define PRV_KEY_SIZE 64
|
||||
#define MAX_MQTT_SLOTS 2
|
||||
#define MAX_LORA_TX_POWER 22
|
||||
#define TXT_TYPE_CLI_COMMAND 1
|
||||
namespace mesh {
|
||||
struct Packet {};
|
||||
void resetLazyPersistenceAfterSuccess(unsigned& when, uint8_t& failures) { when=0; failures=0; }
|
||||
struct Utils {
|
||||
static void toHex(char* out,const uint8_t* data,size_t len) {
|
||||
for(size_t i=0;i<len;++i) sprintf(out+2*i,"%02X",data[i]);
|
||||
}
|
||||
};
|
||||
}
|
||||
struct ContactInfo { bool isRemoteCLIAllowed() const { return true; } };
|
||||
struct WiFiSetupPortal {
|
||||
static bool loadStoredCredentials(char*,size_t,char* password,size_t size) {
|
||||
snprintf(password,size,"wifi-secret");return true;
|
||||
}
|
||||
};
|
||||
struct Identity {
|
||||
int writeTo(uint8_t* out,size_t len) { memset(out,0xA5,len);return len; }
|
||||
};
|
||||
struct Store {
|
||||
int erased=0; bool success=true;
|
||||
bool formatFileSystem(){++erased;return success;}
|
||||
};
|
||||
struct Prefs {
|
||||
float freq=910, bw=125, airtime_factor=1, rx_delay_base=1;
|
||||
uint8_t sf=7, cr=5, path_hash_mode=0, multi_acks=0, rx_ps_level=0, rx_ps_preamble=16;
|
||||
uint32_t rx_ps_rx_us=1, rx_ps_sleep_us=1;
|
||||
int8_t tx_power_dbm=10;
|
||||
char node_name[32]="test";
|
||||
Prefs* getRadioPrefs(){return this;}
|
||||
bool handleCommand(const char*,uint32_t,char*){return false;}
|
||||
bool isDirty() const {return false;}
|
||||
void clearDirty(){}
|
||||
};
|
||||
struct Board {
|
||||
bool rebootToUf2Bootloader(){return false;}
|
||||
bool handleCommand(const char*,uint32_t,char*){return false;}
|
||||
} board;
|
||||
struct Radio {bool setTxPower(int){return true;}} radio_driver;
|
||||
struct AdvertDataParser {static bool isValidName(const char*){return true;}};
|
||||
struct StrHelper {static void strncpy(char* out,const char* in,size_t len){::strncpy(out,in,len);}};
|
||||
void recalcRxPowerSavingFromLevel(uint8_t,uint8_t,float,uint8_t,uint32_t*,uint32_t*){}
|
||||
struct StatsFormatHelper {
|
||||
template<class... T> static void formatCoreStats(char* out,T&&...){strcpy(out,"core");}
|
||||
template<class... T> static void formatRadioStats(char* out,T&&...){strcpy(out,"radio");}
|
||||
template<class... T> static void formatRadioDiag(char* out,T&&...){strcpy(out,"diag");}
|
||||
template<class... T> static void formatPacketStats(char* out,T&&...){strcpy(out,"packets");}
|
||||
};
|
||||
struct WebConfigServer {
|
||||
static bool formatWiFiPassword(char* out,size_t len){snprintf(out,len,"> wifi-secret");return true;}
|
||||
};
|
||||
const char* FIRMWARE_VERSION="test";
|
||||
const char* FIRMWARE_BUILD_DATE="test";
|
||||
struct MyMesh {
|
||||
Identity self_id;
|
||||
Store store; Store* _store=&store;
|
||||
Prefs _prefs;
|
||||
struct {char mqtt_slot_password[2][64]={"mqtt-secret","other"};
|
||||
char mqtt_slot_token[2][64]={"mqtt-token","other-token"};} _mqtt_prefs;
|
||||
unsigned dirty_contacts_expiry=1; uint8_t dirty_contacts_failures=1;
|
||||
int value=0; int* _ms=&value; int* _radio=&value; int* _mgr=&value;
|
||||
uint16_t _err_flags=0;
|
||||
bool _radio_available=false, save_ok=true;
|
||||
int resets=0;
|
||||
bool handleCommand(const char*,uint32_t,char*);
|
||||
bool handleDirectCommand(const char*,char*,size_t);
|
||||
void onCLICommandRecv(const ContactInfo&,mesh::Packet*,uint32_t,const char*,char*);
|
||||
bool handleLocalControlCommand(const char* text,char* reply,size_t) {
|
||||
if(!strcmp(text,"get mqtt1.password")||!strcmp(text,"get mqtt1.token")) {
|
||||
strcpy(reply,"> ********");return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
void stopContactsIterator(){}
|
||||
void resetContacts(){++resets;}
|
||||
bool savePrefs(){return save_ok;}
|
||||
int getTotalAirTime(){return 0;}
|
||||
int getReceiveAirTime(){return 0;}
|
||||
int getNumSentFlood(){return 0;}
|
||||
int getNumSentDirect(){return 0;}
|
||||
int getNumRecvFlood(){return 0;}
|
||||
int getNumRecvDirect(){return 0;}
|
||||
bool hasOutbound(){return false;}
|
||||
void markConnectionActive(const ContactInfo&){}
|
||||
void queueMessage(const ContactInfo&,int,mesh::Packet*,uint32_t,const void*,int,const char*){}
|
||||
};
|
||||
'''
|
||||
|
||||
SCENARIOS = r'''
|
||||
int main() {
|
||||
MyMesh node;
|
||||
char reply[160] = {};
|
||||
const char* local[] = {"get password", "get prv.key", "get wifi.pwd", "get mqtt1.password",
|
||||
"get mqtt1.token", "stats-core", "stats-radio", "stats-radio-diag", "stats-packets"};
|
||||
for(const char* command:local) {
|
||||
memset(reply,0,sizeof(reply));
|
||||
assert(node.handleCommand(command,0,reply));
|
||||
assert(strlen(reply)>0);
|
||||
if(!strcmp(command,"get password")) assert(strstr(reply,"no admin password"));
|
||||
if(!strcmp(command,"get prv.key")) {
|
||||
#if ENABLE_PRIVATE_KEY_EXPORT
|
||||
assert(strlen(reply)==130 && !strncmp(reply,"> A5A5",6));
|
||||
#else
|
||||
assert(strstr(reply,"disabled"));
|
||||
#endif
|
||||
}
|
||||
if(!strcmp(command,"get wifi.pwd")) assert(!strcmp(reply,"> wifi-secret"));
|
||||
if(!strcmp(command,"get mqtt1.password")) assert(!strcmp(reply,"> mqtt-secret"));
|
||||
if(!strcmp(command,"get mqtt1.token")) assert(!strcmp(reply,"> mqtt-token"));
|
||||
memset(reply,0,sizeof(reply));
|
||||
node.handleCommand(command,100,reply);
|
||||
assert(!strstr(reply,"secret") && !strstr(reply,"token") && !strstr(reply,"A5A5"));
|
||||
// In particular, an authenticated LoRa packet carrying timestamp zero
|
||||
// still enters the production receiver with remote restrictions.
|
||||
memset(reply,0,sizeof(reply));
|
||||
node.onCLICommandRecv(ContactInfo{},nullptr,0,command,reply);
|
||||
assert(!strstr(reply,"secret") && !strstr(reply,"token") && !strstr(reply,"A5A5"));
|
||||
}
|
||||
assert(node.handleCommand("set freq 915.25",0,reply));
|
||||
assert(node._prefs.freq==915.25f);
|
||||
assert(!node.handleCommand("set freq 920",100,reply));
|
||||
node.onCLICommandRecv(ContactInfo{},nullptr,0,"set freq 920",reply);
|
||||
assert(node._prefs.freq==915.25f);
|
||||
node.save_ok=false;
|
||||
assert(node.handleCommand("set freq 920",0,reply));
|
||||
assert(node._prefs.freq==915.25f && strstr(reply,"Error"));
|
||||
assert(node.handleCommand("set freq 920oops",0,reply));
|
||||
assert(node._prefs.freq==915.25f && strstr(reply,"Error"));
|
||||
assert(!node.handleCommand("erase",100,reply));
|
||||
node.onCLICommandRecv(ContactInfo{},nullptr,0,"erase",reply);
|
||||
assert(node.store.erased==0);
|
||||
assert(node.handleCommand("erase",0,reply));
|
||||
assert(node.store.erased==1 && node.resets==1 && node.dirty_contacts_expiry==0);
|
||||
assert(strstr(reply,"OK"));
|
||||
node.store.success=false;
|
||||
assert(node.handleCommand("erase",0,reply));
|
||||
assert(node.resets==1 && strstr(reply,"Err"));
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class LocalCliAccessTest(unittest.TestCase):
|
||||
def test_infrastructure_password_read_and_browser_transport_limits(self):
|
||||
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text()
|
||||
getter = extract_braced(source, "void CommonCLI::handleGetCmd(")
|
||||
password = extract_braced(getter, 'if (strcmp(config, "password") == 0)')
|
||||
web = (ROOT / "src/helpers/esp32/WebConfigServer.cpp").read_text()
|
||||
limits = extract_braced(web, "static const char* wcCliUnavailable(")
|
||||
code = r'''
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
struct Prefs { char password[16] = "admin-secret"; } prefs;
|
||||
Prefs* _prefs = &prefs;
|
||||
void get(const char* config, uint32_t sender_timestamp, char* reply) {
|
||||
''' + password + "\n}\n" + limits + r'''
|
||||
int main() {
|
||||
char reply[160] = {};
|
||||
get("password",0,reply);
|
||||
assert(!strcmp(reply,"> admin-secret"));
|
||||
for(uint32_t stamp:{1u,100u,0xFFFFFFFFu}) {
|
||||
get("password",stamp,reply);
|
||||
assert(strstr(reply,"local connection") && !strstr(reply,"admin-secret"));
|
||||
}
|
||||
reply[0]=0;get("passwordx",0,reply);assert(!reply[0]);
|
||||
assert(wcCliUnavailable("get password",false)==nullptr);
|
||||
assert(wcCliUnavailable("get password",true)==nullptr);
|
||||
assert(wcCliUnavailable("log",false)!=nullptr);
|
||||
assert(wcCliUnavailable("log",true)==nullptr);
|
||||
assert(wcCliUnavailable("get acl",true)==nullptr);
|
||||
assert(wcCliUnavailable("start ota",true)!=nullptr);
|
||||
assert(wcCliUnavailable("clock sync",true)!=nullptr);
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
binary = Path(temp) / "test"
|
||||
result = subprocess.run([
|
||||
"c++", "-std=c++17", "-include", "initializer_list", "-x", "c++", "-",
|
||||
"-fsanitize=address,undefined", "-fno-pie", "-no-pie", "-o", str(binary),
|
||||
], input=code, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout+result.stderr)
|
||||
|
||||
def test_real_companion_dispatch_local_binary_and_radio(self):
|
||||
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
implementation = "\n".join(extract_braced(source, signature) for signature in (
|
||||
"static bool isCompanionRadioPrefsCommand(",
|
||||
"bool MyMesh::handleDirectCommand(", "bool MyMesh::handleCommand(",
|
||||
"void MyMesh::onCLICommandRecv("))
|
||||
for export, webconfig in ((0, False), (1, False), (0, True), (1, True)):
|
||||
with self.subTest(export=export, webconfig=webconfig), tempfile.TemporaryDirectory() as temp:
|
||||
binary = Path(temp) / "test"
|
||||
result = subprocess.run([
|
||||
"c++", "-std=c++17", "-x", "c++", "-", "-I"+str(ROOT / "src"),
|
||||
"-DENABLE_PRIVATE_KEY_EXPORT="+str(export),
|
||||
*(["-DWITH_WEBCONFIG=1"] if webconfig else []),
|
||||
"-fsanitize=address,undefined", "-fno-pie", "-no-pie", "-o", str(binary),
|
||||
], input=PREAMBLE+implementation+SCENARIOS, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout+result.stderr)
|
||||
|
||||
def test_each_host_transport_uses_local_dispatch(self):
|
||||
for role in ("simple_repeater", "simple_room_server"):
|
||||
header = (ROOT / "examples" / role / "MyMesh.h").read_text()
|
||||
web = extract_braced(header, "void execAdminCommand(")
|
||||
self.assertIn("handleCommand(0, cmd, reply)", web)
|
||||
local = extract_braced(header, "void handleLocalCommand(")
|
||||
self.assertIn("_command_output = &output", local)
|
||||
self.assertIn("handleCommand(0, command, reply)", local)
|
||||
self.assertIn("_command_output = nullptr", local)
|
||||
stream = extract_braced(header, "void runStreamTerminal(")
|
||||
self.assertIn("handleLocalCommand(command, reply, *_web_terminal)", stream)
|
||||
main = (ROOT / "examples" / role / "main.cpp").read_text()
|
||||
self.assertIn("handleLocalCommand(ethernet_command, reply, ethernet_client)", main)
|
||||
self.assertIn("cancelLocalOutput(ethernet_client)", main)
|
||||
source = (ROOT / "examples" / role / "MyMesh.cpp").read_text()
|
||||
guard = ("sender != nullptr" if role == "simple_repeater"
|
||||
else "gpio_client_index >= 0")
|
||||
self.assertIn("if ("+guard+" && sender_timestamp == 0) sender_timestamp = 1;", source)
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text()
|
||||
framed = extract_braced(companion, "else if (mesh::companion::isRunCliFrame(")
|
||||
self.assertIn("handleCommand(text, 0, reply_buf)", framed)
|
||||
sensor = (ROOT / "examples/simple_sensor/SensorMesh.cpp").read_text()
|
||||
self.assertIn("if (gpio_client_index >= 0 && sender_timestamp == 0) sender_timestamp = 1;", sensor)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,124 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <helpers/LocalCliOutput.h>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
struct FileState { std::string text; size_t reads = 0; bool closed = false, fail = false; };
|
||||
struct File {
|
||||
FileState* state = nullptr;
|
||||
size_t offset = 0;
|
||||
explicit operator bool() const { return state && !state->closed; }
|
||||
size_t size() const { return state->text.size(); }
|
||||
void close() { if (state) state->closed = true; }
|
||||
int read(uint8_t* out, size_t count) {
|
||||
++state->reads;
|
||||
if (state->fail) return -1;
|
||||
count = std::min(count, state->text.size() - offset);
|
||||
memcpy(out, state->text.data() + offset, count);
|
||||
offset += count;
|
||||
return count;
|
||||
}
|
||||
};
|
||||
struct Output : Stream {
|
||||
std::string text;
|
||||
int room = 40;
|
||||
size_t max_write = 7;
|
||||
int availableForWrite() override { return room; }
|
||||
size_t write(const uint8_t* data, size_t count) override {
|
||||
count = std::min(count, max_write);
|
||||
text.append(reinterpret_cast<const char*>(data), count);
|
||||
return count;
|
||||
}
|
||||
};
|
||||
void drain(mesh::LocalCliOutput<File>& job) {
|
||||
for (size_t n = 0; job.busy() && n < 100000; ++n) job.service();
|
||||
ASSERT_FALSE(job.busy());
|
||||
}
|
||||
|
||||
TEST(LocalCliOutput, LargeFileIsLosslessWithPartialWritesAndLengthSnapshot) {
|
||||
FileState file{std::string(90000, 'x')};
|
||||
const auto expected = file.text;
|
||||
mesh::LocalCliOutput<File> job;
|
||||
Output output;
|
||||
ASSERT_TRUE(job.startFile(output, File{&file}));
|
||||
file.text += "new live log entries";
|
||||
drain(job);
|
||||
EXPECT_EQ(output.text, expected + "\r\n EOF\r\n");
|
||||
EXPECT_TRUE(file.closed);
|
||||
EXPECT_EQ(file.reads, (expected.size() + 159) / 160);
|
||||
}
|
||||
|
||||
TEST(LocalCliOutput, SlowClientDoesNotReadUnboundedDataOrStealOutput) {
|
||||
FileState file{std::string(4096, 'a')};
|
||||
mesh::LocalCliOutput<File> job;
|
||||
Output first, second;
|
||||
first.room = 0;
|
||||
ASSERT_TRUE(job.startFile(first, File{&file}));
|
||||
for (int i = 0; i < 1000; ++i) job.service();
|
||||
EXPECT_EQ(file.reads, 1u);
|
||||
EXPECT_TRUE(first.text.empty());
|
||||
EXPECT_TRUE(job.owns(first));
|
||||
EXPECT_FALSE(job.owns(second));
|
||||
FileState other{"different"};
|
||||
EXPECT_FALSE(job.startFile(second, File{&other}));
|
||||
EXPECT_TRUE(other.closed);
|
||||
first.room = 40;
|
||||
drain(job);
|
||||
EXPECT_EQ(first.text, file.text + "\r\n EOF\r\n");
|
||||
EXPECT_TRUE(second.text.empty());
|
||||
}
|
||||
|
||||
TEST(LocalCliOutput, CancelStopsOldOutputBeforeAReplacementConnection) {
|
||||
FileState old{"old connection secret"};
|
||||
mesh::LocalCliOutput<File> job;
|
||||
Output output;
|
||||
output.room = 0;
|
||||
ASSERT_TRUE(job.startFile(output, File{&old}));
|
||||
job.service();
|
||||
job.cancel();
|
||||
EXPECT_TRUE(old.closed);
|
||||
FileState replacement{"new connection"};
|
||||
ASSERT_TRUE(job.startFile(output, File{&replacement}));
|
||||
output.room = 40;
|
||||
drain(job);
|
||||
EXPECT_EQ(output.text, "new connection\r\n EOF\r\n");
|
||||
}
|
||||
|
||||
TEST(LocalCliOutput, AclRowsDrainCompletelyWithoutATableSizedBuffer) {
|
||||
mesh::LocalCliOutput<File> job;
|
||||
Output output;
|
||||
ASSERT_TRUE(job.startRows(output,
|
||||
[](void*, size_t& row, char* out, size_t capacity) -> size_t {
|
||||
if (row == 254) return 0;
|
||||
return snprintf(out, capacity, "03 %064u\r\n", static_cast<unsigned>(row++));
|
||||
}, nullptr, "ACL:\r\n"));
|
||||
drain(job);
|
||||
std::string expected = "ACL:\r\n";
|
||||
for (unsigned n = 0; n < 254; ++n) {
|
||||
char line[80];
|
||||
snprintf(line, sizeof(line), "03 %064u\r\n", n);
|
||||
expected += line;
|
||||
}
|
||||
EXPECT_EQ(output.text, expected);
|
||||
}
|
||||
|
||||
TEST(LocalCliOutput, MissingAndFailedFilesEndWithoutBlockingTheNextCommand) {
|
||||
mesh::LocalCliOutput<File> job;
|
||||
Output output;
|
||||
ASSERT_TRUE(job.startFile(output, File{}));
|
||||
drain(job);
|
||||
EXPECT_EQ(output.text, "\r\n EOF\r\n");
|
||||
output.text.clear();
|
||||
FileState file{"log"}; file.fail = true;
|
||||
ASSERT_TRUE(job.startFile(output, File{&file}));
|
||||
drain(job);
|
||||
EXPECT_EQ(output.text, "\r\nError: log read failed\r\n");
|
||||
EXPECT_TRUE(file.closed);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
@@ -37,6 +37,7 @@ class Print { public: virtual ~Print() {};
|
||||
class Stream: public Print { public:
|
||||
virtual int available()=0; virtual int read()=0; virtual int peek()=0;
|
||||
virtual void flush()=0;
|
||||
virtual int availableForWrite(){return 0;}
|
||||
};
|
||||
""",
|
||||
"esp_heap_caps.h": """#pragma once
|
||||
@@ -91,6 +92,19 @@ int main(){
|
||||
assert(result==data && bytes()==4096);
|
||||
}
|
||||
assert(allocated.empty());
|
||||
{
|
||||
WebTerminalStream t;
|
||||
assert(t.availableForWrite()==4096);
|
||||
std::string data(4096,'b');
|
||||
t.write(reinterpret_cast<const uint8_t*>(data.data()),data.size());
|
||||
assert(t.availableForWrite()==0);
|
||||
uint64_t cursor=0;char chunk[1025];bool lost=false;
|
||||
assert(t.readOutput(cursor,chunk,sizeof(chunk),lost)==1024 && !lost);
|
||||
assert(t.availableForWrite()==0); // A read response alone is not an ACK.
|
||||
assert(t.readOutput(cursor,chunk,sizeof(chunk),lost)==1024 && !lost);
|
||||
assert(t.availableForWrite()==1024); // The next cursor acknowledges it.
|
||||
}
|
||||
assert(allocated.empty());
|
||||
psram=false;internal_free=8192;
|
||||
{WebTerminalStream t;assert(!t.ready());assert(t.write('x')==0);}
|
||||
assert(allocated.empty());
|
||||
|
||||
@@ -150,8 +150,9 @@ TEST(WebConfigKeys, EverySecretKeyIsAlsoAllowed) {
|
||||
// recognises the serial console and answers secret getters in plaintext. These
|
||||
// are the reads that must be masked back down for an HTTP caller.
|
||||
|
||||
TEST(WebConfigKeys, MasksEverySecretReadTheCliCanReach) {
|
||||
TEST(WebConfigKeys, ClassifiesEverySecretReadTheCliCanReach) {
|
||||
const char* masked[] = {
|
||||
"get password",
|
||||
"get prv.key", // this node's identity -- the worst one to leak
|
||||
"get wifi.pwd", // grants the operator's LAN, not just the node
|
||||
"get guest.password",
|
||||
@@ -164,7 +165,7 @@ TEST(WebConfigKeys, MasksEverySecretReadTheCliCanReach) {
|
||||
for (const char* c : masked) EXPECT_TRUE(wcIsSecretReadCommand(c)) << c;
|
||||
}
|
||||
|
||||
TEST(WebConfigKeys, DoesNotMaskReadsThatCarryNoSecret) {
|
||||
TEST(WebConfigKeys, DoesNotClassifyPublicReadsAsSecrets) {
|
||||
const char* plain[] = {
|
||||
"get wifi.ssid", "get mqtt1.username", "get mqtt1.server", "get tx",
|
||||
"get public.key", // public half, safe to read
|
||||
|
||||
@@ -116,6 +116,21 @@ class WebConfigSecretMaskingTest(unittest.TestCase):
|
||||
)
|
||||
self.assertIn('strcmp(key, "wifi.pwd") == 0', secret_classifier)
|
||||
|
||||
def test_explicit_local_cli_reads_are_not_config_snapshots(self):
|
||||
# Both terminal APIs require the authenticated LAN, and neither applies
|
||||
# the config form's secret masking to an explicit command reply.
|
||||
batch = function_body(self.server, "void WebConfigServer::drainBatch(",
|
||||
"void WebConfigServer::attachRoutes(")
|
||||
self.assertIn("execAdminCommand(e.cmd, e.reply)", batch)
|
||||
self.assertNotIn("wcMaskSecretReply", batch)
|
||||
for start, end in [
|
||||
("void WebConfigServer::handleCliPost(", "void WebConfigServer::handleCliResult("),
|
||||
("bool WebConfigServer::checkTerminalAccess(", "void WebConfigServer::handleTerminalPost("),
|
||||
]:
|
||||
handler = function_body(self.server, start, end)
|
||||
self.assertIn("_mode != MODE_LAN", handler)
|
||||
self.assertIn("checkAuth(req)", handler)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -185,10 +185,12 @@ class WebConfigUiRuntimeTest(unittest.TestCase):
|
||||
suggestions = json.loads(html.unescape(re.search(
|
||||
r'data-test-suggestions="([^"]*)"', dom).group(1)))
|
||||
for command in ("set powersaving off", "get usb.logging", "set wifi.cli ",
|
||||
"set mqtt1.preset ", "get name", "get radio"):
|
||||
"set mqtt1.preset ", "get name", "get radio", "erase",
|
||||
"get prv.key", "get mqtt1.password", "get wifi.pwd",
|
||||
"stats-core", "stats-radio", "stats-packets", "set freq "):
|
||||
self.assertIn(command, suggestions)
|
||||
for command in ("erase", "password ", "setperm ", "get prv.key",
|
||||
"set bridge.enabled ", "get mqtt1.password", "set mqtt2.preset "):
|
||||
for command in ("password ", "setperm ", "get acl",
|
||||
"set bridge.enabled ", "set mqtt2.preset "):
|
||||
self.assertNotIn(command, suggestions)
|
||||
|
||||
def test_stream_terminal_imports_long_cards_pages_lists_and_receives_late_replies(self):
|
||||
@@ -250,6 +252,54 @@ class WebConfigUiRuntimeTest(unittest.TestCase):
|
||||
self.assertIn("firmware help: import, list, to, send", output)
|
||||
self.assertIn('data-test-stream-busy="false"', dom)
|
||||
|
||||
def test_streamed_raw_log_keeps_entire_file_and_allows_slow_progress(self):
|
||||
status, config = self.setup_values()
|
||||
status.update(mode="lan", role="Repeater", cli=True, terminal_stream=True,
|
||||
terminal_max_command=159, password_supported=False)
|
||||
prelude = """
|
||||
<script>
|
||||
(function(){
|
||||
var status=%s,config=%s,sequence=0,output="",offset=0;
|
||||
var dump="log-start\\n"+"packet-row\\n".repeat(10000)+"log-end\\n EOF\\n";
|
||||
var now=Date.now;Date.now=function(){return now()+offset};
|
||||
function response(value){return Promise.resolve({ok:true,status:200,json:function(){return Promise.resolve(value)}})}
|
||||
window.fetch=function(path,options){
|
||||
if(path==="/api/status")return response(status);
|
||||
if(path==="/api/config")return response(config);
|
||||
if(path==="/api/presets")return response({presets:[]});
|
||||
if(path==="/api/terminal"){
|
||||
sequence=JSON.parse(options.body).seq;output=dump;
|
||||
return response({accepted:true});
|
||||
}
|
||||
if(path.indexOf("/api/terminal?")===0){
|
||||
var from=Number(new URLSearchParams(path.split("?")[1]).get("after"));
|
||||
var chunk=output.slice(from,from+3072),cursor=from+chunk.length;
|
||||
offset+=2000; // A complete dump takes over 30 seconds, but keeps progressing.
|
||||
return response({output:chunk,cursor:cursor,seq:sequence,done:cursor>=dump.length,
|
||||
closed:false,lost:false,more:false});
|
||||
}
|
||||
return response({});
|
||||
};
|
||||
window.addEventListener("load",function(){
|
||||
setTimeout(function(){cliStreamRun(["log"])},75);
|
||||
setTimeout(function(){output+="later-output\\n"},6000);
|
||||
setTimeout(function(){
|
||||
var text=document.getElementById("term-out").textContent;
|
||||
document.body.setAttribute("data-test-complete-log",String(text.includes(dump)));
|
||||
document.body.setAttribute("data-test-later-output",String(text.includes("later-output")));
|
||||
document.body.setAttribute("data-test-log-busy",String(cli.busy));
|
||||
document.body.setAttribute("data-test-log-timeout",String(text.includes("could not be confirmed")));
|
||||
},6800);
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
""" % (json.dumps(status), json.dumps(config))
|
||||
dom = self.run_page(prelude, virtual_time=7000)
|
||||
self.assertIn('data-test-complete-log="true"', dom)
|
||||
self.assertIn('data-test-later-output="true"', dom)
|
||||
self.assertIn('data-test-log-busy="false"', dom)
|
||||
self.assertIn('data-test-log-timeout="false"', dom)
|
||||
|
||||
def test_console_stays_hidden_when_disabled_or_on_setup_ap(self):
|
||||
for mode in ("lan", "setup"):
|
||||
with self.subTest(mode=mode):
|
||||
|
||||
Reference in new issue
Block a user