Files
buzz/mobile/android/app/build.gradle.kts
Tom Brow 2e3bebe9b6 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>
2026-11-23 09:35:56 -07:00

281 lines
12 KiB
Plaintext

import java.net.URI
import java.util.Base64
import java.util.Properties
plugins {
id("com.android.application")
id("kotlin-android")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
val uploadKeystorePath = providers.environmentVariable("BUZZ_ANDROID_UPLOAD_KEYSTORE_PATH").orNull
val uploadKeystorePassword = providers.environmentVariable("BUZZ_ANDROID_UPLOAD_KEYSTORE_PASSWORD").orNull
val uploadKeyAlias = providers.environmentVariable("BUZZ_ANDROID_UPLOAD_KEY_ALIAS").orNull
val uploadKeyPassword = providers.environmentVariable("BUZZ_ANDROID_UPLOAD_KEY_PASSWORD").orNull
val uploadSigningValues =
mapOf(
"BUZZ_ANDROID_UPLOAD_KEYSTORE_PATH" to uploadKeystorePath,
"BUZZ_ANDROID_UPLOAD_KEYSTORE_PASSWORD" to uploadKeystorePassword,
"BUZZ_ANDROID_UPLOAD_KEY_ALIAS" to uploadKeyAlias,
"BUZZ_ANDROID_UPLOAD_KEY_PASSWORD" to uploadKeyPassword,
)
val missingUploadSigningValues = uploadSigningValues.filterValues { it.isNullOrBlank() }.keys
val hasUploadSigning = missingUploadSigningValues.isEmpty()
val dartDefines = providers.gradleProperty("dart-defines").orNull.orEmpty()
val pushGatewayDefinePrefix = "BUZZ_PUSH_GATEWAY_URL="
val pushGatewayOrigins =
dartDefines.split(',').mapNotNull { encoded ->
val define = runCatching { String(Base64.getDecoder().decode(encoded)) }.getOrNull()
define
?.takeIf { it.startsWith(pushGatewayDefinePrefix) }
?.removePrefix(pushGatewayDefinePrefix)
}
fun isValidPushGatewayOrigin(value: String, requireHttps: Boolean): Boolean {
val uri = runCatching { URI(value) }.getOrNull() ?: return false
val scheme = uri.scheme?.lowercase()
return (scheme == "https" || (!requireHttps && scheme == "http")) &&
!uri.host.isNullOrBlank() &&
uri.rawUserInfo == null &&
(uri.rawPath.isNullOrEmpty() || uri.rawPath == "/") &&
uri.rawQuery == null &&
uri.rawFragment == null &&
(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)
val hasValidPushGatewayOrigin =
pushGatewayOrigins.isEmpty() ||
(pushGatewayOrigins.size == 1 &&
isValidPushGatewayOrigin(pushGatewayOrigins.single(), requireHttps))
if (!hasValidPushGatewayOrigin) {
throw GradleException(
"When supplied, BUZZ_PUSH_GATEWAY_URL must be an " +
(if (requireHttps) "HTTPS" else "HTTP(S)") +
" origin without " + (if (requireHttps) "an explicit port, " else "") +
"credentials, path, query, or fragment.",
)
}
}
}
// Worktree-aware debug identity (gitignored, written by
// scripts/mobile-worktree-overrides.sh): debug builds from a git worktree get a
// branch-labelled app name and a unique applicationId suffix so builds from
// multiple worktrees install side by side. Release builds never read this.
val worktreePropsFile = rootProject.file("worktree.properties")
val worktreeProps =
Properties().apply {
if (worktreePropsFile.isFile) worktreePropsFile.inputStream().use { load(it) }
}
// Optional gitignored developer overrides are loaded after the generated
// worktree values. They are consumed only by the debug build type below, so a
// long-lived device test build can keep a stable, descriptive local identity
// without changing release/profile or being overwritten by the worktree script.
val appOverridesFile = rootProject.file("AppOverrides.properties")
val appOverrides =
Properties().apply {
if (appOverridesFile.isFile) appOverridesFile.inputStream().use { load(it) }
}
val worktreeLabel = worktreeProps.getProperty("label")?.takeIf { it.isNotBlank() }
if (worktreeLabel != null && !worktreeLabel.matches(Regex("""[A-Za-z0-9._-]+"""))) {
throw GradleException(
"worktree.properties label must match [A-Za-z0-9._-]+ (safe for string " +
"resources), got: " + worktreeLabel,
)
}
val worktreeAppName = worktreeProps.getProperty("appName")?.takeIf { it.isNotBlank() }
if (worktreeAppName != null && !worktreeAppName.matches(Regex("""[A-Za-z0-9._() \-]+"""))) {
throw GradleException(
"worktree.properties appName must contain only letters, numbers, spaces, ., _, -, or " +
"parentheses, got: " + worktreeAppName,
)
}
val worktreeIdSuffix =
worktreeProps.getProperty("applicationIdSuffix")?.takeIf { it.isNotBlank() }
val debugIdSuffix =
appOverrides.getProperty("applicationIdSuffix")?.takeIf { it.isNotBlank() }
?: worktreeIdSuffix
if (debugIdSuffix != null && !debugIdSuffix.matches(Regex("""\.[a-z][a-z0-9_]*"""))) {
throw GradleException(
"debug applicationIdSuffix must match \\.[a-z][a-z0-9_]*, got: " +
debugIdSuffix,
)
}
val debugAppName = appOverrides.getProperty("appName")?.takeIf { it.isNotBlank() }
if (
debugAppName != null &&
!debugAppName.matches(Regex("""[A-Za-z0-9][A-Za-z0-9 ._()\-]{0,39}"""))
) {
throw GradleException(
"debug appName must be 1-40 resource-safe characters, got: " + debugAppName,
)
}
// Release signing modes:
// - "upload-keystore" (default): sign with the CI-vended upload keystore;
// release builds fail loudly when any credential is missing.
// - "external": deliberately produce an UNSIGNED release bundle for a
// pipeline that signs through the central APK Signer service (Cashkite,
// BOT-1234). No keystore material may be present in this mode.
val releaseSigningMode =
providers.environmentVariable("BUZZ_ANDROID_RELEASE_SIGNING").orNull ?: "upload-keystore"
val externalReleaseSigning = releaseSigningMode == "external"
if (releaseSigningMode !in setOf("upload-keystore", "external")) {
throw GradleException(
"BUZZ_ANDROID_RELEASE_SIGNING must be \"upload-keystore\" or \"external\", got: " +
releaseSigningMode,
)
}
if (externalReleaseSigning && uploadSigningValues.values.any { !it.isNullOrBlank() }) {
throw GradleException(
"BUZZ_ANDROID_RELEASE_SIGNING=external must not be combined with " +
"BUZZ_ANDROID_UPLOAD_* credentials; unset one of them.",
)
}
android {
namespace = "xyz.block.buzz.mobile"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_17.toString()
}
defaultConfig {
applicationId = "xyz.block.buzz.mobile"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
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 {
if (hasUploadSigning) {
create("upload") {
storeFile = file(requireNotNull(uploadKeystorePath))
storePassword = uploadKeystorePassword
keyAlias = uploadKeyAlias
keyPassword = uploadKeyPassword
}
}
}
buildTypes {
debug {
// Only debug builds take the worktree identity; release/profile
// keep the production applicationId and label.
if (debugIdSuffix != null) {
applicationIdSuffix = debugIdSuffix
}
val resolvedAppName =
debugAppName
?: worktreeAppName
?: worktreeLabel?.let { "Buzz ($it)" }
if (resolvedAppName != null) {
resValue("string", "app_name", resolvedAppName)
}
}
release {
if (hasUploadSigning) {
signingConfig = signingConfigs.getByName("upload")
}
}
}
}
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")
testImplementation(kotlin("test"))
androidTestImplementation(kotlin("test"))
androidTestImplementation("androidx.test.ext:junit:1.3.0")
androidTestImplementation("androidx.test:runner:1.7.0")
}
gradle.taskGraph.whenReady {
val buildsRelease = allTasks.any { task ->
task.project == project && task.name in setOf("assembleRelease", "bundleRelease")
}
if (buildsRelease && externalReleaseSigning) {
// External signing: the unsigned bundle goes to the central APK
// Signer. All keystore checks are intentionally skipped; the
// guard above already rejected any BUZZ_ANDROID_UPLOAD_* values.
return@whenReady
}
if (buildsRelease && !hasUploadSigning) {
throw GradleException(
"Release builds require Android upload signing credentials. Missing: " +
missingUploadSigningValues.sorted().joinToString(", ") +
". For central APK Signer pipelines set BUZZ_ANDROID_RELEASE_SIGNING=external.",
)
}
if (buildsRelease) {
val configuredKeystore = File(requireNotNull(uploadKeystorePath))
if (!configuredKeystore.isAbsolute) {
throw GradleException(
"BUZZ_ANDROID_UPLOAD_KEYSTORE_PATH must be absolute: $configuredKeystore",
)
}
val keystore = file(configuredKeystore)
val repositoryRoot = rootProject.projectDir.parentFile.parentFile.canonicalFile
if (keystore.canonicalFile.toPath().startsWith(repositoryRoot.toPath())) {
throw GradleException(
"BUZZ_ANDROID_UPLOAD_KEYSTORE_PATH must be outside the repository: $keystore",
)
}
if (!keystore.isFile || !keystore.canRead()) {
throw GradleException(
"BUZZ_ANDROID_UPLOAD_KEYSTORE_PATH is not a readable file: $keystore",
)
}
}
}
flutter {
source = "../.."
}