mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +00:00
test(mobile): cover diagnostic attribution, wiring and relay rejections
Extend the reported-or-counted coverage: session attribution when the key is missing or the answer arrives after the member changed, signed-out push stop assertions, the hosted admission and self-hosted probe wiring, frames the socket cannot decode, and the relay's refusal reasons. Timestamp-window refusals whose wording the code does not recognize are skipped until it and the spec agree. Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost> Signed-off-by: Tom Brow <tomb@block.xyz>
This commit is contained in:
82
mobile/test/shared/diagnostics/recording_diagnostics.dart
Normal file
82
mobile/test/shared/diagnostics/recording_diagnostics.dart
Normal file
@@ -0,0 +1,82 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
/// A reporter that records what it was given: the error's type and the
|
||||
/// operation. The member is whatever the test last named.
|
||||
class RecordingDiagnostics extends NoopDiagnosticReporter {
|
||||
final errors = <(Type, DiagnosticOperation)>[];
|
||||
String? _member;
|
||||
|
||||
List<DiagnosticOperation> get operations => [
|
||||
for (final (_, operation) in errors) operation,
|
||||
];
|
||||
|
||||
@override
|
||||
String? get member => _member;
|
||||
|
||||
@override
|
||||
void setMember(String? pubkey) => _member = pubkey;
|
||||
|
||||
@override
|
||||
void reportError(
|
||||
Object error,
|
||||
StackTrace? stackTrace, {
|
||||
required DiagnosticOperation operation,
|
||||
}) => errors.add((error.runtimeType, operation));
|
||||
}
|
||||
|
||||
/// Who a report names while a request signed by one key is in flight.
|
||||
enum NamedMember {
|
||||
other('another member'),
|
||||
signer('the signer'),
|
||||
none('no one');
|
||||
|
||||
const NamedMember(this.label);
|
||||
final String label;
|
||||
|
||||
/// Whether a report from work signed by [signer] goes out.
|
||||
bool get reported => this != other;
|
||||
|
||||
String? pubkey(String signer) => switch (this) {
|
||||
other => 'e' * 64,
|
||||
NamedMember.signer => signer,
|
||||
none => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// A loopback relay that sends [first] as raw frames (text or binary) as soon as a
|
||||
/// client connects, then the NIP-42 challenge, and accepts the AUTH it gets
|
||||
/// back. [onFrame] sees every other frame the client sends, with the socket.
|
||||
Future<HttpServer> loopbackRelay({
|
||||
List<Object> first = const [],
|
||||
void Function(WebSocket socket, List<dynamic> frame)? onFrame,
|
||||
bool challenge = true,
|
||||
bool closeAfterFirst = false,
|
||||
}) async {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(() => server.close(force: true));
|
||||
server.listen((request) async {
|
||||
final ws = await WebSocketTransformer.upgrade(request);
|
||||
for (final frame in first) {
|
||||
ws.add(frame);
|
||||
}
|
||||
if (closeAfterFirst) {
|
||||
await ws.close();
|
||||
return;
|
||||
}
|
||||
ws.listen((raw) {
|
||||
final frame = jsonDecode(raw as String) as List<dynamic>;
|
||||
if (frame.first == 'AUTH') {
|
||||
final id = (frame[1] as Map<String, dynamic>)['id'];
|
||||
ws.add(jsonEncode(['OK', id, true, '']));
|
||||
} else {
|
||||
onFrame?.call(ws, frame);
|
||||
}
|
||||
});
|
||||
if (challenge) ws.add(jsonEncode(['AUTH', 'challenge']));
|
||||
});
|
||||
return server;
|
||||
}
|
||||
205
mobile/test/shared/hosted/diagnostic_wiring_test.dart
Normal file
205
mobile/test/shared/hosted/diagnostic_wiring_test.dart
Normal file
@@ -0,0 +1,205 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:buzz/features/onboarding/self_hosted_entry_sheet.dart';
|
||||
import 'package:buzz/shared/community/community.dart';
|
||||
import 'package:buzz/shared/deeplink/deep_link.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/hosted/account_identity_store.dart';
|
||||
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
||||
import 'package:buzz/shared/hosted/hosted_admission.dart';
|
||||
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
|
||||
import 'package:buzz/shared/hosted/self_hosted_entry.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/recording_diagnostics.dart';
|
||||
|
||||
// The sockets that check a community before it is joined belong to a member
|
||||
// who is not active yet, so what they report goes out only while reports name
|
||||
// that member or no one.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('the self-hosted entry probe', () {
|
||||
// The test binding refuses real connections; the probe uses a loopback one.
|
||||
setUp(() {
|
||||
final overrides = HttpOverrides.current;
|
||||
HttpOverrides.global = null;
|
||||
addTearDown(() => HttpOverrides.global = overrides);
|
||||
});
|
||||
|
||||
Community community(HttpServer server, nostr.Keys keys) => Community.create(
|
||||
name: 'Example',
|
||||
relayUrl: 'ws://127.0.0.1:${server.port}',
|
||||
pubkey: keys.public,
|
||||
nsec: keys.nsec,
|
||||
);
|
||||
|
||||
for (final member in NamedMember.values) {
|
||||
test('reports a frame it cannot decode while reports name '
|
||||
'${member.label}', () async {
|
||||
final server = await loopbackRelay(first: ['not json']);
|
||||
final keys = nostr.Keys.generate();
|
||||
final diagnostics = RecordingDiagnostics()
|
||||
..setMember(member.pubkey(keys.public));
|
||||
|
||||
await SelfHostedEntry.probeRelay(
|
||||
community(server, keys),
|
||||
const {},
|
||||
diagnostics,
|
||||
);
|
||||
|
||||
expect(diagnostics.operations, [
|
||||
if (member.reported) DiagnosticOperation.relayFrame,
|
||||
]);
|
||||
});
|
||||
|
||||
test('built by the app reports as the probe does while reports name '
|
||||
'${member.label}', () async {
|
||||
final server = await loopbackRelay(first: ['not json']);
|
||||
final keys = nostr.Keys.generate();
|
||||
final diagnostics = RecordingDiagnostics()
|
||||
..setMember(member.pubkey(keys.public));
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
diagnosticReporterProvider.overrideWithValue(diagnostics),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
|
||||
await container.read(relayProbeProvider)(
|
||||
community(server, keys),
|
||||
const {},
|
||||
);
|
||||
|
||||
expect(diagnostics.operations, [
|
||||
if (member.reported) DiagnosticOperation.relayFrame,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
test(
|
||||
'a relay that is not a Buzz relay is reported once and refused',
|
||||
() async {
|
||||
final server = await loopbackRelay(
|
||||
first: ['<html>Welcome to nginx</html>'],
|
||||
challenge: false,
|
||||
closeAfterFirst: true,
|
||||
);
|
||||
final keys = nostr.Keys.generate();
|
||||
final diagnostics = RecordingDiagnostics();
|
||||
|
||||
await expectLater(
|
||||
SelfHostedEntry.probeRelay(
|
||||
community(server, keys),
|
||||
const {},
|
||||
diagnostics,
|
||||
),
|
||||
throwsA(isA<StateError>()),
|
||||
);
|
||||
|
||||
expect(diagnostics.operations, [DiagnosticOperation.relayFrame]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('hosted admission', () {
|
||||
final keys = nostr.Keys.generate();
|
||||
const link = AddCommunityDeepLink(
|
||||
relayUrl: 'wss://example.communities.buzz.xyz',
|
||||
name: 'Example',
|
||||
);
|
||||
|
||||
for (final member in NamedMember.values) {
|
||||
test('reports a frame it cannot decode while reports name '
|
||||
'${member.label}', () async {
|
||||
FlutterSecureStorage.setMockInitialValues({});
|
||||
final server = await loopbackRelay(first: ['not json']);
|
||||
final account = _Account(keys.public);
|
||||
addTearDown(account.dispose);
|
||||
final store = AccountIdentityStore(subject: 'owner');
|
||||
await store.create(keys.nsec);
|
||||
await store.confirmBackup(
|
||||
BackupReceipt(
|
||||
backend: BuilderlabAccountClient.origin.origin,
|
||||
subject: 'owner',
|
||||
pubkey: keys.public,
|
||||
backupId: 'backup',
|
||||
),
|
||||
);
|
||||
final diagnostics = RecordingDiagnostics()
|
||||
..setMember(member.pubkey(keys.public));
|
||||
final admission = HostedAdmission(
|
||||
account: account,
|
||||
relayAuth: HostedRelayAuth(account, enabled: false),
|
||||
store: store,
|
||||
diagnostics: diagnostics,
|
||||
);
|
||||
addTearDown(admission.dispose);
|
||||
|
||||
// The admission connects to its own relay address; the test relay
|
||||
// answers there instead.
|
||||
final community = await HttpOverrides.runWithHttpOverrides(
|
||||
() => admission.prepare(link, 'owner', keys.public),
|
||||
_Loopback(server.port),
|
||||
);
|
||||
|
||||
expect(community.pubkey, keys.public);
|
||||
expect(diagnostics.operations, [
|
||||
if (member.reported) DiagnosticOperation.relayFrame,
|
||||
]);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
class _Account extends BuilderlabAccountClient {
|
||||
_Account(this.bound);
|
||||
|
||||
final String bound;
|
||||
|
||||
@override
|
||||
BuilderlabAccount get account =>
|
||||
BuilderlabAccount(subject: 'owner', expiresAt: DateTime.utc(2100));
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> currentIdentity() async => {
|
||||
'identity': {'pubkey_hex': bound},
|
||||
};
|
||||
}
|
||||
|
||||
/// Sends every connection to the loopback relay on [port], whatever address
|
||||
/// it was made for.
|
||||
class _Loopback extends HttpOverrides {
|
||||
_Loopback(this.port);
|
||||
|
||||
final int port;
|
||||
|
||||
@override
|
||||
HttpClient createHttpClient(SecurityContext? context) =>
|
||||
_LoopbackClient(super.createHttpClient(context), port);
|
||||
}
|
||||
|
||||
class _LoopbackClient extends Fake implements HttpClient {
|
||||
_LoopbackClient(this._inner, this._port);
|
||||
|
||||
final HttpClient _inner;
|
||||
final int _port;
|
||||
|
||||
@override
|
||||
String? get userAgent => _inner.userAgent;
|
||||
|
||||
@override
|
||||
set userAgent(String? value) => _inner.userAgent = value;
|
||||
|
||||
@override
|
||||
Future<HttpClientRequest> openUrl(String method, Uri url) => _inner.openUrl(
|
||||
method,
|
||||
url.replace(scheme: 'http', host: '127.0.0.1', port: _port),
|
||||
);
|
||||
|
||||
@override
|
||||
void close({bool force = false}) => _inner.close(force: force);
|
||||
}
|
||||
96
mobile/test/shared/hosted/push_stop_attribution_test.dart
Normal file
96
mobile/test/shared/hosted/push_stop_attribution_test.dart
Normal file
@@ -0,0 +1,96 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
||||
import 'package:buzz/shared/hosted/builderlab_build.dart';
|
||||
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
|
||||
import 'package:buzz/shared/relay/relay_provider.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/recording_diagnostics.dart';
|
||||
|
||||
// A push stop for a removed community runs after sign-out, with the session
|
||||
// that just ended. A reply it cannot understand is reported only while reports
|
||||
// name the community's key or no one.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final keys = nostr.Keys.generate();
|
||||
final organization = Uri.parse('https://account.example.com');
|
||||
const relayHost = 'buzz.example.com';
|
||||
final expiry = DateTime.now().toUtc().add(const Duration(days: 1));
|
||||
const current = '/api/goose/v1/buzz/nostr-identities/current';
|
||||
const assertions = '/api/goose/v1/buzz/identity/assertions';
|
||||
|
||||
// Which request gets a reply that is not a JSON object.
|
||||
for (final garbled in [current, assertions]) {
|
||||
for (final member in NamedMember.values) {
|
||||
test('a garbled reply to ${garbled.split('/').last} is '
|
||||
'${member.reported ? '' : 'not '}reported while reports name '
|
||||
'${member.label}', () async {
|
||||
FlutterSecureStorage.setMockInitialValues({});
|
||||
await const FlutterSecureStorage().write(
|
||||
key: 'buzz_hosted_session_account_example_com_v1',
|
||||
value: jsonEncode({
|
||||
'origin': organization.toString(),
|
||||
'credential': 'secret',
|
||||
'subject': 'member',
|
||||
'expires_at': expiry.toIso8601String(),
|
||||
}),
|
||||
);
|
||||
final diagnostics = RecordingDiagnostics();
|
||||
final account = BuilderlabAccountClient(
|
||||
accountOrigin: organization,
|
||||
diagnostics: diagnostics,
|
||||
httpClient: MockClient((request) async {
|
||||
if (request.url.path == garbled) return http.Response('[]', 200);
|
||||
return switch (request.url.path) {
|
||||
'/api/goose/v1/auth/me' => http.Response(
|
||||
jsonEncode({
|
||||
'subject': 'member',
|
||||
'expires_at': expiry.toIso8601String(),
|
||||
}),
|
||||
200,
|
||||
),
|
||||
current => http.Response(
|
||||
jsonEncode({
|
||||
'identity': {'pubkey_hex': keys.public},
|
||||
}),
|
||||
200,
|
||||
),
|
||||
_ => http.Response('{}', 404),
|
||||
};
|
||||
}),
|
||||
);
|
||||
final auth = HostedRelayAuth(
|
||||
account,
|
||||
organization: account,
|
||||
organizationRelay: (relay) =>
|
||||
BuilderlabBuild.matchesRelay(relay, [relayHost]),
|
||||
enabled: true,
|
||||
discover: (_) async => true,
|
||||
);
|
||||
addTearDown(auth.dispose);
|
||||
// The session the push stop runs on is the one that just ended.
|
||||
expect(await account.restore(), isNotNull);
|
||||
await account.clearLocalSession();
|
||||
diagnostics.setMember(member.pubkey(keys.public));
|
||||
|
||||
final headers = await auth.headers(
|
||||
RelayConfig(baseUrl: 'https://$relayHost', nsec: keys.nsec),
|
||||
background: true,
|
||||
);
|
||||
|
||||
// A push stop never fails on an assertion it cannot get: the relay
|
||||
// decides.
|
||||
expect(headers, isEmpty);
|
||||
expect(diagnostics.operations, [
|
||||
if (member.reported) DiagnosticOperation.accountResponse,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
44
mobile/test/shared/relay/relay_frame_reporting_test.dart
Normal file
44
mobile/test/shared/relay/relay_frame_reporting_test.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay_socket.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/recording_diagnostics.dart';
|
||||
|
||||
// A frame the app cannot decode is reported, once. A frame it can decode is
|
||||
// not, whatever it says.
|
||||
void main() {
|
||||
for (final (name, frame, reported) in <(String, Object, bool)>[
|
||||
('a truncated frame', '["EVENT","sub",{"id":"ab', true),
|
||||
('an empty frame', '', true),
|
||||
('text that is not JSON', '<html>502 Bad Gateway</html>', true),
|
||||
('an object where an array belongs', '{"error":"nope"}', true),
|
||||
('a JSON string', '"hello"', true),
|
||||
('a binary frame', utf8.encode('["NOTICE","binary"]'), false),
|
||||
('an empty array', '[]', false),
|
||||
('a frame of a type the app ignores', '["NOTICE","hello"]', false),
|
||||
]) {
|
||||
test('$name is ${reported ? '' : 'not '}reported', () async {
|
||||
final server = await loopbackRelay(first: [frame]);
|
||||
final keys = nostr.Keys.generate();
|
||||
final diagnostics = RecordingDiagnostics()..setMember(keys.public);
|
||||
final socket = RelaySocket(
|
||||
wsUrl: 'ws://127.0.0.1:${server.port}',
|
||||
nsec: keys.nsec,
|
||||
onMessage: (_) {},
|
||||
onConnected: () {},
|
||||
onDisconnected: (_) {},
|
||||
)..diagnostics = diagnostics;
|
||||
addTearDown(socket.dispose);
|
||||
|
||||
await socket.connect();
|
||||
|
||||
expect(socket.state, SocketState.connected);
|
||||
expect(diagnostics.operations, [
|
||||
if (reported) DiagnosticOperation.relayFrame,
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
192
mobile/test/shared/relay/relay_rejection_reporting_test.dart
Normal file
192
mobile/test/shared/relay/relay_rejection_reporting_test.dart
Normal file
@@ -0,0 +1,192 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:buzz/shared/auth/auth_provider.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart' as http_testing;
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/recording_diagnostics.dart';
|
||||
|
||||
// What the relay's refusals do to the error list: only a reason that marks the
|
||||
// request as invalid is reported, apart from the outcomes the app handles
|
||||
// itself. Every other reason is counted, not reported. Reasons are the relay's
|
||||
// own wording.
|
||||
void main() {
|
||||
// The relay's reasons for a request it refuses as invalid.
|
||||
const reported = [
|
||||
'invalid: bad signature',
|
||||
// Limits.
|
||||
'invalid: a DM may hold at most 9 people; agents do not count',
|
||||
'invalid: content exceeds maximum size of 262144 bytes (got 262145)',
|
||||
'invalid: channel name is longer than 255 characters',
|
||||
// Push lease refusals.
|
||||
'invalid: endpoint already leased',
|
||||
'invalid: stale generation',
|
||||
'invalid: lease quota exceeded',
|
||||
];
|
||||
// Refusals the app handles as expected outcomes, and every other reason.
|
||||
const counted = [
|
||||
'invalid: event timestamp too far from server time',
|
||||
'rate-limited: quota exceeded; retry in 7s',
|
||||
'rate-limited: too many concurrent requests',
|
||||
'restricted: only members can post in this channel',
|
||||
'blocked: not a member',
|
||||
'auth-required: not authenticated',
|
||||
'error: query timed out',
|
||||
'duplicate: already have this event',
|
||||
'something the relay says in no known form',
|
||||
'',
|
||||
];
|
||||
// The spec counts every refusal for a timestamp outside the relay's window.
|
||||
// The code reports these three, whose wording differs from the one it
|
||||
// recognizes, so each is skipped until the two agree.
|
||||
const clockWindow = [
|
||||
'invalid: canvas event timestamp too far in the future',
|
||||
'invalid: event timestamp out of range: created_at=1, now=500, '
|
||||
'delta=-499s (max ±120s)',
|
||||
'invalid: leave request timestamp out of range (delta=300s, max ±120s)',
|
||||
];
|
||||
|
||||
final rows = <(String, bool, String?)>[
|
||||
for (final reason in reported) (reason, true, null),
|
||||
for (final reason in counted) (reason, false, null),
|
||||
for (final reason in clockWindow)
|
||||
(
|
||||
reason,
|
||||
false,
|
||||
'the code reports it; the spec says a clock-window refusal is counted',
|
||||
),
|
||||
];
|
||||
|
||||
for (final (reason, isReported, skip) in rows) {
|
||||
final expected = isReported ? 1 : 0;
|
||||
test('an OK refusal "$reason" is ${isReported ? '' : 'not '}reported', () {
|
||||
final harness = _session();
|
||||
harness.session.debugAttachSocketForTest(_Socket());
|
||||
|
||||
final refused = harness.session.publish(_event('event-1'));
|
||||
harness.session.debugHandleMessage(['OK', 'event-1', false, reason]);
|
||||
|
||||
expect(refused, throwsA(isA<Exception>()));
|
||||
expect(harness.reporter.errors, hasLength(expected));
|
||||
expect(harness.reporter.errors.map((e) => e.$2), [
|
||||
if (isReported) DiagnosticOperation.relayRejection,
|
||||
]);
|
||||
}, skip: skip);
|
||||
|
||||
test(
|
||||
'a CLOSED refusal "$reason" is ${isReported ? '' : 'not '}reported',
|
||||
() {
|
||||
final harness = _session();
|
||||
|
||||
harness.session.debugHandleMessage(['CLOSED', 'sub-1', reason]);
|
||||
|
||||
expect(harness.reporter.errors.map((e) => e.$2), [
|
||||
if (isReported) DiagnosticOperation.relayRejection,
|
||||
]);
|
||||
},
|
||||
skip: skip,
|
||||
);
|
||||
}
|
||||
|
||||
// A reply for nothing pending, as for a typing indicator or a reply that
|
||||
// arrives after the publish timed out.
|
||||
for (final (accepted, reason, isReported) in [
|
||||
(false, 'invalid: bad signature', true),
|
||||
(false, 'blocked: not a member', false),
|
||||
(true, 'invalid: bad signature', false),
|
||||
(true, '', false),
|
||||
]) {
|
||||
test('an unexpected OK ${accepted ? 'accepting' : 'refusing'} with '
|
||||
'"$reason" is ${isReported ? '' : 'not '}reported', () {
|
||||
final harness = _session();
|
||||
|
||||
harness.session.debugHandleMessage(['OK', 'unknown', accepted, reason]);
|
||||
|
||||
expect(harness.reporter.errors.map((e) => e.$2), [
|
||||
if (isReported) DiagnosticOperation.relayRejection,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
test('an OK frame without a reason is not reported', () {
|
||||
final harness = _session();
|
||||
|
||||
harness.session.debugHandleMessage(['OK', 'unknown', false]);
|
||||
|
||||
expect(harness.reporter.errors, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
class _Harness {
|
||||
_Harness(this.session, this.reporter);
|
||||
|
||||
final RelaySessionNotifier session;
|
||||
final RecordingDiagnostics reporter;
|
||||
}
|
||||
|
||||
/// A session whose own key is the member reports name.
|
||||
_Harness _session() {
|
||||
final keys = nostr.Keys.generate();
|
||||
final reporter = RecordingDiagnostics()..setMember(keys.public);
|
||||
final session = RelaySessionNotifier(
|
||||
httpClient: http_testing.MockClient((_) async => http.Response('[]', 200)),
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
authProvider.overrideWith(() => _PendingAuth()),
|
||||
relaySessionProvider.overrideWith(() => session),
|
||||
relayConfigProvider.overrideWith(() => _Config(keys.nsec)),
|
||||
diagnosticReporterProvider.overrideWithValue(reporter),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.read(relaySessionProvider);
|
||||
return _Harness(session, reporter);
|
||||
}
|
||||
|
||||
NostrEvent _event(String id) => NostrEvent(
|
||||
id: id,
|
||||
pubkey: 'alice',
|
||||
createdAt: 20,
|
||||
kind: 1,
|
||||
tags: const [],
|
||||
content: 'hello',
|
||||
sig: 'sig',
|
||||
);
|
||||
|
||||
class _Config extends RelayConfigNotifier {
|
||||
_Config(this._nsec);
|
||||
|
||||
final String _nsec;
|
||||
|
||||
@override
|
||||
RelayConfig build() =>
|
||||
RelayConfig(baseUrl: 'https://relay.example', nsec: _nsec);
|
||||
}
|
||||
|
||||
class _PendingAuth extends AuthNotifier {
|
||||
@override
|
||||
Future<AuthState> build() => Completer<AuthState>().future;
|
||||
}
|
||||
|
||||
class _Socket extends RelaySocket {
|
||||
_Socket()
|
||||
: super(
|
||||
wsUrl: 'wss://relay.example',
|
||||
nsec: null,
|
||||
onMessage: (_) {},
|
||||
onConnected: () {},
|
||||
onDisconnected: (_) {},
|
||||
);
|
||||
|
||||
@override
|
||||
void send(List<dynamic> payload) {}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:buzz/shared/auth/auth_provider.dart';
|
||||
import 'package:buzz/shared/community/community.dart';
|
||||
import 'package:buzz/shared/community/community_provider.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_member_binding.dart';
|
||||
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
||||
import 'package:buzz/shared/relay/relay.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart' as http_testing;
|
||||
import 'package:nostr/nostr.dart' as nostr;
|
||||
|
||||
import '../diagnostics/recording_diagnostics.dart';
|
||||
|
||||
// More ways the member can differ from the key a session signs with, on top of
|
||||
// relay_session_attribution_test.dart.
|
||||
void main() {
|
||||
// A session without a key signs for no one, so it reports only while reports
|
||||
// name no one either.
|
||||
for (final (label, member, reported) in [
|
||||
('a member', nostr.Keys.generate().public, false),
|
||||
('no one', null, true),
|
||||
]) {
|
||||
test('a session with no key is ${reported ? '' : 'not '}reported while '
|
||||
'reports name $label', () async {
|
||||
final reporter = RecordingDiagnostics()..setMember(member);
|
||||
final session = RelaySessionNotifier(
|
||||
httpClient: http_testing.MockClient(
|
||||
(_) async => http.Response('[]', 200),
|
||||
),
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
authProvider.overrideWith(() => _PendingAuth()),
|
||||
relaySessionProvider.overrideWith(() => session),
|
||||
relayConfigProvider.overrideWith(() => _Config(null)),
|
||||
diagnosticReporterProvider.overrideWithValue(reporter),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.read(relaySessionProvider);
|
||||
session.debugAttachSocketForTest(_Socket());
|
||||
|
||||
final refused = session.publish(_event('event-1'));
|
||||
session.debugHandleMessage(['OK', 'event-1', false, 'invalid: bad']);
|
||||
await expectLater(refused, throwsA(isA<Exception>()));
|
||||
|
||||
expect(reporter.operations, [
|
||||
if (reported) DiagnosticOperation.relayRejection,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
// The relay answers over a real socket after the app has moved on to
|
||||
// another member.
|
||||
for (final member in NamedMember.values) {
|
||||
test('a refusal that arrives over the socket is '
|
||||
'${member.reported ? '' : 'not '}reported while reports name '
|
||||
'${member.label}', () async {
|
||||
final answer = Completer<void>();
|
||||
final server = await loopbackRelay(
|
||||
onFrame: (socket, frame) async {
|
||||
if (frame.first != 'EVENT') return;
|
||||
final id = (frame[1] as Map<String, dynamic>)['id'];
|
||||
await answer.future;
|
||||
socket.add(jsonEncode(['OK', id, false, 'invalid: bad signature']));
|
||||
},
|
||||
);
|
||||
final keys = nostr.Keys.generate();
|
||||
final reporter = RecordingDiagnostics()..setMember(keys.public);
|
||||
final connected = Completer<void>();
|
||||
final session = RelaySessionNotifier(
|
||||
httpClient: http_testing.MockClient(
|
||||
(_) async => http.Response('[]', 200),
|
||||
),
|
||||
socketFactory:
|
||||
({
|
||||
required wsUrl,
|
||||
required nsec,
|
||||
required onMessage,
|
||||
required onConnected,
|
||||
required onDisconnected,
|
||||
}) => RelaySocket(
|
||||
wsUrl: 'ws://127.0.0.1:${server.port}',
|
||||
nsec: nsec,
|
||||
onMessage: onMessage,
|
||||
onConnected: () {
|
||||
onConnected();
|
||||
if (!connected.isCompleted) connected.complete();
|
||||
},
|
||||
onDisconnected: onDisconnected,
|
||||
),
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
relaySessionProvider.overrideWith(() => session),
|
||||
relayConfigProvider.overrideWith(() => _Config(keys.nsec)),
|
||||
authProvider.overrideWith(() => _Authenticated(keys.public)),
|
||||
diagnosticReporterProvider.overrideWithValue(reporter),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(authProvider.future);
|
||||
final listener = container.listen(relaySessionProvider, (_, _) {});
|
||||
addTearDown(listener.close);
|
||||
await connected.future;
|
||||
|
||||
final refused = session.publish(_event('event-1'));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
reporter.setMember(member.pubkey(keys.public));
|
||||
answer.complete();
|
||||
await expectLater(refused, throwsA(isA<Exception>()));
|
||||
|
||||
expect(reporter.operations, [
|
||||
if (member.reported) DiagnosticOperation.relayRejection,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
// Through the providers the app runs: a switch changes the key and, a
|
||||
// moment later, the member. Reports from the new session follow the new
|
||||
// member; none names the old one.
|
||||
test('after a switch the new session reports under the new member', () async {
|
||||
final reporter = RecordingDiagnostics();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
authProvider.overrideWith(() => _PendingAuth()),
|
||||
diagnosticReporterProvider.overrideWithValue(reporter),
|
||||
activeCommunityProvider.overrideWith((ref) async => null),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
container.listen(diagnosticMemberProvider, (_, _) {});
|
||||
container.listen(relaySessionProvider, (_, _) {});
|
||||
final first = nostr.Keys.generate();
|
||||
final second = nostr.Keys.generate();
|
||||
Future<void> refuse(String id) async {
|
||||
final session = container.read(relaySessionProvider.notifier);
|
||||
session.debugAttachSocketForTest(_Socket());
|
||||
final refused = session.publish(_event(id));
|
||||
session.debugHandleMessage(['OK', id, false, 'invalid: bad']);
|
||||
await expectLater(refused, throwsA(isA<Exception>()));
|
||||
}
|
||||
|
||||
final config = container.read(relayConfigProvider.notifier);
|
||||
config.update(baseUrl: 'https://relay.example', nsec: first.nsec);
|
||||
container.read(diagnosticMemberProvider);
|
||||
await refuse('one');
|
||||
expect(reporter.operations, hasLength(1));
|
||||
|
||||
config.update(baseUrl: 'https://relay.example', nsec: second.nsec);
|
||||
container.read(diagnosticMemberProvider);
|
||||
await refuse('two');
|
||||
|
||||
expect(reporter.member, second.public);
|
||||
expect(reporter.operations, hasLength(2));
|
||||
});
|
||||
}
|
||||
|
||||
NostrEvent _event(String id) => NostrEvent(
|
||||
id: id,
|
||||
pubkey: 'alice',
|
||||
createdAt: 20,
|
||||
kind: 1,
|
||||
tags: const [],
|
||||
content: 'hello',
|
||||
sig: 'sig',
|
||||
);
|
||||
|
||||
class _Config extends RelayConfigNotifier {
|
||||
_Config(this._nsec);
|
||||
|
||||
final String? _nsec;
|
||||
|
||||
@override
|
||||
RelayConfig build() =>
|
||||
RelayConfig(baseUrl: 'https://relay.example', nsec: _nsec);
|
||||
}
|
||||
|
||||
class _PendingAuth extends AuthNotifier {
|
||||
@override
|
||||
Future<AuthState> build() => Completer<AuthState>().future;
|
||||
}
|
||||
|
||||
class _Authenticated extends AuthNotifier {
|
||||
_Authenticated(this._pubkey);
|
||||
|
||||
final String _pubkey;
|
||||
|
||||
@override
|
||||
Future<AuthState> build() async => AuthState(
|
||||
status: AuthStatus.authenticated,
|
||||
community: Community(
|
||||
id: 'community-1',
|
||||
name: 'Example',
|
||||
relayUrl: 'https://relay.example',
|
||||
pubkey: _pubkey,
|
||||
addedAt: DateTime(2026),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Socket extends RelaySocket {
|
||||
_Socket()
|
||||
: super(
|
||||
wsUrl: 'wss://relay.example',
|
||||
nsec: null,
|
||||
onMessage: (_) {},
|
||||
onConnected: () {},
|
||||
onDisconnected: (_) {},
|
||||
);
|
||||
|
||||
@override
|
||||
void send(List<dynamic> payload) {}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
Reference in New Issue
Block a user