mirror of
https://github.com/block/buzz.git
synced 2026-11-28 12:12:04 +00:00
Follow-ups from the review of #9811 (Android push enrollment): the review items that were safe to leave for after merge. - **A timed-out gateway call is now aborted.** The 15 s timeout used to abandon the POST while it kept running, so a retry could race the original request at the gateway. The gateway client now sends through `boundedHttpResponse`, which aborts the request at the deadline (and caps the reply size). - **An Android gateway reply the app can't read is reported to diagnostics,** as #9806 does for iOS. Malformed replies (no JSON object, missing fields, or an oversized reply with the expected status) throw `AndroidPushGatewayResponseInvalid`, which `enrollBuzzPush` reports under the push gateway operation. Refusals and transport failures stay unreported, and a refusal keeps its status even when its body is over the cap. - **The delegation sweep after enrollment keeps the enrolling relay while it is still wanted.** It now sweeps with the desired relays plus the enrolling origin, but only while `stillWanted()` holds, so an opt-out that landed during the delegation still sees that delegation revoked. - **Tests for two paths that had none:** an opt-out that lands while the gateway answers the delegation ends the attempt quietly (no lease, delegation revoked, no failure retry), and an opted-out iOS community enrolls nothing. Two other items from the review, both Codex findings on an earlier head of #9811 (reusing a revoked grant after a lost re-delegation; deleting a key after a lost renewal), were already fixed and tested before #9811 merged, so nothing changes here for them. ### Validation Added tests: - [the enrolling relay keeps its delegation before the caller lists it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart): the sweep keeps a still-wanted relay that the desired list doesn't show yet, and revokes a delegation whose community opted out while it was in flight. - [turning push off while it delegates ends the attempt quietly](157d6d4759/mobile/test/features/settings/android_notifications_test.dart): production bootstrap, opt-out while the delegation response is held. - [only a gateway reply the app cannot read is reported](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart) and [a gateway call that times out is aborted, not abandoned](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart). - [a community that opted out enrolls nothing](157d6d4759/mobile/test/shared/push/push_bridge_test.dart) (iOS). - [an unavailable gateway keeps the journal and a refusal clears it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart): now also with refusal bodies over the 64 KiB cap. Each test was checked to fail with its guard removed. No device or full-app run: every change is on the Android push gateway path (which needs a gateway-configured Android build) or is a test, and the behavior changed is timeout, malformed-reply and race handling that the tests above drive directly against the production authority and bootstrap. ### Regressions - iOS is unchanged apart from the new test; the abort and diagnostics changes are Android-only code. - `boundedHttpResponse` gains an optional `timeout` that defaults to its old 30 s, so existing callers behave as before. - Gateway replies are capped at 64 KiB. Gateway responses are small JSON objects, so an oversized reply with the expected status is itself a defect and is reported. An oversized refusal is handled as that refusal (a 503 stays retryable, a 403 discards the pending enrollment). --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
301 lines
9.7 KiB
Dart
301 lines
9.7 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
|
|
import 'package:buzz/shared/push/android_push_authority.dart';
|
|
import 'package:buzz/shared/push/android_push_gateway.dart';
|
|
import 'package:buzz/shared/push/android_push_keystore.dart';
|
|
import 'package:buzz/shared/push/push_bridge.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/testing.dart';
|
|
|
|
import '../../helpers/android_push_fakes.dart';
|
|
import '../../helpers/recording_diagnostics.dart';
|
|
|
|
const _channel = MethodChannel('buzz/push_registration');
|
|
|
|
void main() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
|
|
setUp(() {
|
|
fcmDeviceToken.value = null;
|
|
fcmRegistrationError.value = null;
|
|
pushUnavailableReason.value = null;
|
|
pushEndpointGrants.value = const [];
|
|
pushEndpointGrantError.value = null;
|
|
installBuzzPushMethodHandler();
|
|
});
|
|
|
|
tearDown(() {
|
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
|
.setMockMethodCallHandler(_channel, null);
|
|
debugDefaultTargetPlatformOverride = null;
|
|
debugAndroidPushAuthority = null;
|
|
});
|
|
|
|
Future<void> native(String method, Map<String, Object?> arguments) =>
|
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
|
.handlePlatformMessage(
|
|
_channel.name,
|
|
_channel.codec.encodeMethodCall(MethodCall(method, arguments)),
|
|
(_) {},
|
|
);
|
|
|
|
test('asks the native side to register and to refresh the token', () async {
|
|
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
|
final methods = <String>[];
|
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
|
.setMockMethodCallHandler(_channel, (call) async {
|
|
methods.add(call.method);
|
|
return null;
|
|
});
|
|
|
|
await startBuzzPushRegistration();
|
|
await refreshBuzzPushToken();
|
|
|
|
expect(methods, ['startRegistration', 'refreshToken']);
|
|
});
|
|
|
|
// Each row: the state before, native token events, then what Settings sees.
|
|
// "Unavailable" is reserved for a phone that cannot get a token at all or
|
|
// cannot attest; a token fetch failing while a token is held is transient.
|
|
const attest = 'The phone cannot attest its key.';
|
|
for (final row
|
|
in <
|
|
({
|
|
String name,
|
|
String? token,
|
|
String? shown,
|
|
List<(String, String)> events,
|
|
String? reason,
|
|
})
|
|
>[
|
|
(
|
|
name: 'a token clears an earlier registration failure',
|
|
token: null,
|
|
shown: null,
|
|
events: [('fail', 'no network'), ('token', 'fcm-token')],
|
|
reason: null,
|
|
),
|
|
(
|
|
name: 'a failure with no token shows unavailable',
|
|
token: null,
|
|
shown: null,
|
|
events: [('fail', 'no network')],
|
|
reason: 'no network',
|
|
),
|
|
(
|
|
name: 'a token does not clear an attestation failure',
|
|
token: null,
|
|
shown: attest,
|
|
events: [('token', 'fcm-token')],
|
|
reason: attest,
|
|
),
|
|
(
|
|
name: 'a failure while a token is held shows nothing',
|
|
token: 'fcm-token',
|
|
shown: null,
|
|
events: [('fail', 'SERVICE_NOT_AVAILABLE')],
|
|
reason: null,
|
|
),
|
|
(
|
|
name: 'a failure then a token leave an attestation failure',
|
|
token: null,
|
|
shown: attest,
|
|
events: [('fail', 'no network'), ('token', 'fcm-token')],
|
|
reason: attest,
|
|
),
|
|
(
|
|
name: 'two different failures then a token clear the row',
|
|
token: null,
|
|
shown: null,
|
|
events: [
|
|
('fail', 'no network'),
|
|
('fail', 'SERVICE_NOT_AVAILABLE'),
|
|
('token', 'fcm-token'),
|
|
],
|
|
reason: null,
|
|
),
|
|
]) {
|
|
test(row.name, () async {
|
|
fcmDeviceToken.value = row.token;
|
|
pushUnavailableReason.value = row.shown;
|
|
|
|
for (final (kind, value) in row.events) {
|
|
if (kind == 'fail') {
|
|
await native('fcmRegistrationFailed', {'message': value});
|
|
expect(fcmRegistrationError.value, value);
|
|
} else {
|
|
await native('fcmTokenChanged', {'token': value});
|
|
expect(fcmDeviceToken.value, value);
|
|
expect(fcmRegistrationError.value, isNull);
|
|
}
|
|
}
|
|
|
|
expect(pushUnavailableReason.value, row.reason);
|
|
});
|
|
}
|
|
|
|
test('enrolls through the Dart authority and exposes its grants', () async {
|
|
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
|
var now = 1_750_000_000;
|
|
final gateway = FakePushGateway(nowSeconds: () => now);
|
|
debugAndroidPushAuthority = AndroidPushAuthority(
|
|
keystore: FakeAndroidKeystore(),
|
|
gateway: fakeGatewayClient(gateway),
|
|
store: _MemoryStore(),
|
|
now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000),
|
|
sleep: (_) async {},
|
|
);
|
|
fcmDeviceToken.value = 'fcm-token';
|
|
pushUnavailableReason.value = 'stale';
|
|
|
|
final grant = (await enrollBuzzPush(
|
|
'wss://relay.example/',
|
|
'https://gateway.example/',
|
|
relayOrigin: 'wss://relay.example',
|
|
relayPubkey: 'a' * 64,
|
|
desiredRelays: () => {'wss://relay.example'},
|
|
))!;
|
|
|
|
expect(grant.relayOrigin, 'wss://relay.example');
|
|
expect(grant.relayPubkey, 'a' * 64);
|
|
expect(pushUnavailableReason.value, isNull);
|
|
expect(pushEndpointGrants.value.single.endpointGrant, grant.endpointGrant);
|
|
expect(
|
|
(await readBuzzPushEndpointGrants()).single.installationId,
|
|
grant.installationId,
|
|
);
|
|
});
|
|
|
|
test('a phone that cannot attest reports push as unavailable', () async {
|
|
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
|
var now = 1_750_000_000;
|
|
debugAndroidPushAuthority = AndroidPushAuthority(
|
|
keystore: FakeAndroidKeystore()..attests = false,
|
|
gateway: fakeGatewayClient(FakePushGateway(nowSeconds: () => now)),
|
|
store: _MemoryStore(),
|
|
now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000),
|
|
sleep: (_) async {},
|
|
);
|
|
fcmDeviceToken.value = 'fcm-token';
|
|
|
|
await expectLater(
|
|
enrollBuzzPush(
|
|
'wss://relay.example/',
|
|
'https://gateway.example/',
|
|
relayOrigin: 'wss://relay.example',
|
|
relayPubkey: 'a' * 64,
|
|
desiredRelays: () => {'wss://relay.example'},
|
|
),
|
|
throwsA(isA<AndroidPushAttestationUnavailable>()),
|
|
);
|
|
|
|
expect(pushUnavailableReason.value, isNotNull);
|
|
});
|
|
|
|
test('only a gateway reply the app cannot read is reported', () async {
|
|
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
|
fcmDeviceToken.value = 'fcm-token';
|
|
final diagnostics = RecordingDiagnostics();
|
|
|
|
Future<void> enroll() => enrollBuzzPush(
|
|
'wss://relay.example/',
|
|
'https://gateway.example/',
|
|
relayOrigin: 'wss://relay.example',
|
|
relayPubkey: 'a' * 64,
|
|
desiredRelays: () => {'wss://relay.example'},
|
|
diagnostics: diagnostics,
|
|
).then((_) {});
|
|
|
|
for (final (reply, reported) in [
|
|
// A refusal and gateway trouble are routine.
|
|
(http.Response(jsonEncode({'error': 'unavailable'}), 503), false),
|
|
// Even when the refusal's body is too large to read.
|
|
(http.Response('x' * 65537, 503), false),
|
|
// A challenge with no fields, and a body that is not JSON, are not.
|
|
(http.Response(jsonEncode({}), 200), true),
|
|
(http.Response('<html>', 200), true),
|
|
(http.Response('x' * 65537, 200), true),
|
|
]) {
|
|
diagnostics.errors.clear();
|
|
debugAndroidPushAuthority = AndroidPushAuthority(
|
|
keystore: FakeAndroidKeystore(),
|
|
gateway: AndroidPushGatewayClient(
|
|
baseUrl: Uri.parse('https://push.example'),
|
|
client: MockClient((_) async => reply),
|
|
),
|
|
store: _MemoryStore(),
|
|
sleep: (_) async {},
|
|
);
|
|
await expectLater(enroll(), throwsA(anything));
|
|
expect(diagnostics.errors, [
|
|
if (reported)
|
|
(
|
|
AndroidPushGatewayResponseInvalid,
|
|
DiagnosticOperation.pushGatewayResponse,
|
|
),
|
|
], reason: '${reply.statusCode} ${reply.body.length} bytes');
|
|
}
|
|
});
|
|
|
|
test('a gateway call that times out is aborted, not abandoned', () async {
|
|
final aborted = Completer<void>();
|
|
final gateway = AndroidPushGatewayClient(
|
|
baseUrl: Uri.parse('https://push.example'),
|
|
timeout: const Duration(milliseconds: 10),
|
|
client: _HangingClient(aborted),
|
|
);
|
|
|
|
await expectLater(
|
|
gateway.post('/v1/installations/challenges', {'v': 1}),
|
|
throwsA(isA<TimeoutException>()),
|
|
);
|
|
await aborted.future.timeout(const Duration(seconds: 1));
|
|
});
|
|
|
|
test('enrolling without a token fails loudly', () async {
|
|
debugDefaultTargetPlatformOverride = TargetPlatform.android;
|
|
|
|
await expectLater(
|
|
enrollBuzzPush(
|
|
'wss://relay.example/',
|
|
'https://gateway.example/',
|
|
relayOrigin: 'wss://relay.example',
|
|
relayPubkey: 'a' * 64,
|
|
desiredRelays: () => {'wss://relay.example'},
|
|
),
|
|
throwsStateError,
|
|
);
|
|
});
|
|
}
|
|
|
|
class _MemoryStore implements AndroidPushStateStore {
|
|
String? value;
|
|
|
|
@override
|
|
Future<String?> read() async => value;
|
|
|
|
@override
|
|
Future<void> write(String? next) async => value = next;
|
|
}
|
|
|
|
/// Never answers, and completes [aborted] when the request's abort trigger
|
|
/// fires.
|
|
class _HangingClient extends http.BaseClient {
|
|
_HangingClient(this.aborted);
|
|
|
|
final Completer<void> aborted;
|
|
|
|
@override
|
|
Future<http.StreamedResponse> send(http.BaseRequest request) {
|
|
final trigger = (request as http.Abortable).abortTrigger;
|
|
if (trigger == null) throw StateError('the request is not abortable');
|
|
trigger.then((_) => aborted.complete());
|
|
return Completer<http.StreamedResponse>().future;
|
|
}
|
|
}
|