Files
buzz/mobile/test/shared/push/push_lease_revocation_outbox_test.dart
Tom Brow e2bbd8430c 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 <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-20 09:09:29 -08:00

662 lines
20 KiB
Dart

import 'dart:async';
import 'dart:convert';
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';
import 'package:buzz/shared/push/push_lease_revocation_outbox.dart';
import 'package:buzz/shared/push/push_subscription.dart';
import 'package:buzz/shared/relay/relay_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import '../community/community_storage_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeSecureStorage secure;
late BuzzPushLeaseRevocationStorage storage;
late _Clock clock;
late _WakeScheduler scheduler;
late nostr.Keys keys;
setUp(() {
secure = FakeSecureStorage();
storage = BuzzPushLeaseRevocationStorage(secure: secure);
clock = _Clock(1_000_000);
scheduler = _WakeScheduler();
keys = nostr.Keys.generate();
});
test(
'revocation and tombstone sockets carry the hosted relay assertion',
() async {
// A hosted relay refuses the WebSocket upgrade without the assertion, so a
// queued revocation or a removal tombstone would retry forever.
// The test binding answers every HttpClient request with a 400, but this
// test runs a real local relay.
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}';
final upgrades = <HttpHeaders>[];
server.listen((request) async {
if (WebSocketTransformer.isUpgradeRequest(request)) {
upgrades.add(request.headers);
final socket = await WebSocketTransformer.upgrade(request);
socket.add(jsonEncode(['AUTH', 'challenge']));
socket.listen((message) {
final frame = jsonDecode(message as String) as List<dynamic>;
if (frame.first == 'AUTH' || frame.first == 'EVENT') {
final event = frame[1] as Map<String, dynamic>;
socket.add(jsonEncode(['OK', event['id'], true, '']));
}
});
return;
}
request.response
..headers.contentType = ContentType('application', 'nostr+json')
..write(
jsonEncode(_descriptorJson(origin, nostr.Keys.generate().public)),
)
..close();
});
final auth = _AssertingRelayAuth();
addTearDown(auth.dispose);
await publishBuzzPushLeaseRevocation(
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,
),
relayAuth: auth,
);
expect(
upgrades.single.value('nostr-federated-identity'),
'Bearer hosted-token',
);
expect(auth.configs.single.baseUrl, 'http://127.0.0.1:${server.port}');
expect(auth.configs.single.nsec, keys.nsec);
// A removed community's failure must not hide the active one's recovery.
expect(auth.backgrounds.single, isTrue);
// A new socket rereads NIP-FI discovery, so a community that started
// enforcing since its last read still gets the assertion.
expect(auth.freshes.single, isTrue);
// Removing the community publishes its tombstone the same way.
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
addTearDown(() => debugDefaultTargetPlatformOverride = null);
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(const MethodChannel('buzz/push'), (
call,
) async {
expect(call.method, 'endpointGrants');
return [
{
'relayOrigin': origin,
'relayPubkey': 'a' * 64,
'installationId': 'c' * 32,
'endpointGrant': 'grant',
'endpointHash': 'b' * 64,
'endpointEpoch': 1,
'generation': 1,
'expiresAt': 1752624000,
},
];
});
addTearDown(
() => messenger.setMockMethodCallHandler(
const MethodChannel('buzz/push'),
null,
),
);
final container = ProviderContainer(
overrides: [hostedRelayAuthProvider.overrideWithValue(auth)],
);
addTearDown(container.dispose);
await container.read(communityPushLeaseDeactivatorProvider)(
Community(
id: 'removed',
name: 'Removed',
addedAt: DateTime.utc(2026),
relayUrl: origin,
pubkey: keys.public,
nsec: keys.nsec,
),
generation: 9,
);
expect(upgrades, hasLength(2));
expect(
upgrades.last.value('nostr-federated-identity'),
'Bearer hosted-token',
);
expect(auth.configs.last.baseUrl, 'http://127.0.0.1:${server.port}');
expect(auth.configs.last.nsec, keys.nsec);
expect(auth.backgrounds.last, isTrue);
},
);
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<dynamic>;
final event = frame[1] as Map<String, dynamic>;
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,
clock: clock,
scheduler: scheduler,
publisher: (_) async {},
);
final community =
Community.create(
name: 'Test',
relayUrl: 'wss://relay.example',
nsec: keys.nsec,
).copyWith(
pubkey: keys.public,
pushNotificationsEnabled: true,
pushSubscriptionState: const BuzzPushLeaseSubscriptionState.desired()
.withReservedGeneration(4),
);
final grant = _grant(expiresAt: clock.seconds + 3600);
await outbox.enqueueCommunity(community, readGrants: () async => [grant]);
await outbox.enqueueCommunity(community, readGrants: () async => [grant]);
final records = await storage.loadAll();
expect(records, hasLength(1));
expect(
records.single.leaseAddress,
'${keys.public}|wss://relay.example|${community.pushLeaseInstallationId}',
);
expect(records.single.generation, 6);
expect(records.single.expiresAt, grant.expiresAt);
expect(records.single.relayUrl, 'https://relay.example/');
});
test('removal without a grant retains cleanup through restart', () async {
final community =
Community.create(
name: 'Test',
relayUrl: 'wss://relay.example',
nsec: keys.nsec,
).copyWith(
pubkey: keys.public,
pushNotificationsEnabled: true,
pushSubscriptionState: const BuzzPushLeaseSubscriptionState.desired()
.withReservedGeneration(4),
);
final first = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async => throw StateError('offline'),
);
expect(
await first.enqueueCommunity(community, readGrants: () async => []),
isTrue,
);
await first.trigger();
first.dispose();
final pending = (await storage.loadAll()).single;
expect(pending.installationId, community.pushLeaseInstallationId);
expect(pending.expiresAt, isNull);
clock.seconds = pending.nextAttemptAt;
final published = <BuzzPushLeaseRevocationRecord>[];
final restarted = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (record) async => published.add(record),
);
await restarted.trigger();
expect(published.single.installationId, community.pushLeaseInstallationId);
expect(published.single.generation, 7);
expect(await storage.loadAll(), isEmpty);
restarted.dispose();
});
test('legacy community revokes its grant-addressed lease', () async {
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async {},
);
final community = Community(
id: 'legacy',
name: 'Legacy',
relayUrl: 'wss://relay.example',
pubkey: keys.public,
nsec: keys.nsec,
pushNotificationsEnabled: true,
pushSubscriptionState: const BuzzPushLeaseSubscriptionState.desired()
.withReservedGeneration(4),
addedAt: DateTime.fromMillisecondsSinceEpoch(0),
);
final grant = _grant(expiresAt: clock.seconds + 3600);
await outbox.enqueueCommunity(community, readGrants: () async => [grant]);
expect(
(await storage.loadAll()).single.leaseAddress,
'${keys.public}|wss://relay.example|${grant.installationId}',
);
});
test('concurrent reconnect and resume triggers share one attempt', () async {
final started = Completer<void>();
final release = Completer<void>();
var calls = 0;
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async {
calls += 1;
if (!started.isCompleted) started.complete();
await release.future;
},
);
await outbox.enqueue(_record(keys: keys, clock: clock));
final startup = outbox.start();
await started.future;
final reconnect = outbox.trigger();
final resume = outbox.trigger();
expect(calls, 1);
expect(identical(reconnect, resume), isTrue);
release.complete();
await Future.wait([startup, reconnect, resume]);
expect(calls, 1);
expect(await storage.loadAll(), isEmpty);
});
test('failure reserves durable backoff and restart waits for it', () async {
var failedCalls = 0;
final first = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async {
failedCalls += 1;
throw StateError('offline');
},
);
await first.enqueue(_record(keys: keys, clock: clock));
await first.trigger();
final pending = (await storage.loadAll()).single;
expect(failedCalls, 1);
expect(pending.attemptCount, 1);
expect(pending.generation, 8);
expect(pending.nextAttemptAt, clock.seconds + 15);
var restartedCalls = 0;
final restarted = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async => restartedCalls += 1,
);
await restarted.start();
await restarted.trigger();
await restarted.trigger();
expect(restartedCalls, 0);
clock.seconds = pending.nextAttemptAt;
await restarted.trigger();
expect(restartedCalls, 1);
expect(await storage.loadAll(), isEmpty);
});
test('repeated failed restarts cannot create a retry storm', () async {
await storage.replaceAll([_record(keys: keys, clock: clock)]);
var calls = 0;
for (var restart = 0; restart < 4; restart += 1) {
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async {
calls += 1;
throw StateError('offline');
},
);
await outbox.start();
await Future.wait([outbox.trigger(), outbox.trigger(), outbox.trigger()]);
outbox.dispose();
}
expect(calls, 1);
final pending = (await storage.loadAll()).single;
expect(pending.attemptCount, 1);
expect(pending.nextAttemptAt, greaterThan(clock.seconds));
});
test('retry delay grows exponentially and remains bounded', () async {
await storage.replaceAll([
_record(
keys: keys,
clock: clock,
).copyWith(expiresAt: clock.seconds + 10_000_000),
]);
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async => throw StateError('offline'),
);
final delays = <int>[];
for (var attempt = 0; attempt < 14; attempt += 1) {
await outbox.trigger();
final pending = (await storage.loadAll()).single;
delays.add(pending.nextAttemptAt - clock.seconds);
clock.seconds = pending.nextAttemptAt;
}
expect(delays.take(4), [15, 30, 60, 120]);
expect(delays.every((delay) => delay <= 6 * 60 * 60), isTrue);
expect(delays.last, 3 * 60 * 60);
});
test('expired lease is erased without a relay attempt', () async {
final expired = _record(
keys: keys,
clock: clock,
).copyWith(expiresAt: clock.seconds);
await storage.replaceAll([expired]);
var calls = 0;
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async => calls += 1,
);
await outbox.start();
expect(calls, 0);
expect(await storage.loadAll(), isEmpty);
});
test('different records are globally serialized', () async {
final firstStarted = Completer<void>();
final releaseFirst = Completer<void>();
var inFlight = 0;
var maximumInFlight = 0;
var calls = 0;
final outbox = _outbox(
storage: storage,
clock: clock,
scheduler: scheduler,
publisher: (_) async {
calls += 1;
inFlight += 1;
maximumInFlight = inFlight > maximumInFlight
? inFlight
: maximumInFlight;
if (calls == 1) {
firstStarted.complete();
await releaseFirst.future;
}
inFlight -= 1;
},
);
await outbox.enqueue(_record(keys: keys, clock: clock));
final otherKeys = nostr.Keys.generate();
await outbox.enqueue(
_record(keys: otherKeys, clock: clock, installationId: '1' * 32),
);
final draining = outbox.trigger();
await firstStarted.future;
expect(calls, 1);
releaseFirst.complete();
await draining;
expect(calls, 2);
expect(maximumInFlight, 1);
expect(await storage.loadAll(), isEmpty);
});
}
BuzzPushLeaseRevocationOutbox _outbox({
required BuzzPushLeaseRevocationStorage storage,
required _Clock clock,
required _WakeScheduler scheduler,
required BuzzPushLeaseRevocationPublisher publisher,
}) => BuzzPushLeaseRevocationOutbox(
storage: storage,
publisher: publisher,
now: clock.call,
jitter: () => 0,
reportError: (_, _) {},
scheduleWake: scheduler.schedule,
);
BuzzPushLeaseRevocationRecord _record({
required nostr.Keys keys,
required _Clock clock,
String installationId = '00000000000000000000000000000000',
}) => BuzzPushLeaseRevocationRecord(
relayUrl: 'https://relay.example',
relayOrigin: 'wss://relay.example',
memberPubkey: keys.public,
nsec: keys.nsec,
installationId: installationId,
generation: 7,
expiresAt: clock.seconds + 3600,
attemptCount: 0,
nextAttemptAt: clock.seconds,
);
BuzzPushEndpointGrant _grant({required int expiresAt}) => BuzzPushEndpointGrant(
relayOrigin: 'wss://relay.example',
relayPubkey: 'a' * 64,
installationId: '0' * 32,
endpointGrant: 'opaque',
endpointHash: 'b' * 64,
endpointEpoch: 1,
generation: 1,
expiresAt: expiresAt,
);
class _RecordingDiagnostics extends NoopDiagnosticReporter {
final operations = <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,
}) => operations.add(operation);
}
class _Clock {
_Clock(this.seconds);
int seconds;
DateTime call() => DateTime.fromMillisecondsSinceEpoch(seconds * 1000);
}
class _WakeScheduler {
final List<_ScheduledWake> _wakes = [];
void Function() schedule(Duration delay, void Function() callback) {
final wake = _ScheduledWake();
_wakes.add(wake);
return () => wake.cancelled = true;
}
}
class _ScheduledWake {
bool cancelled = false;
}
class _AssertingRelayAuth extends HostedRelayAuth {
_AssertingRelayAuth() : super(BuilderlabAccountClient(), enabled: false);
final configs = <RelayConfig>[];
final backgrounds = <bool>[];
final freshes = <bool>[];
@override
Future<Map<String, String>> headers(
RelayConfig config, {
bool background = false,
bool fresh = false,
}) async {
configs.add(config);
backgrounds.add(background);
freshes.add(fresh);
return {'Nostr-Federated-Identity': 'Bearer hosted-token'};
}
}
Map<String, dynamic> _descriptorJson(String origin, String relayPubkey) => {
'supported_extensions': ['nip-er', 'buzz-push-v1'],
'push': {
'origin': origin,
'keys': [
{'id': 'relay-v1', 'pubkey': relayPubkey, 'current': true},
],
'push_kinds': [9, 40002, 45001, 45003],
'h_grammar': 'uuid-lowercase',
'class_support': {
'apns': ['default'],
},
'limitation': {
'max_lease_ttl': 2592000,
'max_leases_per_pubkey': 16,
'max_subscriptions_per_lease': 16,
'max_kinds': 16,
'max_authors': 20,
'max_h': 50,
'max_tag_values': 20,
'max_ignore': 8,
'max_content_len': 65536,
'max_plaintext_len': 32768,
'max_endpoint_len': 4096,
'max_string_len': 512,
},
},
};