From 2f1be8652523df71c100e4e513da911be1f2b9ce Mon Sep 17 00:00:00 2001 From: Tom Brow Date: Tue, 24 Nov 2026 22:14:05 -0800 Subject: [PATCH] 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 Co-authored-by: studio --- .../xyz/block/buzz/mobile/AgeRestriction.kt | 36 ++++++++ .../xyz/block/buzz/mobile/MainActivity.kt | 2 +- .../buzz/mobile/PushNotificationOpenPlugin.kt | 15 +++- .../kotlin/xyz/block/buzz/mobile/PushWake.kt | 5 +- .../buzz/mobile/PushWakeNotifications.kt | 23 +++-- .../block/buzz/mobile/AgeRestrictionTest.kt | 56 +++++++++++++ .../age_gate/age_signal_provider.dart | 53 ++++++++++++ .../age_gate/age_signal_push_bootstrap.dart | 27 +++--- mobile/lib/shared/push/push_bridge.dart | 9 +- .../features/age_gate/age_gate_app_test.dart | 83 ++++++++++++++----- .../age_gate/age_signal_provider_test.dart | 14 +++- mobile/test/shared/push/push_bridge_test.dart | 30 ++++--- 12 files changed, 289 insertions(+), 64 deletions(-) create mode 100644 mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/AgeRestriction.kt create mode 100644 mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/AgeRestriction.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/AgeRestriction.kt new file mode 100644 index 0000000000..35901b9fd0 --- /dev/null +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/AgeRestriction.kt @@ -0,0 +1,36 @@ +package xyz.block.buzz.mobile + +/** + * A confirmed age restriction, as push wakes see it. + * + * Like the iOS restriction session, it lives only as long as the process that + * confirmed it, and nothing is saved: a later launch starts unrestricted and + * checks again. Wakes run in the same process as the app, so while it holds + * no wake posts anything. + */ +internal object AgeRestriction { + private val lock = Any() + + // Guarded by lock. + private var restricted = false + + /** Whether a wake should be skipped without fetching anything. */ + val isRestricted: Boolean + get() = synchronized(lock) { restricted } + + /** + * Restricts, then removes what is already posted with [cancelAll]. Posting + * goes through [unlessRestricted], so nothing a wake posts outlives this. + */ + fun restrict(cancelAll: () -> Unit) = synchronized(lock) { + restricted = true + cancelAll() + } + + fun release() = synchronized(lock) { restricted = false } + + /** Runs [post] unless restricted, and never during [restrict]. */ + fun unlessRestricted(post: () -> Unit) = synchronized(lock) { + if (!restricted) post() + } +} diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt index 1e4005989a..8a4de527d0 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt @@ -155,7 +155,7 @@ class MainActivity : FlutterFragmentActivity() { identityFilePlugin = IdentityFilePlugin(this, flutterEngine.dartExecutor.binaryMessenger) browserAuthPlugin = BrowserAuthPlugin(this, flutterEngine.dartExecutor.binaryMessenger) hapticsPlugin = HapticsPlugin(this, flutterEngine.dartExecutor.binaryMessenger) - pushNotificationOpenPlugin = PushNotificationOpenPlugin(flutterEngine.dartExecutor.binaryMessenger) + pushNotificationOpenPlugin = PushNotificationOpenPlugin(this, flutterEngine.dartExecutor.binaryMessenger) .also { it.onLaunch(intent) } huddleMediaPlugin = HuddleMediaPlugin( diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushNotificationOpenPlugin.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushNotificationOpenPlugin.kt index c03c13516f..8a758bc5f1 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushNotificationOpenPlugin.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushNotificationOpenPlugin.kt @@ -1,6 +1,8 @@ package xyz.block.buzz.mobile +import android.content.Context import android.content.Intent +import androidx.core.app.NotificationManagerCompat import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MethodChannel @@ -10,8 +12,11 @@ import io.flutter.plugin.common.MethodChannel * * A tap that starts the app is held until Dart asks for it, since its handler * isn't installed yet. A tap while the app runs is delivered at once. + * + * The same channel carries the age gate's purge and restore, as on iOS. */ -internal class PushNotificationOpenPlugin(messenger: BinaryMessenger) { +internal class PushNotificationOpenPlugin(context: Context, messenger: BinaryMessenger) { + private val notifications = NotificationManagerCompat.from(context.applicationContext) private val channel = MethodChannel(messenger, "buzz/push") private var pending: Map? = null @@ -22,6 +27,14 @@ internal class PushNotificationOpenPlugin(messenger: BinaryMessenger) { result.success(pending) pending = null } + "purgeAgeRestrictedNotifications" -> { + AgeRestriction.restrict(notifications::cancelAll) + result.success(null) + } + "restoreAgeRestrictedNotifications" -> { + AgeRestriction.release() + result.success(null) + } else -> result.notImplemented() } } diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt index 985c67c062..4564ab9812 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt @@ -71,7 +71,10 @@ internal object PushWake { // Declined permission costs nothing else: nothing is fetched, so // nothing is recorded as shown, and a later grant sees new messages. val foreground = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) - if (foreground || !NotificationManagerCompat.from(context).areNotificationsEnabled()) { + // A confirmed age restriction skips the wake the same way, and also + // keeps a run already going from posting (see WakeNotifier). The log + // leaves it out: the system log must not reveal the age decision. + if (foreground || AgeRestriction.isRestricted || !NotificationManagerCompat.from(context).areNotificationsEnabled()) { Log.i(TAG, "wake ignored foreground=$foreground") handled.countDown() return diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt index 568e9bfa31..7135816801 100644 --- a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt +++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt @@ -181,7 +181,7 @@ internal class WakeNotifier(private val context: Context) { if (silent) NotificationCompat.GROUP_ALERT_SUMMARY else NotificationCompat.GROUP_ALERT_ALL, ) .build() - manager.notify(tag, CONVERSATION_ID, notification) + AgeRestriction.unlessRestricted { manager.notify(tag, CONVERSATION_ID, notification) } } } @@ -193,18 +193,15 @@ internal class WakeNotifier(private val context: Context) { ?: throw IllegalStateException("No launch intent"), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) - manager.notify( - GENERIC_TAG, - GENERIC_ID, - NotificationCompat.Builder(context, OTHER_CHANNEL) - .setSmallIcon(R.drawable.ic_stat_buzz) - .setContentTitle(context.getString(R.string.app_name)) - .setContentText(context.getString(R.string.notification_new_activity)) - .setCategory(NotificationCompat.CATEGORY_MESSAGE) - .setAutoCancel(true) - .setContentIntent(tap) - .build(), - ) + val notification = NotificationCompat.Builder(context, OTHER_CHANNEL) + .setSmallIcon(R.drawable.ic_stat_buzz) + .setContentTitle(context.getString(R.string.app_name)) + .setContentText(context.getString(R.string.notification_new_activity)) + .setCategory(NotificationCompat.CATEGORY_MESSAGE) + .setAutoCancel(true) + .setContentIntent(tap) + .build() + AgeRestriction.unlessRestricted { manager.notify(GENERIC_TAG, GENERIC_ID, notification) } } fun cancelGeneric() = manager.cancel(GENERIC_TAG, GENERIC_ID) diff --git a/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt b/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt new file mode 100644 index 0000000000..ee37a7abc8 --- /dev/null +++ b/mobile/android/app/src/test/kotlin/xyz/block/buzz/mobile/AgeRestrictionTest.kt @@ -0,0 +1,56 @@ +package xyz.block.buzz.mobile + +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class AgeRestrictionTest { + @AfterTest + fun release() = AgeRestriction.release() + + @Test + fun restrictionCancelsPostedNotificationsAndBlocksPostingUntilReleased() { + val posted = mutableListOf() + AgeRestriction.unlessRestricted { posted += "before" } + + AgeRestriction.restrict { posted.clear() } + AgeRestriction.unlessRestricted { posted += "restricted" } + + assertTrue(AgeRestriction.isRestricted) + assertEquals(emptyList(), posted) + + AgeRestriction.release() + AgeRestriction.unlessRestricted { posted += "released" } + + assertFalse(AgeRestriction.isRestricted) + assertEquals(listOf("released"), posted) + } + + @Test + fun postingInProgressFinishesBeforeRestrictionCancels() { + val events = mutableListOf() + val posting = java.util.concurrent.CountDownLatch(1) + val restricting = Thread { + posting.await() + AgeRestriction.restrict { events += "cancelAll" } + } + restricting.start() + + AgeRestriction.unlessRestricted { + posting.countDown() + // Post only once the restricting thread waits for this one, or has + // finished because nothing made it wait. + val deadline = System.nanoTime() + 5_000_000_000L + while (restricting.state != Thread.State.BLOCKED && restricting.isAlive) { + check(System.nanoTime() < deadline) { "restrict neither waited nor finished" } + Thread.yield() + } + events += "post" + } + restricting.join() + + assertEquals(listOf("post", "cancelAll"), events) + } +} diff --git a/mobile/lib/features/age_gate/age_signal_provider.dart b/mobile/lib/features/age_gate/age_signal_provider.dart index 59c262713d..6f8118dba9 100644 --- a/mobile/lib/features/age_gate/age_signal_provider.dart +++ b/mobile/lib/features/age_gate/age_signal_provider.dart @@ -4,6 +4,8 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import '../../shared/push/push_bridge.dart'; + const ageSignalChannel = MethodChannel('buzz/age_signal'); /// Maximum lifetime of a launch age check. Access never waits for this timer. @@ -27,6 +29,18 @@ bool shouldBlockForAgeSignal(Map response) { return upper is int && upper >= 0 && upper < 18; } +/// Native notification purge performed once restriction is confirmed. +final ageRestrictedNotificationPurgerProvider = + Provider Function()>( + (ref) => purgeAgeRestrictedBuzzNotifications, + ); + +/// Releases only the current process's confirmed notification restriction. +final ageAllowedNotificationRestorerProvider = + Provider Function()>( + (ref) => restoreAgeRestrictedBuzzNotifications, + ); + /// Access decision, independent of whether a platform check has completed. enum AgeSignalState { allowed, restricted } @@ -41,6 +55,7 @@ class AgeSignalNotifier extends Notifier { final AgeSignalRequest _requestSignal; final Duration _requestTimeout; Future? _attempt; + Future? _confirmedPurge; int _generation = 0; @override @@ -49,6 +64,7 @@ class AgeSignalNotifier extends Notifier { // later. A new provider lifecycle starts allowed, without cached denial. _generation += 1; _attempt = null; + _confirmedPurge = null; ref.onDispose(() => _generation += 1); return AgeSignalState.allowed; } @@ -56,6 +72,14 @@ class AgeSignalNotifier extends Notifier { /// Checks once. Failure ends the attempt; neither retry nor cleanup gates UI. Future request() => _attempt ??= _check(++_generation); + /// Hands over, once, the purge started when restriction was confirmed. + /// Completes with whether it succeeded; its error is already reported. + Future? takeConfirmedPurge() { + final purge = _confirmedPurge; + _confirmedPurge = null; + return purge; + } + Future _check(int generation) async { try { final response = await Future.sync( @@ -67,6 +91,19 @@ class AgeSignalNotifier extends Notifier { _generation += 1; if (response != null && shouldBlockForAgeSignal(response)) { state = AgeSignalState.restricted; + // The check can answer while Buzz is in the background, where no + // frame mounts the push cleanup until the user returns. Purge now, + // so wakes stop posting at once; the cleanup retries a failure. + _confirmedPurge = + Future.sync(ref.read(ageRestrictedNotificationPurgerProvider)).then( + (_) => true, + onError: (Object error, StackTrace stackTrace) { + reportPushLeaseCleanupError(error, stackTrace); + return false; + }, + ); + } else { + _releaseNativeRestriction(); } } catch (error) { if (generation != _generation) return; @@ -76,8 +113,24 @@ class AgeSignalNotifier extends Notifier { debugPrint( 'Age check unavailable (${error.runtimeType}); access allowed.', ); + _releaseNativeRestriction(); } } + + /// On Android a confirmed restriction lives in the process, which can + /// outlive this engine: reopening Buzz builds a new notifier that starts + /// allowed. So only a check that finishes here without restricting lifts + /// it, never the initial allowed state. iOS restores from the push + /// bootstrap instead. + void _releaseNativeRestriction() { + if (defaultTargetPlatform != TargetPlatform.android) return; + unawaited( + Future.sync(ref.read(ageAllowedNotificationRestorerProvider)).catchError( + (Object error, StackTrace stackTrace) => + reportPushLeaseCleanupError(error, stackTrace), + ), + ); + } } /// Explicit pre-release testing opt-in. Production builds keep enforcement disabled. diff --git a/mobile/lib/features/age_gate/age_signal_push_bootstrap.dart b/mobile/lib/features/age_gate/age_signal_push_bootstrap.dart index 281ce3c766..6a162b9a29 100644 --- a/mobile/lib/features/age_gate/age_signal_push_bootstrap.dart +++ b/mobile/lib/features/age_gate/age_signal_push_bootstrap.dart @@ -35,18 +35,6 @@ final ageSignalPushSnapshotRetryWaitProvider = return Future.delayed; }); -/// Releases only the current process's confirmed notification restriction. -final ageAllowedNotificationRestorerProvider = - Provider Function()>( - (ref) => restoreAgeRestrictedBuzzNotifications, - ); - -/// Native notification purge performed once restriction is confirmed. -final ageRestrictedNotificationPurgerProvider = - Provider Function()>( - (ref) => purgeAgeRestrictedBuzzNotifications, - ); - /// Delay between successful maintenance purges while restriction remains active. const ageRestrictedNotificationMaintenanceDelay = Duration(seconds: 30); @@ -91,7 +79,13 @@ class AgeSignalPushBootstrap extends HookConsumerWidget { previousState.value = state; consecutiveFailures.value = 0; } - if (state == AgeSignalState.restricted) return null; + // On Android the age check itself releases the restriction once it + // finishes allowed (see AgeSignalNotifier). Restoring here would lift a + // restriction the process still holds from an earlier engine. + if (state == AgeSignalState.restricted || + defaultTargetPlatform == TargetPlatform.android) { + return null; + } var cancelled = false; unawaited(() async { try { @@ -156,7 +150,12 @@ class _AgeRestrictedPushCleanup extends HookConsumerWidget { VoidCallback? cancelMaintenancePurge; unawaited(() async { try { - await purgeNotifications(); + final confirmed = ref + .read(ageSignalProvider.notifier) + .takeConfirmedPurge(); + final needsPurge = confirmed == null || !await confirmed; + if (cancelled) return; + if (needsPurge) await purgeNotifications(); consecutivePurgeFailures.value = 0; if (!cancelled && remainingMaintenancePurges.value > 0) { remainingMaintenancePurges.value -= 1; diff --git a/mobile/lib/shared/push/push_bridge.dart b/mobile/lib/shared/push/push_bridge.dart index b36f868196..a41bfd44cd 100644 --- a/mobile/lib/shared/push/push_bridge.dart +++ b/mobile/lib/shared/push/push_bridge.dart @@ -530,15 +530,20 @@ void reportPushLeaseCleanupError(Object error, StackTrace stackTrace) { debugPrintStack(stackTrace: stackTrace); } +/// Platforms whose native push code honors a confirmed age restriction. +bool get _ageRestrictionPlatform => + defaultTargetPlatform == TargetPlatform.iOS || + defaultTargetPlatform == TargetPlatform.android; + /// Restores notification presentation without reading community storage. Future restoreAgeRestrictedBuzzNotifications() async { - if (defaultTargetPlatform != TargetPlatform.iOS) return; + if (!_ageRestrictionPlatform) return; await _channel.invokeMethod('restoreAgeRestrictedNotifications'); } /// Removes notifications rendered before a confirmed age restriction. Future purgeAgeRestrictedBuzzNotifications() async { - if (defaultTargetPlatform != TargetPlatform.iOS) return; + if (!_ageRestrictionPlatform) return; await _channel.invokeMethod('purgeAgeRestrictedNotifications'); } diff --git a/mobile/test/features/age_gate/age_gate_app_test.dart b/mobile/test/features/age_gate/age_gate_app_test.dart index 723aa677e5..eae110accc 100644 --- a/mobile/test/features/age_gate/age_gate_app_test.dart +++ b/mobile/test/features/age_gate/age_gate_app_test.dart @@ -290,15 +290,21 @@ void main() { await tester.pump(); expect(snapshotRestorations, 2); }, + // iOS restores from the push bootstrap, retrying a failure. + variant: TargetPlatformVariant.only(TargetPlatform.iOS), ); for (final outcome in ['minor', 'adult', 'error', 'malformed', 'timeout']) { testWidgets('normal app and push start before native $outcome result', ( tester, ) async { + // On Android only a check that finishes allowed releases the native + // restriction, which a live process may still hold from an earlier + // engine; the first, still-pending build releases nothing. final response = Completer(); var requests = 0; var restrictions = 0; + var restores = 0; final relaySession = _CountingRelaySessionNotifier(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(ageSignalChannel, (_) { @@ -317,7 +323,7 @@ void main() { AgeSignalNotifier(requestTimeout: const Duration(seconds: 1)), ), ageAllowedNotificationRestorerProvider.overrideWithValue( - () async {}, + () async => restores++, ), ageRestrictedNotificationPurgerProvider.overrideWithValue(() async { restrictions++; @@ -332,6 +338,7 @@ void main() { expect(find.byType(BuzzPushBootstrap), findsOneWidget); expect(relaySession.builds, 1); expect(requests, 1); + expect(restores, 0); if (outcome == 'timeout') { await tester.pump(const Duration(seconds: 2)); @@ -350,6 +357,7 @@ void main() { await tester.pump(); final restricted = outcome == 'minor'; expect(restrictions, restricted ? 1 : 0); + expect(restores, restricted ? 0 : 1); expect( find.byType(AgeRestrictionPage), restricted ? findsOneWidget : findsNothing, @@ -361,7 +369,7 @@ void main() { ); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); - }); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); } testWidgets( @@ -392,31 +400,68 @@ void main() { testWidgets('retries a failed restricted notification purge', (tester) async { var purges = 0; + final firstPurge = Completer(); + final container = ProviderContainer( + overrides: [ + ageSignalProvider.overrideWith( + () => AgeSignalNotifier( + requestSignal: () async => {'status': 'signal', 'ageUpper': 17}, + ), + ), + communityListProvider.overrideWith( + () => _UnavailableCommunityListNotifier(), + ), + ageAllowedNotificationRestorerProvider.overrideWithValue(() async {}), + ageRestrictedNotificationPurgerProvider.overrideWithValue(() { + purges += 1; + return switch (purges) { + 1 => firstPurge.future, + 2 => Future.error( + StateError('injected notification purge failure'), + ), + _ => Future.value(), + }; + }), + ageRestrictedNotificationMaintenanceScheduleProvider.overrideWithValue( + (_) => () {}, + ), + ageSignalPushSnapshotRetryWaitProvider.overrideWithValue((_) async {}), + ], + ); + addTearDown(container.dispose); + await container.read(ageSignalProvider.notifier).request(); + expect(container.read(ageSignalProvider), AgeSignalState.restricted); await tester.pumpWidget( - ProviderScope( - overrides: [ - ageSignalProvider.overrideWith(() => _BlockingAgeSignalNotifier()), - communityListProvider.overrideWith( - () => _UnavailableCommunityListNotifier(), - ), - ageRestrictedNotificationPurgerProvider.overrideWithValue(() async { - purges += 1; - if (purges == 1) { - throw StateError('injected notification purge failure'); - } - }), - ageSignalPushSnapshotRetryWaitProvider.overrideWithValue( - (_) async {}, - ), - ], + UncontrolledProviderScope( + container: container, child: const AgeSignalPushBootstrap(child: SizedBox()), ), ); await tester.pump(); + expect(purges, 1); + + // A resume while the confirmed purge is still running retires the effect + // waiting on it. The new effect purges, fails once and retries. + for (final state in [ + AppLifecycleState.inactive, + AppLifecycleState.hidden, + AppLifecycleState.paused, + AppLifecycleState.hidden, + AppLifecycleState.inactive, + AppLifecycleState.resumed, + ]) { + tester.binding.handleAppLifecycleStateChanged(state); + } + await tester.pump(); + await tester.pump(); + expect(purges, 3); + + firstPurge.completeError(StateError('injected notification purge failure')); + await tester.pump(); await tester.pump(); - expect(purges, 2); + expect(purges, 3); }); testWidgets( diff --git a/mobile/test/features/age_gate/age_signal_provider_test.dart b/mobile/test/features/age_gate/age_signal_provider_test.dart index 688475fd03..990b824be7 100644 --- a/mobile/test/features/age_gate/age_signal_provider_test.dart +++ b/mobile/test/features/age_gate/age_signal_provider_test.dart @@ -12,10 +12,16 @@ void main() { .setMockMethodCallHandler(ageSignalChannel, null); }); + var purges = 0; + setUp(() => purges = 0); + ProviderContainer enabledContainer({AgeSignalNotifier Function()? create}) { final container = ProviderContainer( overrides: [ ageSignalProvider.overrideWith(create ?? AgeSignalNotifier.new), + ageRestrictedNotificationPurgerProvider.overrideWithValue(() async { + purges += 1; + }), ], ); addTearDown(container.dispose); @@ -52,12 +58,14 @@ void main() { final container = enabledContainer(); expect(container.read(ageSignalProvider), AgeSignalState.allowed); await container.read(ageSignalProvider.notifier).request(); + final restricted = upper >= 0 && upper < 18; expect( container.read(ageSignalProvider), - upper >= 0 && upper < 18 - ? AgeSignalState.restricted - : AgeSignalState.allowed, + restricted ? AgeSignalState.restricted : AgeSignalState.allowed, ); + // With no widget or frame at all: an answer that arrives in the + // background must stop wakes from posting at once. + expect(purges, restricted ? 1 : 0); }); } diff --git a/mobile/test/shared/push/push_bridge_test.dart b/mobile/test/shared/push/push_bridge_test.dart index 5bff882310..7d7eb6aebb 100644 --- a/mobile/test/shared/push/push_bridge_test.dart +++ b/mobile/test/shared/push/push_bridge_test.dart @@ -61,17 +61,27 @@ void main() { }, ); - test('purges notifications delivered before age restriction', () async { - debugDefaultTargetPlatformOverride = TargetPlatform.iOS; - TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger - .setMockMethodCallHandler(_channel, (call) async { - expect(call.method, 'purgeAgeRestrictedNotifications'); - expect(call.arguments, isNull); - return null; - }); + for (final platform in [TargetPlatform.iOS, TargetPlatform.android]) { + test('purges and restores age-restricted notifications on ' + '${platform.name}', () async { + debugDefaultTargetPlatformOverride = platform; + final methods = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, (call) async { + methods.add(call.method); + expect(call.arguments, isNull); + return null; + }); - await purgeAgeRestrictedBuzzNotifications(); - }); + await purgeAgeRestrictedBuzzNotifications(); + await restoreAgeRestrictedBuzzNotifications(); + + expect(methods, [ + 'purgeAgeRestrictedNotifications', + 'restoreAgeRestrictedNotifications', + ]); + }); + } test('reads and exposes persisted endpoint grants on iOS', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS;