Deutsch
GuideSupabase · Database

SECURITY DEFINER functions in Supabase, done right

When a Supabase function should run as SECURITY DEFINER, and the five rules that keep it safe: empty search_path, caller checks, revoked EXECUTE, tested SQL.

By Tim GeithnerPublished 7 min read

Short answer

A SECURITY DEFINER function runs with the rights of its owner, which in Supabase is an admin role that skips row level security. In the public schema it is also an API endpoint anyone can call. Use one only when you need it, set search_path = ‘’, schema-qualify every name, check the caller inside with auth.uid(), and revoke EXECUTE from public and anon (and from authenticated if only your server should call it).

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • A SECURITY DEFINER function runs as its owner. In Supabase that owner skips row level security, so the function sees every row.
  • Every function in the public schema is an API endpoint. By default, anon and every signed-in user can call it.
  • Five rules: pin search_path = '', schema-qualify every name, check the caller with auth.uid(), revoke EXECUTE from public and anon, and keep internal helpers out of exposed schemas.
  • Never take “which user” from a parameter. Read it from the session inside the function.
  • Revoking from anon alone does nothing while PUBLIC still has EXECUTE. We tested it.

What SECURITY DEFINER actually does

A Postgres function normally runs with the rights of whoever calls it. That is security invoker, the default. A security definer function runs with the rights of the role that created it instead.

In a Supabase project, functions created by a migration or in the dashboard belong to postgres, and that role is not held back by row level security. So inside a definer function, your RLS policies are effectively switched off. Supabase’s own guide on database functions says to prefer security invoker and warns that a definer function “can return rows the caller isn’t allowed to read”.

The second half of the problem is reach. Supabase exposes the public schema through its Data API, and functions there can be called from the browser with supabase.rpc("name", …). Postgres grants EXECUTE on every new function to PUBLIC, and Supabase’s default privileges grant it to anon and authenticated as well. Put both together and you get an admin-powered endpoint that a visitor without an account can call.

When you really need one

There are three good reasons. If your function is not one of them, make it security invoker and let RLS do its job.

JobWhy definer helpsExample
Policy helperA policy has to read a table the user cannot read, without running into that table’s own policiesis_member(workspace_id) checks workspace_members
Controlled writeUsers may change a table only in one narrow wayspend_credit() takes exactly one credit from the caller
Server-only operationOnly your backend should do it, but it needs to be callable through the APIadd_credits() after a verified payment webhook

AI builders also reach for security definer for a fourth reason: a query fails because of RLS, and the quickest way to make the error go away is to run it as the owner. That is the one to remove.

The broken pattern, tested

Here is a small documents table with RLS on and an owner-only read policy. Users can see their own documents and nothing else:

documents table
create table public.documents (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id) on delete cascade,
  title text not null,
  archived boolean not null default false
);

alter table public.documents enable row level security;

create policy "Owners can read their documents"
  on public.documents for select
  to authenticated
  using ((select auth.uid()) = user_id);

There is no update policy, so an “archive” button fails. A typical AI-written fix adds this function:

Vulnerablearchive_document.sql
create function public.archive_document(doc_id uuid)
returns void
language plpgsql
security definer
as $$
begin
  update documents set archived = true where id = doc_id;
end;
$$;

The button works now. We ran it against a Postgres database set up like a Supabase project, with two users:

  • User B archived user A’s document by calling the function with A’s document ID. RLS never got a say, because the function runs as the owner.
  • A signed-out visitor archived a document as well. anon could call the function through the default grants.
  • The function has no pinned search_path, so the unqualified name documents is looked up wherever the session’s path points.

Find these functions in your project

Run this in the SQL Editor. It lists every definer function in public, shows whether its search_path is pinned and who can call it:

Definer functions in public and who can call them
select p.proname as function_name,
       pg_get_function_identity_arguments(p.oid) as arguments,
       coalesce(array_to_string(p.proconfig, ', '), 'no search_path set') as settings,
       has_function_privilege('anon', p.oid, 'execute') as anon_can_call,
       has_function_privilege('authenticated', p.oid, 'execute') as users_can_call
from pg_proc p
join pg_namespace n on n.oid = p.pronamespace
where p.prosecdef
  and n.nspname = 'public'
order by p.proname;

Every row with no search_path set needs a fix. Every row where anon_can_call is true needs a reason. If you expose other schemas in Settings → API, change 'public' to cover them too. The Security Advisor in your dashboard checks the same things: lint 0011 for a mutable search path, and 0028 and 0029 for definer functions that signed-out or signed-in users can call.

Five rules for a safe definer function

Pin the search path

Add set search_path = '' to the function. The PostgreSQL manual explains why: without it, a caller who can create objects in a schema on the path can mask the table or function you meant, and their object then runs with the owner’s rights. Supabase’s RLS guide asks for an empty path on every definer function.

Schema-qualify every name

With an empty path, documents no longer resolves. Write public.documents, auth.uid() and so on. It reads a little longer and removes the whole class of look-alike tricks.

Check the caller inside the function

EXECUTE decides who may call the function, not which rows they may touch. Read the user from the session with (select auth.uid()), refuse to run without one, and filter every statement by it. Never accept a user_id parameter for “the current user”.

Revoke EXECUTE from public and anon

Revoke from public and anon in one statement, then grant back only what is needed. For a function only your server calls, revoke from authenticated too and grant to service_role.

Keep internal helpers out of exposed schemas

A helper that only your policies call does not need to be an endpoint. Put it in a schema such as private that is not listed under Exposed schemas. Supabase’s RLS guide says never to create a definer function in an exposed schema; where a function must stay callable through the API, rules 3 and 4 carry the weight.

The fixed function, tested

Before you fix the definer function, ask whether you need it. Here an update policy plus a security invoker function would do the same job. If you keep the definer, for example because the function also writes to a log table that users cannot write to, this is the safe shape:

Safearchive_document.sql
create or replace function public.archive_document(doc_id uuid)
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
  if (select auth.uid()) is null then
    raise exception 'not signed in';
  end if;

  update public.documents
     set archived = true
   where id = doc_id
     and user_id = (select auth.uid());

  if not found then
    raise exception 'document not found';
  end if;
end;
$$;

revoke execute on function public.archive_document(uuid) from public, anon;
grant execute on function public.archive_document(uuid) to authenticated;

What changed, and what our test showed afterwards:

  • User B calling it with A’s document ID now gets document not found, and A’s document stays untouched. The error does not even confirm that the ID exists.
  • User A can still archive her own document.
  • A signed-out visitor gets permission denied for function archive_document.
  • The finder query above now shows search_path="" and anon_can_call = false.

Functions only your server should call

Some functions should never be called from a browser at all. Granting credits after a payment is the classic example. In one of our own test apps, a small credits app built like a Lovable project, the migration contained this pattern on purpose: a security definer function add_credits(_user uuid, _amount int) granted to authenticated, called by the browser on the payment success page, with no check of the caller or the payment and no pinned search path. Any signed-in user could give any account any number of credits. The ShipRely engine found this pattern in our test apps; the same app also has a correctly built spend_credit() function that the audit must leave alone.

The fix is to make it unreachable for users and call it only from your verified payment webhook with the secret key:

Safeadd_credits.sql
create function public.add_credits(_user uuid, _amount integer)
returns integer
language plpgsql
security definer
set search_path = ''
as $$
declare
  _balance integer;
begin
  insert into public.credit_accounts (user_id, balance)
  values (_user, _amount)
  on conflict (user_id) do update
    set balance = public.credit_accounts.balance + excluded.balance
  returning balance into _balance;

  return _balance;
end;
$$;

revoke execute on function public.add_credits(uuid, integer) from public, anon, authenticated;
grant execute on function public.add_credits(uuid, integer) to service_role;

Here a _user parameter is fine, because only service_role can call the function and your webhook decides the user after it has verified the payment. In our test, signed-in users and anon both got permission denied, while service_role added 35 and then 12 credits to the right account. For the webhook side, see the Stripe guide and the fix for credits granted on the client.

A fix prompt for your AI builder

Harden SECURITY DEFINER functions

Find every function in my Supabase migrations that is declared SECURITY DEFINER. For each one, write a new migration that:

  • adds SET search_path = ‘’ and schema-qualifies every table and function name inside it (public.table_name, auth.uid());
  • if the function acts for the current user: removes any user id parameter, reads the user with (select auth.uid()), raises an exception when it is null, and filters every statement by that user;
  • runs REVOKE EXECUTE ON FUNCTION ... FROM public, anon; then GRANT EXECUTE only to the roles that need it (service_role only for functions that grant credits, change plans or do admin work);
  • switches the function to SECURITY INVOKER instead if an RLS policy can do the same job.

Do not change other objects. Show me the migration and a list of the functions you changed and why.

Test it yourself

Use the role switch from the RLS testing guide to call the function as a real user and as a visitor:

Call it as a signed-out visitor
begin;
set local role anon;
select public.archive_document('00000000-0000-0000-0000-000000000000');
rollback;

After the fix this fails with permission denied for function archive_document. Then repeat as a second signed-in user with someone else’s document ID, as shown in the row level security guide, and check that nothing changed.

Frequently asked questions

Is SECURITY DEFINER always dangerous?

No. It is the right tool for a few jobs, such as a policy helper that has to read a membership table, or a function that lets a user spend one credit without giving them write access to the credits table. It becomes dangerous when the function trusts its parameters, has no pinned search_path or can be called by roles that should not call it.

Can anon call my functions in Supabase?

By default, yes. Postgres gives EXECUTE on new functions to PUBLIC, and Supabase’s default privileges also grant it to anon and authenticated. Every function in an exposed schema such as public can then be called through the Data API, for example with supabase.rpc(). Revoke EXECUTE from public and anon on every function that visitors do not need.

Why is revoking EXECUTE from anon not enough?

Because PUBLIC still has it, and every role, anon included, gets what PUBLIC has. We tested this: after revoke … from anon, anon could still call the function. Revoke from public and anon in the same statement, then grant EXECUTE back to the roles that need it.

What does set search_path = ‘’ change?

It stops the function from looking up unqualified names in schemas a caller might control, so nobody can slip in a look-alike table or function that then runs with the owner’s rights. With an empty path you must write public.documents instead of documents. The Supabase Security Advisor flags functions without a pinned search_path.

Sources

  1. 1.CREATE FUNCTION: Writing SECURITY DEFINER Functions Safely — PostgreSQL Documentation
  2. 2.Database Functions — Supabase Docs
  3. 3.Row Level Security — Supabase Docs
  4. 4.Performance and Security Advisors — Supabase Docs
  5. 5.CWE-250: Execution with Unnecessary Privileges — MITRE

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt