Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose")
}

// App Check (Play Integrity) needs the Google Services plugin, which requires google-services.json.
// Apply it only when that file is present so the build still works before Firebase is configured.
if (project.file("google-services.json").exists()) {
apply(plugin = "com.google.gms.google-services")
}

fun String.asBuildConfigStringLiteral(): String =
"\"" + replace("\\", "\\\\").replace("\"", "\\\"") + "\""

Expand Down Expand Up @@ -409,6 +415,11 @@ dependencies {
implementation("org.json:json:20240303")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.9.0")

// Firebase App Check (Play Integrity) — attests requests come from the genuine app.
implementation(platform("com.google.firebase:firebase-bom:33.7.0"))
implementation("com.google.firebase:firebase-appcheck")
implementation("com.google.firebase:firebase-appcheck-playintegrity")

testImplementation("junit:junit:4.13.2")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.8.1")

Expand Down
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
android:required="false" />

<application
android:name=".App"
android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/com/b2/ultraprocessed/App.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.b2.ultraprocessed

import android.app.Application
import com.b2.ultraprocessed.network.llm.AppCheckTokenProvider

/**
* Application entry point. Installs Firebase App Check (Play Integrity) at startup so proxy requests
* can carry an attestation token. This is a no-op until `google-services.json` is present; see
* [AppCheckTokenProvider] and `documentation/15-backend-abuse-controls.md`.
*/
class App : Application() {
override fun onCreate() {
super.onCreate()
AppCheckTokenProvider.initialize(this)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.b2.ultraprocessed.network.llm

import android.content.Context
import com.google.firebase.FirebaseApp
import com.google.firebase.appcheck.FirebaseAppCheck
import com.google.firebase.appcheck.playintegrity.PlayIntegrityAppCheckProviderFactory
import kotlinx.coroutines.tasks.await

/**
* Firebase App Check (Play Integrity) attestation for the Cloud Run proxy calls.
*
* Dormant until Firebase is configured: [initialize] installs the Play Integrity provider only when a
* default [FirebaseApp] exists (i.e. `google-services.json` has been added to `:app`). [currentToken]
* returns null whenever attestation is unavailable, so callers simply omit the header and the request
* still works while the backend enforcement flag (`APP_CHECK_ENABLED`) is off. Once Firebase + Play
* Integrity are set up and the backend flag is on, this token is what proves a request came from the
* genuine, unmodified app.
*
* See `documentation/15-backend-abuse-controls.md` for the rollout order.
*/
object AppCheckTokenProvider {

const val X_FIREBASE_APPCHECK_HEADER = "X-Firebase-AppCheck"

/** Install the Play Integrity provider if Firebase is configured; otherwise stay dormant. */
fun initialize(context: Context) {
val firebaseApp = runCatching { FirebaseApp.getInstance() }.getOrNull()
?: runCatching { FirebaseApp.initializeApp(context) }.getOrNull()
?: return
runCatching {
FirebaseAppCheck.getInstance(firebaseApp)
.installAppCheckProviderFactory(
PlayIntegrityAppCheckProviderFactory.getInstance(),
)
}
}

/** A fresh App Check token, or null when attestation is unavailable (e.g. Firebase not configured). */
suspend fun currentToken(): String? = runCatching {
FirebaseAppCheck.getInstance().getAppCheckToken(false).await().token.ifBlank { null }
}.getOrNull()
}
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,14 @@ class ProxyFoodLabelLlmWorkflow(
}
val url = "${baseUrl.trimEnd('/')}/analyze"
AnalysisTelemetry.event("proxy_request_start url=$url")
val request = Request.Builder()
val requestBuilder = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.post(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
.build()
AppCheckTokenProvider.currentToken()?.let {
requestBuilder.header(AppCheckTokenProvider.X_FIREBASE_APPCHECK_HEADER, it)
}
val request = requestBuilder.build()

val body = suspendCancellableCoroutine { continuation ->
val call = client.newCall(request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,14 @@ class ProxyResultChatWorkflow(
.put("history", JSONArray(trimHistory(history).map { it.toJson() }))
val url = "${baseUrl.trimEnd('/')}/chat"
AnalysisTelemetry.event("proxy_chat_request_start url=$url")
val request = Request.Builder()
val requestBuilder = Request.Builder()
.url(url)
.header("Content-Type", "application/json")
.post(payload.toString().toRequestBody(JSON_MEDIA_TYPE))
.build()
AppCheckTokenProvider.currentToken()?.let {
requestBuilder.header(AppCheckTokenProvider.X_FIREBASE_APPCHECK_HEADER, it)
}
val request = requestBuilder.build()
client.newCall(request).execute().use { response ->
val raw = response.body?.string().orEmpty()
AnalysisTelemetry.event("proxy_chat_response http=${response.code}")
Expand Down
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ plugins {
id("com.android.application") version "9.1.1" apply false
id("org.jetbrains.kotlin.android") version "2.2.10" apply false
id("org.jetbrains.kotlin.plugin.compose") version "2.2.10" apply false
id("com.google.gms.google-services") version "4.4.2" apply false
}
Loading