From 51dcf35e1448a0104018f1e54f4ebac6cc4fe01d Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Wed, 18 Nov 2026 11:35:18 -0800 Subject: [PATCH] feat(mobile): report malformed relay frames, query bodies and invalid rejections Co-authored-by: studio Signed-off-by: Tom Brow --- .../lib/shared/relay/relay_closed_policy.dart | 19 ++++++ mobile/lib/shared/relay/relay_session.dart | 19 +++++- mobile/lib/shared/relay/relay_socket.dart | 13 +++- .../relay/relay_closed_policy_test.dart | 20 +++++++ .../test/shared/relay/relay_session_test.dart | 59 +++++++++++++++++++ .../relay/relay_socket_frames_test.dart | 50 ++++++++++++++++ 6 files changed, 177 insertions(+), 3 deletions(-) create mode 100644 mobile/test/shared/relay/relay_socket_frames_test.dart diff --git a/mobile/lib/shared/relay/relay_closed_policy.dart b/mobile/lib/shared/relay/relay_closed_policy.dart index 9f0b0dfa28..2680f1e214 100644 --- a/mobile/lib/shared/relay/relay_closed_policy.dart +++ b/mobile/lib/shared/relay/relay_closed_policy.dart @@ -45,6 +45,25 @@ bool isRelayDeadlineError(Object error) { message.startsWith(_queryTimedOutPrefix); } +/// Reported when the relay says a request the app sent is invalid. It never +/// reaches callers, and it carries no relay text: the reason is free text. +class RelayInvalidRequest implements Exception { + const RelayInvalidRequest(); + + @override + String toString() => 'RelayInvalidRequest'; +} + +/// Whether [message], a relay `OK` or `CLOSED` reason, says the app sent +/// something invalid. Refusals the app handles as expected outcomes, an +/// archived channel or an open channel name that is taken, are not. +bool isInvalidRequestRejection(String message) { + final normalized = message.trim().toLowerCase(); + return normalized.startsWith('invalid:') && + !normalized.startsWith('invalid: channel is archived') && + !normalized.startsWith('invalid: an open channel named'); +} + /// Recovery policy for a relay `CLOSED` subscription message. enum RelayClosedClass { /// A transient failure that may recover when the same REQ is retried. diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index b11db4bf3e..c9aa7dedbe 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -283,10 +283,15 @@ class RelaySessionNotifier extends Notifier { final List events; try { events = await _queryDecoder(response); - } catch (_) { + } catch (error, stackTrace) { if (retired()) { throw StateError('Relay query belongs to a retired session'); } + _diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.relayQuery, + ); rethrow; } if (retired()) { @@ -637,6 +642,7 @@ class RelaySessionNotifier extends Notifier { _handleDisconnected(generation, error, closeCode: socket.closeCode); }, ); + socket.diagnostics = _diagnostics; _socket = socket; try { @@ -888,6 +894,7 @@ class RelaySessionNotifier extends Notifier { ? data[2] as String : 'subscription closed by relay'; final closedClass = classifyRelayClosed(message); + _reportInvalidRequest(message); final historySub = _historySubscriptions.remove(subId); if (historySub != null) { @@ -992,6 +999,15 @@ class RelaySessionNotifier extends Notifier { }); } + void _reportInvalidRequest(String message) { + if (!isInvalidRequestRejection(message)) return; + _diagnostics.reportError( + const RelayInvalidRequest(), + StackTrace.current, + operation: DiagnosticOperation.relayRejection, + ); + } + void _handleOk(List data) { if (data.length < 3) return; final eventId = data[1] as String; @@ -1003,6 +1019,7 @@ class RelaySessionNotifier extends Notifier { final pending = _pendingEvents.remove(eventId); if (pending == null) return; pending.timeout.cancel(); + if (!accepted) _reportInvalidRequest(message); if (accepted) { // We don't have the full event here; create a minimal placeholder. diff --git a/mobile/lib/shared/relay/relay_socket.dart b/mobile/lib/shared/relay/relay_socket.dart index 95eadd73b6..84e4e4b42f 100644 --- a/mobile/lib/shared/relay/relay_socket.dart +++ b/mobile/lib/shared/relay/relay_socket.dart @@ -7,6 +7,7 @@ import 'package:nostr/nostr.dart' as nostr; import 'package:web_socket_channel/io.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import 'nostr_models.dart'; import 'relay_websocket.dart'; import 'package:buzz/shared/crypto/event_signing.dart'; @@ -76,6 +77,9 @@ class RelaySocket { /// Scoped assertion supplied by the connection owner before connecting. Map headers = const {}; + /// Where frames the relay sent that this client can't parse are reported. + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(); + RelaySocket({ required String wsUrl, required String? nsec, @@ -209,8 +213,13 @@ class RelaySocket { final List data; try { data = jsonDecode(text) as List; - } catch (_) { - return; // Malformed JSON. + } catch (error, stackTrace) { + diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.relayFrame, + ); + return; } if (data.isEmpty) return; diff --git a/mobile/test/shared/relay/relay_closed_policy_test.dart b/mobile/test/shared/relay/relay_closed_policy_test.dart index b9f098e429..acdd16d763 100644 --- a/mobile/test/shared/relay/relay_closed_policy_test.dart +++ b/mobile/test/shared/relay/relay_closed_policy_test.dart @@ -28,6 +28,26 @@ void main() { } }); + group('isInvalidRequestRejection', () { + const cases = { + 'invalid: bad signature': true, + 'INVALID: malformed filter': true, + 'invalid: channel is archived': false, + 'invalid: an open channel named "general" already exists': false, + 'duplicate: channel already exists': false, + 'restricted: access revoked': false, + 'rate-limited: quota exceeded; retry in 4s': false, + 'error: query timed out': false, + '': false, + }; + + for (final entry in cases.entries) { + test(entry.key.isEmpty ? '(empty)' : entry.key, () { + expect(isInvalidRequestRejection(entry.key), entry.value); + }); + } + }); + test('parseRateLimitRetrySeconds handles canonical and absent hints', () { expect( parseRateLimitRetrySeconds('rate-limited: quota exceeded; retry in 17s'), diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index 6c8fd9a43b..4b9ee4aadd 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -679,6 +679,23 @@ void main() { ); }); + test('a body that fails to decode is reported', () async { + final reporter = _RecordingDiagnostics(); + final harness = _queryHarness( + client: http_testing.MockClient((_) async => json('{"oops"')), + diagnostics: reporter, + ); + addTearDown(harness.container.dispose); + + await expectLater( + harness.session.queryRelay(const []), + throwsA(isA()), + ); + expect(reporter.errors, [ + (FormatException, DiagnosticOperation.relayQuery), + ]); + }); + test('an error status keeps its body and skips decoding', () async { var decodes = 0; const body = '{"error":"nope"}'; @@ -722,10 +739,12 @@ void main() { }); test('a retired session reports retirement, not a decode error', () async { + final reporter = _RecordingDiagnostics(); final decoder = _GatedDecoder(); final harness = _queryHarness( client: http_testing.MockClient((_) async => json('{"oops"')), queryDecoder: decoder.call, + diagnostics: reporter, ); addTearDown(harness.container.dispose); @@ -736,6 +755,7 @@ void main() { decoder.gate.complete(); await outcome; + expect(reporter.errors, isEmpty); }); test('an age restriction during decoding discards the events', () async { @@ -2311,6 +2331,42 @@ void main() { reason: 'only `rate-limited:` rejections signal back-pressure', ); }); + + test('an invalid rejection is reported without the relay text', () async { + final reporter = _RecordingDiagnostics(); + final harness = _queryHarness( + client: http_testing.MockClient((_) async => http.Response('[]', 200)), + diagnostics: reporter, + ); + addTearDown(harness.container.dispose); + final session = harness.session; + session.debugAttachSocketForTest(_RecordingRelaySocket()); + + final archived = session.publish(_event(id: 'event-1')); + session.debugHandleMessage([ + 'OK', + 'event-1', + false, + 'invalid: channel is archived', + ]); + await expectLater(archived, throwsA(isA())); + expect(reporter.errors, isEmpty); + + final invalid = session.publish(_event(id: 'event-2')); + session.debugHandleMessage([ + 'OK', + 'event-2', + false, + 'invalid: bad signature', + ]); + await expectLater(invalid, throwsA(isA())); + session.debugHandleMessage(['CLOSED', 'sub-1', 'invalid: bad filter']); + + expect(reporter.errors, [ + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + ]); + }); } class _ControlledHttpClient extends http.BaseClient { @@ -2393,6 +2449,7 @@ _QueryHarness _queryHarness({ required http.Client client, RelayQueryDecoder? queryDecoder, AgeSignalNotifier? age, + DiagnosticReporter? diagnostics, }) { final session = RelaySessionNotifier( httpClient: client, @@ -2402,6 +2459,8 @@ _QueryHarness _queryHarness({ final container = ProviderContainer( overrides: [ if (age != null) ageSignalProvider.overrideWith(() => age), + if (diagnostics != null) + diagnosticReporterProvider.overrideWithValue(diagnostics), authProvider.overrideWith(() => _PendingAuthNotifier()), relaySessionProvider.overrideWith(() => session), relayConfigProvider.overrideWith( diff --git a/mobile/test/shared/relay/relay_socket_frames_test.dart b/mobile/test/shared/relay/relay_socket_frames_test.dart new file mode 100644 index 0000000000..4b633d8144 --- /dev/null +++ b/mobile/test/shared/relay/relay_socket_frames_test.dart @@ -0,0 +1,50 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/relay/relay_socket.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('reports a frame it cannot parse and keeps reading', () async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + server.listen((request) async { + final ws = await WebSocketTransformer.upgrade(request); + ws.add('not json'); + ws.add('["NOTICE","still here"]'); + }); + + final reporter = _RecordingDiagnostics(); + final received = Completer>(); + final socket = RelaySocket( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: null, + onMessage: (message) { + if (!received.isCompleted) received.complete(message); + }, + onConnected: () {}, + onDisconnected: (_) {}, + )..diagnostics = reporter; + addTearDown(socket.dispose); + unawaited(socket.connect()); + + expect(await received.future, ['NOTICE', 'still here']); + expect(reporter.errors, [ + (FormatException, DiagnosticOperation.relayFrame), + ]); + }); +} + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) { + errors.add((error.runtimeType, operation)); + } +}