How to stop pg_cron jobs from running on a restored project or branch
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 asenvironment = 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_detailstable on the copy shows runs of jobs that you scheduled on the production project. - The
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 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 from cron.job order by jobid;select jobname, command from cron.job where 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:
select cron.alter_job(job_id := jobid, active := false) from cron.job where 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.
create schema if not exists ops;create table if not exists ops.home (id int primary key default 1,token text not null,check (id = 1));create or replace function ops.is_home() returns booleanlanguage sql stable as $$select exists (select 1 from ops.home)$$; -
On the production project only, add the row by hand, outside any migration.
insert into ops.home (id, token) values (1, gen_random_uuid()::text); -
In every job, put the HTTP calls and the writes inside the check.
select cron.schedule('nightly-sync', '<cron schedule>', $job$do $b$ beginif ops.is_home() thenperform 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 from cron.job where 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.
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.
| 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.
select vault.create_secret('<secret>', 'job_secret'); -
In each job, sign the timestamp and the body, and send both with the request.
do $b$declarepayload jsonb := '{"job": "nightly-sync"}';ts text := extract(epoch from now())::bigint::text;secret text := (select decrypted_secret from vault.decrypted_secrets where name = 'job_secret');beginperform 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
Authorizationheader with your publishable key. -
In the receiver, verify the signature, and reject any request that fails.
const encoder = new TextEncoder()// Reject timestamps older or newer than this many secondsconst MAX_AGE_SECONDS = 300function hexToBytes(hex: string): Uint8Array | null {if (!/^[0-9a-f]{64}$/i.test(hex)) return nullreturn Uint8Array.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 requestconst secret = Deno.env.get('CRON_SECRET')const timestamp = req.headers.get('x-timestamp')const signature = hexToBytes(req.headers.get('x-signature') ?? '')const body = await req.text()if (!secret || !timestamp || !signature) {return new Response('forbidden', { status: 403 })}const age = Math.abs(Date.now() / 1000 - Number(timestamp))if (!Number.isFinite(age) || age > MAX_AGE_SECONDS) {return new Response('forbidden', { status: 403 })}const key = await crypto.subtle.importKey('raw',encoder.encode(secret),{ name: 'HMAC', hash: 'SHA-256' },false,['verify'])const valid = await crypto.subtle.verify('HMAC',key,signature,encoder.encode(`${timestamp}.${body}`))if (!valid) {return new Response('forbidden', { status: 403 })}// Handle the requestreturn new Response('ok')}) -
Right after you start creating the copy, set a new secret in Vault and in the receiver.
select vault.update_secret((select id from vault.secrets where name = 'job_secret'),'<new secret>');read -rs NEW_SECRETexport NEW_SECRETsupabase secrets set CRON_SECRET="$NEW_SECRET" --project-ref <project-ref>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_usercan 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 isfalse, 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.