Skip to content

Commit 2f1be86

Browse files
browstudio
andauthored
Apply a confirmed age restriction to Android push wakes (#9925)
Follow-up to [#9804 handle Android push wakes](#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>
1 parent 9bddaa1 commit 2f1be86

12 files changed

Lines changed: 289 additions & 64 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package xyz.block.buzz.mobile
2+
3+
/**
4+
* A confirmed age restriction, as push wakes see it.
5+
*
6+
* Like the iOS restriction session, it lives only as long as the process that
7+
* confirmed it, and nothing is saved: a later launch starts unrestricted and
8+
* checks again. Wakes run in the same process as the app, so while it holds
9+
* no wake posts anything.
10+
*/
11+
internal object AgeRestriction {
12+
private val lock = Any()
13+
14+
// Guarded by lock.
15+
private var restricted = false
16+
17+
/** Whether a wake should be skipped without fetching anything. */
18+
val isRestricted: Boolean
19+
get() = synchronized(lock) { restricted }
20+
21+
/**
22+
* Restricts, then removes what is already posted with [cancelAll]. Posting
23+
* goes through [unlessRestricted], so nothing a wake posts outlives this.
24+
*/
25+
fun restrict(cancelAll: () -> Unit) = synchronized(lock) {
26+
restricted = true
27+
cancelAll()
28+
}
29+
30+
fun release() = synchronized(lock) { restricted = false }
31+
32+
/** Runs [post] unless restricted, and never during [restrict]. */
33+
fun unlessRestricted(post: () -> Unit) = synchronized(lock) {
34+
if (!restricted) post()
35+
}
36+
}

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/MainActivity.kt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ class MainActivity : FlutterFragmentActivity() {
155155
identityFilePlugin = IdentityFilePlugin(this, flutterEngine.dartExecutor.binaryMessenger)
156156
browserAuthPlugin = BrowserAuthPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
157157
hapticsPlugin = HapticsPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
158-
pushNotificationOpenPlugin = PushNotificationOpenPlugin(flutterEngine.dartExecutor.binaryMessenger)
158+
pushNotificationOpenPlugin = PushNotificationOpenPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
159159
.also { it.onLaunch(intent) }
160160

161161
huddleMediaPlugin = HuddleMediaPlugin(

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushNotificationOpenPlugin.kt‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package xyz.block.buzz.mobile
22

3+
import android.content.Context
34
import android.content.Intent
5+
import androidx.core.app.NotificationManagerCompat
46
import io.flutter.plugin.common.BinaryMessenger
57
import io.flutter.plugin.common.MethodChannel
68

@@ -10,8 +12,11 @@ import io.flutter.plugin.common.MethodChannel
1012
*
1113
* A tap that starts the app is held until Dart asks for it, since its handler
1214
* isn't installed yet. A tap while the app runs is delivered at once.
15+
*
16+
* The same channel carries the age gate's purge and restore, as on iOS.
1317
*/
14-
internal class PushNotificationOpenPlugin(messenger: BinaryMessenger) {
18+
internal class PushNotificationOpenPlugin(context: Context, messenger: BinaryMessenger) {
19+
private val notifications = NotificationManagerCompat.from(context.applicationContext)
1520
private val channel = MethodChannel(messenger, "buzz/push")
1621
private var pending: Map<String, String>? = null
1722

@@ -22,6 +27,14 @@ internal class PushNotificationOpenPlugin(messenger: BinaryMessenger) {
2227
result.success(pending)
2328
pending = null
2429
}
30+
"purgeAgeRestrictedNotifications" -> {
31+
AgeRestriction.restrict(notifications::cancelAll)
32+
result.success(null)
33+
}
34+
"restoreAgeRestrictedNotifications" -> {
35+
AgeRestriction.release()
36+
result.success(null)
37+
}
2538
else -> result.notImplemented()
2639
}
2740
}

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWake.kt‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ internal object PushWake {
7171
// Declined permission costs nothing else: nothing is fetched, so
7272
// nothing is recorded as shown, and a later grant sees new messages.
7373
val foreground = ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
74-
if (foreground || !NotificationManagerCompat.from(context).areNotificationsEnabled()) {
74+
// A confirmed age restriction skips the wake the same way, and also
75+
// keeps a run already going from posting (see WakeNotifier). The log
76+
// leaves it out: the system log must not reveal the age decision.
77+
if (foreground || AgeRestriction.isRestricted || !NotificationManagerCompat.from(context).areNotificationsEnabled()) {
7578
Log.i(TAG, "wake ignored foreground=$foreground")
7679
handled.countDown()
7780
return

‎mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushWakeNotifications.kt‎

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ internal class WakeNotifier(private val context: Context) {
181181
if (silent) NotificationCompat.GROUP_ALERT_SUMMARY else NotificationCompat.GROUP_ALERT_ALL,
182182
)
183183
.build()
184-
manager.notify(tag, CONVERSATION_ID, notification)
184+
AgeRestriction.unlessRestricted { manager.notify(tag, CONVERSATION_ID, notification) }
185185
}
186186
}
187187

@@ -193,18 +193,15 @@ internal class WakeNotifier(private val context: Context) {
193193
?: throw IllegalStateException("No launch intent"),
194194
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
195195
)
196-
manager.notify(
197-
GENERIC_TAG,
198-
GENERIC_ID,
199-
NotificationCompat.Builder(context, OTHER_CHANNEL)
200-
.setSmallIcon(R.drawable.ic_stat_buzz)
201-
.setContentTitle(context.getString(R.string.app_name))
202-
.setContentText(context.getString(R.string.notification_new_activity))
203-
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
204-
.setAutoCancel(true)
205-
.setContentIntent(tap)
206-
.build(),
207-
)
196+
val notification = NotificationCompat.Builder(context, OTHER_CHANNEL)
197+
.setSmallIcon(R.drawable.ic_stat_buzz)
198+
.setContentTitle(context.getString(R.string.app_name))
199+
.setContentText(context.getString(R.string.notification_new_activity))
200+
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
201+
.setAutoCancel(true)
202+
.setContentIntent(tap)
203+
.build()
204+
AgeRestriction.unlessRestricted { manager.notify(GENERIC_TAG, GENERIC_ID, notification) }
208205
}
209206

210207
fun cancelGeneric() = manager.cancel(GENERIC_TAG, GENERIC_ID)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package xyz.block.buzz.mobile
2+
3+
import kotlin.test.AfterTest
4+
import kotlin.test.Test
5+
import kotlin.test.assertEquals
6+
import kotlin.test.assertFalse
7+
import kotlin.test.assertTrue
8+
9+
class AgeRestrictionTest {
10+
@AfterTest
11+
fun release() = AgeRestriction.release()
12+
13+
@Test
14+
fun restrictionCancelsPostedNotificationsAndBlocksPostingUntilReleased() {
15+
val posted = mutableListOf<String>()
16+
AgeRestriction.unlessRestricted { posted += "before" }
17+
18+
AgeRestriction.restrict { posted.clear() }
19+
AgeRestriction.unlessRestricted { posted += "restricted" }
20+
21+
assertTrue(AgeRestriction.isRestricted)
22+
assertEquals(emptyList(), posted)
23+
24+
AgeRestriction.release()
25+
AgeRestriction.unlessRestricted { posted += "released" }
26+
27+
assertFalse(AgeRestriction.isRestricted)
28+
assertEquals(listOf("released"), posted)
29+
}
30+
31+
@Test
32+
fun postingInProgressFinishesBeforeRestrictionCancels() {
33+
val events = mutableListOf<String>()
34+
val posting = java.util.concurrent.CountDownLatch(1)
35+
val restricting = Thread {
36+
posting.await()
37+
AgeRestriction.restrict { events += "cancelAll" }
38+
}
39+
restricting.start()
40+
41+
AgeRestriction.unlessRestricted {
42+
posting.countDown()
43+
// Post only once the restricting thread waits for this one, or has
44+
// finished because nothing made it wait.
45+
val deadline = System.nanoTime() + 5_000_000_000L
46+
while (restricting.state != Thread.State.BLOCKED && restricting.isAlive) {
47+
check(System.nanoTime() < deadline) { "restrict neither waited nor finished" }
48+
Thread.yield()
49+
}
50+
events += "post"
51+
}
52+
restricting.join()
53+
54+
assertEquals(listOf("post", "cancelAll"), events)
55+
}
56+
}

‎mobile/lib/features/age_gate/age_signal_provider.dart‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import 'package:flutter/foundation.dart';
44
import 'package:flutter/services.dart';
55
import 'package:hooks_riverpod/hooks_riverpod.dart';
66

7+
import '../../shared/push/push_bridge.dart';
8+
79
const ageSignalChannel = MethodChannel('buzz/age_signal');
810

911
/// Maximum lifetime of a launch age check. Access never waits for this timer.
@@ -27,6 +29,18 @@ bool shouldBlockForAgeSignal(Map<Object?, Object?> response) {
2729
return upper is int && upper >= 0 && upper < 18;
2830
}
2931

32+
/// Native notification purge performed once restriction is confirmed.
33+
final ageRestrictedNotificationPurgerProvider =
34+
Provider<Future<void> Function()>(
35+
(ref) => purgeAgeRestrictedBuzzNotifications,
36+
);
37+
38+
/// Releases only the current process's confirmed notification restriction.
39+
final ageAllowedNotificationRestorerProvider =
40+
Provider<Future<void> Function()>(
41+
(ref) => restoreAgeRestrictedBuzzNotifications,
42+
);
43+
3044
/// Access decision, independent of whether a platform check has completed.
3145
enum AgeSignalState { allowed, restricted }
3246

@@ -41,6 +55,7 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
4155
final AgeSignalRequest _requestSignal;
4256
final Duration _requestTimeout;
4357
Future<void>? _attempt;
58+
Future<bool>? _confirmedPurge;
4459
int _generation = 0;
4560

4661
@override
@@ -49,13 +64,22 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
4964
// later. A new provider lifecycle starts allowed, without cached denial.
5065
_generation += 1;
5166
_attempt = null;
67+
_confirmedPurge = null;
5268
ref.onDispose(() => _generation += 1);
5369
return AgeSignalState.allowed;
5470
}
5571

5672
/// Checks once. Failure ends the attempt; neither retry nor cleanup gates UI.
5773
Future<void> request() => _attempt ??= _check(++_generation);
5874

75+
/// Hands over, once, the purge started when restriction was confirmed.
76+
/// Completes with whether it succeeded; its error is already reported.
77+
Future<bool>? takeConfirmedPurge() {
78+
final purge = _confirmedPurge;
79+
_confirmedPurge = null;
80+
return purge;
81+
}
82+
5983
Future<void> _check(int generation) async {
6084
try {
6185
final response = await Future.sync(
@@ -67,6 +91,19 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
6791
_generation += 1;
6892
if (response != null && shouldBlockForAgeSignal(response)) {
6993
state = AgeSignalState.restricted;
94+
// The check can answer while Buzz is in the background, where no
95+
// frame mounts the push cleanup until the user returns. Purge now,
96+
// so wakes stop posting at once; the cleanup retries a failure.
97+
_confirmedPurge =
98+
Future.sync(ref.read(ageRestrictedNotificationPurgerProvider)).then(
99+
(_) => true,
100+
onError: (Object error, StackTrace stackTrace) {
101+
reportPushLeaseCleanupError(error, stackTrace);
102+
return false;
103+
},
104+
);
105+
} else {
106+
_releaseNativeRestriction();
70107
}
71108
} catch (error) {
72109
if (generation != _generation) return;
@@ -76,8 +113,24 @@ class AgeSignalNotifier extends Notifier<AgeSignalState> {
76113
debugPrint(
77114
'Age check unavailable (${error.runtimeType}); access allowed.',
78115
);
116+
_releaseNativeRestriction();
79117
}
80118
}
119+
120+
/// On Android a confirmed restriction lives in the process, which can
121+
/// outlive this engine: reopening Buzz builds a new notifier that starts
122+
/// allowed. So only a check that finishes here without restricting lifts
123+
/// it, never the initial allowed state. iOS restores from the push
124+
/// bootstrap instead.
125+
void _releaseNativeRestriction() {
126+
if (defaultTargetPlatform != TargetPlatform.android) return;
127+
unawaited(
128+
Future.sync(ref.read(ageAllowedNotificationRestorerProvider)).catchError(
129+
(Object error, StackTrace stackTrace) =>
130+
reportPushLeaseCleanupError(error, stackTrace),
131+
),
132+
);
133+
}
81134
}
82135

83136
/// Explicit pre-release testing opt-in. Production builds keep enforcement disabled.

‎mobile/lib/features/age_gate/age_signal_push_bootstrap.dart‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,18 +35,6 @@ final ageSignalPushSnapshotRetryWaitProvider =
3535
return Future<void>.delayed;
3636
});
3737

38-
/// Releases only the current process's confirmed notification restriction.
39-
final ageAllowedNotificationRestorerProvider =
40-
Provider<Future<void> Function()>(
41-
(ref) => restoreAgeRestrictedBuzzNotifications,
42-
);
43-
44-
/// Native notification purge performed once restriction is confirmed.
45-
final ageRestrictedNotificationPurgerProvider =
46-
Provider<Future<void> Function()>(
47-
(ref) => purgeAgeRestrictedBuzzNotifications,
48-
);
49-
5038
/// Delay between successful maintenance purges while restriction remains active.
5139
const ageRestrictedNotificationMaintenanceDelay = Duration(seconds: 30);
5240

@@ -91,7 +79,13 @@ class AgeSignalPushBootstrap extends HookConsumerWidget {
9179
previousState.value = state;
9280
consecutiveFailures.value = 0;
9381
}
94-
if (state == AgeSignalState.restricted) return null;
82+
// On Android the age check itself releases the restriction once it
83+
// finishes allowed (see AgeSignalNotifier). Restoring here would lift a
84+
// restriction the process still holds from an earlier engine.
85+
if (state == AgeSignalState.restricted ||
86+
defaultTargetPlatform == TargetPlatform.android) {
87+
return null;
88+
}
9589
var cancelled = false;
9690
unawaited(() async {
9791
try {
@@ -156,7 +150,12 @@ class _AgeRestrictedPushCleanup extends HookConsumerWidget {
156150
VoidCallback? cancelMaintenancePurge;
157151
unawaited(() async {
158152
try {
159-
await purgeNotifications();
153+
final confirmed = ref
154+
.read(ageSignalProvider.notifier)
155+
.takeConfirmedPurge();
156+
final needsPurge = confirmed == null || !await confirmed;
157+
if (cancelled) return;
158+
if (needsPurge) await purgeNotifications();
160159
consecutivePurgeFailures.value = 0;
161160
if (!cancelled && remainingMaintenancePurges.value > 0) {
162161
remainingMaintenancePurges.value -= 1;

‎mobile/lib/shared/push/push_bridge.dart‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -530,15 +530,20 @@ void reportPushLeaseCleanupError(Object error, StackTrace stackTrace) {
530530
debugPrintStack(stackTrace: stackTrace);
531531
}
532532

533+
/// Platforms whose native push code honors a confirmed age restriction.
534+
bool get _ageRestrictionPlatform =>
535+
defaultTargetPlatform == TargetPlatform.iOS ||
536+
defaultTargetPlatform == TargetPlatform.android;
537+
533538
/// Restores notification presentation without reading community storage.
534539
Future<void> restoreAgeRestrictedBuzzNotifications() async {
535-
if (defaultTargetPlatform != TargetPlatform.iOS) return;
540+
if (!_ageRestrictionPlatform) return;
536541
await _channel.invokeMethod<void>('restoreAgeRestrictedNotifications');
537542
}
538543

539544
/// Removes notifications rendered before a confirmed age restriction.
540545
Future<void> purgeAgeRestrictedBuzzNotifications() async {
541-
if (defaultTargetPlatform != TargetPlatform.iOS) return;
546+
if (!_ageRestrictionPlatform) return;
542547
await _channel.invokeMethod<void>('purgeAgeRestrictedNotifications');
543548
}
544549

0 commit comments

Comments
 (0)