You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Stop pg_cron jobs on a restored project or branch from calling your production endpoints, such as an Edge Function that a job reaches through pg_net.
This guide uses the following terms:
Production project: the Supabase project that you copy from. It serves your live app.
Production endpoints: the live URLs that your jobs call, such as Edge Functions, your own APIs, and third-party services.
Copy: a branch of the production project, or a project that you create by restoring a backup of it to a new project.
A copy starts running your pg_cron jobs on its own, before you can disable them. A job that calls a production endpoint can then send requests to your live app.
Overview
The following table shows what each kind of copy contains and which protection applies.
Copy
What it contains
Protection
Branch without data
Jobs defined in your migrations, created active. Jobs you created by hand on the production project are not included.
Home row guard
Branch with data, created with supabase branches create --with-data
All of your data and jobs. Jobs that were active on the production project are active on the branch.
Rotate a secret that the receiver checks
Restore to a new project, from a physical backup or point-in-time recovery (PITR)
All of your data and jobs. Jobs that were active when the backup was taken are active on the new project.
Rotate a secret that the receiver checks
Three facts make prevention hard:
Job commands often contain the URL of a production endpoint or an API key. A copy can reach and authenticate to your live app.
A copy looks identical to the production project. It has the same system_identifier, the same settings, and the same rows, including a marker row such as environment = production.
A physical restore starts without giving you a chance to edit the copy.
Diagnose the problem
You see one of the following symptoms:
A production endpoint, such as an Edge Function, receives requests that you didn't send after you create a branch or restore a project.
The cron.job_run_details table on the copy shows runs of jobs that you scheduled on the production project.
The net._http_response table on the copy holds responses from your production endpoints.
Run the following SQL using the SQL Editor in the Supabase Dashboard or with psql over a direct connection. To connect with psql, see Direct connection.
Option 1: List the jobs on the copy
select jobid, jobname, schedule, active fromcron.joborder by jobid;
select jobname, command fromcron.jobwhere command ilike '%http%';
A job with active set to true runs on the copy. A job whose command contains the URL of a production endpoint calls that endpoint from the copy.
Option 2: Check your receiver logs
Open the logs of the endpoint that your jobs call, and look for requests from the time you created the copy. Requests that you didn't send come from the copy.
Option 3: Contact support
If a job is owned by a role that you can't alter, contact Support.
Solve the problem
Run each SQL block in this section the same way as in Diagnose the problem: with the SQL Editor or with psql.
The guards in this section are examples. Rename the schemas, tables, functions, headers, and secrets to fit your project, and change the checks if another approach suits your setup. Each guard rests on one idea, which its description explains. Test your version on a throwaway branch before you rely on it.
Add a guard to the production project before you create a copy. A copy carries the jobs and guards that exist when you create it.
Stop the jobs on the copy
On a branch or a restored project, suspend every job:
selectcron.alter_job(job_id := jobid, active := false) fromcron.jobwhere active;
Jobs can run before you reach this step, so add one of the following guards to protect your production endpoints.
Branch without data: add a home row guard
The home row guard makes each job look for a marker row before it runs. Only the production project has the row, so jobs on a branch without data skip their work.
The guard has the following parts.
Part
What it does
ops.home table
Holds the marker row. A migration creates it, empty, on every branch.
Marker row
You add it by hand on the production project. It exists nowhere else.
ops.is_home() function
Returns true when the table has a row, and false when the table is empty.
Check in each job
Runs the HTTP calls and the writes only when ops.is_home() returns true.
A branch without data replays your migrations and copies no data. On the production project, the row exists and jobs run as usual. On the branch, the table is empty, ops.is_home() returns false, and each job skips its HTTP calls and writes.
Add a migration that creates an empty table and a helper function. Apply it to the production project before you create a branch, so every branch replays it.
createschemaif not exists ops;
createtableif not exists ops.home (
id intprimary key default 1,
token textnot null,
check (id =1)
);
create or replacefunctionops.is_home() returns boolean
language sql stable as $$
select exists (select1fromops.home)
$$;
On the production project only, add the row by hand, outside any migration.
In every job, put the HTTP calls and the writes inside the check.
selectcron.schedule('nightly-sync', '<cron schedule>', $job$
do $b$ begin
if ops.is_home() then
perform net.http_post(
url :='https://<project-ref>.supabase.co/functions/v1/sync',
headers :='{"Content-Type": "application/json"}'::jsonb
);
end if;
end $b$;
$job$);
To add the check to a job you already created, add a migration that updates the job's command with cron.alter_job. To list the jobs that don't use the check:
select jobname fromcron.jobwhere command not like'%ops.is_home()%';
To adapt the guard, rename the schema, table, and function. You can also write the check inline in a job, as if exists (select 1 from ops.home), instead of calling the function.
Keep the following rules in mind:
Seeding the row in a migration defeats the guard. The branch replays the migration, and the check passes.
Keep the URLs of production endpoints and API keys out of migrations. Branches copy the jobs that carry them.
Check ops.is_home() in every job. A job without the check calls your production endpoints.
The guard prevents accidents. It isn't an access control, because anyone who can write to ops.home can change it. Keep the table in a schema that the API doesn't expose, such as ops, or enable row level security on it.
Branch with data or restore: rotate a secret that the receiver checks
The rotating secret guard makes the receiver verify each caller. The receiver is the Edge Function or API that your jobs call. It isn't part of any copy, so it can refuse requests from one.
Each job signs its request with a shared secret, and the receiver checks the signature. When you create a copy, you rotate the secret on both sides. The copy holds the old secret, so its signatures no longer verify.
The guard has the following parts.
Part
What it does
Vault secret
Stores the shared secret on the production project.
Job
Signs the timestamp and the request body with the secret using HMAC-SHA256, and sends the timestamp and the signature. The secret never leaves the database.
Receiver
Recomputes the signature. It returns HTTP 403 for a mismatch, an old timestamp, a missing header, or an unset CRON_SECRET.
Rotation
Replaces the secret in Vault and in the receiver after you start creating a copy.
Before you create a copy, the job and the receiver hold the same secret, so signatures verify. A copy is built from a snapshot taken when you create it, so it holds that secret. When you rotate right after, the production project and the receiver hold the new secret, and the copy holds the old one. The copy's jobs sign with the old secret, and the receiver rejects them.
The job sends a signature. pg_net keeps a queued request's headers in a table that other database roles can read until the worker sends the request. A signature exposes no secret there.
On the production project, store the secret in Vault. Use a long random value.
In each job, sign the timestamp and the body, and send both with the request.
do $b$
declare
payload jsonb :='{"job": "nightly-sync"}';
ts text := extract(epoch from now())::bigint::text;
secret text := (
select decrypted_secret fromvault.decrypted_secretswhere name ='job_secret'
);
begin
perform net.http_post(
url :='https://<project-ref>.supabase.co/functions/v1/sync',
headers := jsonb_build_object(
'Content-Type', 'application/json',
'x-timestamp', ts,
'x-signature', encode(extensions.hmac(ts ||'.'|| payload::text, secret, 'sha256'), 'hex')
),
body := payload
);
end $b$;
If the function verifies JWTs, also send an Authorization header with your publishable key.
In the receiver, verify the signature, and reject any request that fails.
constencoder=newTextEncoder()// Reject timestamps older or newer than this many secondsconstMAX_AGE_SECONDS=300functionhexToBytes(hex: string): Uint8Array|null{if(!/^[0-9a-f]{64}$/i.test(hex))returnnullreturnUint8Array.from(hex.match(/../g)!.map((byte)=>parseInt(byte,16)))}Deno.serve(async(req)=>{// Read the secret on each request so a rotated value applies to the next requestconstsecret=Deno.env.get('CRON_SECRET')consttimestamp=req.headers.get('x-timestamp')constsignature=hexToBytes(req.headers.get('x-signature')??'')constbody=awaitreq.text()if(!secret||!timestamp||!signature){returnnewResponse('forbidden',{status: 403})}constage=Math.abs(Date.now()/1000-Number(timestamp))if(!Number.isFinite(age)||age>MAX_AGE_SECONDS){returnnewResponse('forbidden',{status: 403})}constkey=awaitcrypto.subtle.importKey('raw',encoder.encode(secret),{name: 'HMAC',hash: 'SHA-256'},false,['verify'])constvalid=awaitcrypto.subtle.verify('HMAC',key,signature,encoder.encode(`${timestamp}.${body}`))if(!valid){returnnewResponse('forbidden',{status: 403})}// Handle the requestreturnnewResponse('ok')})
Right after you start creating the copy, set a new secret in Vault and in the receiver.
selectvault.update_secret(
(select id fromvault.secretswhere name ='job_secret'),
'<new secret>'
);
When the terminal waits for input, paste the same value that you set in Vault.
To adapt the guard, choose any header names, any body, and any timestamp limit. The receiver can read the secret from Edge Function secrets, as in the example, or from the configuration of your own API. You can rotate by hand, with a script, or on a schedule.
Keep the following rules in mind:
Rotate right after you start creating the copy. The copy is built from a snapshot taken when you create it. A secret that you rotated earlier is already in the copy. The copy's jobs start on their own.
Change both sides together. If only one side changes, the receiver rejects your jobs on the production project.
A captured request can be replayed until its timestamp expires. Make the receiver idempotent.
A copy can decrypt the Vault secret, and a downloaded backup holds it. The old secret stays valid until you rotate, so rotate on a schedule as well.
Handle the secret with care:
supabase_read_only_user can read decrypted Vault secrets. Keep read-only and backup roles away from the secret, or treat them as holders of it.
Keep the secret out of saved SQL snippets and shell history. The example reads the new value without echoing it or storing it in history.
Confirm the problem is solved
On a branch without data, run select ops.is_home();. The result is false, and guarded jobs make no calls.
After a rotation, open your receiver logs. Requests from the copy return HTTP 403, and requests from the production project succeed.
On any copy, run select jobname, active from cron.job order by jobid; and check that the jobs you want to stop are inactive.
Limits of these guards
The guards cover scheduled jobs that call endpoints you control. The following cases are outside their scope:
Database Webhooks, triggers that call pg_net, and foreign data wrappers.
Restoring a backup in place, over the same project.
Third-party APIs. To protect one, rotate that provider's key.
A copy's own writes to its own database still happen, but they only affect the copy.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Stop
pg_cronjobs on a restored project or branch from calling your production endpoints, such as an Edge Function that a job reaches throughpg_net.This guide uses the following terms:
A copy starts running your
pg_cronjobs on its own, before you can disable them. A job that calls a production endpoint can then send requests to your live app.Overview
The following table shows what each kind of copy contains and which protection applies.
supabase branches create --with-dataThree facts make prevention hard:
system_identifier, the same settings, and the same rows, including a marker row such asenvironment = production.Diagnose the problem
You see one of the following symptoms:
cron.job_run_detailstable on the copy shows runs of jobs that you scheduled on the production project.net._http_responsetable on the copy holds responses from your production endpoints.Run the following SQL using the SQL Editor in the Supabase Dashboard or with
psqlover a direct connection. To connect withpsql, see Direct connection.Option 1: List the jobs on the copy
A job with
activeset totrueruns on the copy. A job whose command contains the URL of a production endpoint calls that endpoint from the copy.Option 2: Check your receiver logs
Open the logs of the endpoint that your jobs call, and look for requests from the time you created the copy. Requests that you didn't send come from the copy.
Option 3: Contact support
If a job is owned by a role that you can't alter, contact Support.
Solve the problem
Run each SQL block in this section the same way as in Diagnose the problem: with the SQL Editor or with
psql.The guards in this section are examples. Rename the schemas, tables, functions, headers, and secrets to fit your project, and change the checks if another approach suits your setup. Each guard rests on one idea, which its description explains. Test your version on a throwaway branch before you rely on it.
Add a guard to the production project before you create a copy. A copy carries the jobs and guards that exist when you create it.
Stop the jobs on the copy
On a branch or a restored project, suspend every job:
Jobs can run before you reach this step, so add one of the following guards to protect your production endpoints.
Branch without data: add a home row guard
The home row guard makes each job look for a marker row before it runs. Only the production project has the row, so jobs on a branch without data skip their work.
The guard has the following parts.
ops.hometableops.is_home()functiontruewhen the table has a row, andfalsewhen the table is empty.ops.is_home()returnstrue.A branch without data replays your migrations and copies no data. On the production project, the row exists and jobs run as usual. On the branch, the table is empty,
ops.is_home()returnsfalse, and each job skips its HTTP calls and writes.Add a migration that creates an empty table and a helper function. Apply it to the production project before you create a branch, so every branch replays it.
On the production project only, add the row by hand, outside any migration.
In every job, put the HTTP calls and the writes inside the check.
To add the check to a job you already created, add a migration that updates the job's command with
cron.alter_job. To list the jobs that don't use the check:To adapt the guard, rename the schema, table, and function. You can also write the check inline in a job, as
if exists (select 1 from ops.home), instead of calling the function.Keep the following rules in mind:
ops.is_home()in every job. A job without the check calls your production endpoints.The guard prevents accidents. It isn't an access control, because anyone who can write to
ops.homecan change it. Keep the table in a schema that the API doesn't expose, such asops, or enable row level security on it.A branch with data or a restore also copies the row, so the check passes there. For those copies, rotate a secret that the receiver checks.
Branch with data or restore: rotate a secret that the receiver checks
The rotating secret guard makes the receiver verify each caller. The receiver is the Edge Function or API that your jobs call. It isn't part of any copy, so it can refuse requests from one.
Each job signs its request with a shared secret, and the receiver checks the signature. When you create a copy, you rotate the secret on both sides. The copy holds the old secret, so its signatures no longer verify.
The guard has the following parts.
CRON_SECRET.Before you create a copy, the job and the receiver hold the same secret, so signatures verify. A copy is built from a snapshot taken when you create it, so it holds that secret. When you rotate right after, the production project and the receiver hold the new secret, and the copy holds the old one. The copy's jobs sign with the old secret, and the receiver rejects them.
The job sends a signature.
pg_netkeeps a queued request's headers in a table that other database roles can read until the worker sends the request. A signature exposes no secret there.On the production project, store the secret in Vault. Use a long random value.
In each job, sign the timestamp and the body, and send both with the request.
If the function verifies JWTs, also send an
Authorizationheader with your publishable key.In the receiver, verify the signature, and reject any request that fails.
Right after you start creating the copy, set a new secret in Vault and in the receiver.
When the terminal waits for input, paste the same value that you set in Vault.
To adapt the guard, choose any header names, any body, and any timestamp limit. The receiver can read the secret from Edge Function secrets, as in the example, or from the configuration of your own API. You can rotate by hand, with a script, or on a schedule.
Keep the following rules in mind:
Handle the secret with care:
supabase_read_only_usercan read decrypted Vault secrets. Keep read-only and backup roles away from the secret, or treat them as holders of it.Confirm the problem is solved
select ops.is_home();. The result isfalse, and guarded jobs make no calls.select jobname, active from cron.job order by jobid;and check that the jobs you want to stop are inactive.Limits of these guards
The guards cover scheduled jobs that call endpoints you control. The following cases are outside their scope:
pg_net, and foreign data wrappers.A copy's own writes to its own database still happen, but they only affect the copy.
Related resources
All reactions