Sample alert How it works Coverage PENTEST METHODOLOGY DOCS PRICING FAQ MCP CONTACT LOG IN SCAN MY APP →

iOS app AI backend open to anyone: how to lock it

FIX / OPEN MOBILE BACKEND / 9 MIN READ

If your app’s AI proxy answers a request that has no token, anyone on the internet can use it and you pay for every answer. To fix it, check a user session on every call. Add App Attest or Firebase App Check as a second check. Set a per-user limit and budget on the server.

This guide shows how to test the proxy with curl, how to add each check in order, and how to confirm that the checks work.

Why is an open AI proxy a problem?

Many guides tell you to hide the AI key behind a proxy. This advice is correct. A proxy is a server function that receives the request from the app, adds the secret key, and sends the request to the AI provider. The key never ships in the app.

The proxy is only as safe as its checks. A proxy with no checks is a public AI endpoint. The address of the proxy is in the app, and anyone can read it from the network traffic. An attacker does not need the key. The attacker sends requests to the proxy, and the proxy adds the key.

A 2026 study from Wake Forest University tested 444 AI chatbot apps for iPhone. The Hacker News reports that 282 apps leaked paid AI access. Of these, 92 apps used a proxy that accepted any caller, and 54 apps sent a plaintext key. Another 136 apps leaked tokens that an attacker could replay. The Aviatrix summary gives the same split as percentages and estimates the loss at $46,000.

The usual causes in AI-generated apps are:

  • No auth check. The Edge Function or the Cloud Function never reads the user token.
  • A check that only reads the token. The function checks that a header exists, but it does not verify the signature.
  • The public key as the check. The function accepts the Supabase anon key. This key is in every copy of the app.
  • No limit. A valid user can send an unlimited number of requests.

If the AI key itself is in the app, read the guide for a key in an iOS app first. This guide covers the next step, a proxy that is open.

How do I confirm that my proxy is open?

Find the address that the app calls. Then call it without a token.

  1. Open the app code. Search for fetch(, functions.invoke, URLSession, and your AI provider name.
  2. Note the full address and the request body. A common address looks like https://<project>.supabase.co/functions/v1/chat.
  3. If you cannot find the call, use a proxy tool such as Proxyman or Charles to read the app traffic.
  4. Send the same request with curl. Send no Authorization header.
curl -i -X POST "https://<project>.supabase.co/functions/v1/chat" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Say hello"}]}'

A correct result is 401 or 403. A 200 status with an AI answer means that the proxy is open.

  1. Repeat the test with only the public anon key. Supabase functions often accept it.
curl -i -X POST "https://<project>.supabase.co/functions/v1/chat" \
  -H "Authorization: Bearer <ANON_KEY>" \
  -H "Content-Type: application/json" \
  -d '{"messages":[{"role":"user","content":"Say hello"}]}'
  1. Repeat the test with a header value that you invented, for example Bearer test.

An answer to any of these tests is a failure. Also check the request body. If the app sends the model name or the system prompt, the caller controls them. An attacker can choose an expensive model. Read the guide for an app used as a free chatbot to see how this looks in the logs.

Warning: Each successful test costs a small amount of money. Use a short prompt and a few requests only.

How do I fix it now?

Do these steps in order. Each step closes one gap.

  1. Set a spend cap at the AI provider. Open the billing page of the provider and set a hard monthly limit. This stops the loss while you work.
  2. Require a user session. See the next section.
  3. Add an app check. See the App Attest section.
  4. Add a per-user limit. See the limits section.
  5. Test again from outside. Repeat the curl tests.

How do I require a user session?

The app must send the access token of the signed-in user. The server must verify the token. A header that exists is not enough.

How does the app send the token?

In Expo with supabase-js, functions.invoke adds the user token for you when a session exists. To make a direct call, read the session and send the token:

import { supabase } from "@/lib/supabase";

export async function askAI(prompt: string) {
  const { data: { session } } = await supabase.auth.getSession();
  if (!session) throw new Error("Not signed in");

  const res = await fetch(`${process.env.EXPO_PUBLIC_SUPABASE_URL}/functions/v1/chat`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${session.access_token}`,
    },
    body: JSON.stringify({ prompt }),
  });
  if (!res.ok) throw new Error(`AI call failed: ${res.status}`);
  return res.json();
}

Send only the prompt. Do not send the model name or the system prompt. The server sets them.

How does the Supabase Edge Function verify the token?

Create a Supabase client with the header of the caller. Then call auth.getUser(). This call asks the Auth server to verify the token. See also the guide for an Edge Function with no JWT check.

// supabase/functions/chat/index.ts
import { createClient } from "npm:@supabase/supabase-js@2";

Deno.serve(async (req) => {
  const authHeader = req.headers.get("Authorization") ?? "";
  const userClient = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_ANON_KEY")!,
    { global: { headers: { Authorization: authHeader } } },
  );

  const { data: { user }, error } = await userClient.auth.getUser();
  if (error || !user) {
    return new Response("Unauthorized", { status: 401 });
  }

  const { prompt } = await req.json();
  if (typeof prompt !== "string" || prompt.length > 2000) {
    return new Response("Bad request", { status: 400 });
  }

  const ai = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
    },
    body: JSON.stringify({
      model: "gpt-4o-mini",
      max_tokens: 500,
      messages: [{ role: "user", content: prompt }],
    }),
  });
  return new Response(await ai.text(), {
    status: ai.status,
    headers: { "Content-Type": "application/json" },
  });
});

The anon key is only the project key for the client here. The user token in the header is the real check. Keep the default setting that makes the platform verify the JWT before your code runs. Do not set verify_jwt = false for this function.

Store the AI key as a secret:

supabase secrets set OPENAI_API_KEY=<new key>

How do I add App Attest or Firebase App Check?

A user session proves that an account exists. Anyone can create an account with a script. An app check adds a second proof: the request comes from your real app on a real Apple device.

Apple App Attest is the base service. The app asks iOS to create a key pair in the Secure Enclave. Apple signs a statement for that key. Your server verifies the statement. The Apple documentation names three main calls on DCAppAttestService: generateKey, attestKey, and generateAssertion. The property isSupported is false on some devices and in the Simulator.

The steps are:

  1. The app calls generateKey once and stores the keyId.
  2. The app asks the server for a random challenge.
  3. The app calls attestKey with the hash of the challenge. It sends the result to the server.
  4. The server verifies the Apple certificate chain, the app ID, and the key. It stores the public key.
  5. For each sensitive request, the app calls generateAssertion. The server verifies the signature and checks that the counter grows.

The server checks are strict, and one error makes them useless. Most teams use Firebase App Check, which does this work for you.

How do I use Firebase App Check with App Attest?

Firebase App Check works with any backend. It does not need Firebase Auth or Firestore. You use it as a token service.

  1. Add your app in the Firebase console, in the App Check section. Select the App Attest provider.
  2. Add the App Attest capability in Xcode. Set the App Attest environment in the .entitlements file to production. App Check does not accept sandbox tokens.
  3. Add the FirebaseAppCheck package.
  4. Set the provider factory before FirebaseApp.configure().
import FirebaseCore
import FirebaseAppCheck

class AppAttestFactory: NSObject, AppCheckProviderFactory {
  func createProvider(with app: FirebaseApp) -> AppCheckProvider? {
    return AppAttestProvider(app: app)
  }
}

// In your app startup code:
AppCheck.setAppCheckProviderFactory(AppAttestFactory())
FirebaseApp.configure()

For an Expo app, you need a native module. Expo Go cannot load it. Use a development build and the React Native Firebase App Check module. Follow the Firebase App Check documentation for iOS and the module setup page for the exact calls.

  1. In the app, get a token and send it in the X-Firebase-AppCheck header.

How does the server verify the App Check token?

The Firebase documentation for custom backends shows this pattern for Node.js. Reject the request with 401 if the header is missing or the check fails.

import { getAppCheck } from "firebase-admin/app-check";

export async function requireAppCheck(req: Request) {
  const token = req.headers.get("X-Firebase-AppCheck");
  if (!token) return false;
  try {
    await getAppCheck().verifyToken(token);
    return true;
  } catch {
    return false;
  }
}

For an endpoint that costs money, use replay protection. The call verifyToken(token, { consume: true }) marks a token as used, and the result has an alreadyConsumed field. The Firebase documentation lists this feature as beta. It adds one network call to each request. The client must also ask for limited-use tokens.

Caution: Do not turn on enforcement in the Firebase console before most users run the new app version. Old versions send no token. Enforcement blocks them.

How do I add a per-user limit and a budget?

A real user with a real app can still send too many requests. A bug in an agent loop can do the same. Set limits on the server.

Make a table that counts calls for each user and each day:

create table public.ai_usage (
  user_id uuid not null references auth.users(id) on delete cascade,
  day date not null default current_date,
  calls int not null default 0,
  primary key (user_id, day)
);
alter table public.ai_usage enable row level security;

create function public.consume_ai_call(p_user uuid, p_limit int)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare c int;
begin
  insert into public.ai_usage (user_id, day, calls)
  values (p_user, current_date, 1)
  on conflict (user_id, day)
  do update set calls = public.ai_usage.calls + 1
  returning calls into c;
  return c <= p_limit;
end;
$$;

revoke execute on function public.consume_ai_call(uuid, int)
  from public, anon, authenticated;

The revoke line matters. Only the server, with the service role key, can call the function. The browser or the app cannot call it. The table has no policy, so the app cannot read it either.

Call the function in the Edge Function, after the user check:

const admin = createClient(
  Deno.env.get("SUPABASE_URL")!,
  Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
const { data: allowed } = await admin.rpc("consume_ai_call", {
  p_user: user.id,
  p_limit: 50,
});
if (!allowed) return new Response("Daily limit reached", { status: 429 });

Also set these limits:

  • A maximum input size. The example above rejects a prompt longer than 2000 characters.
  • A maximum output size. Set max_tokens on every call.
  • A fixed model. The server chooses the model. The app cannot.
  • A global budget. Set the spend cap at the AI provider, as in step 1 of the fix.
  • A rate limit for bursts. A daily count does not stop 50 calls in one second. See the guide for a per-user rate limit.

How do I check if someone already used the proxy?

  1. Open the usage page of the AI provider. Look for a spike, a night peak, or a model that your app does not use.
  2. Open the Edge Function logs in the Supabase dashboard. Look for many calls from the same IP address or with no user.
  3. Compare the number of calls with the number of active users. A large gap is a sign of abuse.
  4. If you find abuse, rotate the AI key. Then apply the fixes above.

How do I stop this problem in the future?

  • Treat every function that calls a paid API as a public endpoint until it has a user check.
  • Add a release test: call each AI endpoint with no token and expect 401.
  • Keep the model name, the system prompt, and the limits on the server.
  • Check the proxy again after each AI code regeneration. Generated code often drops the auth check. See the Rork security checklist.

When should I get help?

Get help when the AI provider bill shows large use that you cannot explain, or when the proxy also reads or writes user data. Get help if you must write your own App Attest server code. The checks are strict, and a small error can leave the check open or block real users.

Common questions

I moved the OpenAI key to a server. Is my app safe now?
Not yet. The key is hidden, but the server can still answer anyone. Add a user check, a per-user limit, and an app check.
Is App Attest enough without a login?
No. App Attest proves that the request comes from your real app. It does not tell you which user sent it. Keep the user login and the per-user limit.
Does App Check stop all abuse?
No. It makes abuse harder because a script cannot easily copy a real app and device. A real user with a real app can still send too many requests. Limit each user.
Does App Attest work in the iOS Simulator?
No. The service reports that it is not supported in the Simulator. Use the debug provider of Firebase App Check for development builds.
What limit must I set for each user?
Start with a low daily count that fits normal use, for example 50 calls. Raise it for paid users. Log every call so that you can tune the number.

Test your ai backend

A VibeEval scan sends requests to the backend URLs of your app without a token and reports the endpoints that still return AI answers.

14-day free trial · Cancel anytime

SCAN YOUR APP →