From e2bbd8430c5b6ffcea23f354d3589fb68a3198e8 Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Fri, 20 Nov 2026 09:09:29 -0800 Subject: [PATCH] feat(mobile): report explicit diagnostic errors (#9673) Step one of [mobile diagnostic reporting](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md), second piece: the explicit error reports the spec lists, through the reporter added in [#9613 diagnostic reporting module](https://github.com/block/buzz/pull/9613). A build without a destination (every build from this repository alone) still reports nothing. ### What's in it Each report carries its `operation` tag, the error's type and stack trace, and no error text (the filter replaces it). - **Event subscriber (`eventSubscriber`):** a subscriber that throws while the relay session delivers a buffered batch is reported, and the rest of the batch is still delivered. In a build without a destination the error still surfaces as uncaught, so it fails the test that hit it and prints in development, as before. Before, one throw dropped the rest of the batch, and those events never came back because their delivery keys were already recorded. - **Relay frames (`relayFrame`):** a frame the socket can't decode, or whose body isn't a JSON array, is reported instead of silently skipped. - **Relay queries (`relayQuery`):** an HTTP query body that can't be decoded, including the read-state snapshot. - **Invalid-request rejections (`relayRejection`):** an `OK false` or `CLOSED` whose reason starts with `invalid:`, reported as a fixed `RelayInvalidRequest` with no relay text, including an `OK` with no pending publish (a typing indicator, or a reply after a timeout). Refusals the app handles as expected outcomes (an archived channel, an Unarchive of a channel that is no longer archived, an open channel name that is taken, an agent whose `policy:` refuses being added, a sole owner's Leave refused as the last owner, a guest's Add Members refused because only members can add people, an event whose timestamp is outside the relay's window, so a wrong device clock does not report every publish) are left out. The long-lived relay session, the short-lived sockets (hosted admission, the self-hosted probe, one-shot publishes such as agent registration and push tombstones) and the account assertion requests made for a community's key (relay access and push stop assertions) report frames and rejections the same way, except while reports name a member other than the key they sign with. A removed or inactive community's tombstone, or the probe of a community being joined, then reports nothing rather than naming the wrong member. With no member set (first run, or after the last community is removed) it reports under the install identifier. - **Account responses (`accountResponse`):** a Builderlab account response that isn't a JSON object, or a 2xx exchange or `/v1/auth/me` response missing its credential, subject or expiry. Non-2xx statuses are expected outcomes and aren't reported. - **Push gateway responses (`pushGatewayResponse`):** a malformed push capability descriptor from the relay. A relay that leaves `supported_extensions` out or sends none has no push and isn't reported, and a fetch that finishes after a community switch has begun isn't reported either, since it would name the next member. Push gateway replies aren't reported yet. - **Stored data (`storedData`):** a saved community list that can't be read back. - **Member on switch:** switching communities now looks the new member up in storage, not in the provider's list, which can still be the previous one while it reloads after sign-in. It reads storage before tearing anything down, so a failed read leaves the switch unchanged and retryable. - **Filter:** also drops a report's additional data (`extra`). Nothing sets it today. - The spec's status line now says what is implemented. - Event delivery moves from `relay_session.dart` into a part file, unchanged apart from the subscriber guard, so the session stays under its size limit. ### Regressions None expected: each change only adds a report where an error was already caught or skipped. The one behavior change is that a throwing event subscriber no longer costs the rest of its batch. ### Validation Added tests for each report site (relay session, socket frames, one-shot publishes, read-state snapshot, closed-reason policy, account client, push descriptor and capability provider, community storage), for the relay session (member changed mid-request), one-shot sockets and assertion requests reporting nothing while another member is set and reporting with none set, for the member on switch and a switch whose read fails then retries, and for the filter dropping additional data and leaving a message-less event without one. Full-app run on an iPhone 17 Pro simulator at b4f05ad (debug build, no reporting destination): signed-in launch and channel list, scrolling history in several channels, a thread, sending a message and a reaction, search, switching communities and back, background and foreground with live updates afterwards, and kill and relaunch with saved communities restored. No regressions and no exceptions from the changed code. --------- Signed-off-by: Tom Brow Co-authored-by: studio --- docs/mobile-diagnostic-reporting.md | 6 +- .../onboarding/self_hosted_entry_sheet.dart | 8 +- mobile/lib/shared/agents/remote_agents.dart | 6 + .../shared/community/community_provider.dart | 13 +- .../shared/community/community_storage.dart | 25 +- .../shared/diagnostics/diagnostic_filter.dart | 3 + .../diagnostics/diagnostic_reporter.dart | 70 +++++- .../sentry_diagnostic_reporter.dart | 18 +- .../lib/shared/hosted/builderlab_account.dart | 51 +++- .../lib/shared/hosted/hosted_admission.dart | 8 + .../shared/hosted/hosted_flow_provider.dart | 2 + .../lib/shared/hosted/hosted_relay_auth.dart | 3 + .../lib/shared/hosted/self_hosted_entry.dart | 8 + mobile/lib/shared/push/dev_push_lease.dart | 18 +- .../push/push_lease_revocation_outbox.dart | 4 + .../push/push_relay_capability_provider.dart | 30 +++ .../lib/shared/relay/relay_closed_policy.dart | 33 +++ mobile/lib/shared/relay/relay_session.dart | 60 ++--- .../shared/relay/relay_session_delivery.dart | 63 +++++ .../shared/relay/relay_session_snapshot.dart | 24 +- mobile/lib/shared/relay/relay_socket.dart | 13 +- .../lib/shared/relay/signed_event_relay.dart | 14 ++ .../test/shared/auth/auth_provider_test.dart | 1 + .../community/community_provider_test.dart | 68 ++++++ .../community/community_storage_test.dart | 26 +++ .../diagnostic_reporting_test.dart | 13 ++ .../assertion_report_attribution_test.dart | 107 +++++++++ .../hosted/builderlab_account_test.dart | 67 ++++++ .../test/shared/push/dev_push_lease_test.dart | 37 ++- .../push_lease_revocation_outbox_test.dart | 109 +++++++++ .../push_relay_capability_provider_test.dart | 43 +++- .../read_state_snapshot_transport_test.dart | 29 ++- .../relay/relay_closed_policy_test.dart | 27 +++ .../relay/relay_session_attribution_test.dart | 219 ++++++++++++++++++ .../test/shared/relay/relay_session_test.dart | 205 ++++++++++++++++ .../relay/relay_socket_frames_test.dart | 50 ++++ .../relay/submit_signed_event_once_test.dart | 108 +++++++++ 37 files changed, 1498 insertions(+), 91 deletions(-) create mode 100644 mobile/lib/shared/relay/relay_session_delivery.dart create mode 100644 mobile/test/shared/hosted/assertion_report_attribution_test.dart create mode 100644 mobile/test/shared/relay/relay_session_attribution_test.dart create mode 100644 mobile/test/shared/relay/relay_socket_frames_test.dart create mode 100644 mobile/test/shared/relay/submit_signed_event_once_test.dart diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index 12bbf69cd7..48c2d46571 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -1,6 +1,6 @@ # Mobile diagnostic reporting -Status: step one agreed, not yet implemented. +Status: step one in progress. Implemented: the reporting module and explicit error reports (for push, the relay's capability descriptor; push gateway replies are not reported yet). Still to come: networking counts. Terminology is defined in [CONTEXT.md](../CONTEXT.md#mobile-builds). The decisions behind this spec are in [ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md) and [ADR 0008](adr/0008-sentry-for-mobile-diagnostic-reporting.md). @@ -41,7 +41,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - **One reporting module.** All app code reports through a single interface with three operations: report an error, count a networking event (with an optional duration), and leave a breadcrumb. It has two implementations: one backed by the Sentry Flutter SDK and one that does nothing. Nothing outside this module imports the SDK. - **The reporting destination is a build-time setting**, named with the implementation to match the existing `BUZZ_` build settings. When it is absent, the app uses the do-nothing implementation and never initializes the SDK. There is no check on the kind of build, no in-app switch and no notice ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)). - **Crashes and uncaught errors** are captured by the SDK's own handlers for native crashes, Flutter framework errors and uncaught asynchronous Dart errors, installed at startup around the app. -- **Explicit error reports** are added at the places where the app meets something that should never happen: a relay frame or query response that cannot be decoded, a relay rejection whose reason says the app sent something invalid (except a refusal the app already handles as an expected outcome, such as an archived channel or a channel name that is taken, which is counted), an account or push gateway response that cannot be understood, saved data that cannot be read back, and an event subscriber that throws while handling an event. +- **Explicit error reports** are added at the places where the app meets something that should never happen: a relay frame or query response that cannot be decoded, a relay rejection whose reason says the app sent something invalid (except a refusal the app already handles as an expected outcome, such as an archived channel, an Unarchive of a channel that is no longer archived, a channel name that is taken, an agent whose policy refuses the addition, a guest adding people, a sole owner leaving or an event whose timestamp is outside the relay's window, which is counted; that last one is left out for every event, so a device with a wrong clock does not report every publish, at the cost of hiding a signed event retried after the window has passed), an account or push gateway response that cannot be understood, saved data that cannot be read back, and an event subscriber that throws while handling an event. - **Routine failures are counted, never reported.** Timeouts, disconnects, unreachable or insecure hosts, rate limits, refused or expired sign-ins and server errors increment a count. That includes the relay's own errors, such as a query that timed out or too many subscriptions. Of the reasons a relay gives for a rejection, only the one that marks the request as invalid is reported, with the exception above; every other reason is counted. - **Networking measurements.** Every request through the app's shared HTTP client and every relay connection event (connected, disconnected, reconnect attempt, request timed out, subscription closed by the relay) is counted with four attributes: backend, endpoint, outcome and kind of failure. The backend is the host name of the server the app was talking to. Endpoints are names from a fixed list, never raw paths. Durations are recorded for requests and for time to connect. HTTP is measured where the app's shared HTTP client already classifies transport failures; relay connections are measured by hand in the relay session, since the SDK documents no WebSocket instrumentation. - **Counts are handed to the SDK as they happen**, including while the network is down. The app does no buffering of its own, and the SDK's default limit on unsent data is kept. Accepted consequence: in a long outage the oldest unsent reports can be dropped. @@ -75,7 +75,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - Alert rules, dashboards and the destination's own configuration, which belong to whoever owns the destination. - Diagnostic reporting in a [public build](../CONTEXT.md#public-build). Nothing prevents it, but what a report carries was chosen for internal builds. Turning it on there first needs the member's public key and the server host names removed, the rest of the list reviewed, and a way to tell people ([ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md)). Because identity and every attribute pass through one module, that is a small code change. - Usage or behavior data of any kind, beyond the SDK's session records described above. -- Fixing the bugs the reports will reveal, including two found while planning: one subscriber that throws can lose the rest of a batch of events, and a catch-all in account requests presents every error as an outage. +- Fixing the bugs the reports will reveal, including one found while planning: a catch-all in account requests presents every error as an outage. ## Further notes diff --git a/mobile/lib/features/onboarding/self_hosted_entry_sheet.dart b/mobile/lib/features/onboarding/self_hosted_entry_sheet.dart index c0ffd2bef7..0aeb77e828 100644 --- a/mobile/lib/features/onboarding/self_hosted_entry_sheet.dart +++ b/mobile/lib/features/onboarding/self_hosted_entry_sheet.dart @@ -17,11 +17,17 @@ import '../../shared/widgets/modal_presentation.dart'; import '../../shared/widgets/onboarding_step_page.dart'; import '../../shared/widgets/onboarding_loading_page.dart'; import '../../shared/widgets/buzz_titled_sheet_layout.dart'; +import '../../shared/diagnostics/diagnostic_reporter.dart'; /// The socket boundary every entry probe connects through. final relayProbeProvider = Provider Function(Community, Map)>( - (ref) => SelfHostedEntry.probeRelay, + (ref) => + (community, headers) => SelfHostedEntry.probeRelay( + community, + headers, + ref.read(diagnosticReporterProvider), + ), ); /// Local preparation seam; the production service validates and retains keys. diff --git a/mobile/lib/shared/agents/remote_agents.dart b/mobile/lib/shared/agents/remote_agents.dart index 193dfccd37..00496f04ad 100644 --- a/mobile/lib/shared/agents/remote_agents.dart +++ b/mobile/lib/shared/agents/remote_agents.dart @@ -9,6 +9,7 @@ import 'package:nostr/nostr.dart' as nostr; import 'package:shared_preferences/shared_preferences.dart'; import 'package:uuid/uuid.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../community/community.dart'; import 'first_agent_bestie.dart'; import '../me/default_agent.dart'; @@ -113,6 +114,7 @@ final remoteAgentControllerProvider = Provider((ref) { ref.invalidate(defaultAgentProvider); }, relayAuth: ref.watch(hostedRelayAuthProvider), + diagnostics: ref.read(diagnosticReporterProvider), ); ref.onDispose(controller.dispose); return controller; @@ -212,6 +214,7 @@ class RemoteAgentController extends ChangeNotifier { required this.account, required AccountIdentityStore keys, required this.relayAuth, + this.diagnostics = const NoopDiagnosticReporter(), this.onCreated, }) : _keys = keys { account.subjectChanges.addListener(_accountChanged); @@ -220,6 +223,7 @@ class RemoteAgentController extends ChangeNotifier { final BuilderlabAccountClient account; final AccountIdentityStore _keys; final HostedRelayAuth relayAuth; + final DiagnosticReporter diagnostics; /// Completes community preferences before clearing the resumable setup. final Future Function(Community community, String pubkey)? onCreated; @@ -791,6 +795,7 @@ class RemoteAgentController extends ChangeNotifier { await submitSignedEventOnce( wsUrl: config.wsUrl, headers: await relayAuth.headers(config, fresh: true), + diagnostics: diagnostics, nsec: key.nsec, kind: 30177, content: jsonEncode({ @@ -814,6 +819,7 @@ class RemoteAgentController extends ChangeNotifier { await submitSignedEventOnce( wsUrl: config.wsUrl, headers: await relayAuth.headers(config, fresh: true), + diagnostics: diagnostics, nsec: key.nsec, kind: 5, content: '', diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index 791f907c79..6f3df02e74 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -87,7 +87,7 @@ final communityTransitionProvider = Provider( ); final communityStorageProvider = Provider((ref) { - return CommunityStorage(); + return CommunityStorage(diagnostics: ref.read(diagnosticReporterProvider)); }); typedef CommunitySnapshotWriter = @@ -113,6 +113,7 @@ final communityPushLeaseDeactivatorProvider = community, generation: generation, relayAuth: ref.read(hostedRelayAuthProvider), + diagnostics: ref.read(diagnosticReporterProvider), ); }); @@ -135,6 +136,7 @@ Future _deactivateCommunityPushLease( Community community, { int? generation, required HostedRelayAuth relayAuth, + required DiagnosticReporter diagnostics, }) async { final state = community.pushSubscriptionState; final acceptedGeneration = state.acceptedGeneration; @@ -197,6 +199,7 @@ Future _deactivateCommunityPushLease( content: content, tags: tags, createdAt: createdAt, + diagnostics: diagnostics, ), ); pushLeaseCleanupError.value = null; @@ -524,9 +527,15 @@ class CommunityListNotifier extends AsyncNotifier> { final storage = ref.read(communityStorageProvider); final activeId = await storage.loadActiveId(); if (activeId == id) return; + // From storage: while the list reloads (after sign-in, say), state can + // still hold the previous list. Read before anything changes, so a + // failed read leaves the switch to retry. + final target = (await storage.loadAll()) + .where((c) => c.id == id) + .firstOrNull; await ref.read(communityTransitionProvider).run(); await storage.saveActiveId(id); - _reportAs(state.value?.where((c) => c.id == id).firstOrNull); + _reportAs(target); // Reassign list state to trigger activeCommunityProvider (which watches // communityListProvider.future) to rebuild and pick up the new active ID. // We can't use ref.invalidate(activeCommunityProvider) here because that diff --git a/mobile/lib/shared/community/community_storage.dart b/mobile/lib/shared/community/community_storage.dart index b676fb47e3..bc78354b0f 100644 --- a/mobile/lib/shared/community/community_storage.dart +++ b/mobile/lib/shared/community/community_storage.dart @@ -4,6 +4,7 @@ import 'package:crypto/crypto.dart'; import 'package:uuid/uuid.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../hosted/organization_environment.dart'; import '../hosted/known_community_address.dart'; import '../storage/secure_storage.dart'; @@ -29,11 +30,16 @@ class CommunityStorage { /// their keys, for a build that can reach them. final bool Function(Community community) _visible; + /// Where saved communities that can't be read back are reported. + final DiagnosticReporter _diagnostics; + CommunityStorage({ FlutterSecureStorage? secure, bool Function(Community community)? visible, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), }) : _secure = secure ?? communitySecureStorage, - _visible = visible ?? reachableInBuild; + _visible = visible ?? reachableInBuild, + _diagnostics = diagnostics; /// An internal build reaches only its organization's community. static bool reachableInBuild(Community community) => @@ -243,10 +249,19 @@ class CommunityStorage { } List _decodeList(String raw) { - final list = jsonDecode(raw) as List; - return list - .map((entry) => Community.fromJson(entry as Map)) - .toList(); + try { + final list = jsonDecode(raw) as List; + return list + .map((entry) => Community.fromJson(entry as Map)) + .toList(); + } catch (error, stackTrace) { + _diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.storedData, + ); + rethrow; + } } /// Replaces the communities this build shows, keeping the others. diff --git a/mobile/lib/shared/diagnostics/diagnostic_filter.dart b/mobile/lib/shared/diagnostics/diagnostic_filter.dart index 5f15cd06b3..8006aa1806 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_filter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_filter.dart @@ -160,6 +160,9 @@ abstract final class DiagnosticFilter { SentryRuntime.fromJson(_only(runtime.toJson(), _runtime)), ]; event.tags?.removeWhere((key, _) => !_allowsTag(key)); + // Nothing sets additional data today; drop it so nothing later can. + // ignore: deprecated_member_use + event.extra = null; event.message = switch (event.message) { final message? => SentryMessage(stripUrlTails(message.formatted)), null => null, diff --git a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart index 5b43be168c..43e5a1e1e6 100644 --- a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:hooks_riverpod/hooks_riverpod.dart'; /// The one interface app code uses for diagnostic reporting. @@ -23,6 +25,9 @@ abstract interface class DiagnosticReporter { /// Attributes later reports and counts to [pubkey], or to no one. void setMember(String? pubkey); + /// The member later reports and counts name, as last given to [setMember]. + String? get member; + /// Whether this build has a reporting destination. Only then does Settings /// offer the checks below. bool get reporting; @@ -111,7 +116,14 @@ class NoopDiagnosticReporter implements DiagnosticReporter { Object error, StackTrace? stackTrace, { required DiagnosticOperation operation, - }) {} + }) { + // A throwing subscriber is a bug in the app, and the delivery guard + // catches it. With no destination, surface it the way an uncaught throw + // would: it fails the test that hit it and prints in development. + if (operation == DiagnosticOperation.eventSubscriber) { + Zone.current.handleUncaughtError(error, stackTrace ?? StackTrace.current); + } + } @override void countNetworkEvent(NetworkEvent event) {} @@ -122,6 +134,9 @@ class NoopDiagnosticReporter implements DiagnosticReporter { @override void setMember(String? pubkey) {} + @override + String? get member => null; + @override bool get reporting => false; @@ -132,6 +147,59 @@ class NoopDiagnosticReporter implements DiagnosticReporter { void crashForTest() {} } +/// Reports from work signed by [signer], such as a one-shot socket for a +/// community that may not be active. They go through while [reporter] names +/// [signer] or no member (reports then carry the install identifier), and are +/// dropped while it names another member, who didn't hit them. +class SignerDiagnosticReporter implements DiagnosticReporter { + const SignerDiagnosticReporter(this.reporter, {required this.signer}); + + final DiagnosticReporter reporter; + final String? signer; + + bool get _current => switch (reporter.member) { + null => true, + final member => member == signer, + }; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) { + if (_current) { + reporter.reportError(error, stackTrace, operation: operation); + } + } + + @override + void countNetworkEvent(NetworkEvent event) { + if (_current) reporter.countNetworkEvent(event); + } + + @override + void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb) { + if (_current) reporter.leaveBreadcrumb(breadcrumb); + } + + /// Signed work never changes who the app's reports name. + @override + void setMember(String? pubkey) {} + + @override + String? get member => reporter.member; + + @override + bool get reporting => reporter.reporting; + + @override + void sendTestReport() => reporter.sendTestReport(); + + @override + void crashForTest() => reporter.crashForTest(); +} + /// The reporter chosen at startup. The root scope overrides it; tests /// override it with a fake that records what it was given. final diagnosticReporterProvider = Provider( diff --git a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart index 9e90ea3f80..edcb2b72f1 100644 --- a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart +++ b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart @@ -67,11 +67,19 @@ class SentryDiagnosticReporter implements DiagnosticReporter { ); @override - void setMember(String? pubkey) => _drop( - () => _hub.configureScope( - (scope) => scope.setUser(pubkey == null ? null : SentryUser(id: pubkey)), - ), - ); + String? get member => _member; + String? _member; + + @override + void setMember(String? pubkey) { + _member = pubkey; + _drop( + () => _hub.configureScope( + (scope) => + scope.setUser(pubkey == null ? null : SentryUser(id: pubkey)), + ), + ); + } @override bool get reporting => true; diff --git a/mobile/lib/shared/hosted/builderlab_account.dart b/mobile/lib/shared/hosted/builderlab_account.dart index 6862882e38..c603bf0270 100644 --- a/mobile/lib/shared/hosted/builderlab_account.dart +++ b/mobile/lib/shared/hosted/builderlab_account.dart @@ -9,6 +9,7 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:http/http.dart' as http; import 'package:buzz/shared/http/app_http_client.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../storage/secure_storage.dart'; import 'hosted_environment.dart'; @@ -64,12 +65,17 @@ class BuilderlabAccountClient { FlutterSecureStorage? storage, Uri? accountOrigin, this.onSessionChanged, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), DateTime Function() now = DateTime.now, }) : _now = now, + _diagnostics = diagnostics, _http = httpClient ?? newAppHttpClient(), _storage = storage ?? defaultStorage, accountOrigin = accountOrigin ?? origin; + /// Where a response body this client can't understand is reported. + final DiagnosticReporter _diagnostics; + /// Device-only: the session never syncs or restores onto another device. @visibleForTesting static const defaultStorage = accountSecureStorage; @@ -248,7 +254,7 @@ class BuilderlabAccountClient { if (credential is! String || credential.isEmpty || credential.length > 512) { - throw AccountFailure.invalidResponse; + _invalidResponse('exchange response has no usable credential'); } final verified = await _verify(credential); if (DateTime.tryParse( @@ -257,7 +263,7 @@ class BuilderlabAccountClient { : '', ) != verified.expiresAt) { - throw AccountFailure.invalidResponse; + _invalidResponse('exchange and session expiry differ'); } if (stored != null && stored.subject != verified.subject) { throw AccountFailure.differentAccount; @@ -367,7 +373,7 @@ class BuilderlabAccountClient { final expiry = result['expires_at']; final parsed = expiry is String ? DateTime.tryParse(expiry) : null; if (subject is! String || subject.isEmpty || parsed == null) { - throw AccountFailure.invalidResponse; + _invalidResponse('session response lacks a subject or expiry'); } if (!parsed.isAfter(DateTime.now().toUtc())) throw AccountFailure.signedOut; final needsSetup = @@ -501,6 +507,7 @@ class BuilderlabAccountClient { '/v1/buzz/nostr-identities/current', credential: signedOut.credential, body: {}, + signer: pubkey, ); final identity = current['identity']; if (identity is! Map || identity['pubkey_hex'] != pubkey) { @@ -590,12 +597,22 @@ class BuilderlabAccountClient { } } + /// [signer], or the key behind [signingKey], is the identity the request + /// is made for. Its reports go out only while that identity, or no one, is + /// the member reports name: the outbox may ask for a removed community. Future> _request( String path, { String? credential, Map? body, String? signingKey, + String? signer, }) async { + signer ??= signingKey == null + ? null + : AccountIdentityStore.publicKeyForNsec(signingKey); + final diagnostics = signer == null + ? _diagnostics + : SignerDiagnosticReporter(_diagnostics, signer: signer); try { final request = http.Request( @@ -653,8 +670,21 @@ class BuilderlabAccountClient { _unavailable(path, 'http$status'); }, ); - final value = jsonDecode(utf8.decode(response.bodyBytes)); - if (value is! Map) throw AccountFailure.invalidResponse; + final Object? value; + try { + value = jsonDecode(utf8.decode(response.bodyBytes)); + if (value is! Map) { + // Not const: Sentry drops a repeat of the last error object. + throw FormatException('account response is not an object'); + } + } on FormatException catch (error, stackTrace) { + diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.accountResponse, + ); + throw AccountFailure.invalidResponse; + } return value; } on AccountFailure { rethrow; @@ -667,6 +697,17 @@ class BuilderlabAccountClient { } } + /// A 2xx response whose required fields are missing or unreadable: the + /// caller sees an invalid response, and it is reported. + Never _invalidResponse(String what) { + _diagnostics.reportError( + FormatException(what), + StackTrace.current, + operation: DiagnosticOperation.accountResponse, + ); + throw AccountFailure.invalidResponse; + } + Never _unavailable(String path, String cause) { lastUnavailableCause = cause; debugPrint('Builderlab ${accountOrigin.host} $path: unavailable ($cause)'); diff --git a/mobile/lib/shared/hosted/hosted_admission.dart b/mobile/lib/shared/hosted/hosted_admission.dart index aaf46f0ea3..afd371489c 100644 --- a/mobile/lib/shared/hosted/hosted_admission.dart +++ b/mobile/lib/shared/hosted/hosted_admission.dart @@ -15,6 +15,7 @@ import 'hosted_communities.dart'; import 'hosted_join_policy.dart'; import 'hosted_relay_auth.dart'; import '../relay/relay_provider.dart'; +import '../diagnostics/diagnostic_reporter.dart'; /// Builds a community only after scoped backup evidence and current binding. /// The caller persists it through the existing community transition owner. @@ -26,10 +27,12 @@ class HostedAdmission { required this.relayAuth, Future Function(HostedJoinPolicy)? confirmPolicy, Future Function(Community)? probe, + this.diagnostics = const NoopDiagnosticReporter(), }) : _confirmPolicy = confirmPolicy ?? ((_) async => false), _http = client ?? newAppHttpClient(), _probe = probe; final HostedRelayAuth relayAuth; + final DiagnosticReporter diagnostics; final BuilderlabAccountClient account; final AccountIdentityStore store; final http.Client _http; @@ -165,6 +168,11 @@ class HostedAdmission { RelayConfig(baseUrl: community.relayUrl, nsec: community.nsec), fresh: true, ); + // Until the joining identity is active, reports name another member. + socket.diagnostics = SignerDiagnosticReporter( + diagnostics, + signer: pubkeyFromNsec(community.nsec), + ); await socket.connect().timeout(const Duration(seconds: 30)); if (socket.state != SocketState.connected) throw AccountFailure.denied; } finally { diff --git a/mobile/lib/shared/hosted/hosted_flow_provider.dart b/mobile/lib/shared/hosted/hosted_flow_provider.dart index d91f622325..54e221f595 100644 --- a/mobile/lib/shared/hosted/hosted_flow_provider.dart +++ b/mobile/lib/shared/hosted/hosted_flow_provider.dart @@ -14,6 +14,7 @@ import 'hosted_community_connection.dart'; import 'hosted_flow.dart'; import 'hosted_identity_service.dart'; import 'hosted_relay_auth.dart'; +import '../diagnostics/diagnostic_reporter.dart'; // Set by a community-entry surface while it owns setup presentation. final hostedInlineEntryProvider = NotifierProvider( @@ -58,6 +59,7 @@ HostedFlow createHostedFlow( late final HostedFlow flow; final admission = HostedAdmission( relayAuth: ref.read(hostedRelayAuthProvider), + diagnostics: ref.read(diagnosticReporterProvider), account: account, store: store, confirmPolicy: (policy) => flow.confirmJoinPolicy(policy), diff --git a/mobile/lib/shared/hosted/hosted_relay_auth.dart b/mobile/lib/shared/hosted/hosted_relay_auth.dart index 8b05d534f5..3e238d3710 100644 --- a/mobile/lib/shared/hosted/hosted_relay_auth.dart +++ b/mobile/lib/shared/hosted/hosted_relay_auth.dart @@ -7,6 +7,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:http/http.dart' as http; import 'package:buzz/shared/http/app_http_client.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../relay/relay_provider.dart'; import 'builderlab_account.dart'; import 'account_identity_store.dart'; @@ -18,6 +19,7 @@ import '../push/push_bridge.dart'; final builderlabAccountProvider = Provider((ref) { final account = BuilderlabAccountClient( + diagnostics: ref.read(diagnosticReporterProvider), // Hosted communities that enforce NIP-FI need the extension to mint too. // A build without hosted relay auth still clears a copy an earlier build // shared, so the extension cannot keep minting after sign-out. @@ -41,6 +43,7 @@ final organizationAccountProvider = Provider((ref) { if (origin == null) return null; final account = BuilderlabAccountClient( accountOrigin: origin, + diagnostics: ref.read(diagnosticReporterProvider), // The notification extension mints its own assertions for these relays. onSessionChanged: (credential) => shareOrganizationSessionWithNotifications( origin: origin, diff --git a/mobile/lib/shared/hosted/self_hosted_entry.dart b/mobile/lib/shared/hosted/self_hosted_entry.dart index ccb987a482..0df6c1e74d 100644 --- a/mobile/lib/shared/hosted/self_hosted_entry.dart +++ b/mobile/lib/shared/hosted/self_hosted_entry.dart @@ -5,11 +5,13 @@ import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:nostr/nostr.dart' as nostr; import '../community/community.dart'; +import '../relay/relay_provider.dart'; import '../relay/relay_socket.dart'; import '../storage/secure_storage.dart'; import 'account_identity_store.dart'; import 'community_entry_requirements.dart'; import 'device_identity_source.dart'; +import '../diagnostics/diagnostic_reporter.dart'; /// A self-hosted attempt keeps its key before any network operation. Retrying /// after a refused connection or process death never rotates that identity. @@ -165,6 +167,7 @@ class SelfHostedEntry { static Future probeRelay( Community community, [ Map headers = const {}, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), ]) async { final socket = RelaySocket( wsUrl: community.relayUrl, @@ -175,6 +178,11 @@ class SelfHostedEntry { ); try { socket.headers = headers; + // Until the joining identity is active, reports name another member. + socket.diagnostics = SignerDiagnosticReporter( + diagnostics, + signer: pubkeyFromNsec(community.nsec), + ); await socket.connect().timeout(const Duration(seconds: 20)); if (socket.state != SocketState.connected) { throw StateError('Community refused entry'); diff --git a/mobile/lib/shared/push/dev_push_lease.dart b/mobile/lib/shared/push/dev_push_lease.dart index c93fb4c6c4..bb7bef58ab 100644 --- a/mobile/lib/shared/push/dev_push_lease.dart +++ b/mobile/lib/shared/push/dev_push_lease.dart @@ -50,12 +50,14 @@ class BuzzPushLeaseDescriptor { factory BuzzPushLeaseDescriptor.fromRelayInformation( Map information, ) { - final extensions = _stringList( - information['supported_extensions'], - name: 'supported_extensions', - ); + // NIP-11 makes the list optional: a relay may leave it out or send none. + final advertised = information['supported_extensions']; + if (advertised == null || (advertised is List && advertised.isEmpty)) { + throw const BuzzPushNotAdvertised(); + } + final extensions = _stringList(advertised, name: 'supported_extensions'); if (!extensions.contains('buzz-push-v1')) { - throw const FormatException('NIP-11 does not advertise buzz-push-v1'); + throw const BuzzPushNotAdvertised(); } final push = _stringMap(information['push'], name: 'push'); @@ -206,6 +208,12 @@ class BuzzPushLeaseDescriptor { } } +/// The relay does not offer Buzz push: an expected answer, not a fault. +class BuzzPushNotAdvertised extends FormatException { + const BuzzPushNotAdvertised() + : super('NIP-11 does not advertise buzz-push-v1'); +} + /// The desired lease requires channel IDs that this relay cannot accept yet. class BuzzPushChannelGrammarException implements Exception { const BuzzPushChannelGrammarException(); diff --git a/mobile/lib/shared/push/push_lease_revocation_outbox.dart b/mobile/lib/shared/push/push_lease_revocation_outbox.dart index 5dd4840643..9c55eeaeae 100644 --- a/mobile/lib/shared/push/push_lease_revocation_outbox.dart +++ b/mobile/lib/shared/push/push_lease_revocation_outbox.dart @@ -11,6 +11,7 @@ import 'package:nostr/nostr.dart' as nostr; import '../storage/secure_storage.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../community/community.dart'; import '../hosted/hosted_relay_auth.dart'; import '../relay/relay_provider.dart'; @@ -530,6 +531,7 @@ Uri _buzzPushRelayUri(String relayUrl) { Future publishBuzzPushLeaseRevocation( BuzzPushLeaseRevocationRecord record, { required HostedRelayAuth relayAuth, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), }) async { final descriptor = await fetchBuzzPushLeaseDescriptor(record.relayUrl); if (descriptor.origin != record.relayOrigin) { @@ -560,6 +562,7 @@ Future publishBuzzPushLeaseRevocation( content: content, tags: tags, createdAt: createdAt, + diagnostics: diagnostics, ), ); } @@ -576,6 +579,7 @@ final buzzPushLeaseRevocationOutboxProvider = publisher: (record) => publishBuzzPushLeaseRevocation( record, relayAuth: ref.read(hostedRelayAuthProvider), + diagnostics: ref.read(diagnosticReporterProvider), ), ); ref.onDispose(outbox.dispose); diff --git a/mobile/lib/shared/push/push_relay_capability_provider.dart b/mobile/lib/shared/push/push_relay_capability_provider.dart index ae4999d5c7..cdc228cca4 100644 --- a/mobile/lib/shared/push/push_relay_capability_provider.dart +++ b/mobile/lib/shared/push/push_relay_capability_provider.dart @@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../community/community_provider.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../relay/relay_provider.dart'; import '../relay/relay_session.dart'; import 'dev_push_lease.dart'; @@ -42,19 +43,48 @@ final currentRelayPushDescriptorProvider = return null; } + // A fetch can finish after a community switch has begun, when reports + // already name the next member. Its report would be misattributed. + var current = true; + final unregister = ref.read(communityTransitionProvider).register( + () async { + current = false; + }, + ); + ref.onDispose(() { + current = false; + unregister(); + }); return discoverBuzzPushRelayCapability( config.baseUrl, fetchDescriptor: ref.read(buzzPushDescriptorFetcherProvider), + diagnostics: ref.read(diagnosticReporterProvider), + isCurrent: () => current, ); }); +bool _alwaysCurrent() => true; + Future discoverBuzzPushRelayCapability( String relayBaseUrl, { required BuzzPushDescriptorFetcher fetchDescriptor, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), + bool Function() isCurrent = _alwaysCurrent, }) async { try { return await fetchDescriptor(relayBaseUrl); } catch (error, stackTrace) { + // A relay without Buzz push, or one that can't be reached, is expected; a + // descriptor that can't be read is not. + if (error is FormatException && + error is! BuzzPushNotAdvertised && + isCurrent()) { + diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.pushGatewayResponse, + ); + } debugPrint('Current relay does not advertise valid push: $error'); debugPrintStack(stackTrace: stackTrace); return null; diff --git a/mobile/lib/shared/relay/relay_closed_policy.dart b/mobile/lib/shared/relay/relay_closed_policy.dart index 9e12a89028..1b4f9ba5c4 100644 --- a/mobile/lib/shared/relay/relay_closed_policy.dart +++ b/mobile/lib/shared/relay/relay_closed_policy.dart @@ -45,6 +45,39 @@ 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. +/// Not const: Sentry drops a repeat of the last error object. +class RelayInvalidRequest implements Exception { + 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, an Unarchive of a channel that is no longer archived, an +/// open channel name that is taken, an agent whose policy refuses the +/// addition, a guest adding people, a sole owner leaving or an event whose +/// timestamp is outside the relay's window, are not. The timestamp refusal is +/// left out for every event, not only read-state updates: a device clock that +/// is off would otherwise report every publish, though this also hides a +/// signed event retried after the window has passed. +bool isInvalidRequestRejection(String message) { + final normalized = message.trim().toLowerCase(); + return normalized.startsWith('invalid:') && + !normalized.startsWith('invalid: channel is archived') && + !normalized.startsWith('invalid: channel is not archived') && + !normalized.startsWith('invalid: an open channel named') && + !normalized.startsWith('invalid: policy:') && + !normalized.startsWith( + 'invalid: only members can add people in this channel', + ) && + !normalized.startsWith('invalid: cannot remove the last owner') && + !normalized.contains('timestamp too far from server time'); +} + /// Explicit access refusal; cached private history must not mask this error. bool isRelayAccessDenied(Object error) { if (error is RelayException && error.statusCode == 403) return true; diff --git a/mobile/lib/shared/relay/relay_session.dart b/mobile/lib/shared/relay/relay_session.dart index 552255862d..1079a09ad1 100644 --- a/mobile/lib/shared/relay/relay_session.dart +++ b/mobile/lib/shared/relay/relay_session.dart @@ -12,6 +12,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../features/age_gate/age_signal_provider.dart'; import '../auth/auth.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../hosted/hosted_relay_auth.dart'; import '../hosted/builderlab_account.dart'; import 'nostr_filters.dart'; @@ -33,6 +34,7 @@ export 'relay_session_types.dart'; part 'relay_session_auth.dart'; part 'relay_session_background.dart'; +part 'relay_session_delivery.dart'; part 'relay_session_test_hooks.dart'; part 'relay_session_subscriptions.dart'; part 'relay_session_snapshot.dart'; @@ -124,10 +126,18 @@ class RelaySessionNotifier extends Notifier { @visibleForTesting set debugRelayUrl(String? value) => _relayUrl = value; + DiagnosticReporter _diagnostics = const NoopDiagnosticReporter(); + @override SessionState build() { final config = ref.watch(relayConfigProvider); _relayUrl = config.baseUrl; + // A switch names the next member before this session is rebuilt, so the + // old community's in-flight replies must not be filed under it. + _diagnostics = SignerDiagnosticReporter( + ref.read(diagnosticReporterProvider), + signer: pubkeyFromNsec(config.nsec), + ); final auth = ref.watch(authProvider.select(_sessionAuthKey)); _ageRestricted = ref.watch(ageSignalProvider) == AgeSignalState.restricted; @@ -279,10 +289,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()) { @@ -633,6 +648,7 @@ class RelaySessionNotifier extends Notifier { _handleDisconnected(generation, error, closeCode: socket.closeCode); }, ); + socket.diagnostics = _diagnostics; _socket = socket; try { @@ -884,6 +900,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) { @@ -996,6 +1013,7 @@ class RelaySessionNotifier extends Notifier { ? data[3] as String : ''; + if (!accepted) _reportInvalidRequest(message); final pending = _pendingEvents.remove(eventId); if (pending == null) return; pending.timeout.cancel(); @@ -1035,46 +1053,6 @@ class RelaySessionNotifier extends Notifier { } } - void _scheduleFlush() { - _flushTimer ??= Timer( - const Duration(milliseconds: _eventBatchMs), - _flushEventBuffer, - ); - } - - void _flushBufferedEventsNow() { - _flushTimer?.cancel(); - _flushTimer = null; - _flushEventBuffer(); - } - - void _flushEventBuffer() { - _flushTimer = null; - if (_eventBuffer.isEmpty) return; - - final batch = List<_BufferedEvent>.from(_eventBuffer); - _eventBuffer.clear(); - - for (final buffered in batch) { - final sub = _liveSubscriptions[buffered.subId]; - if (sub == null) continue; - - // Deduplicate per subscription. The same relay event can legitimately - // match multiple live subscriptions, e.g. the channel list unread listener - // and the open channel message listener. - final deliveryKey = '${buffered.subId}:${buffered.event.id}'; - if (_recentDeliveryKeys.contains(deliveryKey)) continue; - - // Cap the dedup set to prevent unbounded memory growth. - if (_recentDeliveryKeys.length >= _maxRecentDeliveryKeys) { - _recentDeliveryKeys.clear(); - } - _recentDeliveryKeys.add(deliveryKey); - - sub.onEvent(buffered.event); - } - } - String _nextSubId(String prefix) { _subIdCounter++; return '$prefix-$_subIdCounter'; diff --git a/mobile/lib/shared/relay/relay_session_delivery.dart b/mobile/lib/shared/relay/relay_session_delivery.dart new file mode 100644 index 0000000000..6b5d3e483e --- /dev/null +++ b/mobile/lib/shared/relay/relay_session_delivery.dart @@ -0,0 +1,63 @@ +part of 'relay_session.dart'; + +extension _RelaySessionDelivery on RelaySessionNotifier { + void _scheduleFlush() { + _flushTimer ??= Timer( + const Duration(milliseconds: RelaySessionNotifier._eventBatchMs), + _flushEventBuffer, + ); + } + + void _flushBufferedEventsNow() { + _flushTimer?.cancel(); + _flushTimer = null; + _flushEventBuffer(); + } + + void _flushEventBuffer() { + _flushTimer = null; + if (_eventBuffer.isEmpty) return; + + final batch = List<_BufferedEvent>.from(_eventBuffer); + _eventBuffer.clear(); + + for (final buffered in batch) { + final sub = _liveSubscriptions[buffered.subId]; + if (sub == null) continue; + + // Deduplicate per subscription. The same relay event can legitimately + // match multiple live subscriptions, e.g. the channel list unread listener + // and the open channel message listener. + final deliveryKey = '${buffered.subId}:${buffered.event.id}'; + if (_recentDeliveryKeys.contains(deliveryKey)) continue; + + // Cap the dedup set to prevent unbounded memory growth. + if (_recentDeliveryKeys.length >= + RelaySessionNotifier._maxRecentDeliveryKeys) { + _recentDeliveryKeys.clear(); + } + _recentDeliveryKeys.add(deliveryKey); + + // A subscriber that throws must not cost the rest of the batch: its + // delivery keys are already recorded, so lost events never come back. + try { + sub.onEvent(buffered.event); + } catch (error, stackTrace) { + _diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.eventSubscriber, + ); + } + } + } + + void _reportInvalidRequest(String message) { + if (!isInvalidRequestRejection(message)) return; + _diagnostics.reportError( + RelayInvalidRequest(), + StackTrace.current, + operation: DiagnosticOperation.relayRejection, + ); + } +} diff --git a/mobile/lib/shared/relay/relay_session_snapshot.dart b/mobile/lib/shared/relay/relay_session_snapshot.dart index 8434a3bb82..3e4ad497dd 100644 --- a/mobile/lib/shared/relay/relay_session_snapshot.dart +++ b/mobile/lib/shared/relay/relay_session_snapshot.dart @@ -94,12 +94,24 @@ extension on RelaySessionNotifier { final response = await send(request, readStateSnapshotMaxEnvelopeBytes); // Inflating, parsing and Schnorr verification must not block Flutter's // UI isolate. - final events = await _snapshotDecoder(( - bytes: response.bodyBytes, - contentType: response.headers['content-type'], - viewer: viewer, - community: community, - )); + final List events; + try { + events = await _snapshotDecoder(( + bytes: response.bodyBytes, + contentType: response.headers['content-type'], + viewer: viewer, + community: community, + )); + } catch (error, stackTrace) { + // A retired session reports that, not whatever its bytes decoded to. + checkContext(); + _diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.relayQuery, + ); + rethrow; + } checkContext(); return events; } 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/lib/shared/relay/signed_event_relay.dart b/mobile/lib/shared/relay/signed_event_relay.dart index fc12f8172d..30b158ecf4 100644 --- a/mobile/lib/shared/relay/signed_event_relay.dart +++ b/mobile/lib/shared/relay/signed_event_relay.dart @@ -2,7 +2,9 @@ import 'dart:async'; import 'package:nostr/nostr.dart' as nostr; +import '../diagnostics/diagnostic_reporter.dart'; import 'nostr_models.dart'; +import 'relay_closed_policy.dart'; import 'relay_session.dart'; import 'relay_socket.dart'; import 'package:buzz/shared/crypto/event_signing.dart'; @@ -78,6 +80,7 @@ Future submitSignedEventOnce({ int? createdAt, Duration timeout = const Duration(seconds: 12), Map headers = const {}, + DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), }) async { final privateKey = nostr.Nip19.decode(payload: nsec).data; if (privateKey.isEmpty) throw const FormatException('Invalid nsec'); @@ -89,6 +92,9 @@ Future submitSignedEventOnce({ createdAt: createdAt, ); final event = NostrEvent.fromJson(signed.toMap()); + // The signer may be a community that isn't active, such as a removed one's + // push tombstone; its reports must not name the active member. + final reporter = SignerDiagnosticReporter(diagnostics, signer: event.pubkey); final result = Completer(); late final RelaySocket socket; socket = RelaySocket( @@ -115,6 +121,13 @@ Future submitSignedEventOnce({ ), ); } else { + if (isInvalidRequestRejection(detail)) { + reporter.reportError( + RelayInvalidRequest(), + StackTrace.current, + operation: DiagnosticOperation.relayRejection, + ); + } result.completeError(Exception('Relay rejected event: $detail')); } } @@ -127,6 +140,7 @@ Future submitSignedEventOnce({ }, ); socket.headers = headers; + socket.diagnostics = reporter; final resultFuture = result.future.timeout(timeout); try { await socket.connect(); diff --git a/mobile/test/shared/auth/auth_provider_test.dart b/mobile/test/shared/auth/auth_provider_test.dart index acbc3ad1a4..41dabec075 100644 --- a/mobile/test/shared/auth/auth_provider_test.dart +++ b/mobile/test/shared/auth/auth_provider_test.dart @@ -413,6 +413,7 @@ void main() { } class _MemberRecorder extends NoopDiagnosticReporter { + @override String? member; @override diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index e3e4abc4b3..100005bfb6 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -938,6 +938,58 @@ void main() { expect(reporter.member, isNull); }); + test('switching names the member from storage, not a stale list', () async { + final reporter = _MemberRecorder(); + container = createContainer( + overrides: [diagnosticReporterProvider.overrideWithValue(reporter)], + ); + await container.read(communityListProvider.future); + final keys = nostr.Keys.generate(); + final saved = Community.create( + name: 'Saved', + relayUrl: 'https://saved.example.com', + nsec: keys.nsec, + ); + // Saved, but not yet in the provider's list, as while it reloads after + // sign-in. + await communityStorage.save(saved); + + await container + .read(communityListProvider.notifier) + .switchCommunity(saved.id); + + expect(reporter.member, keys.public); + }); + + test('a switch whose read fails changes nothing and can retry', () async { + final storage = _FailingLoadStorage(fakeSecure); + communityStorage = storage; + container = createContainer(); + final notifier = container.read(communityListProvider.notifier); + final a = Community.create( + name: 'A', + relayUrl: 'https://a.example.com', + nsec: nostr.Keys.generate().nsec, + ); + final b = Community.create( + name: 'B', + relayUrl: 'https://b.example.com', + nsec: nostr.Keys.generate().nsec, + ); + await container.read(communityListProvider.future); + await notifier.addCommunity(a); + await notifier.addCommunity(b); + await notifier.switchCommunity(a.id); + + storage.failNextLoad = true; + await expectLater(notifier.switchCommunity(b.id), throwsStateError); + expect(await storage.loadActiveId(), a.id); + + await notifier.switchCommunity(b.id); + expect(await storage.loadActiveId(), b.id); + expect((await container.read(activeCommunityProvider.future))?.id, b.id); + }); + group('activeCommunityProvider', () { test('returns null when no communities', () async { container = createContainer(); @@ -1017,8 +1069,24 @@ class _SnapshotStore extends InMemorySharedPreferencesStore { } class _MemberRecorder extends NoopDiagnosticReporter { + @override String? member = 'unset'; @override void setMember(String? pubkey) => member = pubkey; } + +class _FailingLoadStorage extends CommunityStorage { + _FailingLoadStorage(FlutterSecureStorage secure) : super(secure: secure); + + bool failNextLoad = false; + + @override + Future> loadAll() { + if (failNextLoad) { + failNextLoad = false; + throw StateError('keychain read failed'); + } + return super.loadAll(); + } +} diff --git a/mobile/test/shared/community/community_storage_test.dart b/mobile/test/shared/community/community_storage_test.dart index 822c358de3..7fe5cae091 100644 --- a/mobile/test/shared/community/community_storage_test.dart +++ b/mobile/test/shared/community/community_storage_test.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_storage.dart'; import 'package:buzz/shared/push/push_subscription.dart'; @@ -112,6 +113,20 @@ void main() { expect(result, isEmpty); }); + test('saved communities that cannot be read back are reported', () async { + final reporter = _RecordingDiagnostics(); + final reporting = CommunityStorage( + secure: fakeSecure, + diagnostics: reporter, + ); + await fakeSecure.write(key: 'buzz_communities', value: '{"oops"'); + + await expectLater(reporting.loadAll(), throwsFormatException); + expect(reporter.errors, [ + (FormatException, DiagnosticOperation.storedData), + ]); + }); + test('save and loadAll round-trips a community', () async { final ws = Community.create( name: 'Test', @@ -353,3 +368,14 @@ void main() { }); }); } + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => errors.add((error.runtimeType, operation)); +} diff --git a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart index 9d57b00891..5e54121a01 100644 --- a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart +++ b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart @@ -99,6 +99,19 @@ void main() { )).message?.formatted, 'failed https://e.org/p and wss://r.org/x', ), + ( + 'an event without a message gets none', + () async => (await event(SentryEvent())).message, + null, + ), + ( + 'additional data is dropped', + () async => (await event( + // ignore: deprecated_member_use + SentryEvent(extra: {'body': 'private-marker'}), + )).extra, // ignore: deprecated_member_use + null, + ), ( 'a tag not on the list is dropped', () async => (await event( diff --git a/mobile/test/shared/hosted/assertion_report_attribution_test.dart b/mobile/test/shared/hosted/assertion_report_attribution_test.dart new file mode 100644 index 0000000000..259fcf4892 --- /dev/null +++ b/mobile/test/shared/hosted/assertion_report_attribution_test.dart @@ -0,0 +1,107 @@ +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; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final keys = nostr.Keys.generate(); + final organization = Uri.parse('https://block.example.com'); + const relayHost = 'buzz.block.example.com'; + final expiry = DateTime.now().toUtc().add(const Duration(days: 1)); + + // An assertion for a removed community, say, while another community is + // active: its report would name the wrong member. + for (final (label, member, reported) in [ + ('another member', nostr.Keys.generate().public, false), + ('the signer', keys.public, true), + ('no member', null, true), + ]) { + test('an unreadable assertion with $label set is ' + '${reported ? '' : 'not '}reported', () async { + FlutterSecureStorage.setMockInitialValues({}); + await const FlutterSecureStorage().write( + key: 'buzz_hosted_session_block_example_com_v1', + value: jsonEncode({ + 'origin': organization.toString(), + 'credential': 'secret', + 'subject': 'member', + 'expires_at': expiry.toIso8601String(), + }), + ); + final diagnostics = _RecordingDiagnostics()..setMember(member); + BuilderlabAccountClient client({Uri? origin}) => BuilderlabAccountClient( + accountOrigin: origin, + diagnostics: diagnostics, + httpClient: MockClient( + (request) async => switch (request.url.path) { + '/api/goose/v1/auth/me' => http.Response( + jsonEncode({ + 'subject': 'member', + 'expires_at': expiry.toIso8601String(), + }), + 200, + ), + '/api/goose/v1/buzz/nostr-identities/current' => http.Response( + jsonEncode({ + 'identity': {'pubkey_hex': keys.public}, + }), + 200, + ), + '/api/goose/v1/buzz/identity/assertions' => http.Response( + '[]', + 200, + ), + _ => http.Response('{}', 404), + }, + ), + ); + final auth = HostedRelayAuth( + client(), + organization: client(origin: organization), + organizationRelay: (relay) => + BuilderlabBuild.matchesRelay(relay, [relayHost]), + enabled: true, + discover: (_) async => true, + ); + addTearDown(auth.dispose); + + await expectLater( + auth.headers( + RelayConfig(baseUrl: 'https://$relayHost', nsec: keys.nsec), + ), + throwsA(isA()), + ); + + expect(diagnostics.operations, [ + if (reported) DiagnosticOperation.accountResponse, + ]); + }); + } +} + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final operations = []; + String? _member; + + @override + String? get member => _member; + + @override + void setMember(String? pubkey) => _member = pubkey; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => operations.add(operation); +} diff --git a/mobile/test/shared/hosted/builderlab_account_test.dart b/mobile/test/shared/hosted/builderlab_account_test.dart index fa7049d7d5..d35298a429 100644 --- a/mobile/test/shared/hosted/builderlab_account_test.dart +++ b/mobile/test/shared/hosted/builderlab_account_test.dart @@ -1,3 +1,4 @@ +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/hosted/known_community_sync.dart'; import '../community/community_storage_test.dart' show FakeSecureStorage; import 'dart:async'; @@ -270,6 +271,61 @@ void main() { expect((await retry).subject, 'account-1'); }); + for (final (name, body) in [ + ('a body that is not JSON', '{"oops"'), + ('a body that is not an object', '[]'), + ]) { + test('$name is reported as an account response error', () async { + final reporter = _RecordingDiagnostics(); + final client = BuilderlabAccountClient( + httpClient: MockClient((_) async => http.Response(body, 200)), + diagnostics: reporter, + ); + await expectLater( + client.exchange(code: 'code', verifier: verifier), + throwsA(AccountFailure.invalidResponse), + ); + expect(reporter.errors, [ + (FormatException, DiagnosticOperation.accountResponse), + ]); + }); + } + + // 200 responses that parse but lack what the client requires. + for (final (name, exchange, me) in <(String, Object, Object)>[ + ('an exchange with no credential', {}, {}), + ( + 'a session with no subject', + {'session_credential': 'secret', 'expires_at': expiry}, + {'expires_at': expiry}, + ), + ( + 'a session with an unreadable expiry', + {'session_credential': 'secret', 'expires_at': expiry}, + {'subject': 'account-1', 'expires_at': 'soon'}, + ), + ]) { + test('$name is reported as an account response error', () async { + final reporter = _RecordingDiagnostics(); + final client = BuilderlabAccountClient( + httpClient: MockClient( + (request) async => http.Response( + jsonEncode(request.url.path.endsWith('/exchange') ? exchange : me), + 200, + ), + ), + diagnostics: reporter, + ); + await expectLater( + client.exchange(code: 'code', verifier: verifier), + throwsA(AccountFailure.invalidResponse), + ); + expect(reporter.errors, [ + (FormatException, DiagnosticOperation.accountResponse), + ]); + }); + } + test('invalid verification cannot persist an exchanged credential', () async { final transport = MockClient( (request) async => http.Response( @@ -679,3 +735,14 @@ class _SessionStorage extends FlutterSecureStorage { await super.delete(key: key); } } + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => errors.add((error.runtimeType, operation)); +} diff --git a/mobile/test/shared/push/dev_push_lease_test.dart b/mobile/test/shared/push/dev_push_lease_test.dart index 8e2e17bdcd..dff8d16c0c 100644 --- a/mobile/test/shared/push/dev_push_lease_test.dart +++ b/mobile/test/shared/push/dev_push_lease_test.dart @@ -478,22 +478,45 @@ void main() { } } - for (final extensions in [ - null, - false, - [], - ['nip-er'], + // NIP-11 makes the list optional, so leaving push out of it, or sending + // none, is a relay without push. Only a list of the wrong shape is + // malformed. + for (final (extensions, advertisedNone) in <(Object?, bool)>[ + (null, true), + ([], true), + (['nip-er'], true), + (false, false), + ([''], false), ]) { - test('invalid extension advertisement $extensions fails', () { + test('extension advertisement $extensions ' + '${advertisedNone ? 'is no push' : 'is malformed'}', () { final information = _descriptorJson(relay.public) ..addAll(metadata) ..['supported_extensions'] = extensions; expect( () => BuzzPushLeaseDescriptor.fromRelayInformation(information), - throwsA(isA()), + throwsA( + advertisedNone + ? isA() + : isA().having( + (error) => error is BuzzPushNotAdvertised, + 'is not advertised', + isFalse, + ), + ), ); }); } + + test('an absent extension list is no push', () { + final information = _descriptorJson(relay.public) + ..addAll(metadata) + ..remove('supported_extensions'); + expect( + () => BuzzPushLeaseDescriptor.fromRelayInformation(information), + throwsA(isA()), + ); + }); }); test('descriptor rejects canonical origin with a trailing slash', () { diff --git a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart index 476276683f..ca94f4cb28 100644 --- a/mobile/test/shared/push/push_lease_revocation_outbox_test.dart +++ b/mobile/test/shared/push/push_lease_revocation_outbox_test.dart @@ -4,6 +4,7 @@ import 'dart:io'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/hosted/builderlab_account.dart'; import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; import 'package:buzz/shared/push/push_bridge.dart'; @@ -155,6 +156,96 @@ void main() { }, ); + test('a tombstone refusal reports only while its community or no one is ' + 'the member reports name', () async { + // After the active community is removed, reports name the next one while + // the outbox still publishes the removed community's tombstone. + final overrides = HttpOverrides.current; + HttpOverrides.global = null; + addTearDown(() => HttpOverrides.global = overrides); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + final origin = 'ws://127.0.0.1:${server.port}'; + server.listen((request) async { + if (WebSocketTransformer.isUpgradeRequest(request)) { + final socket = await WebSocketTransformer.upgrade(request); + socket.add(jsonEncode(['AUTH', 'challenge'])); + socket.listen((message) { + final frame = jsonDecode(message as String) as List; + final event = frame[1] as Map; + final accepted = frame.first == 'AUTH'; + socket.add( + jsonEncode([ + 'OK', + event['id'], + accepted, + accepted ? '' : 'invalid: bad signature', + ]), + ); + }); + return; + } + request.response + ..headers.contentType = ContentType('application', 'nostr+json') + ..write( + jsonEncode(_descriptorJson(origin, nostr.Keys.generate().public)), + ) + ..close(); + }); + final auth = _AssertingRelayAuth(); + addTearDown(auth.dispose); + final record = BuzzPushLeaseRevocationRecord( + relayUrl: 'http://127.0.0.1:${server.port}', + relayOrigin: origin, + memberPubkey: keys.public, + nsec: keys.nsec, + installationId: 'c' * 32, + generation: 7, + expiresAt: null, + attemptCount: 0, + nextAttemptAt: 0, + ); + + final diagnostics = _RecordingDiagnostics() + ..setMember(nostr.Keys.generate().public); + await expectLater( + publishBuzzPushLeaseRevocation( + record, + relayAuth: auth, + diagnostics: diagnostics, + ), + throwsA(anything), + ); + expect(diagnostics.operations, isEmpty); + + diagnostics.setMember(keys.public); + await expectLater( + publishBuzzPushLeaseRevocation( + record, + relayAuth: auth, + diagnostics: diagnostics, + ), + throwsA(anything), + ); + expect(diagnostics.operations, [DiagnosticOperation.relayRejection]); + + // With no member set, as after the last community is removed, the report + // carries the install identifier. + diagnostics.setMember(null); + await expectLater( + publishBuzzPushLeaseRevocation( + record, + relayAuth: auth, + diagnostics: diagnostics, + ), + throwsA(anything), + ); + expect(diagnostics.operations, [ + DiagnosticOperation.relayRejection, + DiagnosticOperation.relayRejection, + ]); + }); + test('community removal journals one precise lease address', () async { final outbox = _outbox( storage: storage, @@ -480,6 +571,24 @@ BuzzPushEndpointGrant _grant({required int expiresAt}) => BuzzPushEndpointGrant( expiresAt: expiresAt, ); +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final operations = []; + String? _member; + + @override + String? get member => _member; + + @override + void setMember(String? pubkey) => _member = pubkey; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => operations.add(operation); +} + class _Clock { _Clock(this.seconds); diff --git a/mobile/test/shared/push/push_relay_capability_provider_test.dart b/mobile/test/shared/push/push_relay_capability_provider_test.dart index 2593eefb10..bd26370f67 100644 --- a/mobile/test/shared/push/push_relay_capability_provider_test.dart +++ b/mobile/test/shared/push/push_relay_capability_provider_test.dart @@ -1,18 +1,53 @@ +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/push/push_relay_capability_provider.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { - for (final failure in [ - const FormatException('malformed descriptor'), - StateError('relay unreachable'), + for (final (failure, reported) in <(Object, bool)>[ + (const FormatException('malformed descriptor'), true), + (const BuzzPushNotAdvertised(), false), + (StateError('relay unreachable'), false), ]) { - test('$failure keeps capability inactive', () async { + test('$failure keeps capability inactive' + '${reported ? ' and is reported' : ''}', () async { + final reporter = _RecordingDiagnostics(); final descriptor = await discoverBuzzPushRelayCapability( 'https://relay.example', fetchDescriptor: (_) async => throw failure, + diagnostics: reporter, ); expect(descriptor, isNull); + expect(reporter.operations, [ + if (reported) DiagnosticOperation.pushGatewayResponse, + ]); }); } + + test('a malformed descriptor that arrives after a switch began is not ' + 'reported', () async { + final reporter = _RecordingDiagnostics(); + final descriptor = await discoverBuzzPushRelayCapability( + 'https://relay.example', + fetchDescriptor: (_) async => + throw const FormatException('malformed descriptor'), + diagnostics: reporter, + isCurrent: () => false, + ); + + expect(descriptor, isNull); + expect(reporter.operations, isEmpty); + }); +} + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final operations = []; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => operations.add(operation); } diff --git a/mobile/test/shared/relay/read_state_snapshot_transport_test.dart b/mobile/test/shared/relay/read_state_snapshot_transport_test.dart index 25ffa70623..f6b97f07ec 100644 --- a/mobile/test/shared/relay/read_state_snapshot_transport_test.dart +++ b/mobile/test/shared/relay/read_state_snapshot_transport_test.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:buzz/shared/auth/auth_provider.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/hosted/builderlab_account.dart'; import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; import 'package:buzz/shared/relay/read_state_snapshot.dart'; @@ -263,12 +264,18 @@ void main() { envelope(events: [event()..['content'] = 'x' * _maxBytes]), }; for (final entry in invalidEnvelopes.entries) { - test('rejects ${entry.key} atomically', () async { - final h = harness(responseClient(entry.value())); + test('rejects ${entry.key} atomically and reports it', () async { + final reporter = _RecordingDiagnostics(); + final h = _Harness( + keys.nsec, + responseClient(entry.value()), + diagnostics: reporter, + ); await expectLater( h.session.fetchReadStateSnapshot(), throwsFormatException, ); + expect(reporter.operations, [DiagnosticOperation.relayQuery]); }); } @@ -507,20 +514,34 @@ void main() { class _Harness { final RelaySessionNotifier session; final _Config config; - _Harness(String nsec, http.Client client) + _Harness(String nsec, http.Client client, {DiagnosticReporter? diagnostics}) : session = RelaySessionNotifier(httpClient: client), config = _Config(nsec) { - _container(session, config); + _container(session, config, diagnostics: diagnostics); } } +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final operations = []; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => operations.add(operation); +} + void _container( RelaySessionNotifier session, _Config config, { HostedRelayAuth? auth, + DiagnosticReporter? diagnostics, }) { final container = ProviderContainer( overrides: [ + if (diagnostics != null) + diagnosticReporterProvider.overrideWithValue(diagnostics), authProvider.overrideWith(_PendingAuth.new), if (auth != null) hostedRelayAuthProvider.overrideWithValue(auth), relayConfigProvider.overrideWith(() => config), diff --git a/mobile/test/shared/relay/relay_closed_policy_test.dart b/mobile/test/shared/relay/relay_closed_policy_test.dart index b9f098e429..e1b85b896b 100644 --- a/mobile/test/shared/relay/relay_closed_policy_test.dart +++ b/mobile/test/shared/relay/relay_closed_policy_test.dart @@ -28,6 +28,33 @@ void main() { } }); + group('isInvalidRequestRejection', () { + const cases = { + 'invalid: bad signature': true, + 'INVALID: malformed filter': true, + 'invalid: channel is archived': false, + 'invalid: channel is not archived': false, + 'invalid: an open channel named "general" already exists': false, + 'invalid: event timestamp too far from server time': false, + 'invalid: policy:nobody \u2014 this agent has disabled external channel additions': + false, + 'invalid: policy:owner_only': false, + 'invalid: cannot remove the last owner': false, + 'invalid: only members can add people in this channel': 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_attribution_test.dart b/mobile/test/shared/relay/relay_session_attribution_test.dart new file mode 100644 index 0000000000..35e188e4f4 --- /dev/null +++ b/mobile/test/shared/relay/relay_session_attribution_test.dart @@ -0,0 +1,219 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/auth/auth_provider.dart'; +import 'package:buzz/shared/community/community.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; + +// A community switch names the next member while the old session is still +// live, so each report is checked against the member when it is made. +void main() { + for (final (label, member, reported) in [ + ('another member', _Member.other, false), + ('its own key', _Member.signer, true), + ('no one', _Member.none, true), + ]) { + test('a session reports only while $label is the member', () async { + final harness = await _connectedSession(); + final session = harness.session; + final reporter = harness.reporter; + void nameMember() => reporter.setMember(switch (member) { + _Member.other => nostr.Keys.generate().public, + _Member.signer => harness.keys.public, + _Member.none => null, + }); + + // Each request starts while the session's own key is the member. + final rejected = session.publish(_event('event-1')); + final query = session.queryRelay(const [ + NostrFilter(kinds: [1]), + ]); + await Future.delayed(Duration.zero); + nameMember(); + + session.debugHandleSocketMessageForTest([ + 'OK', + 'event-1', + false, + 'invalid: bad signature', + ]); + await expectLater(rejected, throwsA(isA())); + harness.decode.complete(); + await expectLater(query, throwsA(isA())); + harness.sendFrames(); + await harness.noticed.future; + + expect(reporter.errors, [ + if (reported) ...[ + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + (FormatException, DiagnosticOperation.relayQuery), + (FormatException, DiagnosticOperation.relayFrame), + ], + ]); + }); + } +} + +enum _Member { other, signer, none } + +class _Harness { + _Harness({ + required this.session, + required this.reporter, + required this.keys, + required this.decode, + required this.noticed, + required this.sendFrames, + }); + + final RelaySessionNotifier session; + final _RecordingDiagnostics reporter; + final nostr.Keys keys; + final Completer decode; + final Completer noticed; + final void Function() sendFrames; +} + +/// A session connected through a real socket to a loopback relay, with its +/// own key as the member. +Future<_Harness> _connectedSession() async { + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + final clients = []; + server.listen((request) async { + final ws = await WebSocketTransformer.upgrade(request); + clients.add(ws); + ws.listen((frame) { + final message = jsonDecode(frame as String) as List; + if (message.first == 'AUTH') { + final id = (message[1] as Map)['id']; + ws.add(jsonEncode(['OK', id, true, ''])); + } + }); + ws.add(jsonEncode(['AUTH', 'challenge'])); + }); + + final keys = nostr.Keys.generate(); + final reporter = _RecordingDiagnostics()..setMember(keys.public); + final decode = Completer(); + final noticed = Completer(); + final connected = Completer(); + final session = RelaySessionNotifier( + httpClient: http_testing.MockClient((_) async => http.Response('[]', 200)), + queryDecoder: (_) async { + await decode.future; + throw const FormatException('bad body'); + }, + socketFactory: + ({ + required wsUrl, + required nsec, + required onMessage, + required onConnected, + required onDisconnected, + }) => RelaySocket( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: nsec, + onMessage: (message) { + if (message.first == 'NOTICE' && !noticed.isCompleted) { + noticed.complete(); + } + onMessage(message); + }, + onConnected: () { + onConnected(); + if (!connected.isCompleted) connected.complete(); + }, + onDisconnected: onDisconnected, + ), + ); + final container = ProviderContainer( + overrides: [ + relaySessionProvider.overrideWith(() => session), + relayConfigProvider.overrideWith( + () => _RelayConfig( + RelayConfig(baseUrl: 'https://relay.example', nsec: 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; + return _Harness( + session: session, + reporter: reporter, + keys: keys, + decode: decode, + noticed: noticed, + sendFrames: () => clients.last + ..add('not json') + ..add('["NOTICE","still here"]'), + ); +} + +NostrEvent _event(String id) => NostrEvent( + id: id, + pubkey: 'alice', + createdAt: 20, + kind: 1, + tags: const [], + content: 'hello', + sig: 'sig', +); + +class _RelayConfig extends RelayConfigNotifier { + _RelayConfig(this._config); + + final RelayConfig _config; + + @override + RelayConfig build() => _config; +} + +class _Authenticated extends AuthNotifier { + _Authenticated(this._pubkey); + + final String _pubkey; + + @override + Future build() async => AuthState( + status: AuthStatus.authenticated, + community: Community( + id: 'community-1', + name: 'Example', + relayUrl: 'https://relay.example', + pubkey: _pubkey, + addedAt: DateTime(2026), + ), + ); +} + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + String? _member; + + @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)); +} diff --git a/mobile/test/shared/relay/relay_session_test.dart b/mobile/test/shared/relay/relay_session_test.dart index 6d50b90fbe..cb77642e5e 100644 --- a/mobile/test/shared/relay/relay_session_test.dart +++ b/mobile/test/shared/relay/relay_session_test.dart @@ -13,6 +13,7 @@ import 'package:buzz/features/channels/agent_activity/observer_subscription.dart import 'package:buzz/features/channels/agent_activity/observer_models.dart'; import 'package:buzz/shared/auth/auth_provider.dart'; import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/relay/relay.dart'; import 'package:buzz/shared/relay/relay_query_response.dart'; @@ -678,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"}'; @@ -721,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); @@ -735,6 +755,7 @@ void main() { decoder.gate.complete(); await outcome; + expect(reporter.errors, isEmpty); }); test('an age restriction during decoding discards the events', () async { @@ -1310,6 +1331,39 @@ void main() { }, ); + test( + 'a subscriber that throws is reported and the rest of its batch still arrives', + () async { + final reporter = _RecordingDiagnostics(); + final delivered = []; + final flush = await _batchWithThrowingSubscriber(reporter, delivered); + + flush(); + + expect(delivered, ['event-2']); + expect(reporter.errors, [ + (StateError, DiagnosticOperation.eventSubscriber), + ]); + }, + ); + + test( + 'with no destination, a throwing subscriber surfaces as uncaught and the batch still arrives', + () async { + final delivered = []; + final flush = await _batchWithThrowingSubscriber( + const NoopDiagnosticReporter(), + delivered, + ); + final uncaught = []; + + runZonedGuarded(flush, (error, _) => uncaught.add(error)); + + expect(delivered, ['event-2']); + expect(uncaught, [isA()]); + }, + ); + test('delivers the same live event to each matching subscription', () async { final session = RelaySessionNotifier(); final firstEvents = []; @@ -2237,6 +2291,75 @@ 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())); + // A read-state retry past the relay's clock window, which the app + // recovers from. + final stale = session.publish(_event(id: 'event-stale')); + session.debugHandleMessage([ + 'OK', + 'event-stale', + false, + 'invalid: event timestamp too far from server time', + ]); + await expectLater(stale, throwsA(isA())); + // Ordinary outcomes of Add Members (for an agent's policy or a guest) and + // of a sole owner's Leave. + for (final (id, reason) in [ + ('event-policy', 'invalid: policy:nobody'), + ('event-owner-only', 'invalid: policy:owner_only'), + ('event-last-owner', 'invalid: cannot remove the last owner'), + ( + 'event-guest-add', + 'invalid: only members can add people in this channel', + ), + ]) { + final refused = session.publish(_event(id: id)); + session.debugHandleMessage(['OK', id, false, reason]); + await expectLater(refused, 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']); + // No pending publish, as for a typing indicator or a reply after timeout. + session.debugHandleMessage([ + 'OK', + 'event-3', + false, + 'invalid: bad signature', + ]); + + expect(reporter.errors, [ + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + ]); + }); } class _ControlledHttpClient extends http.BaseClient { @@ -2319,6 +2442,7 @@ _QueryHarness _queryHarness({ required http.Client client, RelayQueryDecoder? queryDecoder, AgeSignalNotifier? age, + DiagnosticReporter? diagnostics, }) { final session = RelaySessionNotifier( httpClient: client, @@ -2328,6 +2452,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( @@ -2512,3 +2638,82 @@ class _PendingAuthNotifier extends AuthNotifier { @override Future build() => Completer().future; } + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => errors.add((error.runtimeType, operation)); +} + +/// Subscribes a handler that throws on `event-1` and buffers `event-1` and +/// `event-2`. Returns the flush that delivers them. +Future _batchWithThrowingSubscriber( + DiagnosticReporter reporter, + List delivered, +) async { + final sockets = <_ControlledRelaySocket>[]; + final keychain = nostr.Keys.generate(); + final auth = _ReloadingAuthNotifier()..pubkey = keychain.public; + final session = RelaySessionNotifier( + socketFactory: + ({ + required wsUrl, + required nsec, + required onMessage, + required onConnected, + required onDisconnected, + }) { + final socket = _ControlledRelaySocket( + wsUrl: wsUrl, + nsec: nsec, + onMessage: onMessage, + onConnected: onConnected, + onDisconnected: onDisconnected, + ); + sockets.add(socket); + return socket; + }, + ); + final container = ProviderContainer( + overrides: [ + relaySessionProvider.overrideWith(() => session), + relayConfigProvider.overrideWith( + () => _FakeRelayConfigNotifier( + baseUrl: 'https://relay.example', + nsec: keychain.nsec, + ), + ), + authProvider.overrideWith(() => auth), + diagnosticReporterProvider.overrideWithValue(reporter), + ], + ); + addTearDown(container.dispose); + await container.read(authProvider.future); + final listener = container.listen(relaySessionProvider, (_, _) {}); + addTearDown(listener.close); + await Future.delayed(Duration.zero); + sockets.single.connectSuccessfully(); + + final subscribed = session.subscribe(_channelFilter, (event) { + if (event.id == 'event-1') throw StateError('handler bug'); + delivered.add(event.id); + }); + await Future.delayed(Duration.zero); + final subId = sockets.single.sent.single[1]; + session.debugHandleSocketMessageForTest(['EOSE', subId]); + await subscribed; + + for (final id in ['event-1', 'event-2']) { + session.debugHandleSocketMessageForTest([ + 'EVENT', + subId, + _event(id: id).toJson(), + ]); + } + return session.debugFlushEventBuffer; +} 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)); + } +} diff --git a/mobile/test/shared/relay/submit_signed_event_once_test.dart b/mobile/test/shared/relay/submit_signed_event_once_test.dart new file mode 100644 index 0000000000..b24bf1be75 --- /dev/null +++ b/mobile/test/shared/relay/submit_signed_event_once_test.dart @@ -0,0 +1,108 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/relay/relay_closed_policy.dart'; +import 'package:buzz/shared/relay/signed_event_relay.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:nostr/nostr.dart' as nostr; + +void main() { + // A relay that authenticates the socket, then answers the event with + // [reason]. + Future relayRefusing(String reason) 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(jsonEncode(['AUTH', 'challenge'])); + ws.listen((raw) { + final frame = jsonDecode(raw as String) as List; + final id = (frame[1] as Map)['id']; + if (frame[0] == 'AUTH') ws.add(jsonEncode(['OK', id, true, ''])); + if (frame[0] == 'EVENT') ws.add(jsonEncode(['OK', id, false, reason])); + }); + }); + return server; + } + + for (final (reason, reported) in [ + ('invalid: bad signature', true), + ('invalid: event timestamp too far from server time', false), + ('blocked: not a member', false), + ]) { + test( + 'a refusal "$reason" ${reported ? 'is' : 'is not'} reported', + () async { + final server = await relayRefusing(reason); + final keys = nostr.Keys.generate(); + final reporter = _RecordingDiagnostics()..setMember(keys.public); + + await expectLater( + submitSignedEventOnce( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: keys.nsec, + kind: 1, + content: '', + tags: const [], + diagnostics: reporter, + ), + throwsA(isA()), + ); + + expect(reporter.errors, [ + if (reported) + (RelayInvalidRequest, DiagnosticOperation.relayRejection), + ]); + }, + ); + } + + // A removed community's tombstone, say, signs with a key other than the + // active member's, and its report would name the wrong member. With no + // member set, as on first run, reports carry the install identifier. + for (final (member, reported) in [ + (nostr.Keys.generate().public, false), + (null, true), + ]) { + test('a refusal while the member is ${member ?? 'unset'} ' + '${reported ? 'is' : 'is not'} reported', () async { + final server = await relayRefusing('invalid: bad signature'); + final reporter = _RecordingDiagnostics()..setMember(member); + + await expectLater( + submitSignedEventOnce( + wsUrl: 'ws://127.0.0.1:${server.port}', + nsec: nostr.Keys.generate().nsec, + kind: 1, + content: '', + tags: const [], + diagnostics: reporter, + ), + throwsA(isA()), + ); + + expect(reporter.errors, [ + if (reported) (RelayInvalidRequest, DiagnosticOperation.relayRejection), + ]); + }); + } +} + +class _RecordingDiagnostics extends NoopDiagnosticReporter { + final errors = <(Type, DiagnosticOperation)>[]; + String? _member; + + @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)); +}