From 34ec249af41fcc2cc164820fb5a577ab3434052f Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 22 Oct 2026 23:57:28 -0400 Subject: [PATCH] fix(#768, #778, #780, #781): Gemini review findings on Epic C From the Gemini adversarial review of Epics A and C, each checked before fixing: - TCP framing now matches ArduinoSerialInterface::checkRecvFrame: a zero length is skipped, and a frame over MAX_FRAME_SIZE (176) is read to its end and cut. New raw-socket tests; both fail on the old code. - Remote preset tests waited for the fake to hold a login session; they now wait for the client to receive LOGIN_SUCCESS for that node. - The release guard folds case and backslashes before matching, so '../../Test/' and '..\..\test\' are caught too. - The runner listens on 127.0.0.1 unless given --host, and a bad seed file exits 65 with a one-line message instead of a stack trace. Co-Authored-By: Claude Opus 5.5 --- test/fake_radio/connector_scenarios_test.dart | 36 ++++++-- test/fake_radio/fake_radio_tcp_test.dart | 85 +++++++++++++++++++ test/fake_radio/release_guard_test.dart | 24 ++++-- test/fake_radio/runner_test.dart | 28 +++++- .../support/fake_radio/fake_radio_runner.dart | 4 +- test/support/fake_radio/fake_radio_tcp.dart | 11 ++- tool/fake_radio.dart | 35 ++++++-- tool/fake_radio/README.md | 3 +- 8 files changed, 196 insertions(+), 30 deletions(-) create mode 100644 test/fake_radio/fake_radio_tcp_test.dart diff --git a/test/fake_radio/connector_scenarios_test.dart b/test/fake_radio/connector_scenarios_test.dart index cdd485fb..c6f09a29 100644 --- a/test/fake_radio/connector_scenarios_test.dart +++ b/test/fake_radio/connector_scenarios_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:drift/native.dart'; +import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; @@ -201,10 +202,7 @@ void main() { Future> apply({required bool temporary}) async { final node = nodes[label]!; final target = contact(label); - await connector.sendFrame( - buildSendLoginFrame(target.publicKey, node.adminPassword), - ); - await _until(radio, () => radio.hasAdminSession(node), 'login'); + await _login(connector, radio, target, node.adminPassword); // Built as repeater_settings_screen.dart builds a preset save. final pending = [ temporary @@ -268,10 +266,7 @@ void main() { test('a bad value comes back as the firmware error (#748)', () async { final node = nodes[label]!; final target = contact(label); - await connector.sendFrame( - buildSendLoginFrame(target.publicKey, node.adminPassword), - ); - await _until(radio, () => radio.hasAdminSession(node), 'login'); + await _login(connector, radio, target, node.adminPassword); final service = RepeaterCommandService(connector); addTearDown(service.dispose); final sub = connector.receivedFrames.listen((frame) { @@ -316,6 +311,31 @@ void main() { } } +/// Logs in to [target] the way the app does, and waits until the CLIENT has +/// received LOGIN_SUCCESS for that node, not just until the fake holds a +/// session (MyMesh.cpp:1153: code, permissions, then the 6-byte key prefix). +Future _login( + MeshCoreConnector connector, + FakeRadio radio, + Contact target, + String password, +) async { + var confirmed = false; + final sub = connector.receivedFrames.listen((f) { + if (f.length >= 8 && + f[0] == pushCodeLoginSuccess && + listEquals(f.sublist(2, 8), target.publicKey.sublist(0, 6))) { + confirmed = true; + } + }); + try { + await connector.sendFrame(buildSendLoginFrame(target.publicKey, password)); + await _until(radio, () => confirmed, 'LOGIN_SUCCESS at the client'); + } finally { + await sub.cancel(); + } +} + /// Waits for [done], advancing the fake radio's clock as real time passes so /// ACKs and remote replies arrive. Future _until( diff --git a/test/fake_radio/fake_radio_tcp_test.dart b/test/fake_radio/fake_radio_tcp_test.dart new file mode 100644 index 00000000..4cee65c9 --- /dev/null +++ b/test/fake_radio/fake_radio_tcp_test.dart @@ -0,0 +1,85 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../support/fake_radio/fake_radio.dart'; +import '../support/fake_radio/fake_radio_codes.dart'; +import '../support/fake_radio/fake_radio_tcp.dart'; + +// The fake's TCP framing against firmware ArduinoSerialInterface:: +// checkRecvFrame: frames split across reads, a zero length skipped, and a +// frame over MAX_FRAME_SIZE read to its end and cut. + +void main() { + late FakeRadio radio; + late FakeRadioTcpServer server; + late Socket socket; + late StreamController> replies; + late StreamIterator> next; + + setUp(() async { + radio = FakeRadio(); + server = await FakeRadioTcpServer.start(radio); + socket = await Socket.connect(server.host, server.port); + replies = StreamController>(); + next = StreamIterator(replies.stream); + final buf = []; + socket.listen((data) { + buf.addAll(data); + while (buf.length >= 3 && buf.length >= 3 + (buf[1] | buf[2] << 8)) { + final len = buf[1] | buf[2] << 8; + replies.add(buf.sublist(3, 3 + len)); + buf.removeRange(0, 3 + len); + } + }); + }); + + tearDown(() async { + socket.destroy(); + await server.close(); + }); + + List frame(List payload) => [ + 0x3c, + payload.length & 0xFF, + payload.length >> 8, + ...payload, + ]; + + Future> nextReply() async { + expect(await next.moveNext().timeout(const Duration(seconds: 5)), isTrue); + return next.current; + } + + test('a frame split across two writes is put back together', () async { + final f = frame([fwCmdDeviceQuery, 3]); + socket.add(f.sublist(0, 2)); + await socket.flush(); + await Future.delayed(const Duration(milliseconds: 50)); + socket.add(f.sublist(2)); + expect((await nextReply())[0], fwRespDeviceInfo); + }); + + test('a zero-length frame is skipped, and the next one is handled', () async { + socket.add([ + ...frame([]), + ...frame([fwCmdDeviceQuery, 3]), + ]); + expect((await nextReply())[0], fwRespDeviceInfo); + expect(radio.received, hasLength(1)); + }); + + test('a frame over MAX_FRAME_SIZE is read to its end, then cut', () async { + final big = [fwCmdDeviceQuery, 3, ...List.filled(200, 0x41)]; + socket.add([ + ...frame(big), + ...frame([fwCmdGetDeviceTime]), + ]); + expect((await nextReply())[0], fwRespDeviceInfo); + expect((await nextReply())[0], fwRespCurrTime); + expect(radio.received.first, hasLength(maxFrameSize)); + expect(radio.received.first, Uint8List.fromList(big.take(176).toList())); + }); +} diff --git a/test/fake_radio/release_guard_test.dart b/test/fake_radio/release_guard_test.dart index fff2ac15..8ca94e38 100644 --- a/test/fake_radio/release_guard_test.dart +++ b/test/fake_radio/release_guard_test.dart @@ -16,14 +16,18 @@ List forbiddenImports(String source) => [ if (_forbidden(m.group(1)!)) m.group(1)!, ]; -bool _forbidden(String uri) => - uri.contains('fake_radio') || - uri.contains('/test/') || - uri.startsWith('test/') || - uri.contains('../test') || - uri.contains('/tool/') || - uri.startsWith('tool/') || - uri.contains('../tool'); +bool _forbidden(String raw) { + // Windows and macOS resolve paths without regard to case, and a Windows + // path may use backslashes, so compare a folded form. + final uri = raw.toLowerCase().replaceAll(r'\', '/'); + return uri.contains('fake_radio') || + uri.contains('/test/') || + uri.startsWith('test/') || + uri.contains('../test') || + uri.contains('/tool/') || + uri.startsWith('tool/') || + uri.contains('../tool'); +} void main() { test('nothing under lib/ imports the fake radio, test/ or tool/', () { @@ -50,8 +54,10 @@ import 'package:meshcore_open/x/fake_radio_runner.dart'; export '../tool/fake_radio.dart'; part 'test/thing.dart'; import "../services/storage_service.dart"; +import '../../Test/Support/Helpers.dart'; +import '..\\..\\test\\support\\helpers.dart'; '''), - hasLength(4), + hasLength(6), ); }); } diff --git a/test/fake_radio/runner_test.dart b/test/fake_radio/runner_test.dart index 98b4d7a9..a9ec8181 100644 --- a/test/fake_radio/runner_test.dart +++ b/test/fake_radio/runner_test.dart @@ -209,7 +209,7 @@ void main() { addTearDown(proc.kill); final out = proc.stdout.transform(utf8.decoder).asBroadcastStream(); await out - .firstWhere((l) => l.contains('on port $port')) + .firstWhere((l) => l.contains('on 127.0.0.1:$port')) .timeout(const Duration(seconds: 60)); final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); @@ -232,4 +232,30 @@ void main() { }, timeout: const Timeout(Duration(minutes: 2)), ); + + test( + 'a bad seed file stops the runner with a message, not a stack trace', + () async { + final root = Platform.environment['FLUTTER_ROOT']; + if (root == null) { + markTestSkipped('FLUTTER_ROOT not set: not under flutter test'); + return; + } + final bad = + File('${Directory.systemTemp.createTempSync('seed').path}/b.json') + ..writeAsStringSync( + '{"format": "offband-fake-radio-seed", ' + '"format_version": 1, "contacts": [{"name": "A", "key": "11a"}]}', + ); + final result = await Process.run( + '$root/bin/dart${Platform.isWindows ? '.bat' : ''}', + ['run', 'tool/fake_radio.dart', '--seed', bad.path], + runInShell: Platform.isWindows, + ); + expect(result.exitCode, 65, reason: '${result.stdout}${result.stderr}'); + expect('${result.stderr}', contains("can't use ${bad.path}")); + expect('${result.stderr}', isNot(contains('#0 '))); + }, + timeout: const Timeout(Duration(minutes: 2)), + ); } diff --git a/test/support/fake_radio/fake_radio_runner.dart b/test/support/fake_radio/fake_radio_runner.dart index a13809b3..f66b224d 100644 --- a/test/support/fake_radio/fake_radio_runner.dart +++ b/test/support/fake_radio/fake_radio_runner.dart @@ -27,7 +27,9 @@ class FakeRadioRunner { }) async { final server = await FakeRadioTcpServer.start( radio, - address: address ?? InternetAddress.anyIPv4, + // Loopback unless asked: a fake radio need not be reachable from the + // network. + address: address ?? InternetAddress.loopbackIPv4, port: port, ); final ticker = Timer.periodic(tick, (_) => radio.clock.advance(tick)); diff --git a/test/support/fake_radio/fake_radio_tcp.dart b/test/support/fake_radio/fake_radio_tcp.dart index aa6f38fc..72ca1f2b 100644 --- a/test/support/fake_radio/fake_radio_tcp.dart +++ b/test/support/fake_radio/fake_radio_tcp.dart @@ -14,6 +14,10 @@ import 'fake_radio.dart'; const int _appToRadioStart = 0x3c; const int _radioToAppStart = 0x3e; +/// `MAX_FRAME_SIZE` (src/helpers/BaseSerialInterface.h:5 at +/// offband-v1.5.0-beta7). +const int maxFrameSize = 176; + /// The fake radio on a TCP port, for the client's real `connectTcp` path and /// for the desktop app (#768, #780). class FakeRadioTcpServer { @@ -74,8 +78,13 @@ class FakeRadioTcpServer { if (buffer.length < 3) return; final len = buffer[1] | (buffer[2] << 8); if (buffer.length < 3 + len) return; - final payload = Uint8List.fromList(buffer.sublist(3, 3 + len)); + // ArduinoSerialInterface::checkRecvFrame: a zero length is skipped, + // and a frame over MAX_FRAME_SIZE is read to its end, then cut. + final payload = Uint8List.fromList( + buffer.sublist(3, 3 + (len > maxFrameSize ? maxFrameSize : len)), + ); buffer.removeRange(0, 3 + len); + if (len == 0) continue; for (final reply in radio.handle(payload)) { socket.add(_wrap(reply)); } diff --git a/tool/fake_radio.dart b/tool/fake_radio.dart index 213128d6..002c425d 100644 --- a/tool/fake_radio.dart +++ b/tool/fake_radio.dart @@ -5,19 +5,22 @@ // dart run tool/fake_radio.dart --profile stock --seed my-mesh.json // dart run tool/fake_radio.dart --seed test/fake_radio/traces/rak.json // -// Then in the app: connect over TCP to this PC's address, port 5000. Seed -// files and console commands: tool/fake_radio/README.md. Test code only: it -// lives under test/ and tool/ and never ships in the app. +// Then in the app on the same PC: connect over TCP to 127.0.0.1, port 5000. +// For a phone on the network, add --host 0.0.0.0. Seed files and console +// commands: tool/fake_radio/README.md. Test code only: it lives under test/ +// and tool/ and never ships in the app. import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import '../test/support/fake_radio/fake_radio.dart'; import '../test/support/fake_radio/fake_radio_runner.dart'; Future main(List args) async { var profile = 'offband'; var port = 5000; + var host = InternetAddress.loopbackIPv4; String? seed; for (var i = 0; i < args.length; i++) { switch (args[i]) { @@ -25,22 +28,36 @@ Future main(List args) async { profile = args[++i]; case '--port' when i + 1 < args.length: port = int.parse(args[++i]); + case '--host' when i + 1 < args.length: + host = InternetAddress(args[++i]); case '--seed' when i + 1 < args.length: seed = args[++i]; default: stderr.writeln( - 'usage: dart run tool/fake_radio.dart ' - '[--profile offband|stock] [--port 5000] [--seed file.json]', + 'usage: dart run tool/fake_radio.dart [--profile offband|stock] ' + '[--port 5000] [--host 127.0.0.1] [--seed file.json]', ); exit(64); } } - final radio = fakeRadioFromFile(seed, profile: profile); - final runner = await FakeRadioRunner.start(radio: radio, port: port); + final FakeRadio radio; + try { + radio = fakeRadioFromFile(seed, profile: profile); + } on Object catch (e) { + // A bad seed file: say what is wrong, not a stack trace. + stderr.writeln('can\'t use ${seed ?? 'the built-in seed'}: $e'); + exit(65); + } + final runner = await FakeRadioRunner.start( + radio: radio, + address: host, + port: port, + ); stdout.writeln( - 'Fake radio "${radio.name}" (${radio.profile.name}) on port ' - '${runner.server.port}. ${radio.contacts.length} contact(s), ' + 'Fake radio "${radio.name}" (${radio.profile.name}) on ' + '${runner.server.host}:${runner.server.port}. ' + '${radio.contacts.length} contact(s), ' '${radio.channels.length} channel(s). Type "help" for commands.', ); diff --git a/tool/fake_radio/README.md b/tool/fake_radio/README.md index 5ca24f32..35717ff1 100644 --- a/tool/fake_radio/README.md +++ b/tool/fake_radio/README.md @@ -10,12 +10,13 @@ From the repo root: dart run tool/fake_radio.dart --profile offband --port 5000 ``` -In the app, connect over TCP to this PC's address (`127.0.0.1` on the same machine) and port `5000`. +In the app on the same PC, connect over TCP to `127.0.0.1`, port `5000`. It listens only on this PC unless you add `--host 0.0.0.0`, which lets a phone on the same network connect to this PC's address. | Option | Default | Meaning | |---|---|---| | `--profile` | `offband` | `offband` (pinned to `offband-v1.5.0-beta7`) or `stock` (MeshCore `companion-v1.17.1`) | | `--port` | `5000` | TCP port | +| `--host` | `127.0.0.1` | address to listen on; `0.0.0.0` for every network interface | | `--seed` | built-in | a seed file (below) or a captured trace | The radio's clock follows real time, so ACKs and remote-node replies arrive on their own.