# Securing Gemini, OpenAI & Backend API Keys in Vibe-Coded Android Apps Using Play Integrity API, Firebase App Check & Cloudflare Workers

> Eliminate hardcoded LLM API keys from Google AI Studio, Cursor, and Claude Code Android builds before Closed Testing using stateless Cloudflare Worker proxies, Play Integrity binary attestation, and Firebase App Check.

- **Canonical URL**: https://gootester.com/blog/securing-ai-api-keys-play-integrity-firebase-app-check
- **Category**: Testing Strategy, Comparisons & Security (Guide #54)
- **Verified Date**: 2026-11-25
- **Reading Time**: 11 min (1952 words)

## Executive Summary & Citation-Ready Key Takeaways
- Embedding Gemini, OpenAI, Anthropic, or Supabase service-role secrets inside Gradle BuildConfig constants, EXPO_PUBLIC_* variables, VITE_* bundles, or C++ NDK libraries exposes live credentials in plaintext to automated APK and AAB decompilers.
- Google Cloud secret scanners and Play Console security checks actively inspect uploaded Android App Bundles for leaked provider API keys, automatically revoking compromised credentials or flagging policy warnings before Production.
- Routing client AI prompts through a stateless Cloudflare Worker edge proxy keeps upstream provider API keys locked inside encrypted server secrets while enforcing strict payload size caps and per-user token budgets.
- Pairing your edge proxy with Google Play Integrity API or Firebase App Check cryptographically proves incoming requests originate from your authentic Play-signed binary executing on genuine, Play-certified physical Android hardware.
- Registering your Google Play App Signing SHA-256 certificate fingerprint in Firebase—rather than only your local upload keystore—ensures genuine human closed testers pass runtime attestation seamlessly without hitting 403 Forbidden lockouts.

## 1. 1. Why `.env` Files, `BuildConfig` & NDK Strings Never Hide API Keys in an AAB

AI-assisted development tools—including Google AI Studio, Cursor, Claude Code, Bolt, and Lovable—make prototyping multimodal Android apps in Kotlin, Flutter, Expo (React Native), or Capacitor remarkably fast. However, rapid browser prototypes default to calling Gemini or OpenAI directly from client code using environment variables such as `VITE_GEMINI_API_KEY`, `EXPO_PUBLIC_OPENAI_KEY`, `--dart-define`, or Gradle's `BuildConfig.AI_API_KEY`.

The moment you compile that project into an Android App Bundle (`.aab`) and distribute it on Play Store tracks, **every string embedded inside DEX bytecode, bundled JavaScript assets (`index.android.bundle`), or native `.so` libraries is public plaintext**. Automated scraping bots continuously pull newly published apps and run `jadx`, `apktool`, and TLS proxy interception—extracting hardcoded LLM keys and draining thousands of dollars in API quota within minutes.

Even worse, Google's automated secret-scanning infrastructure inspects uploaded App Bundles and public repositories for exposed Google Cloud / Gemini `AIza...` keys, automatically revoking compromised keys or flagging Security & Trust warnings inside Play Console right in the middle of your 14-day closed test.

> **Base64 Encoding and XOR Obfuscation Are Not Security**: Splitting an API key across three strings or hiding it in C++ JNI code still hands the live secret to any attacker running Frida or an HTTPS MITM proxy on a rooted phone. Remove provider secrets from the client binary completely.

## 2. 2. Moving LLM Secrets Behind a Stateless Cloudflare Worker Edge Proxy

The clean, zero-cost architectural fix for indie developers is placing a thin, stateless edge gateway—such as a **Cloudflare Worker**—between your Android app and upstream AI providers. Your provider credentials live exclusively inside Cloudflare's encrypted secret store (`wrangler secret put GEMINI_API_KEY`), never touching Git repositories, Gradle caches, or compiled `.aab` bundles.

Beyond hiding credentials, an edge proxy gives you server-side control over cost and abuse before a single prompt reaches your paid LLM billing meter. Your Worker should hardcode the allowed upstream model (`gemini-2.5-flash`), cap `maxOutputTokens`, validate JSON request body byte length, and enforce per-user or per-device sliding-window rate limits.

For Firebase-centric indie stacks that prefer zero custom proxy code, **Firebase AI Logic (Vertex AI in Firebase)** provides an equivalent managed proxy layer paired natively with Firebase App Check so client SDKs call Gemini without embedding raw Cloud API keys.

```javascript
export default {
  async fetch(request, env) {
    if (request.method !== "POST") return new Response("Method Not Allowed", { status: 405 });
    const appCheckJwt = request.headers.get("X-Firebase-AppCheck");
    if (!appCheckJwt || !(await verifyAppCheckJwks(appCheckJwt, env.FIREBASE_PROJECT_NUMBER))) {
      return Response.json({ error: "ATTESTATION_REQUIRED" }, { status: 401 });
    }
    const { prompt } = await request.json();
    if (typeof prompt !== "string" || prompt.length > 4000) {
      return Response.json({ error: "PAYLOAD_TOO_LARGE" }, { status: 400 });
    }
    const upstream = await fetch(
      "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
      {
        method: "POST",
        headers: { "Content-Type": "application/json", "x-goog-api-key": env.GEMINI_API_KEY },
        body: JSON.stringify({ contents: [{ parts: [{ text: prompt }] }] })
      }
    );
    return new Response(upstream.body, { status: upstream.status, headers: { "Content-Type": "application/json" } });
  }
};
```

## 3. 3. Verifying Genuine Play-Signed Installs with Google Play Integrity API

Moving your Gemini or OpenAI key behind `https://api.example.com/v1/generate` solves key extraction, but without client attestation an attacker can still inspect your app's HTTPS endpoint URL and replay `curl` requests against *your* proxy for free LLM completions! That is the exact problem solved by the **Google Play Integrity API**.

Using `StandardIntegrityManager` (`com.google.android.play:integrity`), your app warms an attestation provider once at startup and generates low-latency cryptographic tokens bound to a SHA-256 digest (`requestHash`) of each outgoing payload. Your backend decrypts and verifies Google's signed verdict across three dimensions: **Application Integrity** (`PLAY_RECOGNIZED`), **Device Integrity** (`MEETS_DEVICE_INTEGRITY`), and **Account Licensing** (`LICENSED`).

Critically for 14-day closed testing: any human tester who joins your Closed Testing track via Google Groups (`testers@gootester.com`), accepts your opt-in URL, and installs the app from the Google Play Store receives genuine **`PLAY_RECOGNIZED`** and **`LICENSED`** verdicts automatically—identical to public Production users!

| Play Integrity Field | Expected Verdict in Closed Testing | What It Cryptographically Proves |
| --- | --- | --- |
| appRecognitionVerdict | PLAY_RECOGNIZED | Binary package & signing SHA-256 match your authentic Google Play distribution |
| deviceRecognitionVerdict | MEETS_DEVICE_INTEGRITY | App is executing on genuine, Play-certified Android hardware (not a tampered bot emulator) |
| appLicensingVerdict | LICENSED | Active Google account legitimately acquired or opted into your app via Google Play |
| requestDetails.requestHash | Matches SHA-256(payload) | Attestation token was minted for this exact prompt and cannot be replayed on altered text |

## 4. 4. Turnkey Edge Verification with Firebase App Check + Play Integrity

If implementing direct Google Cloud `decodeIntegrityToken` OAuth service-account calls feels heavy for an MVP, **Firebase App Check** wraps the Play Integrity provider into standard, short-lived RS256 JWTs (`X-Firebase-AppCheck`). Your Cloudflare Worker or Node/Go backend can verify those JWTs locally at the edge against Google's cached public JWKS endpoint (`https://firebaseappcheck.googleapis.com/v1/jwks`) in under two milliseconds.

Pay special attention to Android certificate registration during setup. When Play App Signing is enabled (mandatory for all modern App Bundles), Google strips your local upload key signature and re-signs split APKs using **Google's App Signing Key**. You MUST copy the **App signing key certificate SHA-256 fingerprint** from **Play Console > Test and release > Setup > App integrity** into Firebase Project Settings!

For local Android Studio emulator debugging during development, initialize `DebugAppCheckProviderFactory.getInstance()` strictly inside `if (BuildConfig.DEBUG)` blocks—guarded so release AAB builds unconditionally compile only `PlayIntegrityAppCheckProviderFactory`.

1. **Rotate Any Previously Committed Client Keys**: Delete any Gemini, OpenAI, or backend secret that ever touched Git history or a prior APK/AAB build, and store the new key in server secrets.
2. **Register Play App Signing SHA-256 Fingerprint**: Copy the SHA-256 certificate digest from Play Console > App integrity > App signing key certificate (not your local upload keystore) into Firebase / Cloud Console.
3. **Enable Play Integrity API in Linked Cloud Project**: Link your Play Console app to your Google Cloud project under App integrity > Play Integrity API with default 10,000 daily request quota enabled.
4. **Roll Out Soft Monitoring Before Hard 401 Enforcement**: Log X-Firebase-AppCheck validation metrics during Day 1 of Closed Testing to confirm 100% pass rates on real devices before enabling hard 401 rejection.

## 5. 5. Avoiding Self-Inflicted `403 Attestation` Lockouts During Closed Testing

Every week, well-intentioned developers lock their own closed testers out of AI features on Day 1 because of two subtle attestation misconfigurations. The first is pasting their local `.jks` **Upload key SHA-256** into Firebase App Check while forgetting the **App signing key SHA-256**—causing every single Play Store install to fail signature validation with `403 Forbidden`.

The second pitfall is enforcing `MEETS_STRONG_INTEGRITY` (hardware-backed recent security-patch attestation) unconditionally on consumer productivity apps. Legitimate physical Android 11, 12, and 13 phones owned by real human testers routinely satisfy `MEETS_DEVICE_INTEGRITY` while lacking recent OEM quarterly patches required for `STRONG` hardware verdicts.

Require `PLAY_RECOGNIZED` + `MEETS_DEVICE_INTEGRITY` as your standard baseline, set sensible upstream spend caps ($10–$25 monthly budget alerts in Google Cloud / OpenAI), and return clear user-facing error toasts if rate limits trigger rather than crashing the UI thread.

- Dual SHA-256 Registration: Register the Play App Signing SHA-256 in Firebase so Play Store Closed Testing & Production builds pass seamlessly.
- Device Verdict Floor: Enforce `MEETS_DEVICE_INTEGRITY` rather than `MEETS_STRONG_INTEGRITY` unless building regulated banking or wallet software.
- Hard Billing Caps: Configure provider hard monthly spend limits alongside per-IP / per-user daily token quotas in Cloudflare KV or D1.
- Graceful Degradation: Ensure offline or `429 Too Many Requests` proxy responses render a clean retry state instead of throwing unhandled JSON parse crashes.

## 6. 6. Unifying Runtime Secret Security with Zero-Credential Closed Testing

True security discipline spans both your compiled Android binary and your Play Console release operations. Just as you should never ship a live Gemini API key inside a client `.aab`, you should never hand over your Google Play Console login, Google Cloud service-account JSON keys, or `.jks` upload keystore to third-party testing freelancers.

GOOtester's architecture reinforces both halves of this security posture. You authorize `testers@gootester.com` via Play Console's native Google Groups field—sharing zero credentials—and our real human testers ($6 Basic, $12 Standard, $20 Premium) install your genuine Play-signed binary directly from the Google Play Store on certified physical handsets, satisfying `PLAY_RECOGNIZED` and `LICENSED` Play Integrity checks out of the box.

Meanwhile, if you run GOOtester's standalone physical-device ADB QA sweep on a dedicated pre-release build to benchmark startup latency and memory footprint, our isolated diagnostic workflow validates graceful error handling without ever mingling automated ADB sessions with your 14-day human opt-in track.

### Pre-Upload Secret Scan Command for CI/CD

Run `unzip -p app-release.aab base/dex/classes.dex | strings | grep -E 'AIza|sk-'` in CI before uploading to Play Console to guarantee zero accidental client key leaks.

### Handling Reviewer Login Credentials Safely

If your AI app requires sign-in, create a dedicated rate-limited demo account (`developer@example.com`) under Play Console > App content > App access so Google reviewers can test without hitting blank walls.

## Pre-Submission Verification Checklist

- [ ] Audit your codebase and compiled AAB with `strings` / `jadx` to verify zero `AIza...`, `sk-...`, or service-role secrets exist client-side.
- [ ] Move all Gemini, OpenAI, and paid third-party calls behind a Cloudflare Worker proxy or Firebase AI Logic backend.
- [ ] Register your Play Console 'App signing key certificate' SHA-256 fingerprint (not just your upload key) in Firebase App Check / Google Cloud.
- [ ] Require PLAY_RECOGNIZED and MEETS_DEVICE_INTEGRITY verdicts rather than overly restrictive MEETS_STRONG_INTEGRITY checks.
- [ ] Configure per-user daily request quotas and hard monthly billing caps on your upstream AI provider account.
- [ ] Provide a rate-limited demo test credential in Play Console > App access if AI screens sit behind authentication.

## Frequently Asked Questions

### Is storing my Gemini or OpenAI key in Android local.properties and reading BuildConfig safe?
No! While excluding `local.properties` from Git keeps the secret off GitHub, Gradle compiles `BuildConfig` fields directly into plaintext constants inside `classes.dex` in your published `.aab`, where bots extract them in seconds.

### Do human testers on a Google Play Closed Testing track pass Play Integrity PLAY_RECOGNIZED checks?
Yes. When testers opt in via your Google Group (`testers@gootester.com`) and download your app from the Google Play Store on certified Android devices, Play Integrity returns `PLAY_RECOGNIZED`, `MEETS_DEVICE_INTEGRITY`, and `LICENSED`.

### Why did Firebase App Check start returning 403 errors as soon as I uploaded my app to Closed Testing?
Almost always because Firebase Project Settings only has your local debug or upload keystore SHA-256 registered. Copy the 'App signing key certificate' SHA-256 from Play Console > Setup > App integrity and paste it into Firebase.

### Does GOOtester ever need my Google Cloud keys, keystore, or Play Console login?
Never. GOOtester operates on a strict zero-credential delegation model: you only add `testers@gootester.com` to your Closed Testing Google Groups setting and share your public Play Store Web Opt-In URL.
