Files
buzz/mobile/test/shared/push/push_bridge_test.dart
Tom Brow 2f1be86525 Apply a confirmed age restriction to Android push wakes (#9925)
Follow-up to [#9804 handle Android push
wakes](https://github.com/block/buzz/pull/9804), from its review: a
confirmed age restriction now applies to Android push wakes, as it
already does on iOS.

## What it does

- A new native `AgeRestriction` holds a confirmed restriction for the
life of the app process. Like the iOS restriction session, nothing is
saved: a later launch starts unrestricted and the age check runs again.
- The age gate's purge (`purgeAgeRestrictedNotifications`) now runs on
Android. It sets the restriction and cancels every notification Buzz has
posted. Restore (`restoreAgeRestrictedNotifications`) clears it. Both
were iOS-only before.
- On Android the restriction is released only when an age check in the
current engine finishes without restricting (allowed, or failing open).
The process can outlive the engine, for example after Back from the
restricted screen, and a reopened app starts its age state as allowed,
so releasing on that first build would lift a restriction the process
still holds before the new check answers. A retired check releases
nothing. iOS keeps restoring from the push bootstrap as before.
- The purge starts as soon as the age check confirms a restriction, not
when the restricted screen first draws. The check can answer while Buzz
is in the background, where Flutter draws no frames until the user
returns, so before this wakes kept posting until then. This also closes
the same gap on iOS. The restricted screen still retries a failed purge,
and a retry that a resume has replaced stays quiet, so a late failure
can't purge again.
- While the restriction holds, a push wake is skipped before it fetches
anything, the same way as when notifications are turned off.
- Every post from a wake (conversations and the generic "New activity")
checks the restriction under the same lock the purge takes. So a wake
already running when the restriction arrives posts nothing after the
purge, and a post already in progress finishes before the purge cancels
it.

## Decisions

- **Process lifetime, as on iOS.** Wakes run in the app's process, so an
in-memory flag covers every wake while the confirming process lives. A
wake that starts a fresh process (after the app was killed) is not
restricted until the app runs its check again. That matches iOS, where
the restriction ends with the process holding its lock.
- **No release-config change here.** `BUZZ_AGE_GATING_ENABLED` is still
set only for iOS builds, and no build sets the Firebase config yet.
Adding either to an Android build is a separate release change.

### Validation

Added tests:
[`AgeRestrictionTest.kt`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt)
covers restrict, release and a post that is in progress when the
restriction arrives.
[`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/shared/push/push_bridge_test.dart)
now covers the purge and restore calls on iOS and Android. The age
gate's outcome table now runs on Android and counts releases: none while
the check is pending, one after an adult, error, malformed or timed-out
result, none after a minor.


[`age_signal_provider_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_signal_provider_test.dart)'s
upper-bound table now also checks that a confirmed restriction starts
the purge with no widget or frame involved.
[`age_gate_app_test.dart`](https://github.com/block/buzz/blob/android-push-age-gate/mobile/test/features/age_gate/age_gate_app_test.dart)'s
purge retry test now uses the real notifier, with a resume while the
first purge is still running.

On a Pixel 9a (Android 16), a debug build with a local test relay. A
temporary debug hook called the native restrict and release directly,
because the phone was locked and Flutter doesn't draw frames behind the
lock screen:

1. Allowed: a wake posted the new message.
2. Restrict: the posted notification was removed.
3. While restricted: a wake logged `wake ignored foreground=false
restricted=true` and posted nothing.
4. Release: the next wake posted both the message that arrived during
the restriction and the new one.

The Dart side calling purge and restore is covered by the bridge test
above.

## Regressions

None expected: without age gating enabled, the restriction is never set
on Android.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-24 22:14:05 -08:00

541 lines
18 KiB
Dart

import 'dart:async';
import 'package:buzz/shared/community/community.dart';
import 'package:buzz/shared/deeplink/deep_link.dart';
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/push/push_bridge.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';
const _channel = MethodChannel('buzz/push');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
apnsDeviceToken.value = null;
apnsRegistrationError.value = null;
pushEndpointGrants.value = const [];
pushEndpointGrantError.value = null;
pushCommunitySnapshotError.value = null;
pendingPushNotificationLink.value = null;
installBuzzPushMethodHandler();
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, null);
debugDefaultTargetPlatformOverride = null;
});
test('captures APNs token success and clears the previous error', () async {
apnsRegistrationError.value = 'old error';
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('apnsTokenChanged', {'token': '01ab'}),
),
(_) {},
);
expect(apnsDeviceToken.value, '01ab');
expect(apnsRegistrationError.value, isNull);
});
test(
'starts native permission and APNs registration without a result gate',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'startRegistration');
return null;
});
await startBuzzPushRegistration();
},
);
for (final platform in [TargetPlatform.iOS, TargetPlatform.android]) {
test('purges and restores age-restricted notifications on '
'${platform.name}', () async {
debugDefaultTargetPlatformOverride = platform;
final methods = <String>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
methods.add(call.method);
expect(call.arguments, isNull);
return null;
});
await purgeAgeRestrictedBuzzNotifications();
await restoreAgeRestrictedBuzzNotifications();
expect(methods, [
'purgeAgeRestrictedNotifications',
'restoreAgeRestrictedNotifications',
]);
});
}
test('reads and exposes persisted endpoint grants on iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'endpointGrants');
expect(call.arguments, {'gatewayUrl': Env.pushGatewayUrl});
return [_grantMap('opaque-grant')];
});
final grants = await readBuzzPushEndpointGrants();
expect(grants, hasLength(1));
expect(grants.single.relayOrigin, 'wss://relay.example');
expect(grants.single.relayPubkey, 'a' * 64);
expect(grants.single.installationId, 'c' * 32);
expect(grants.single.endpointGrant, 'opaque-grant');
expect(grants.single.endpointHash, 'b' * 64);
expect(grants.single.endpointEpoch, 1);
expect(grants.single.generation, 1);
expect(grants.single.expiresAt, 1752624000);
expect(pushEndpointGrants.value.single.endpointGrant, 'opaque-grant');
expect(pushEndpointGrantError.value, isNull);
});
test(
'debug enrollment carries the configured relay and gateway URLs',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final methods = <String>[];
final enrollmentArguments = <Object?>[];
final snapshotArguments = <Object?>[];
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(_channel, (call) async {
methods.add(call.method);
if (call.method == 'enrollPush') {
enrollmentArguments.add(call.arguments);
return _grantMap('new-grant');
}
if (call.method == 'endpointGrants') {
return [_grantMap('new-grant')];
}
if (call.method == 'syncPushSnapshot') {
snapshotArguments.add(call.arguments);
return null;
}
fail('Unexpected method ${call.method}');
});
final firstGrant = await enrollBuzzPush(
'wss://relay.example/',
'https://gateway-one.example/',
);
final secondGrant = await enrollBuzzPush(
'wss://relay.example/',
'https://gateway-two.example/',
communitiesForSnapshotRefresh: [
Community(
id: 'community-id',
name: 'Community',
relayUrl: 'wss://relay.example/',
pubkey: 'd' * 64,
pushNotificationsEnabled: true,
addedAt: DateTime.fromMillisecondsSinceEpoch(0),
),
],
);
expect(firstGrant!.endpointGrant, 'new-grant');
expect(secondGrant!.endpointGrant, 'new-grant');
expect(enrollmentArguments, [
{
'relayUrl': 'wss://relay.example/',
'gatewayUrl': 'https://gateway-one.example/',
},
{
'relayUrl': 'wss://relay.example/',
'gatewayUrl': 'https://gateway-two.example/',
},
]);
expect(methods, [
'enrollPush',
'endpointGrants',
'enrollPush',
'endpointGrants',
'syncPushSnapshot',
]);
expect(snapshotArguments, [
{
'section': 'communities',
'communities': [
{
'id': 'community-id',
'name': 'Community',
'relayUrl': 'wss://relay.example/',
'pubkey': 'd' * 64,
'policies': <Object?>[],
},
],
'signingKeys': <String, String>{},
},
]);
expect(pushEndpointGrants.value.single.endpointGrant, 'new-grant');
},
);
test('a community that opted out enrolls nothing', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final methods = <String>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
methods.add(call.method);
return null;
});
final grant = await enrollBuzzPush(
'wss://relay.example/',
'https://gateway.example/',
stillWanted: () => false,
);
expect(grant, isNull);
expect(methods, isEmpty);
});
test('a gateway reply the app cannot read is reported and still fails '
'enrollment', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
throw PlatformException(code: 'gateway_response_invalid');
});
final reporter = _RecordingDiagnostics();
await expectLater(
enrollBuzzPush(
'wss://relay.example/',
'https://gateway.example/',
diagnostics: reporter,
),
throwsA(isA<PlatformException>()),
);
expect(reporter.operations, [DiagnosticOperation.pushGatewayResponse]);
});
test('routine enrollment failures are not reported', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final reporter = _RecordingDiagnostics();
for (final code in [
'dev_enrollment_failed',
'missing_apns_token',
'enrollment_in_progress',
]) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
throw PlatformException(code: code);
});
await expectLater(
enrollBuzzPush(
'wss://relay.example/',
'https://gateway.example/',
diagnostics: reporter,
),
throwsA(isA<PlatformException>()),
);
}
expect(reporter.operations, isEmpty);
});
test('shares and clears the hosted session with the extension', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final shared = <Object?>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'syncPushSnapshot');
shared.add(call.arguments);
return null;
});
for (final credential in ['session-credential', null]) {
await shareHostedSessionWithNotifications(
origin: Uri.parse('https://app.example'),
credential: credential,
relayDomains: const ['communities.example'],
communityDomain: 'communities.example',
);
}
expect(shared, [
for (final credential in ['session-credential', null])
{
'section': 'hostedSession',
'origin': 'https://app.example',
'credential': credential,
'relayDomains': ['communities.example'],
'communityDomain': 'communities.example',
},
]);
});
test(
'a build without hosted relay auth clears a shared hosted session',
() async {
expect(HostedRelayAuth.configured && HostedEnvironment.enabled, isFalse);
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final shared = <Object?>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
shared.add((call.arguments as Map)['credential']);
return null;
});
final container = ProviderContainer();
addTearDown(container.dispose);
// A copy an earlier flag-on build shared is removed instead of kept.
await container.read(builderlabAccountProvider).onSessionChanged!('live');
expect(shared, [null]);
},
);
test('exposes APNs registration failure', () async {
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('apnsRegistrationFailed', {'message': 'denied'}),
),
(_) {},
);
expect(apnsRegistrationError.value, 'denied');
});
test('routes a warm notification response with opaque IDs', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 'MESSAGE-ID',
'communityId': 'community-id',
'channelId': 'CHANNEL/GENERAL',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'handled');
expect(
pendingPushNotificationLink.value,
MessageDeepLink(
communityId: 'community-id',
channelId: 'CHANNEL/GENERAL',
messageId: 'MESSAGE-ID',
),
);
});
test(
'preserves the exact reply and containing thread on a warm tap',
() async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('notificationOpened', {
'eventId': 'older-reply',
'communityId': 'community-id',
'channelId': 'channel-id',
'threadRootId': 'direct-parent',
}),
),
response.complete,
);
expect(
_channel.codec.decodeEnvelope((await response.future)!),
'handled',
);
expect(
pendingPushNotificationLink.value,
const MessageDeepLink(
communityId: 'community-id',
channelId: 'channel-id',
messageId: 'older-reply',
threadRootId: 'direct-parent',
),
);
},
);
for (final invalidThread in ['', 42]) {
test('rejects malformed thread ID $invalidThread', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
_channel,
(_) async => {
'eventId': 'reply',
'communityId': 'community',
'channelId': 'channel',
'threadRootId': invalidThread,
},
);
await syncPendingBuzzPushNotificationResponse();
expect(pendingPushNotificationLink.value, isNull);
});
}
test('rejects a notification response with an empty channel ID', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 'message-id',
'communityId': 'community-id',
'channelId': '',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
});
test(
'rejects a notification response with a non-string message ID',
() async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
MethodCall('notificationOpened', {
'eventId': 42,
'communityId': 'community-id',
'channelId': 'channel-id',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
},
);
test('rejects a notification response with an absent message ID', () async {
final response = Completer<ByteData?>();
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
_channel.name,
_channel.codec.encodeMethodCall(
const MethodCall('notificationOpened', {
'communityId': 'community-id',
'channelId': 'channel-id',
}),
),
response.complete,
);
final envelope = await response.future;
expect(envelope, isNotNull);
expect(_channel.codec.decodeEnvelope(envelope!), 'ignored');
expect(pendingPushNotificationLink.value, isNull);
});
test('pulls a cold-start notification response from native iOS', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'takePendingNotificationResponse');
return {
'eventId': 'b' * 64,
'threadRootId': 'a' * 64,
'communityId': 'community-id',
'channelId': '123e4567-e89b-42d3-a456-426614174000',
};
});
await syncPendingBuzzPushNotificationResponse();
expect(
pendingPushNotificationLink.value,
MessageDeepLink(
communityId: 'community-id',
channelId: '123e4567-e89b-42d3-a456-426614174000',
messageId: 'b' * 64,
threadRootId: 'a' * 64,
),
);
});
test(
'pulls a cold-start notification response from native Android',
() async {
debugDefaultTargetPlatformOverride = TargetPlatform.android;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(_channel, (call) async {
expect(call.method, 'takePendingNotificationResponse');
return {
'eventId': 'b' * 64,
'communityId': 'community-id',
'channelId': '123e4567-e89b-42d3-a456-426614174000',
};
});
await syncPendingBuzzPushNotificationResponse();
expect(
pendingPushNotificationLink.value,
MessageDeepLink(
communityId: 'community-id',
channelId: '123e4567-e89b-42d3-a456-426614174000',
messageId: 'b' * 64,
),
);
},
);
}
Map<String, Object> _grantMap(String endpointGrant) => {
'relayOrigin': 'wss://relay.example',
'relayPubkey': 'a' * 64,
'installationId': 'c' * 32,
'endpointGrant': endpointGrant,
'endpointHash': 'b' * 64,
'endpointEpoch': 1,
'generation': 1,
'expiresAt': 1752624000,
};
class _RecordingDiagnostics extends NoopDiagnosticReporter {
final operations = <DiagnosticOperation>[];
@override
void reportError(
Object error,
StackTrace? stackTrace, {
required DiagnosticOperation operation,
}) => operations.add(operation);
}