mirror of
https://github.com/block/buzz.git
synced 2026-11-27 11:41:21 +00:00
feat(mobile): enroll Android devices for push (#9811)
## Summary Ticket 7 of the [Android push plan](https://github.com/block/buzz/blob/main/PLANS/ANDROID_PUSH.md). Android phones can now enroll with the push gateway and publish a relay lease, through the same shared push layer iOS uses. The wake handling side is ticket 6, [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804). - The phone gets an FCM token, then generates a sign-only P-256 Keystore key whose attestation challenge is the SHA-256 of the enrollment transcript. The chain goes to the gateway at enrollment. Every later installation call (delegate, rotate endpoint, revoke delegation, revoke installation) is signed with that key over the transcript bytes the gateway builds. - A rotated FCM token rotates the endpoint. Signing out revokes the delegation and the installation. The first enrollment waits a short random time. - Android 13+ asks for the notification permission at the same point iOS does. Declining keeps the app working. - A phone that cannot attest (no hardware attestation, unlocked bootloader, unlisted boot key) keeps working, and Settings says push is unavailable on this phone. - The relay lease keeps the fixed `transport` value iOS sends. - Firebase config is the same build-time setting [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804) adds: four `BUZZ_FIREBASE_*` environment variables become the string resources Firebase reads. Nothing is committed, and builds without them still work (push reports unavailable). The Gradle hunks (permission, config block, `firebase-messaging` dependency) are copied from that PR verbatim so the two merge cleanly, including its `lifecycle-process` line, which this PR does not use. - The token and permission calls use their own `buzz/push_registration` channel, because Android's notification-open handler from that PR already owns `buzz/push` and a channel has one native handler. - The gateway gets an `enroll_android` transcript vector so Dart and Rust agree on the exact bytes. Enrollment state is journaled before each network attempt, so a lost response resumes with byte-identical requests instead of leaving an orphaned installation. ### Related issue None found. Builds on [#9560 enroll Android installations](https://github.com/block/buzz/pull/9560) and [#9562 verify Key Attestation](https://github.com/block/buzz/pull/9562). ### Validation Journey tests cover first enrollment, a second relay, reuse and renewal, lost responses, token rotation, an installation the gateway dropped, a lost Keystore key, a phone that cannot attest, and sign-out revocation, against a fake gateway that keeps the real gateway's semantics. Transcripts replay the shared vectors byte for byte. A settings journey checks the Notifications row and the unavailable row on Android, and a resume table checks the FCM token refresh: it runs while the relay reconnects, but not when push is off or the relay doesn't offer push. On a physical Pixel 9a (debug build, a local test gateway on a local Postgres, reached over `adb reverse`), the real Keystore key and hardware attestation chain enrolled and delegated, and the gateway accepted the attestation. The same session then ran: a signed delivery authorized against the delegation, endpoint rotation and re-delegation at the next epoch, rotating back, delegation revocation, installation revocation, and re-enrolling the same FCM token afterwards. The notification prompt appears when registration starts, before the token is fetched: <img src="https://github.com/user-attachments/assets/2aed92fe-20c1-4658-b990-51c3f3c96120" width="270" alt="Android notification permission prompt"> Not validated on the device: the FCM wake itself (the local gateway has no credentials to call FCM, so the delivery was authorized and then failed at the FCM hop), lease publication to a relay, and the in-app unavailable row, which only the widget tests exercise. A relay-backed run needs a signed-in test community on the phone. ### Settings while turning off Turning notifications off sends a relay tombstone. Until the relay accepts it, the row now says so, on both platforms. An Android build without a gateway also keeps a saved opt-in visible so it can still be turned off; once off, the row goes away. These are rendered from the Settings journey test. | | Before | After | |---|---|---| | Android build without a gateway, saved opt-in | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--01-before-config-less.png" width="270" alt="Before: no Notifications row"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--02-after-config-less.png" width="270" alt="After: Notifications row with the switch on"> | | After turning off, relay has not accepted yet | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--03-before-turning-off.png" width="270" alt="Before: plain off switch"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--04-after-turning-off.png" width="270" alt="After: Turning off. Notifications may continue until this finishes."> | ### Regressions - iOS enrollment is unchanged: the shared bridge only branches to the Dart authority on Android. iOS gains the pending opt-out subtitle, and its opt-out now also tombstones after a gateway change using the saved lease id. - The Android app gains the `firebase-messaging` dependency and a `POST_NOTIFICATIONS` permission. Backups exclude the push preferences file. ### Known limits - An FCM token rotation while the app is running is picked up on the next resume or launch, because the wake service owns the single messaging service. It could call into the registration plugin once both Android push PRs merge. - After an endpoint rotation, only the active community's lease is republished. Other enabled communities' grants are void until each is opened, the same way their leases lapse at grant expiry today. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
@@ -43,6 +43,26 @@ fun isValidPushGatewayOrigin(value: String, requireHttps: Boolean): Boolean {
|
||||
(if (requireHttps) uri.port == -1 else uri.port == -1 || uri.port in 1..65535)
|
||||
}
|
||||
|
||||
// Firebase Cloud Messaging is configured per distributor at build time and
|
||||
// nothing is committed. Supply all four values from the distributor's Firebase
|
||||
// project (its Android app's settings), or none: a build without them has no
|
||||
// push wake and everything else works.
|
||||
val firebaseValues =
|
||||
mapOf(
|
||||
"google_app_id" to providers.environmentVariable("BUZZ_FIREBASE_APP_ID").orNull,
|
||||
"google_api_key" to providers.environmentVariable("BUZZ_FIREBASE_API_KEY").orNull,
|
||||
"project_id" to providers.environmentVariable("BUZZ_FIREBASE_PROJECT_ID").orNull,
|
||||
"gcm_defaultSenderId" to providers.environmentVariable("BUZZ_FIREBASE_SENDER_ID").orNull,
|
||||
)
|
||||
val suppliedFirebaseValues = firebaseValues.filterValues { !it.isNullOrBlank() }
|
||||
if (suppliedFirebaseValues.isNotEmpty() && suppliedFirebaseValues.size != firebaseValues.size) {
|
||||
throw GradleException(
|
||||
"Firebase configuration needs BUZZ_FIREBASE_APP_ID, BUZZ_FIREBASE_API_KEY, " +
|
||||
"BUZZ_FIREBASE_PROJECT_ID and BUZZ_FIREBASE_SENDER_ID together; supplied only: " +
|
||||
suppliedFirebaseValues.keys.sorted().joinToString(", "),
|
||||
)
|
||||
}
|
||||
|
||||
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
|
||||
doFirst {
|
||||
val requireHttps = !name.endsWith("Debug", ignoreCase = true)
|
||||
@@ -160,6 +180,11 @@ android {
|
||||
versionName = flutter.versionName
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
resValue("string", "app_name", "Buzz")
|
||||
// Firebase reads its options from these resources when no
|
||||
// google-services file is processed.
|
||||
suppliedFirebaseValues.forEach { (name, value) ->
|
||||
resValue("string", name, requireNotNull(value))
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
@@ -197,6 +222,9 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("com.google.firebase:firebase-bom:35.2.0"))
|
||||
implementation("com.google.firebase:firebase-messaging")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.10.0")
|
||||
implementation("com.google.android.play:age-signals:0.0.4")
|
||||
implementation("androidx.appcompat:appcompat:1.6.1")
|
||||
implementation("androidx.browser:browser:1.9.0")
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32"
|
||||
@@ -75,6 +76,11 @@
|
||||
<meta-data
|
||||
android:name="io.sentry.breadcrumbs.network-events"
|
||||
android:value="false" />
|
||||
<!-- FCM would fetch a token at startup for every install. The app asks
|
||||
for one only once the user turns notifications on. -->
|
||||
<meta-data
|
||||
android:name="firebase_messaging_auto_init_enabled"
|
||||
android:value="false" />
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
|
||||
@@ -130,6 +130,8 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
private var mediaUploadChannel: MethodChannel? = null
|
||||
private var ageSignalChannel: MethodChannel? = null
|
||||
private val ageSignalRequest = AgeSignalRequest()
|
||||
private var pushRegistrationPlugin: PushRegistrationPlugin? = null
|
||||
private var pushKeystorePlugin: PushKeystorePlugin? = null
|
||||
private var deviceTranscriptionPlugin: DeviceTranscriptionPlugin? = null
|
||||
private var huddleMediaPlugin: HuddleMediaPlugin? = null
|
||||
private var hapticsPlugin: HapticsPlugin? = null
|
||||
@@ -140,6 +142,8 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
deviceTranscriptionPlugin = DeviceTranscriptionPlugin(flutterEngine.dartExecutor.binaryMessenger)
|
||||
pushRegistrationPlugin = PushRegistrationPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
|
||||
pushKeystorePlugin = PushKeystorePlugin(flutterEngine.dartExecutor.binaryMessenger)
|
||||
flutterEngine.platformViewsController.registry.registerViewFactory(
|
||||
"buzz/transparent-avatar",
|
||||
TransparentAvatarViewFactory(flutterEngine.dartExecutor.binaryMessenger),
|
||||
@@ -248,6 +252,10 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
hostedHpkePlugin = null
|
||||
hapticsPlugin?.dispose()
|
||||
hapticsPlugin = null
|
||||
pushRegistrationPlugin?.dispose()
|
||||
pushRegistrationPlugin = null
|
||||
pushKeystorePlugin?.dispose()
|
||||
pushKeystorePlugin = null
|
||||
ageSignalRequest.retire()
|
||||
huddleMediaPlugin?.dispose()
|
||||
huddleMediaPlugin = null
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package xyz.block.buzz.mobile
|
||||
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.security.InvalidAlgorithmParameterException
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.ProviderException
|
||||
import java.security.Signature
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
|
||||
/**
|
||||
* The push installation's Keystore key: a P-256 key that can only sign, with a
|
||||
* key attestation chain whose challenge Dart supplies. The private key never
|
||||
* leaves the Keystore. Dart owns every decision; this only generates, signs
|
||||
* and reports.
|
||||
*/
|
||||
internal class PushKeystorePlugin(messenger: BinaryMessenger) : MethodChannel.MethodCallHandler {
|
||||
private val channel = MethodChannel(
|
||||
messenger, "buzz/push_keystore", io.flutter.plugin.common.StandardMethodCodec.INSTANCE,
|
||||
messenger.makeBackgroundTaskQueue(),
|
||||
).apply { setMethodCallHandler(this@PushKeystorePlugin) }
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
try {
|
||||
when (call.method) {
|
||||
"current" -> result.success(describe())
|
||||
"generate" -> {
|
||||
val challenge = (call.arguments as? Map<*, *>)?.get("challenge") as? ByteArray
|
||||
if (challenge == null) {
|
||||
result.error("invalid_arguments", "Expected an attestation challenge.", null)
|
||||
} else {
|
||||
generate(challenge, result)
|
||||
}
|
||||
}
|
||||
"sign" -> {
|
||||
val data = (call.arguments as? Map<*, *>)?.get("data") as? ByteArray
|
||||
if (data == null) {
|
||||
result.error("invalid_arguments", "Expected bytes to sign.", null)
|
||||
} else {
|
||||
result.success(sign(data))
|
||||
}
|
||||
}
|
||||
"delete" -> {
|
||||
keyStore().deleteEntry(ALIAS)
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
result.error("keystore_failed", error.message, error.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
|
||||
private fun keyStore(): KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||
|
||||
private fun generate(challenge: ByteArray, result: MethodChannel.Result) {
|
||||
val store = keyStore()
|
||||
store.deleteEntry(ALIAS)
|
||||
try {
|
||||
KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply {
|
||||
initialize(
|
||||
KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN)
|
||||
.setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
|
||||
.setDigests(KeyProperties.DIGEST_SHA256)
|
||||
.setAttestationChallenge(challenge)
|
||||
.build(),
|
||||
)
|
||||
}.generateKeyPair()
|
||||
} catch (error: ProviderException) {
|
||||
result.error("attestation_unavailable", error.message ?: "key generation failed", null)
|
||||
return
|
||||
} catch (error: InvalidAlgorithmParameterException) {
|
||||
result.error("attestation_unavailable", error.message ?: "key generation failed", null)
|
||||
return
|
||||
}
|
||||
// A phone without hardware attestation hands back a lone self-signed
|
||||
// certificate. That chain proves nothing, so it never leaves here.
|
||||
if ((store.getCertificateChain(ALIAS)?.size ?: 0) < 2) {
|
||||
store.deleteEntry(ALIAS)
|
||||
result.error("attestation_unavailable", "no attestation chain", null)
|
||||
return
|
||||
}
|
||||
result.success(describe())
|
||||
}
|
||||
|
||||
private fun describe(): Map<String, Any>? {
|
||||
val store = keyStore()
|
||||
if (!store.containsAlias(ALIAS)) return null
|
||||
val chain = store.getCertificateChain(ALIAS) ?: return null
|
||||
val point = (chain[0].publicKey as ECPublicKey).w
|
||||
return mapOf(
|
||||
"publicKey" to byteArrayOf(0x04) + fixed32(point.affineX.toByteArray()) + fixed32(point.affineY.toByteArray()),
|
||||
"chain" to chain.map { it.encoded },
|
||||
)
|
||||
}
|
||||
|
||||
private fun sign(data: ByteArray): ByteArray {
|
||||
val key = keyStore().getKey(ALIAS, null) as? PrivateKey
|
||||
?: throw IllegalStateException("The push installation key is missing.")
|
||||
return Signature.getInstance("SHA256withECDSA").run {
|
||||
initSign(key)
|
||||
update(data)
|
||||
sign()
|
||||
}
|
||||
}
|
||||
|
||||
/** A big-endian integer as exactly 32 bytes: BigInteger adds or drops a sign byte. */
|
||||
private fun fixed32(bytes: ByteArray): ByteArray {
|
||||
val trimmed = if (bytes.size > 32) bytes.copyOfRange(bytes.size - 32, bytes.size) else bytes
|
||||
return ByteArray(32 - trimmed.size) + trimmed
|
||||
}
|
||||
|
||||
fun dispose() { channel.setMethodCallHandler(null) }
|
||||
|
||||
private companion object {
|
||||
const val ALIAS = "xyz.block.buzz.push.installation.v1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package xyz.block.buzz.mobile
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.google.firebase.FirebaseApp
|
||||
import com.google.firebase.messaging.FirebaseMessaging
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
/**
|
||||
* Notification permission and the FCM registration token, on a channel of
|
||||
* its own: `buzz/push` has one native handler, which opens tapped
|
||||
* notifications. The token and a failure to get one reach Dart as calls, like
|
||||
* the iOS APNs callbacks.
|
||||
*
|
||||
* The permission prompt never gates the token: the installation is enrolled
|
||||
* whether or not notifications may be displayed, as on iOS.
|
||||
*/
|
||||
internal class PushRegistrationPlugin(
|
||||
private val activity: Activity,
|
||||
messenger: BinaryMessenger,
|
||||
) : MethodChannel.MethodCallHandler {
|
||||
private val channel = MethodChannel(messenger, "buzz/push_registration").apply {
|
||||
setMethodCallHandler(this@PushRegistrationPlugin)
|
||||
}
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
when (call.method) {
|
||||
"startRegistration" -> {
|
||||
// A build without Firebase has no token to wait for, and must
|
||||
// not ask the user for a permission that only push needs.
|
||||
if (firebaseConfigured()) {
|
||||
requestNotificationPermission()
|
||||
fetchToken()
|
||||
}
|
||||
result.success(null)
|
||||
}
|
||||
"refreshToken" -> {
|
||||
if (firebaseConfigured()) fetchToken()
|
||||
result.success(null)
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
private fun requestNotificationPermission() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
|
||||
val permission = Manifest.permission.POST_NOTIFICATIONS
|
||||
if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED) return
|
||||
// Ask once, as iOS does. A decline stands until the user changes it in
|
||||
// system settings; asking again on every launch would nag.
|
||||
val asked = activity.getSharedPreferences(PREFERENCES, android.content.Context.MODE_PRIVATE)
|
||||
if (asked.getBoolean(ASKED_KEY, false)) return
|
||||
asked.edit().putBoolean(ASKED_KEY, true).apply()
|
||||
ActivityCompat.requestPermissions(activity, arrayOf(permission), REQUEST_CODE)
|
||||
}
|
||||
|
||||
/** Whether Firebase is set up; when not, tells Dart registration failed. */
|
||||
private fun firebaseConfigured(): Boolean {
|
||||
if (FirebaseApp.getApps(activity).isNotEmpty()) return true
|
||||
channel.invokeMethod(
|
||||
"fcmRegistrationFailed",
|
||||
mapOf("message" to "Firebase is not configured in this build."),
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
private fun fetchToken() {
|
||||
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
|
||||
// `result` throws for a failed task, so read it only after success.
|
||||
val token = if (task.isSuccessful) task.result else null
|
||||
if (!token.isNullOrEmpty()) {
|
||||
channel.invokeMethod("fcmTokenChanged", mapOf("token" to token))
|
||||
} else {
|
||||
channel.invokeMethod(
|
||||
"fcmRegistrationFailed",
|
||||
mapOf("message" to (task.exception?.message ?: "FCM returned no token.")),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun dispose() { channel.setMethodCallHandler(null) }
|
||||
|
||||
companion object {
|
||||
const val REQUEST_CODE = 0x6275
|
||||
private const val PREFERENCES = "buzz_push"
|
||||
private const val ASKED_KEY = "notification_permission_asked"
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,5 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</full-backup-content>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="file" path="bestie-transcripts/"/>
|
||||
@@ -20,5 +21,6 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
|
||||
Reference in New Issue
Block a user