feat(mobile): report malformed relay frames, query bodies and invalid rejections

Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
Signed-off-by: Tom Brow <tomb@block.xyz>
This commit is contained in:
Tom Brow
2026-11-18 11:35:18 -08:00
parent b34c4a7755
commit 51dcf35e14
6 changed files with 177 additions and 3 deletions

View File

@@ -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.

View File

@@ -283,10 +283,15 @@ class RelaySessionNotifier extends Notifier<SessionState> {
final List<NostrEvent> 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<SessionState> {
_handleDisconnected(generation, error, closeCode: socket.closeCode);
},
);
socket.diagnostics = _diagnostics;
_socket = socket;
try {
@@ -888,6 +894,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
? 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<SessionState> {
});
}
void _reportInvalidRequest(String message) {
if (!isInvalidRequestRejection(message)) return;
_diagnostics.reportError(
const RelayInvalidRequest(),
StackTrace.current,
operation: DiagnosticOperation.relayRejection,
);
}
void _handleOk(List<dynamic> data) {
if (data.length < 3) return;
final eventId = data[1] as String;
@@ -1003,6 +1019,7 @@ class RelaySessionNotifier extends Notifier<SessionState> {
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.

View File

@@ -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<String, String> 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<dynamic> data;
try {
data = jsonDecode(text) as List<dynamic>;
} catch (_) {
return; // Malformed JSON.
} catch (error, stackTrace) {
diagnostics.reportError(
error,
stackTrace,
operation: DiagnosticOperation.relayFrame,
);
return;
}
if (data.isEmpty) return;

View File

@@ -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'),

View File

@@ -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<FormatException>()),
);
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<Exception>()));
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<Exception>()));
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(

View File

@@ -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<List<dynamic>>();
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));
}
}