diff --git a/CONTEXT.md b/CONTEXT.md index 812a68ce17..85f74d7836 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -88,7 +88,7 @@ _Avoid_: App Store build, external build ### Diagnostic reporting -Sending crash, error and performance data from a mobile installation to a [reporting destination](#reporting-destination). It exists to diagnose faults: it is not a record of how people use the app, and it never includes what they write. See [ADR 0007](docs/adr/0007-diagnostic-reporting-follows-the-destination.md). +Sending crash, error and performance data from a mobile installation to a [reporting destination](#reporting-destination). It exists to diagnose faults: it is not a record of how people use the app (beyond the SDK's session records, which say when each session started, how long it lasted from start to end, how it ended and how many errors it had), and it never includes what they write. See [ADR 0007](docs/adr/0007-diagnostic-reporting-follows-the-destination.md). _Avoid_: Telemetry, analytics, tracking, observability diff --git a/docs/adr/0007-diagnostic-reporting-follows-the-destination.md b/docs/adr/0007-diagnostic-reporting-follows-the-destination.md index 84e55a83e4..9ee3fd0638 100644 --- a/docs/adr/0007-diagnostic-reporting-follows-the-destination.md +++ b/docs/adr/0007-diagnostic-reporting-follows-the-destination.md @@ -4,13 +4,13 @@ A mobile build does [diagnostic reporting](../../CONTEXT.md#diagnostic-reporting We chose this so that the open-source app carries no organization's destination and no rule about which organizations may collect reports, the same reasoning that keeps organization hosts out of the code in [ADR 0001](0001-internal-and-public-mobile-builds.md). The first use is an organization's internal build, where everyone who has the app is a member of the organization that reads the reports. -A report may carry the stack trace and error type, app, operating system and device details, a trail of recent events written from a fixed list, the host names of the servers the app talks to, the signed-in member's public key and, when the person is signed in to a Builderlab account, that Builderlab's origin and the account's subject identifier, never its email address. Networking measurements also carry the operation's name from a fixed list, its outcome, the kind of failure and how long it took. A report never carries message content, channel or community names, private keys or other secrets, or a URL's query string or fragment. +A report may carry the stack trace and error type, app, operating system and device details, a trail of recent events written from a fixed list, the host names of the servers the app talks to, the signed-in member's public key, a random identifier the app creates for its installation, a random identifier the reporting SDK creates for the installation (which stands in as the user on reports sent while no one is signed in, and appears in the SDK's session records, which also carry when a session started, its length from start to end, how it ended and its error count), on iOS native crash and hang reports only, a hash the SDK computes from the identifier iOS gives the app's vendor, the hardware model and the app's bundle identifier (it stays the same across launches, and across a reinstall while another app from the same vendor stays installed) and, when the person is signed in to a Builderlab account, that Builderlab's origin and the account's subject identifier, never its email address. Networking measurements also carry the operation's name from a fixed list, its outcome, the kind of failure and how long it took. A report never carries message content, channel or community names, private keys or other secrets, or a URL's query string or fragment. ## Considered options - **Tie reporting to the internal build.** Rejected because the kind of build would then carry a second meaning, and a public or development build could never be diagnosed the same way. - **Refuse to start a public build that has a reporting destination.** This would have guaranteed that people outside the distributing organization are never reported on. Rejected in favor of one rule with no exceptions; whoever supplies the destination decides where the build goes. -- **A random identifier per installation in place of the public key.** Rejected because the reports exist so that someone can follow up with the person who hit the fault. +- **A random identifier per installation in place of the public key.** Rejected because the reports exist so that someone can follow up with the person who hit the fault. An installation identifier is now sent alongside the public key instead, so a device's reports can be matched to the members who used it. - **A switch or a notice in Settings.** Rejected for the first use, where the people reported on are the organization's own members. ## Consequences diff --git a/docs/mobile-diagnostic-reporting.md b/docs/mobile-diagnostic-reporting.md index ed15c63f99..bb38d8d4a9 100644 --- a/docs/mobile-diagnostic-reporting.md +++ b/docs/mobile-diagnostic-reporting.md @@ -34,6 +34,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat 18. As a member, I want reporting to never slow the app or block what I am doing, so that diagnosis does not cost me anything. 19. As a developer, I want signing out or switching accounts to change who later reports are attributed to, so that reports are never tagged with the wrong member. 20. As a reviewer, I want all reporting to go through one small interface, so that I can check what leaves the device in one place. +21. As a developer, I want freezes of the main thread reported with their stack (on iOS when the app is blocked for long enough, and on both platforms when the system ends the app for not responding), so that I can fix freezes that never show up as crashes. ## Implementation decisions @@ -45,11 +46,13 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - **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. - **No log lines in step one.** The counts carry the member and the time. The first implementation task confirms that the destination can filter counts by member; if it cannot, the fallback is one log line per outage, sent after it ends. -- **Breadcrumbs come from a fixed list** written by the app: networking events and the app moving to the foreground or background. The SDK's automatic breadcrumbs that could carry content or addresses are turned off or filtered. -- **Who a report is about.** The member's public key is set as the report's user when a session starts and cleared when it ends. When the session is a Builderlab account, the Builderlab's origin and the account's subject identifier are added, never its email address. -- **One filter before anything leaves.** Errors, breadcrumbs and counts all pass through a single filter that removes URL query strings and fragments, drops any attribute not on the allowed list, and replaces free-text failure messages with fixed wording. The SDK's options for sending personal data, screenshots, view hierarchies and session recordings stay off. +- **Breadcrumbs come from a fixed list:** networking events, written by the app, and the app moving to the foreground or background, written by the SDK. The SDK's other automatic breadcrumbs, which could carry content or addresses, are turned off or filtered. +- **Who a report is about.** The member's public key is set as the report's user when a session starts and cleared when it ends. When the session is a Builderlab account, the Builderlab's origin and the account's subject identifier are added, never its email address. Every report also carries the app's own random per-install identifier, created on first launch and kept in a file that device backups and transfers skip, so a phone restored from another gets its own, as a separate field, signed in or not, so reports from one device can be matched to the members who used it, and a member's reports to the devices they used. With no member set, for example before sign-in, the SDK fills the report's user with its own random per-install identifier, on Dart and native reports alike. On iOS, native crash and hang reports also carry the SDK's device app hash: a hash of the identifier iOS gives the app's vendor, the hardware model and the bundle identifier, stable across launches and across a reinstall while another app from the same vendor stays installed. The Dart filter drops it, so Dart reports don't carry it. The SDK also sends session records, so the destination can show a crash-free rate. A session begins each time the app starts or returns after 30 seconds or more in the background. The SDK sends a record when it begins, an update each time an error is counted, and a last record when it ends. Together they carry when the session started, how many errors it had, how it ended (normally, crashed or abnormally), the time from start to end (not time in active use), the release, the environment and the SDK's identifier. +- **One filter before anything leaves.** Errors, breadcrumbs and counts from Dart all pass through a single filter that removes URL query strings and fragments, drops any attribute not on the allowed list, replaces every error's own text with fixed wording, drops what the SDK adds about the failing widget or platform call, and keeps only the app, operating system, device and runtime details among the report's contexts, so the SDK's accessibility settings, locale and the device's own name stay on the device. An error keeps its type and stack trace. The SDK's options for sending personal data, screenshots, view hierarchies and session recordings stay off. +- **Main-thread hangs** are captured by the SDK's own hang detection, at the SDK's default thresholds. The app's Dart code runs on the platform's main thread, so Dart work that blocks it shows up here. On iOS, the SDK reports the main thread being blocked, fully or mostly, for 2 seconds or more while the app is active, with the main thread's stack taken during the hang, including freezes the app recovers from. A hang that is still going when the app is killed, for example by the system watchdog, is sent on the next launch as a fatal hang. The SDK's separate watchdog-termination tracking also reports, on the next launch, a run that ended while the app was in the foreground with nothing else to explain it; it never reports on simulators or for kills in the background. App hang detection is off while a debugger is attached ([sentry-cocoa 9.35.0](https://github.com/getsentry/sentry-cocoa/blob/9.35.0/Sources/Swift/Integrations/AppHangTracking/SentryHangTrackingIntegration.swift)). On Android the SDK reports only freezes the system itself declared "app not responding". On Android 11 and later it reports only one that ended the process, read from the system's exit records on the next launch: the most recent unreported one, and only when the system kept a usable thread dump. Before Android 11 it reports when the main thread has been blocked for 5 seconds and the system has marked the app not responding, never with a debugger attached ([sentry-java 8.64.0](https://github.com/getsentry/sentry-java/blob/8.64.0/sentry-android-core/src/main/java/io/sentry/android/core/AnrIntegrationFactory.java)). So with these defaults, a freeze the app recovers from is reported on iOS, and on Android only before Android 11 and only once the system has marked the app not responding. Dart frames in a hang's stack are readable only with the Dart code's debug symbols at the destination, the same as for crashes. +- **Native reports skip that filter.** Native crashes and app hangs are captured and sent by the native SDKs, which never call the Dart filter. They carry stack traces and, for a native exception, its reason text. No app code puts content in a native exception today, and the SDK's native network breadcrumbs, which would carry request addresses, are off. - **Readable stack traces** need the build's debug symbols at the destination. Uploading them belongs to the release process of whoever distributes the build; this repository documents the requirement and adds nothing organization-specific. -- **Both platforms.** Step one covers the main app on iOS and Android. Background work that runs the app's Dart code in its own engine, as decided for Android push handling in [ADR 0006](adr/0006-android-notifications-run-app-dart-code.md), starts the reporting module the same way once it exists. +- **Both platforms.** Step one covers the main app on iOS and Android. Background work that runs the app's Dart code in its own engine, as decided for Android push handling in [ADR 0006](adr/0006-android-notifications-run-app-dart-code.md), starts the reporting module the same way once it exists. Dart errors are captured in the main app's Flutter engine only: the iOS sheets that start their own engine (channel settings and the profile photo editor) are not covered, though native crashes while they are open still are. - **Reporting never blocks the app.** A call into the reporting module returns at once and nothing waits on the destination. A failure inside reporting is dropped and never reaches the code that made the call. ## Testing decisions @@ -70,7 +73,7 @@ A build that is given a [reporting destination](../CONTEXT.md#reporting-destinat - Requests that bypass the shared HTTP client, such as those made by native media players and image loaders. - 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. +- 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. ## Further notes diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml index ff71d174f7..09a8b7f08b 100644 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ b/mobile/android/app/src/main/AndroidManifest.xml @@ -63,6 +63,18 @@ android:name="flutter_deeplinking_enabled" android:value="false" /> + + + + + diff --git a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml index 8d14fc46fc..14dafc9901 100644 --- a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml +++ b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml @@ -1,17 +1,20 @@ + and would leave an unreadable identity behind. The diagnostics install + ID belongs to one installation, so a restored phone gets its own. Other + app data still backs up and transfers as before. --> + + diff --git a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index b3c85e18c2..734249298e 100644 --- a/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/mobile/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,14 @@ { - "originHash" : "cf0ceb033b4e7c51448393bb935a48ab1346299e1d2e41c5ef7e1095f5820443", "pins" : [ + { + "identity" : "sentry-apple-binaries", + "kind" : "remoteSourceControl", + "location" : "https://github.com/getsentry/sentry-apple-binaries", + "state" : { + "revision" : "8851964e4f4dbabb6b986c5f4c9b8f8996ed2842", + "version" : "9.35.0" + } + }, { "identity" : "swiftdraw", "kind" : "remoteSourceControl", @@ -11,5 +19,5 @@ } } ], - "version" : 3 + "version" : 2 } diff --git a/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved index 81798e1ed8..734249298e 100644 --- a/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/mobile/ios/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,14 @@ { - "originHash" : "a92bafb14ec27dd14811c270b8e5b1824a633f4776a425e690e27a5276f07661", "pins" : [ + { + "identity" : "sentry-apple-binaries", + "kind" : "remoteSourceControl", + "location" : "https://github.com/getsentry/sentry-apple-binaries", + "state" : { + "revision" : "8851964e4f4dbabb6b986c5f4c9b8f8996ed2842", + "version" : "9.35.0" + } + }, { "identity" : "swiftdraw", "kind" : "remoteSourceControl", @@ -11,5 +19,5 @@ } } ], - "version" : 3 + "version" : 2 } diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 9f413e4034..ccc42d80d6 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -36,6 +36,7 @@ import os.log private var communityKeyboardObserver: NSObjectProtocol? private var hapticsChannel: FlutterMethodChannel? private var appGroupChannel: FlutterMethodChannel? + private var diagnosticsChannel: FlutterMethodChannel? private var shareSuggestions: ShareSuggestions? private var qrScannerChannel: FlutterMethodChannel? private var inlinePhotoPickerSupportChannel: FlutterMethodChannel? @@ -173,6 +174,17 @@ import os.log result(FlutterMethodNotImplemented) } } + diagnosticsChannel = FlutterMethodChannel( + name: "buzz/diagnostics", + binaryMessenger: messenger + ) + diagnosticsChannel?.setMethodCallHandler { call, result in + guard call.method == "installIdDirectory" else { + result(FlutterMethodNotImplemented) + return + } + result(Self.diagnosticsInstallIdDirectory()) + } hapticsChannel = FlutterMethodChannel( name: "buzz/haptics", binaryMessenger: messenger @@ -486,6 +498,27 @@ import os.log "ageUpper": NSNull(), ] + /// Where diagnostic reporting keeps this installation's ID: Application + /// Support, which the system never purges, excluded from backups so a + /// phone restored from another gets its own ID. Nil if it can't be made. + private static func diagnosticsInstallIdDirectory() -> String? { + guard + var directory = FileManager.default.urls( + for: .applicationSupportDirectory, in: .userDomainMask + ).first?.appendingPathComponent("Diagnostics", isDirectory: true) + else { return nil } + do { + try FileManager.default.createDirectory( + at: directory, withIntermediateDirectories: true) + var values = URLResourceValues() + values.isExcludedFromBackup = true + try directory.setResourceValues(values) + return directory.path + } catch { + return nil + } + } + private static func handleQrScannerMethodCall( _ call: FlutterMethodCall, result: @escaping FlutterResult diff --git a/mobile/lib/main.dart b/mobile/lib/main.dart index 5348edba84..27750168b6 100644 --- a/mobile/lib/main.dart +++ b/mobile/lib/main.dart @@ -11,6 +11,9 @@ import 'features/age_gate/age_signal_push_bootstrap.dart'; import 'features/agents/agents_page.dart'; import 'features/invites/invite_join_provider.dart'; import 'shared/agents/agents_surface.dart'; +import 'shared/diagnostics/diagnostic_member_binding.dart'; +import 'shared/diagnostics/diagnostic_reporter.dart'; +import 'shared/diagnostics/diagnostic_startup.dart'; import 'shared/push/push_bridge.dart'; import 'shared/relay/media_disk_cache.dart'; import 'shared/relay/relay_closed_policy.dart'; @@ -21,6 +24,13 @@ void main() => runBuzzApp(const App()); Future runBuzzApp(Widget app) async { WidgetsFlutterBinding.ensureInitialized(); + await runWithDiagnostics( + destination: reportingDestination, + app: (reporter) => _startApp(app, reporter), + ); +} + +Future _startApp(Widget app, DiagnosticReporter reporter) async { installBuzzPushMethodHandler(); // Relay upgrades name the app version, so learn it before any socket opens. final userAgent = loadRelayUserAgent( @@ -35,6 +45,7 @@ Future runBuzzApp(Widget app) async { buildRootProviderScope( prefs: prefs, mediaCacheRoot: _mediaCacheRoot, + reporter: reporter, child: app, ), ); @@ -56,6 +67,7 @@ ProviderScope buildRootProviderScope({ required SharedPreferences prefs, required Widget child, Future Function()? mediaCacheRoot, + DiagnosticReporter reporter = const NoopDiagnosticReporter(), }) => ProviderScope( // A relay statement deadline cannot resolve on retry — the same expensive // query would re-run and hit the same limit. Return null (no retry) for @@ -66,6 +78,7 @@ ProviderScope buildRootProviderScope({ agentCreationSurfaceProvider.overrideWithValue( (context, link) async => unawaited(showAgents(context, draft: link)), ), + diagnosticReporterProvider.overrideWithValue(reporter), savedPrefsProvider.overrideWithValue(prefs), if (mediaCacheRoot != null) mediaCacheRootProvider.overrideWith((ref) => mediaCacheRoot()), @@ -74,5 +87,5 @@ ProviderScope buildRootProviderScope({ (scope) => buildMobileInviteJoinRecovery(ref, scope), ), ], - child: AgeSignalPushBootstrap(child: child), + child: DiagnosticMemberBinding(child: AgeSignalPushBootstrap(child: child)), ); diff --git a/mobile/lib/shared/auth/auth_provider.dart b/mobile/lib/shared/auth/auth_provider.dart index c8fdc3dc8e..271d0e2f44 100644 --- a/mobile/lib/shared/auth/auth_provider.dart +++ b/mobile/lib/shared/auth/auth_provider.dart @@ -5,7 +5,9 @@ import 'package:nostr/nostr.dart' as nostr; import '../community/community.dart'; import '../community/community_provider.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../hosted/community_entry_requirements.dart'; +import '../relay/relay_provider.dart' show pubkeyFromNsec; enum AuthStatus { unknown, unauthenticated, authenticated } @@ -77,7 +79,13 @@ class AuthNotifier extends AsyncNotifier { if (shouldContinue != null && !shouldContinue()) return; final storage = ref.read(communityStorageProvider); await storage.save(community); - if (activate) await storage.saveActiveId(community.id); + if (activate) { + await storage.saveActiveId(community.id); + // The derived member settles a frame later; name it on reports now. + ref + .read(diagnosticReporterProvider) + .setMember(pubkeyFromNsec(community.nsec)); + } sync?.trigger(); await syncStoredCommunitySnapshot(ref); diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index d62b12c504..791f907c79 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -13,6 +13,7 @@ import 'package:nostr/nostr.dart' as nostr; import '../auth/auth_provider.dart'; import '../channels/channel_list_snapshot.dart'; +import '../diagnostics/diagnostic_reporter.dart'; import '../hosted/community_entry_requirements.dart'; import '../profile/profile_snapshot.dart'; import '../push/dev_push_lease.dart'; @@ -394,11 +395,13 @@ class CommunityListNotifier extends AsyncNotifier> { final remaining = state.value ?? []; if (remaining.isNotEmpty) { await storage.saveActiveId(remaining.first.id); + _reportAs(remaining.first); // Reassign list state so activeCommunityProvider picks up the new ID. state = AsyncData([...remaining]); ref.invalidate(authProvider); } else { await storage.clearActiveId(); + _reportAs(null); // Invalidate auth so it re-evaluates against the now-empty storage // and transitions to unauthenticated. ref.invalidate(authProvider); @@ -509,6 +512,13 @@ class CommunityListNotifier extends AsyncNotifier> { } } + /// Names [community]'s member on reports from now on. The providers that + /// derive the member from the active community settle a frame later, and a + /// report raised in between would name the previous member. + void _reportAs(Community? community) => ref + .read(diagnosticReporterProvider) + .setMember(pubkeyFromNsec(community?.nsec)); + Future switchCommunity(String id) { return ref.read(communityTransitionProvider).runExclusive(() async { final storage = ref.read(communityStorageProvider); @@ -516,6 +526,7 @@ class CommunityListNotifier extends AsyncNotifier> { if (activeId == id) return; await ref.read(communityTransitionProvider).run(); await storage.saveActiveId(id); + _reportAs(state.value?.where((c) => c.id == id).firstOrNull); // 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/diagnostics/diagnostic_filter.dart b/mobile/lib/shared/diagnostics/diagnostic_filter.dart new file mode 100644 index 0000000000..5f15cd06b3 --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_filter.dart @@ -0,0 +1,200 @@ +import 'package:sentry_flutter/sentry_flutter.dart'; + +/// The one filter every Dart report, breadcrumb and count passes through +/// before it leaves the device. Reports the native SDKs capture themselves +/// (native crashes, app hangs) do not pass through it. +/// +/// It removes URL query strings and fragments, keeps only attributes on the +/// allowed list, and drops breadcrumbs that are not from the app's fixed list. +/// See "One filter before anything leaves" in +/// `docs/mobile-diagnostic-reporting.md`. +abstract final class DiagnosticFilter { + /// Breadcrumb category the app writes for networking events. + static const networkCategory = 'network'; + + /// Breadcrumb category of the SDK's foreground/background entries. + static const lifecycleCategory = 'app.lifecycle'; + + /// Tag carrying the random per-installation identifier on every report. + static const installIdTag = 'install.id'; + + /// Attributes the app itself sets on counts and breadcrumbs. + static const appAttributes = {'backend', 'endpoint', 'outcome', 'failure'}; + + /// Attribute prefixes the SDK sets on every count: its own name and + /// version, the release, the member, and the operating system and device. + static const _sdkAttributePrefixes = ['sentry.', 'user.', 'os.', 'device.']; + + /// Fixed wording that replaces an error's own text. + static const removedText = 'Error text removed before sending.'; + + static const _breadcrumbCategories = {networkCategory, lifecycleCategory}; + + /// Device fields that may leave: the hardware and its state, never the + /// name a person gave it or its locale and timezone. + static const _device = { + 'family', + 'model', + 'model_id', + 'arch', + 'battery_level', + 'orientation', + 'manufacturer', + 'brand', + 'screen_width_pixels', + 'screen_height_pixels', + 'screen_density', + 'screen_dpi', + 'online', + 'charging', + 'low_memory', + 'simulator', + 'memory_size', + 'free_memory', + 'usable_memory', + 'storage_size', + 'free_storage', + 'external_storage_size', + 'external_free_storage', + 'boot_time', + 'processor_count', + 'cpu_description', + 'processor_frequency', + 'device_type', + 'battery_status', + }; + + /// App fields that may leave: which build, and its memory and state. + static const _app = { + 'app_name', + 'app_version', + 'app_identifier', + 'app_build', + 'build_type', + 'app_start_time', + 'app_memory', + 'in_foreground', + }; + + static const _os = { + 'name', + 'version', + 'build', + 'kernel_version', + 'rooted', + 'raw_description', + }; + + static const _runtime = { + 'name', + 'compiler', + 'version', + 'raw_description', + 'build', + }; + + static Map _only( + Map json, + Set keys, + ) => { + for (final entry in json.entries) + if (keys.contains(entry.key)) entry.key: entry.value, + }; + + /// Report contexts that may leave the device: the app, operating system and + /// device details, the Dart runtime, and the SDK's trace identifiers. The + /// SDK adds others on its own, such as accessibility settings and locale. + static const _contexts = { + 'app', + 'device', + 'os', + 'runtime', + 'runtimes', + 'trace', + }; + + static final _urlTail = RegExp( + r'''(\b[a-z][a-z0-9+.-]*://[^\s?#'"]*)[?#][^\s'"]*''', + caseSensitive: false, + ); + + /// Removes the query string and fragment of every URL in [text]. + static String stripUrlTails(String text) => + text.replaceAllMapped(_urlTail, (match) => match.group(1)!); + + /// Whether an attribute [key] may leave the device. + static bool allowsAttribute(String key) => + appAttributes.contains(key) || _sdkAttributePrefixes.any(key.startsWith); + + /// The app tags a report with where it came from and which installation + /// sent it; the SDK tags it with its origin and environment. + static bool _allowsTag(String key) => + key == 'operation' || + key == installIdTag || + key.startsWith('event.') || + allowsAttribute(key); + + /// Filters an error report. + static SentryEvent filterEvent(SentryEvent event) { + event.request = null; + // Kept by name, like tags: the SDK adds contexts such as the widget and + // error description, accessibility settings and locale. + event.contexts.removeWhere((key, _) => !_contexts.contains(key)); + // Within those, only listed fields leave. The native SDKs' contexts carry + // more, such as the device's locale and timezone, which the Dart SDK keeps + // and writes back out. + final contexts = event.contexts; + if (contexts.device case final device?) { + contexts.device = SentryDevice.fromJson(_only(device.toJson(), _device)); + } + if (contexts.app case final app?) { + contexts.app = SentryApp.fromJson(_only(app.toJson(), _app)); + } + if (contexts.operatingSystem case final os?) { + contexts.operatingSystem = SentryOperatingSystem.fromJson( + _only(os.toJson(), _os), + ); + } + contexts.runtimes = [ + for (final runtime in contexts.runtimes) + SentryRuntime.fromJson(_only(runtime.toJson(), _runtime)), + ]; + event.tags?.removeWhere((key, _) => !_allowsTag(key)); + event.message = switch (event.message) { + final message? => SentryMessage(stripUrlTails(message.formatted)), + null => null, + }; + for (final exception in event.exceptions ?? const []) { + // An error's text can quote its input, a server's response body or a + // URL, so only its type, mechanism type and stack trace are kept. + if (exception.value != null) exception.value = removedText; + exception.mechanism?.data = null; + } + event.breadcrumbs = [ + for (final crumb in event.breadcrumbs ?? const []) + ?filterBreadcrumb(crumb), + ]; + return event; + } + + /// Filters a breadcrumb, or returns null to drop it. + static Breadcrumb? filterBreadcrumb(Breadcrumb? crumb) { + if (crumb == null || !_breadcrumbCategories.contains(crumb.category)) { + return null; + } + crumb.message = switch (crumb.message) { + final message? => stripUrlTails(message), + null => null, + }; + if (crumb.category == networkCategory) { + crumb.data?.removeWhere((key, _) => !appAttributes.contains(key)); + } + return crumb; + } + + /// Filters a count. + static SentryMetric filterMetric(SentryMetric metric) { + metric.attributes.removeWhere((key, _) => !allowsAttribute(key)); + return metric; + } +} diff --git a/mobile/lib/shared/diagnostics/diagnostic_member_binding.dart b/mobile/lib/shared/diagnostics/diagnostic_member_binding.dart new file mode 100644 index 0000000000..198a3153cc --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_member_binding.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../relay/relay_provider.dart'; +import 'diagnostic_reporter.dart'; + +/// Keeps later reports attributed to the signed-in member: set when a session +/// starts, changed when the account switches and cleared on sign-out. +final diagnosticMemberProvider = Provider((ref) { + ref.watch(diagnosticReporterProvider).setMember(ref.watch(myPubkeyProvider)); +}); + +/// Holds [diagnosticMemberProvider] for the life of the app. +class DiagnosticMemberBinding extends ConsumerWidget { + const DiagnosticMemberBinding({super.key, required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + ref.watch(diagnosticMemberProvider); + return child; + } +} diff --git a/mobile/lib/shared/diagnostics/diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart new file mode 100644 index 0000000000..61a2c40794 --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_reporter.dart @@ -0,0 +1,108 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +/// The one interface app code uses for diagnostic reporting. +/// +/// See `docs/mobile-diagnostic-reporting.md`. Every call returns at once and +/// never throws: a failure inside reporting is dropped so it cannot reach the +/// code that made the call. +abstract interface class DiagnosticReporter { + /// Reports something that should never happen, such as a frame the app + /// cannot decode. [operation] names where it happened, from a fixed list. + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }); + + /// Counts one networking event, with how long it took when known. + void countNetworkEvent(NetworkEvent event); + + /// Adds one entry to the trail attached to later reports. + void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb); + + /// Attributes later reports and counts to [pubkey], or to no one. + void setMember(String? pubkey); +} + +/// Where an explicit error report comes from. +enum DiagnosticOperation { + relayFrame, + relayQuery, + relayRejection, + accountResponse, + pushGatewayResponse, + storedData, + eventSubscriber, +} + +/// The operation a networking event belongs to. +enum NetworkEndpoint { relayConnection, relayQuery, relayPublish } + +/// How a networking event ended. +enum NetworkOutcome { success, failure } + +/// Why a networking event failed. +enum NetworkFailure { + timeout, + disconnected, + offline, + unreachable, + insecure, + rateLimited, + authRefused, + serverError, + relayError, + relayRefused, +} + +/// One counted networking event. [backend] is the server's host name. +class NetworkEvent { + const NetworkEvent({ + required this.backend, + required this.endpoint, + required this.outcome, + this.failure, + this.duration, + }) : assert((outcome == NetworkOutcome.failure) == (failure != null)); + + final String backend; + final NetworkEndpoint endpoint; + final NetworkOutcome outcome; + final NetworkFailure? failure; + final Duration? duration; +} + +/// One entry in the trail of recent networking events. +class DiagnosticBreadcrumb { + const DiagnosticBreadcrumb(this.event); + + /// Breadcrumbs from the fixed list are networking events. + final NetworkEvent event; +} + +/// Used when the build has no reporting destination. +class NoopDiagnosticReporter implements DiagnosticReporter { + const NoopDiagnosticReporter(); + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) {} + + @override + void countNetworkEvent(NetworkEvent event) {} + + @override + void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb) {} + + @override + void setMember(String? pubkey) {} +} + +/// 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( + (ref) => const NoopDiagnosticReporter(), +); diff --git a/mobile/lib/shared/diagnostics/diagnostic_startup.dart b/mobile/lib/shared/diagnostics/diagnostic_startup.dart new file mode 100644 index 0000000000..c397a30cd1 --- /dev/null +++ b/mobile/lib/shared/diagnostics/diagnostic_startup.dart @@ -0,0 +1,141 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; +import 'package:uuid/uuid.dart'; + +import 'diagnostic_filter.dart'; +import 'diagnostic_reporter.dart'; +import 'sentry_diagnostic_reporter.dart'; + +/// The build's reporting destination, a Sentry DSN supplied at build time. +/// Builds made from this repository alone have none and report nothing. +const reportingDestination = String.fromEnvironment('BUZZ_SENTRY_DSN'); + +/// Runs [app] with the reporter this build calls for. +/// +/// Without a [destination] the SDK is never initialized: a reporting library +/// given an empty destination can still install its hooks (ADR 0007). With +/// one, the SDK's own handlers capture native crashes, Flutter framework +/// errors and uncaught asynchronous Dart errors from then on. A destination +/// the SDK cannot parse is treated as none, so a configuration mistake never +/// stops the app from starting. +Future runWithDiagnostics({ + required String destination, + required FutureOr Function(DiagnosticReporter reporter) app, +}) async { + if (!_isUsable(destination)) return app(const NoopDiagnosticReporter()); + final installId = await diagnosticInstallId(); + await SentryFlutter.init( + (options) => configureDiagnostics(options, destination), + appRunner: () { + // A scope tag also reaches the native SDKs, so native crashes and + // hangs carry it too. + if (installId != null) { + Sentry.configureScope( + (scope) => scope.setTag(DiagnosticFilter.installIdTag, installId), + ); + } + return app(SentryDiagnosticReporter()); + }, + ); +} + +const _installIdFile = 'diagnostics_install_id'; + +/// A random identifier for this installation, so reports from one device can +/// be matched up across sign-ins and sign-outs. Created on first use and kept +/// in a file that device backups and transfers leave behind, so a phone +/// restored from another gets its own: on Android in the files directory, +/// excluded by the backup rules, and on iOS in an Application Support folder +/// the app marks as excluded from backup. Null if storage fails, since +/// reporting must never stop the app from starting. +Future diagnosticInstallId({ + Future Function()? directory, +}) async { + try { + final dir = await (directory ?? _installIdDirectory)(); + final file = File('${dir.path}/$_installIdFile'); + if (await file.exists()) { + final saved = (await file.readAsString()).trim(); + if (saved.isNotEmpty) return saved; + } + final created = const Uuid().v4(); + await dir.create(recursive: true); + await file.writeAsString(created, flush: true); + return created; + } on Object catch (error) { + debugPrint('[Diagnostics] no install ID: ${error.runtimeType}'); + return null; + } +} + +Future _installIdDirectory() async { + if (!Platform.isIOS) return getApplicationSupportDirectory(); + final path = await const MethodChannel( + 'buzz/diagnostics', + ).invokeMethod('installIdDirectory'); + if (path == null) throw StateError('no install ID directory'); + return Directory(path); +} + +bool _isUsable(String destination) { + if (destination.isEmpty) return false; + try { + final dsn = Dsn.parse(destination); + // The native SDKs also need an HTTP(S) host and a public key, which the + // Dart parser lets through; they would fail after Dart installs its + // handlers. The scheme is checked on the raw text because Dart lowercases + // it and Cocoa does not. + if (!(destination.startsWith('https://') || + destination.startsWith('http://')) || + (dsn.uri?.host ?? '').isEmpty || + dsn.publicKey.isEmpty || + dsn.projectId.isEmpty) { + throw const FormatException(); + } + return true; + } on Object catch (error) { + // Dsn.parse throws ArgumentError or FormatException; the message would + // repeat the destination, so only the type is printed. + debugPrint( + '[Diagnostics] reporting off: unusable destination ' + '(${error.runtimeType})', + ); + return false; + } +} + +/// Applies the reporting settings from `docs/mobile-diagnostic-reporting.md`. +void configureDiagnostics(SentryFlutterOptions options, String destination) { + options + ..dsn = destination + ..sendDefaultPii = false + ..attachScreenshot = false + ..attachViewHierarchy = false + // Breadcrumbs come only from the app's fixed list and the SDK's + // foreground/background entries; native ones can carry addresses. + ..enableAutoNativeBreadcrumbs = false + // On iOS this is Cocoa's own network breadcrumbs, which keep each + // request's query and fragment and reach native crash reports, which + // never pass through the filter below. + ..recordHttpBreadcrumbs = false + // Otherwise the SDK replaces debugPrint in non-debug builds with one that + // records a breadcrumb and prints nothing. + ..enablePrintBreadcrumbs = false + ..enableUserInteractionBreadcrumbs = false + ..enableAppLifecycleBreadcrumbs = true + // Main-thread hangs, at the SDK's default thresholds. Dart runs on the + // main thread, so blocking Dart work is what these catch. + ..enableAppHangTracking = true + ..anrEnabled = true + ..enableWatchdogTerminationTracking = true + ..beforeSend = ((event, hint) => DiagnosticFilter.filterEvent(event)) + ..beforeBreadcrumb = ((crumb, hint) => + DiagnosticFilter.filterBreadcrumb(crumb)) + ..beforeSendMetric = ((metric, hint) => + DiagnosticFilter.filterMetric(metric)); +} diff --git a/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart new file mode 100644 index 0000000000..e82a1b41a4 --- /dev/null +++ b/mobile/lib/shared/diagnostics/sentry_diagnostic_reporter.dart @@ -0,0 +1,99 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +import 'diagnostic_filter.dart'; +import 'diagnostic_reporter.dart'; + +/// Sends diagnostic reports through the Sentry SDK. +/// +/// The only file besides startup that imports the SDK. Calls hand their work +/// to the SDK without waiting, and a failure inside reporting is dropped: the +/// spec requires that reporting never fails or delays the caller. +class SentryDiagnosticReporter implements DiagnosticReporter { + SentryDiagnosticReporter({Hub? hub, SentryMetrics? metrics}) + : _hub = hub ?? HubAdapter(), + _metricsOverride = metrics; + + final Hub _hub; + final SentryMetrics? _metricsOverride; + + // Read on each call: the SDK installs its metrics when it starts. + SentryMetrics get _metrics => _metricsOverride ?? Sentry.metrics; + + @override + void reportError( + Object error, + StackTrace? stackTrace, { + required DiagnosticOperation operation, + }) => _drop( + () => _hub.captureException( + error, + stackTrace: stackTrace, + withScope: (scope) => scope.setTag('operation', operation.name), + ), + ); + + @override + void countNetworkEvent(NetworkEvent event) => _drop(() { + final attributes = _attributes(event); + _metrics.count('network.event', 1, attributes: attributes); + if (event.duration case final duration?) { + _metrics.distribution( + 'network.duration', + duration.inMicroseconds / 1000, + unit: SentryMetricUnit.millisecond, + attributes: attributes, + ); + } + return null; + }); + + @override + void leaveBreadcrumb(DiagnosticBreadcrumb breadcrumb) => _drop( + () => _hub.addBreadcrumb( + Breadcrumb( + category: DiagnosticFilter.networkCategory, + level: breadcrumb.event.outcome == NetworkOutcome.failure + ? SentryLevel.warning + : SentryLevel.info, + data: { + for (final entry in _attributes(breadcrumb.event).entries) + entry.key: entry.value.value, + }, + ), + ), + ); + + @override + void setMember(String? pubkey) => _drop( + () => _hub.configureScope( + (scope) => scope.setUser(pubkey == null ? null : SentryUser(id: pubkey)), + ), + ); + + static Map _attributes(NetworkEvent event) => { + 'backend': SentryAttribute.string(event.backend), + 'endpoint': SentryAttribute.string(event.endpoint.name), + 'outcome': SentryAttribute.string(event.outcome.name), + if (event.failure case final failure?) + 'failure': SentryAttribute.string(failure.name), + }; + + static void _drop(Object? Function() send) { + try { + final result = send(); + if (result is Future) { + unawaited(result.then((_) => null, onError: _dropped)); + } + } catch (error) { + _dropped(error); + } + } + + static Null _dropped(Object error) { + debugPrint('[Diagnostics] report dropped: ${error.runtimeType}'); + return null; + } +} diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock index af304aa1bc..5e29804fa8 100644 --- a/mobile/pubspec.lock +++ b/mobile/pubspec.lock @@ -1319,6 +1319,22 @@ packages: url: "https://pub.dev" source: hosted version: "0.3.8" + sentry: + dependency: transitive + description: + name: sentry + sha256: "490ff077d819c07511e4b1b07bcdf7117a87c3cb10b55b56081ac0a56d85d467" + url: "https://pub.dev" + source: hosted + version: "10.5.0" + sentry_flutter: + dependency: "direct main" + description: + name: sentry_flutter + sha256: "67e5cb6b78a5b32036472d75d9b553b8ca7e71d46243b79dc9e3e423945a7d9b" + url: "https://pub.dev" + source: hosted + version: "10.5.0" share_plus: dependency: "direct main" description: @@ -1861,5 +1877,5 @@ packages: source: hosted version: "2.2.4" sdks: - dart: ">=3.11.4 <4.0.0" + dart: ">=3.12.0 <4.0.0" flutter: ">=3.47.9" diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml index c428e54ea7..ffcc681315 100644 --- a/mobile/pubspec.yaml +++ b/mobile/pubspec.yaml @@ -65,6 +65,7 @@ dependencies: flutter_cache_manager: ^3.5.0 file: ^7.0.1 path: ^1.9.1 + sentry_flutter: ^10.5.0 dev_dependencies: leak_tracker: ^11.0.2 diff --git a/mobile/test/shared/auth/auth_provider_test.dart b/mobile/test/shared/auth/auth_provider_test.dart index 2ce7ac25cc..acbc3ad1a4 100644 --- a/mobile/test/shared/auth/auth_provider_test.dart +++ b/mobile/test/shared/auth/auth_provider_test.dart @@ -10,6 +10,7 @@ import 'package:buzz/shared/auth/auth_provider.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/community/community_storage.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import '../community/community_storage_test.dart'; @@ -58,6 +59,32 @@ void main() { ); }); + test('signing in names the new member at once', () async { + final storage = CommunityStorage(secure: FakeSecureStorage()); + final reporter = _MemberRecorder(); + final keys = nostr.Keys.generate(); + final container = ProviderContainer( + overrides: [ + communityStorageProvider.overrideWithValue(storage), + diagnosticReporterProvider.overrideWithValue(reporter), + ], + ); + addTearDown(container.dispose); + await container.read(authProvider.future); + + await container + .read(authProvider.notifier) + .authenticateWithCommunity( + Community.create( + name: 'One', + relayUrl: 'https://one.example', + nsec: keys.nsec, + ), + ); + + expect(reporter.member, keys.public); + }); + test( 'background batch addition preserves the first active community', () async { @@ -384,3 +411,10 @@ void main() { expect(await storage.loadActiveId(), valid.id); }); } + +class _MemberRecorder extends NoopDiagnosticReporter { + String? member; + + @override + void setMember(String? pubkey) => member = pubkey; +} diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index 77b20c270d..1f5481a99a 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -17,6 +17,7 @@ import 'package:buzz/shared/relay/relay_provider.dart' show RelayConfig; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/community/community_storage.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/push/push_subscription.dart'; import 'package:nostr/nostr.dart' as nostr; @@ -906,6 +907,38 @@ void main() { }); }); + test('switching and removing name the new member at once', () async { + final reporter = _MemberRecorder(); + container = createContainer( + overrides: [diagnosticReporterProvider.overrideWithValue(reporter)], + ); + await container.read(communityListProvider.future); + final one = nostr.Keys.generate(); + final two = nostr.Keys.generate(); + final ws1 = Community.create( + name: 'One', + relayUrl: 'https://one.example.com', + nsec: one.nsec, + ); + final ws2 = Community.create( + name: 'Two', + relayUrl: 'https://two.example.com', + nsec: two.nsec, + ); + final notifier = container.read(communityListProvider.notifier); + await notifier.addCommunity(ws1); + await notifier.addCommunity(ws2); + + await notifier.switchCommunity(ws1.id); + expect(reporter.member, one.public); + await notifier.switchCommunity(ws2.id); + expect(reporter.member, two.public); + await notifier.removeCommunity(ws2.id); + expect(reporter.member, one.public); + await notifier.removeCommunity(ws1.id); + expect(reporter.member, isNull); + }); + group('activeCommunityProvider', () { test('returns null when no communities', () async { container = createContainer(); @@ -983,3 +1016,10 @@ class _SnapshotStore extends InMemorySharedPreferencesStore { return removed; } } + +class _MemberRecorder extends NoopDiagnosticReporter { + String? member = 'unset'; + + @override + void setMember(String? pubkey) => member = pubkey; +} diff --git a/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart new file mode 100644 index 0000000000..e01284d71c --- /dev/null +++ b/mobile/test/shared/diagnostics/diagnostic_reporting_test.dart @@ -0,0 +1,463 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_filter.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_member_binding.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/diagnostics/diagnostic_startup.dart'; +import 'package:buzz/shared/diagnostics/sentry_diagnostic_reporter.dart'; +import 'package:buzz/shared/relay/relay_provider.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:sentry_flutter/sentry_flutter.dart'; +// The SDK's own processors and integrations, so tests see what it really +// sends rather than hand-built events. +// ignore: implementation_imports +import 'package:sentry_flutter/src/breadcrumbs/debug_print_integration.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/exception/flutter_error_integration.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/enrichment/flutter_enricher_event_processor.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/enrichment/widget_event_processor.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/url_filter/url_filter_event_processor.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/exception/flutter_exception_event_processor.dart'; +// ignore: implementation_imports +import 'package:sentry_flutter/src/exception/platform_exception_event_processor.dart'; + +void main() { + group('what leaves the device', () { + final options = SentryFlutterOptions(); + configureDiagnostics(options, 'https://key@example.org/1'); + + Breadcrumb? crumb(Breadcrumb input) => + options.beforeBreadcrumb!(input, Hint()); + + Future event(SentryEvent input) async => + (await options.beforeSend!(input, Hint()))!; + + Future> metric( + Map attributes, + ) async => (await options.beforeSendMetric!( + SentryCounterMetric( + timestamp: DateTime(2026), + name: 'network.event', + value: 1, + traceId: SentryId.newId(), + attributes: attributes, + ), + Hint(), + ))!.attributes; + + final rows = <(String, Future Function(), Object?)>[ + ( + 'an HTTP breadcrumb from the SDK is dropped', + () async => crumb( + Breadcrumb.http(url: Uri.parse('https://e.org'), method: 'GET'), + ), + null, + ), + ( + 'a navigation breadcrumb is dropped', + () async => crumb(Breadcrumb(category: 'navigation', message: 'Chat')), + null, + ), + ( + 'a lifecycle breadcrumb is kept', + () async => crumb( + Breadcrumb(category: 'app.lifecycle', data: {'state': 'paused'}), + )?.data, + {'state': 'paused'}, + ), + ( + 'a network breadcrumb keeps only its attributes', + () async => crumb( + Breadcrumb( + category: 'network', + data: {'backend': 'relay.example.org', 'channel': 'secret-room'}, + ), + )?.data, + {'backend': 'relay.example.org'}, + ), + ( + 'a URL in a message loses its query string and fragment', + () async => (await event( + SentryEvent( + message: SentryMessage( + 'failed https://e.org/p?token=abc#frag and wss://r.org/x?y=1', + ), + ), + )).message?.formatted, + 'failed https://e.org/p and wss://r.org/x', + ), + ( + 'a tag not on the list is dropped', + () async => (await event( + SentryEvent( + tags: { + 'operation': 'relayFrame', + 'install.id': 'i', + 'channel': 'x', + }, + ), + )).tags, + {'operation': 'relayFrame', 'install.id': 'i'}, + ), + ( + 'a count keeps its attributes and the member, nothing else', + () async => (await metric({ + 'backend': SentryAttribute.string('relay.example.org'), + 'user.id': SentryAttribute.string('ab'), + 'path': SentryAttribute.string('/channels/secret'), + })).keys.toSet(), + {'backend', 'user.id'}, + ), + ]; + + for (final (name, input, expected) in rows) { + test(name, () async => expect(await input(), expected)); + } + + test('personal data, screenshots and native breadcrumbs stay off', () { + expect(options.sendDefaultPii, isFalse); + expect(options.attachScreenshot, isFalse); + expect(options.attachViewHierarchy, isFalse); + expect(options.enableAutoNativeBreadcrumbs, isFalse); + expect(options.recordHttpBreadcrumbs, isFalse); + expect(options.replay.sessionSampleRate, isNull); + expect(options.tracesSampleRate, isNull); + }); + + test('main-thread hang detection is on at the default thresholds', () { + final defaults = SentryFlutterOptions(); + expect(options.enableAppHangTracking, isTrue); + expect(options.anrEnabled, isTrue); + expect(options.enableWatchdogTerminationTracking, isTrue); + expect(options.appHangTimeoutInterval, defaults.appHangTimeoutInterval); + expect(options.anrTimeoutInterval, defaults.anrTimeoutInterval); + }); + }); + + group('a sent error', () { + late _MemoryTransport transport; + late SentryFlutterOptions options; + late Hub hub; + + setUp(() { + transport = _MemoryTransport(); + options = SentryFlutterOptions(); + configureDiagnostics(options, 'https://key@example.org/1'); + // The processors SentryFlutter.init installs, in its order. + options + ..transport = transport + ..sendClientReports = false + ..addEventProcessor(FlutterExceptionEventProcessor()) + ..addEventProcessor(FlutterEnricherEventProcessor(options)) + ..addEventProcessor(WidgetEventProcessor()) + ..addEventProcessor(UrlFilterEventProcessor(options)) + ..addEventProcessor(PlatformExceptionEventProcessor()); + hub = Hub(options); + }); + tearDown(() => hub.close()); + + final rows = <(String, Object, String)>[ + ('a parse failure', const FormatException('private-marker'), 'Format'), + ('a bad argument', ArgumentError.value('private-marker'), 'Argument'), + ('a server response', StateError('body: private-marker'), 'StateError'), + ( + 'a platform failure', + PlatformException( + code: 'failed', + message: 'open https://e.org/f?token=private-marker', + ), + 'PlatformException', + ), + ]; + for (final (name, error, type) in rows) { + test('keeps only the type and stack of $name', () async { + await hub.captureException(error, stackTrace: StackTrace.current); + final sent = transport.events.single; + + expect(jsonEncode(sent), isNot(contains('private-marker'))); + final exception = (sent['exception']['values'] as List).last as Map; + expect(exception['type'], contains(type)); + expect(exception['value'], DiagnosticFilter.removedText); + expect(exception['stacktrace'], isNotNull); + }); + } + + test('a report right after a member change names the new member', () async { + SentryDiagnosticReporter(hub: hub) + ..setMember('a' * 64) + ..reportError( + StateError('failed'), + StackTrace.current, + operation: DiagnosticOperation.relayFrame, + ); + await transport.first(); + + expect(transport.events.single['user']['id'], 'a' * 64); + }); + + testWidgets('sends only the allowed contexts', (tester) async { + tester.platformDispatcher.accessibilityFeaturesTestValue = + const FakeAccessibilityFeatures(accessibleNavigation: true); + addTearDown( + tester.platformDispatcher.clearAccessibilityFeaturesTestValue, + ); + + await tester.runAsync( + () => hub.captureException( + StateError('failed'), + stackTrace: StackTrace.current, + ), + ); + + expect( + (transport.events.single['contexts'] as Map).keys, + everyElement( + isIn(['app', 'device', 'os', 'runtime', 'runtimes', 'trace']), + ), + ); + }); + + test('keeps only listed fields within contexts', () { + // As the native SDKs report them: the Dart SDK keeps keys it has no + // field for and writes them back out. + final event = SentryEvent( + contexts: Contexts( + device: SentryDevice.fromJson({ + 'name': 'private-marker', + 'model': 'iPhone', + 'locale': 'private-marker', + 'timezone': 'private-marker', + }), + app: SentryApp.fromJson({ + 'app_name': 'Buzz', + 'device_app_hash': 'private-marker', + 'x': 'private-marker', + }), + operatingSystem: SentryOperatingSystem.fromJson({ + 'name': 'iOS', + 'x': 'private-marker', + }), + runtimes: [ + SentryRuntime.fromJson({'name': 'Dart', 'x': 'private-marker'}), + ], + ), + ); + + final contexts = DiagnosticFilter.filterEvent(event).contexts; + + expect(jsonEncode(contexts.toJson()), isNot(contains('private-marker'))); + expect(contexts.device!.model, 'iPhone'); + expect(contexts.app!.name, 'Buzz'); + expect(contexts.operatingSystem!.name, 'iOS'); + }); + + testWidgets('leaves out what a framework error says about the screen', ( + tester, + ) async { + final integration = FlutterErrorIntegration(); + integration(hub, options); + addTearDown(integration.close); + + // A Text without Directionality is a real framework build error. + await tester.pumpWidget(const Text('private-marker')); + expect(tester.takeException(), isA()); + await tester.runAsync(transport.first); + + expect( + jsonEncode(transport.events.single), + isNot(contains('private-marker')), + ); + }); + }); + + test('device logs keep printing in a build that reports', () async { + final options = SentryFlutterOptions(checker: _ReleaseChecker()); + configureDiagnostics(options, 'https://key@example.org/1'); + final printed = []; + final original = debugPrint; + debugPrint = (message, {wrapWidth}) => printed.add(message); + final integration = DebugPrintIntegration(); + try { + integration(Hub(options), options); + debugPrint('an existing log line'); + } finally { + integration.close(); + debugPrint = original; + } + expect(printed, ['an existing log line']); + }); + + for (final (name, destination) in [ + ('no reporting destination', ''), + ('a destination the SDK cannot parse', 'https://key@example.org'), + ('a destination without a public key', 'https://example.org/1'), + ('a destination without an HTTP host', 'ftp://key@example.org/1'), + ('a destination with an uppercase scheme', 'HTTPS://key@example.org/1'), + ]) { + test('a build with $name starts without the SDK', () async { + DiagnosticReporter? started; + await runWithDiagnostics( + destination: destination, + app: (r) => started = r, + ); + + expect(started, isA()); + expect(Sentry.isEnabled, isFalse); + }); + } + + test('an installation keeps one install ID across launches', () async { + final installation = await Directory.systemTemp.createTemp('install'); + addTearDown(() => installation.delete(recursive: true)); + Future storage() async => installation; + + final first = await diagnosticInstallId(directory: storage); + expect(first, isNotNull); + expect(await diagnosticInstallId(directory: storage), first); + + final other = await Directory.systemTemp.createTemp('install'); + addTearDown(() => other.delete(recursive: true)); + expect( + await diagnosticInstallId(directory: () async => other), + isNot(first), + ); + }); + + test('a reporting call that fails does not reach the caller', () async { + for (final reporter in [ + SentryDiagnosticReporter(hub: _FailingHub(), metrics: _FailingMetrics()), + SentryDiagnosticReporter( + hub: _FailingHub(async: true), + metrics: _FailingMetrics(), + ), + ]) { + const event = NetworkEvent( + backend: 'relay.example.org', + endpoint: NetworkEndpoint.relayConnection, + outcome: NetworkOutcome.failure, + failure: NetworkFailure.timeout, + duration: Duration(seconds: 1), + ); + reporter + ..reportError( + StateError('x'), + null, + operation: DiagnosticOperation.relayFrame, + ) + ..countNetworkEvent(event) + ..leaveBreadcrumb(const DiagnosticBreadcrumb(event)) + ..setMember('ab'); + } + // An unhandled asynchronous failure would fail this test. + await pumpEventQueue(); + }); + + test('signing in, switching and signing out change the member', () async { + final reporter = _RecordingReporter(); + final container = ProviderContainer( + overrides: [ + diagnosticReporterProvider.overrideWithValue(reporter), + activeCommunityProvider.overrideWith((ref) async => null), + ], + ); + addTearDown(container.dispose); + container.listen(diagnosticMemberProvider, (_, _) {}); + final relay = container.read(relayConfigProvider.notifier); + + relay.update(baseUrl: 'https://relay.example.org', nsec: _nsec('1')); + container.read(diagnosticMemberProvider); + relay.update(baseUrl: 'https://relay.example.org', nsec: _nsec('2')); + container.read(diagnosticMemberProvider); + relay.update(baseUrl: 'https://relay.example.org'); + container.read(diagnosticMemberProvider); + + expect(reporter.members, [ + null, + pubkeyFromNsec(_nsec('1')), + pubkeyFromNsec(_nsec('2')), + null, + ]); + expect(reporter.members[1], isNot(reporter.members[2])); + }); +} + +String _nsec(String digit) => + nostr.Nip19.encode(prefix: nostr.Nip19Prefix.nsec, data: digit * 64); + +class _RecordingReporter extends NoopDiagnosticReporter { + final members = []; + + @override + void setMember(String? pubkey) => members.add(pubkey); +} + +class _FailingHub extends Fake implements Hub { + _FailingHub({this.async = false}); + + final bool async; + + Future _fail() => + async ? Future.error(StateError('down')) : throw StateError('down'); + + @override + Future captureException( + dynamic throwable, { + dynamic stackTrace, + Hint? hint, + SentryMessage? message, + ScopeCallback? withScope, + }) => _fail(); + + @override + Future addBreadcrumb(Breadcrumb crumb, {Hint? hint}) => _fail(); + + @override + Future configureScope(ScopeCallback callback) => _fail(); +} + +class _FailingMetrics extends Fake implements SentryMetrics { + @override + void count( + String name, + int value, { + Map? attributes, + }) => throw StateError('down'); +} + +class _ReleaseChecker extends RuntimeChecker { + @override + bool isDebugMode() => false; + @override + bool isReleaseMode() => true; + @override + bool isProfileMode() => false; +} + +class _MemoryTransport implements Transport { + final events = >[]; + final _first = Completer(); + + Future first() => _first.future; + + @override + Future send(SentryEnvelope envelope) async { + for (final item in envelope.items) { + if (item.header.type != 'event') continue; + final bytes = await item.dataFactory(); + events.add(jsonDecode(utf8.decode(bytes)) as Map); + if (!_first.isCompleted) _first.complete(); + } + return envelope.header.eventId; + } +}