How to Protect Cloudflare R2 Resources With Firebase App Check

D

Darryl Bayliss

Guest
Towards the end of the year I like to work on my festive app, Christmas Chill, a collection of looped videos that mimic the burning log fire channels you used to see on TV. This year I’m bringing it to Android and moving the videos to the cloud, so I can update them remotely and avoid bloating the app size.

To know which videos are available, the app downloads a JSON catalog of video URLs on start. The catalog and videos live in a Cloudflare R2 bucket behind a public custom domain.

That’s problematic because a public domain is available to everyone. Anyone can query the catalog JSON, read every video URL inside, and download the entire list without ever installing the app. I wanted to change that so only genuine app installs can fetch the catalog and find out where the videos are hosted.

This post covers how I did that using Firebase App Check for Android and a simple Cloudflare Worker on the server side.

Let’s get to it.

The Problem: R2 Can’t Verify Requests by Itself​


R2 is great at what it does. You put files in a bucket, attach a custom domain, and they’re served quickly from Cloudflare’s network. What it can’t do is check who is making the request, so it has no way to decide whether the request came from my app.

Firebase App Check helps to solve that. It forces your app to prove to Google, using Play Integrity, that it’s a genuine install on a genuine device. In return Google hands the app a short lived token, which the app attaches to its requests to the backend. The backend then checks whether the token is genuine and decides whether to serve the request.

The catch is that R2 has no way to check the token by itself, so we need something in between to manage the requests and forward the JSON catalog to the app. A Cloudflare Worker is an ideal fit here. It receives the request, verifies the token, and only then retrieves the file from R2 and returns it to the app.

Before going further let’s put in some caveats:

  • Only the catalog JSON is protected. The videos are served from the same bucket and remain public. The Worker is only attached to the catalog path, so video requests go straight to the R2 bucket. The URLs are only discoverable through the catalog, which will be protected by App Check.
  • This is adding friction. Someone determined enough, with a real device, can still get at the catalog / videos. The aim here is to stop casual scrapers.

Let’s start with the Android app, which has to get a token from Firebase and send it with each request to the catalog.

Adding App Check to Android​


The app has three jobs: get a token from Firebase, send the token along with the catalog request as a header, and cope gracefully when something goes wrong.

Setting Up Firebase and Play Integrity​


Before writing any code, a few things need setting up in the Firebase and Google Play consoles. This assumes your app has already been created in Play Console and uses Play App Signing.

In Firebase

  1. Add your Android app to your Firebase project, download google-services.json into your app module and apply the Google services Gradle plugin.
  2. Go to Security > App Check, open the Apps tab and register your app with the Play Integrity provider.
  3. Add your app’s SHA-256 fingerprints to the app’s settings, making sure to include both the App Signing key and Upload key, which you can copy from the Google Play Console via Protected with Play > Play Store Protection > Manage Play App Signing. Google Play Integrity checks the app against both of these.
  4. Optionally, set the token time to live (TTL) in the app’s settings. It can be between 30 minutes and 7 days, with a default of 1 hour. A longer TTL means fewer attestations, which can help with usage limits.

In Google Play Console

  1. Select your app and go to Test & Release > Play integrity API.
  2. In the Play Integrity API section, choose Link Cloud project and select your Firebase project. This also enables the Play Integrity API for your project. You need to be an Owner of the project to be able to do this.

Your Google Cloud project is setup in Google Play Console


That’s everything needed for release builds. Note that by default, a release build that Google Play doesn’t recognise will fail attestation. You can test release behaviour through the internal testing track in Google Play.

Debug builds get their own testing setup. We’ll come back to that later on.

Play Recognised and Licensed Settings​


Registering the app with the Play Integrity provider isn’t quite the end of the Firebase setup. The provider has a few advanced settings that decide how strict attestation is.

Each setting maps to a verdict label passed from Play Integrity to the App Check SDK. They are Play Recognised and Play Licensed:

  • Play Recognised requires the PLAY_RECOGNIZED label, which tells App Check the app is a genuine build that Google Play knows about. It’s required by default. Apps that aren’t published on Google Play can’t receive this label, so if you distribute to other stores outside of Google Play you’ll need to turn it off.
  • Play Licensed requires the LICENSED label, which means the user installed or updated the app directly from Google Play. It’s not required by default. Only users who installed your app from Google Play are eligible for the label, so turning it on shuts out anyone who installed by other means.

There’s also a Device Integrity setting to ensure devices running your app are capable of enforcing integrity. By default App Check doesn’t explicitly check it, but you can require basic, device or strong integrity depending on your needs.

The table below shows what Google recommends depending on where your app is distributed:


Distribution

Play Recognised

Play Licensed

Device Integrity

Only on Google Play

Required

Required

Don’t explicitly check

Only outside Google Play

Not required

Not required

Device integrity

Both

Required

Not required

Don’t explicitly check

Setting these values when you first register the app for App Check is highly recommended but be careful with the licensed setting. If you’re unsure how your users get your app, stick with the defaults rather than locking out people who installed it another way.

Dependencies​


Next up is adding the app dependencies. First, add the Firebase Bill of Materials (BoM) and the App Check libraries to your version catalog:


Code:
[versions]
firebaseBom = "35.2.0"

[libraries]
firebase-bom = { module = "com.google.firebase:firebase-bom" versionref = "firebaseBom" }
firebase-appcheck = { module = "com.google.firebase:firebase-appcheck" }
firebase-appcheck-playintegrity = { module = "com.google.firebase:firebase-appcheck-playintegrity" }
firebase-appcheck-debug = { module = "com.google.firebase:firebase-appcheck-debug" }

The BoM sets the versions used so the individual libraries don’t need one. Next, in the module’s build.gradle.kts, add the libraries used. The debug library only needs to be set up with debug builds:

Code:
dependencies {
    implementation(platform(libsfirebasebom))
    implementation(libsfirebaseappcheck)
    releaseImplementation(libsfirebaseappcheckplayintegrity)
    debugImplementation(libsfirebaseappcheckdebug)
}

With that done it’s time to get hold of the token to validate your requests.

Provider Factories​


To get a token App Check needs to know how your app will prove itself as genuine. To help with this, App Check provides built-in factories that perform the attestation and are installed when the app starts. There are two you can use:

  • PlayIntegrityAppCheckProviderFactory attests with Play Integrity, which checks that your app is genuine and running on a genuine device. How strict that check is depends on the provider settings above. This is the one to use with release builds.
  • DebugAppCheckProviderFactory skips attestation. On first run it logs a debug token to Logcat, which you register in the Firebase Console, and Firebase then trusts that install. This lets emulators and debug builds get tokens.

In my app each build type gets its own installAppCheck(context) function in a debug or release source set, so the debug provider never ships with live code:


Code:
// src/debug
fun installAppCheck(context: Context) {
    val app = FirebaseAppinitializeApp(context) ?: return
    FirebaseAppCheckgetInstance(app)
        installAppCheckProviderFactory(DebugAppCheckProviderFactorygetInstance())
}


Code:
// src/release
fun installAppCheck(context: Context) {
    val app = FirebaseAppinitializeApp(context) ?: return
    FirebaseAppCheckgetInstance(app)
        installAppCheckProviderFactory(PlayIntegrityAppCheckProviderFactorygetInstance())
}

Then call it from your Application class, so the provider is installed before anything asks for a token:


Code:
// src/main
class ChristmasChillApplication : Application() {
    override fun onCreate() {
        superonCreate()
        installAppCheck(this)
    }
}

Gradle picks the matching installAppCheck for the build type, so this code is the same for debug and release. If your app doesn’t already have an Application class, remember to register it with android:name on the <application> element in your AndroidManifest.xml.

The debug app check provider only works once Firebase knows about the token it generates. To add the token to Firebase:

  1. Run a debug build on your test device.
  2. In Logcat, filter on DebugAppCheckProvider. It logs a message asking you to add a debug secret to the allow list in the Firebase Console, followed by a string. Copy that string.

Android Studio Logcat filtered on DebugAppCheckProvider, showing the Firebase App Check debug token message with the token replaced by a placeholder


  1. In the Firebase Console go to Security > App Check > Apps, open the overflow menu for your app and choose Manage debug tokens, then add the token.

The token is generated once per install, so a new emulator or a reinstall of your app will need a new token adding to Firebase.

Treat debug tokens like credentials as they get a valid App Check token without a verified device. Don’t commit them to a public repository, and delete any you think have been leaked.

Adding the Token to Requests​


With the library set up it’s time to retrieve the token when we need it. A good place to do this is in an OkHttp Interceptor because it sees every request the client makes and can choose which ones need a token.

In the example below the interceptor asks App Check for a token and adds it to the catalog.json request as the X-Firebase-AppCheck header. Every other request passes through untouched, so the token is never sent to URLs that don’t need it:

Code:
class AppCheckInterceptor(
    private val tokenProvider: (forceRefresh: Boolean) -> String?,
) : Interceptor {
    override fun intercept(chain: InterceptorChain): Response {
        if (chainrequest().urlpathSegmentslastOrNull() != "catalog.json") {
            return chainproceed(chainrequest())
        }
        val token = fetchToken(forceRefresh = false)
        return chainproceed(chainrequest().withToken(token))
    }

    private fun fetchToken(forceRefresh: Boolean): String? = try {
        tokenProvider(forceRefresh)
    } catch (e: InterruptedException) {
        ThreadcurrentThread().interrupt() // let OkHttp cancel the call
        null
    } catch (e: Exception) {
        null
    }

    private fun RequestwithToken(token: String?): Request =
        if (tokenisNullOrEmpty()) this else newBuilder().header("X-Firebase-AppCheck" token).build()
}

The interceptor takes a tokenProvider function so it doesn’t depend on Firebase directly, which keeps it easy to test in isolation.

In the app the provider is a small function that wraps getAppCheckToken(). That returns a Task, so the function waits on it with Tasks.await and a 5 second timeout. It’s then passed to the interceptor when the client is built:

Code:
private fun firebaseAppCheckToken(forceRefresh: Boolean): String =
    Tasksawait(FirebaseAppCheckgetInstance().getAppCheckToken(forceRefresh),  TimeUnitSECONDS).token

// ...when building the OkHttpClient
addInterceptor(AppCheckInterceptor(tokenProvider = ::firebaseAppCheckToken))

Blocking is fine here because network calls never run on the main thread, so the interceptor will always find itself on a background thread. The SDK refreshes the token when necessary, so only the occasional request has to wait for a new one.

Getting a token can fail, for example when the device is offline or the timeout is hit. Tasks.await throws in that case, so fetchToken catches it and returns null to stop the app crashing. The request then goes out without the header, and the Worker rejects it with a 401 once enforcement is on. More on enforcement later.

Add the interceptor to the OkHttpClient that fetches the catalog, and those requests will begin to carry the token.

What If the Token Is Rejected?​


A token can look fine to the SDK but become expired by the time the server sees it. So if a request that carried a token comes back with a 401 unauthorised code we can update the interceptor to ask the Firebase App Check SDK for a fresh one using forceRefresh = true and retry the request:

Code:
override fun intercept(chain: InterceptorChain): Response {
    if (chainrequest().urlpathSegmentslastOrNull() != "catalog.json") {
        return chainproceed(chainrequest())
    }
    val token = fetchToken(forceRefresh = false)
    val response = chainproceed(chainrequest().withToken(token))
    if (responsecode != HttpURLConnectionHTTP_UNAUTHORIZED || tokenisNullOrEmpty()) return response

    // The token was rejected, so ask for a fresh one and try again.
    val fresh = fetchToken(forceRefresh = true)
    if (freshisNullOrEmpty()) return response
    responseclose()
    return chainproceed(chainrequest().withToken(fresh))
}

This replaces the intercept function above and reuses its fetchToken and withToken helpers. It only retries if the first request carried a token, since a fresh one wouldn’t change anything otherwise.

To a user this retry happens in the background and helps keep the user experience seamless.

With the app now sending a token, let’s take a look at what the Cloudflare Worker does with it.

Verifying the Token in a Worker​


The Worker is focused on one job. It reads the X-Firebase-AppCheck header passed in from the app, works out if the token is real, and then decides whether to forward the catalog JSON or return an unauthorised response.

An App Check token is a signed JWT, which you can verify using Firebase’s JWKS public keys. You can also use the jose library within the worker to fetch and cache those keys for repeated requests.

Here is what the Worker checks:

  1. The algorithm is RS256
  2. The issuer is https://firebaseappcheck.googleapis.com/<project number> (The project number is your Firebase project number)
  3. The audience includes projects/<project number>
  4. The token hasn’t expired, and wasn’t issued in the future
  5. The sub claim, which is the Firebase App ID, is in the worker allow-list

Here’s a trimmed down version of verifyAppCheck, the function that verifies the JWT. It reads the project number and a comma separated list of allowed App IDs from the Worker’s environment variables:

Code:
import { createRemoteJWKSet jwtVerify } from "jose";

// Created once, so the public keys are cached between requests.
const JWKS = createRemoteJWKSet(new URL("https://firebaseappcheck.googleapis.com/v1/jwks"));

export async function verifyAppCheck(token env keys = JWKS) {
  if (!token) return { ok: false reason: "missing_token" };

  try {
    // Checks the signature, algorithm, issuer, audience and expiry.
    const { payload } = await jwtVerify(token keys {
      algorithms: ["RS256"],
      issuer: `https://firebaseappcheck.googleapis.com/${envPROJECT_NUMBER}`
      audience: `projects/${envPROJECT_NUMBER}`
      requiredClaims: ["exp" "iat" "sub"],
    });

    if (payloadiat > Datenow() /  + ) return { ok: false reason: "issued_in_future" };

    const allowed = envALLOWED_APP_IDSsplit("");
    if (!allowedincludes(payloadsub)) return { ok: false reason: "app_not_allowed" };

    return { ok: true };
  } catch (error) {
    const reason = errorcode === "ERR_JOSE_ALG_NOT_ALLOWED" ? "invalid_alg" : "invalid_token";
    return { ok: false reason };
  }
}

If any check fails, the Worker records a short reason such as missing_token, invalid_alg or app_not_allowed, which comes in handy to diagnose issues during rollout.

Be careful to not mix up the Firebase project number and project ID. These are different things in Firebase and mixing them up will give you a confusing “invalid issuer” error.

Serving the File​


With verifyAppCheck in place, the rest of the Worker is pleasantly small. It only accepts GET and HEAD requests for .json files, verifies the token, then reads the file from R2 through the BUCKET binding and returns it.

A failed check is always logged, but the request is only rejected when the ENFORCE variable is “true”, which we’ll come to in the rollout.

Code:
  async fetch(request env ctx deps = {}) {
    if (requestmethod !== "GET" && requestmethod !== "HEAD") {
      return new Response("Method not allowed" { status:  headers: { Allow: "GET, HEAD" } });
    }

    const url = new URL(requesturl);
    const key = decodeURIComponent(urlpathnamereplace(/^\/+/ ""));
    if (keyincludes("") || !keyendsWith(".json")) {
      return new Response("Not found" { status:  });
    }

    const verify = depsverify ?? verifyAppCheck;
    const result = await verify(requestheadersget("X-Firebase-AppCheck"), env);
    if (!resultok) {
      consolewarn(JSONstringify({ event: "app_check_failed" reason: resultreason key }));
      if (envENFORCE === "true") {
        return new Response("Unauthorized" { status:  });
      }
    }

    const object = await envBUCKETget(key {
      onlyIf: requestheaders // honours If-None-Match / If-Modified-Since
    });
    if (object === null) return new Response("Not found" { status:  });

    const headers = new Headers();
    objectwriteHttpMetadata(headers);
    headersset("ETag" objecthttpEtag);
    headersset("Cache-Control" CACHE_CONTROL);
    headersset("Vary" "X-Firebase-AppCheck");

    // With onlyIf unmet, R2 returns an object without a body.
    if (!("body" in object)) {
      return new Response(null { status:  headers });
    }
    return new Response(requestmethod === "HEAD" ? null : objectbody { status:  headers });
  },

With the Worker serving the catalog the next step is to roll out App Check safely.

Rolling It Out Safely​


So how do we test App Check in a production app without locking out real users?

If you use a default Firebase provider you get some handy metrics which show what requests are being validated by App Check and which ones fail the check. This allows you to pre-vet your implementation before fully enabling App Check.

Unfortunately our Cloudflare Worker doesn’t count as a default Firebase provider, so we don’t get metrics appearing in Firebase. What we can do though is make sure to log any failed checks from our worker as a structured JSON line so it appears in Cloudflare’s observability logs and continue to serve the file so it doesn’t impact the user experience.

We can also add our own ENFORCE environment variable to the worker, as seen in the code above. A failed check is always logged, but the worker only returns an unauthorised response once ENFORCE is "true", which we can switch on once we are confident users’ devices are being validated correctly.

This gives the rollout of App Check a predetermined set of steps we can follow:

  1. Preparation. Set up Firebase and update the app to use App Check, deploy the Worker with enforcement off to handle requests for catalog.json. Nothing is blocked at this point, so the catalog stays readable by anyone until enforcement is on. Test it using a debug build.
  2. Ship the app using App Check. Release to the internal testing track first and check that no backend failures are logged for your install.
  3. Enforce. Set the ENFORCE variable to true once you’re satisfied the remaining failures aren’t coming from genuine users. Any request without a valid token will then receive a 401.

Because every failure is logged with a reason, step 2 becomes a source of information we can use to understand if there are any issues. Here is what app_check_failed events look like coming through to Cloudflare.

A Cloudflare Workers log entry for an app_check_failed event, with the reason missing_token and the key v2/christmas/catalog.json


Once you are ready to enforce the check, any unauthorised requests will fail.

jDpmEvX2s9NOjteuQqYzwKALIDn2-yn822iv.png


Keeping Within Usage Limits​


Each token provided by App Check costs a Play Integrity attestation (the default daily quota is 10,000). To reduce the amount of attestations needed, you can do the following:

  • A longer token lifetime. Setting the App Check TTL to a day or more means far fewer attestations are required, be mindful though that this comes at the cost of a potential stolen token staying valid for longer.
  • Cache the response. Caching the catalog in the app means repeat launches don’t need to hit the Worker at all. Once it’s stale, the app can revalidate with If-None-Match, and the Worker’s 304 means no body is downloaded.

Where to Go Next?​


I’m still fine-tuning my setup to test there are no edge cases before shipping. So far though I’m pretty happy with the way this works. Once App Check is ready for Android I’ll likely begin to move the iOS app over to using it as well and enforce the check across both platforms.

Here are some resources to help with your own implementations:


I hope this helps demystify the process of setting up App Check and helps you start with your own implementations!
 

Thread statistics

Created
Darryl Bayliss,
Replies
0
Views
4
Back
Top