whitebear
← Docs

Guide · Supabase · GitHub Actions · Cloudflare R2 · Workers ·

Daily Supabase backups to R2, with no keys stored

A GitHub Actions job that dumps the database every day into a private Cloudflare R2 bucket, with a 20-minute login from GitHub OIDC and a write-only Worker: no database password or bucket key anywhere.

Supabase's free plan keeps no backups you can download, and a backup job usually means a database password in a CI secret and a bucket key next to it: two keys that read or overwrite everything, living where every workflow can reach them. This is how our apps back up their databases every day without either. GitHub proves which workflow is running with its OIDC token; a small function answers with a database login that expires in 20 minutes; a Cloudflare Worker is the only way into the bucket, and it can only write.

The code here is the shape of ours, with the names changed. It fits in four files.

What you end up with

  • A dump of the whole database every day (pg_dump's custom format, with the auth schema), the roles, and their checksums, in a private R2 bucket, one folder per day, dropped after 90 days.
  • No database password and no bucket key anywhere: not in GitHub, not in the function, not in the Worker.
  • A job that only works when it is your workflow, on main, started by its schedule or by hand. A branch, a pull request or another repository gets a 403.

The pieces

Piece Runs on Does
db-backup.yml GitHub Actions Asks for a login, dumps, uploads
backup-login Supabase Edge Functions Checks the token, makes a role that reads everything and expires in 20 minutes
backup-upload Cloudflare Workers Checks the token, writes the day's three files to the bucket
The bucket Cloudflare R2 Keeps 90 days

Both checks read the same token claims. GitHub signs them, so nothing in them can be made up by the job:

Claim Must be
repository_id Your repository's id (gh api repos/<owner>/<repo> -q .id): survives a rename, unlike the name
repository_owner_id Your organization's id
ref refs/heads/main
workflow_ref <owner>/<repo>/.github/workflows/db-backup.yml@refs/heads/main
event_name schedule or workflow_dispatch
aud What each side expects: the function's name, or the Worker's own address

1. The bucket

npx wrangler r2 bucket create example-db-backups
npx wrangler r2 bucket lifecycle add example-db-backups expire-90d --expire-days 90
npx wrangler r2 bucket lifecycle add example-db-backups abort-multipart --abort-multipart-days 7

The second rule cleans up uploads cut off halfway. Leave the bucket private: no public access, no custom domain, no API token made for it.

2. The login: a role that lasts 20 minutes

An edge function that checks the token and creates a Postgres role that can read everything (pg_read_all_data, past row level security with bypassrls), log in twice at most, and stops working in 20 minutes. Expired roles are dropped on the next call.

The password never reaches the database as text: Postgres accepts a SCRAM-SHA-256 verifier in password '...', so the function computes it and only the job ever sees the password. Nothing in the statement, the logs or pg_authid can be used to log in.

// supabase/functions/backup-login/index.ts
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from 'npm:jose@5';
import postgres from 'npm:postgres@3';

const ISSUER = 'https://token.actions.githubusercontent.com';
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks`));
const REPOSITORY_ID = 123456789; // yours
const OWNER_ID = '987654321';    // yours
const PROJECT_REF = 'abcdefghijklmnopqrst';
const POOLER = { host: 'aws-0-us-east-1.pooler.supabase.com', port: 5432 }; // your project's session pooler

function fromBackupWorkflow(c: JWTPayload) {
  return (
    c.repository_id === REPOSITORY_ID &&
    String(c.repository_owner_id) === OWNER_ID &&
    c.ref === 'refs/heads/main' &&
    c.workflow_ref === `${c.repository}/.github/workflows/db-backup.yml@refs/heads/main` &&
    (c.event_name === 'schedule' || c.event_name === 'workflow_dispatch')
  );
}

const hex = (n: number) =>
  Array.from(crypto.getRandomValues(new Uint8Array(n)), (b) => b.toString(16).padStart(2, '0')).join('');
const b64 = (b: ArrayBuffer | Uint8Array) => btoa(String.fromCharCode(...new Uint8Array(b)));

/** What Postgres stores for a password (RFC 7677): the password itself never leaves this function. */
async function scramVerifier(password: string, iterations = 4096) {
  const enc = new TextEncoder();
  const salt = crypto.getRandomValues(new Uint8Array(16));
  const base = await crypto.subtle.importKey('raw', enc.encode(password), 'PBKDF2', false, ['deriveBits']);
  const salted = await crypto.subtle.deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, base, 256);
  const hmac = await crypto.subtle.importKey('raw', salted, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
  const clientKey = await crypto.subtle.sign('HMAC', hmac, enc.encode('Client Key'));
  const storedKey = await crypto.subtle.digest('SHA-256', clientKey);
  const serverKey = await crypto.subtle.sign('HMAC', hmac, enc.encode('Server Key'));
  return `SCRAM-SHA-256$${iterations}:${b64(salt)}$${b64(storedKey)}:${b64(serverKey)}`;
}

Deno.serve(async (req) => {
  const token = (req.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '');
  try {
    const { payload } = await jwtVerify(token, jwks, { issuer: ISSUER, audience: 'example-db-backup' });
    if (!fromBackupWorkflow(payload)) throw new Error();
  } catch {
    return new Response('Forbidden', { status: 403 });
  }

  const sql = postgres(Deno.env.get('SUPABASE_DB_URL')!, { max: 1, prepare: false });
  try {
    const expired = await sql.unsafe(
      `select rolname from pg_roles where rolname ~ '^backup_[0-9a-f]{16}$' and (rolvaliduntil is null or rolvaliduntil < now())`,
    );
    for (const { rolname } of expired) await sql.unsafe(`drop role if exists "${rolname}"`);

    const role = `backup_${hex(8)}`;
    const password = hex(32);
    const until = new Date(Date.now() + 20 * 60_000).toISOString();
    await sql.unsafe(
      `create role "${role}" login bypassrls connection limit 2 valid until '${until}' ` +
        `password '${await scramVerifier(password)}' in role pg_read_all_data`,
    );
    return Response.json({ user: `${role}.${PROJECT_REF}`, password, host: POOLER.host, port: POOLER.port });
  } finally {
    await sql.end();
  }
});

Deploy it without Supabase's own JWT check, since the caller has no Supabase session: verify_jwt = false for it in supabase/config.toml. The role and the password are built from random hex only, so nothing outside can end up in the SQL.

3. The Worker: write-only

The Worker checks the same claims, with its own address as the audience, and writes only the three file names of the day. It has no route that reads or lists.

// worker/src/index.js
import { createRemoteJWKSet, jwtVerify } from 'jose';

const ISSUER = 'https://token.actions.githubusercontent.com';
const jwks = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks`));

export default {
  async fetch(request, env) {
    if (request.method !== 'PUT') return new Response('Method not allowed', { status: 405 });
    const url = new URL(request.url);
    const token = (request.headers.get('authorization') ?? '').replace(/^Bearer\s+/i, '');
    let claims;
    try {
      ({ payload: claims } = await jwtVerify(token, jwks, { issuer: ISSUER, audience: url.origin }));
    } catch {
      return new Response('Forbidden', { status: 403 });
    }
    const ok =
      String(claims.repository_id) === env.REPOSITORY_ID &&
      String(claims.repository_owner_id) === env.OWNER_ID &&
      claims.ref === 'refs/heads/main' &&
      claims.workflow_ref === `${claims.repository}/.github/workflows/db-backup.yml@refs/heads/main` &&
      ['schedule', 'workflow_dispatch'].includes(claims.event_name);
    if (!ok) return new Response('Forbidden', { status: 403 });

    const key = url.pathname.slice(1);
    const m = /^(\d{4}-\d{2}-\d{2})\/(app\.dump|roles\.sql\.gz|SHA256SUMS)$/.exec(key);
    if (!m) return new Response('Not found', { status: 404 });
    await env.BACKUPS.put(key, request.body);
    return new Response('Stored', { status: 201 });
  },
};
# worker/wrangler.toml
name = "backup-upload"
main = "src/index.js"
compatibility_date = "2026-11-01"

[vars]
REPOSITORY_ID = "123456789"
OWNER_ID = "987654321"

[[r2_buckets]]
binding = "BACKUPS"
bucket_name = "example-db-backups"

npm install jose, then npx wrangler deploy. Its address (https://backup-upload.<you>.workers.dev) is the workflow's UPLOAD_URL and the token's audience.

4. The workflow

id-token: write is the only permission that matters: it lets the job ask GitHub for a token with the audience it names. pg_dump runs in the Postgres image of your database's major version.

# .github/workflows/db-backup.yml
name: Database backup
on:
  schedule:
    - cron: '17 6 * * *'
  workflow_dispatch:
permissions:
  contents: read
  id-token: write
env:
  LOGIN_URL: https://abcdefghijklmnopqrst.supabase.co/functions/v1/backup-login
  UPLOAD_URL: https://backup-upload.example.workers.dev
jobs:
  backup:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - name: Log in
        run: |
          token=$(curl -fsS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=example-db-backup" | jq -r .value)
          echo "::add-mask::$token"
          login=$(curl -fsS -X POST -H "Authorization: Bearer $token" "$LOGIN_URL")
          password=$(jq -r .password <<<"$login")
          echo "::add-mask::$password"
          {
            echo "PGHOST=$(jq -r .host <<<"$login")"
            echo "PGPORT=$(jq -r .port <<<"$login")"
            echo "PGUSER=$(jq -r .user <<<"$login")"
            echo "PGPASSWORD=$password"
            echo "PGDATABASE=postgres"
          } >> "$GITHUB_ENV"

      - name: Dump
        run: |
          mkdir dump
          docker run --rm -e PGHOST -e PGPORT -e PGUSER -e PGPASSWORD -e PGDATABASE -v "$PWD/dump:/dump" postgres:17 sh -c '
            pg_dump -Fc --exclude-schema="vault|pgsodium|pgsodium_masks|_analytics|_realtime|_supavisor" -f /dump/app.dump &&
            pg_dumpall -l postgres --roles-only --no-role-passwords -f /dump/roles.sql'
          gzip -9 dump/roles.sql
          (cd dump && sha256sum app.dump roles.sql.gz > SHA256SUMS)

      - name: Upload
        run: |
          token=$(curl -fsS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$UPLOAD_URL" | jq -r .value)
          echo "::add-mask::$token"
          day=$(date -u +%Y-%m-%d)
          for f in app.dump roles.sql.gz SHA256SUMS; do
            curl -fsS -X PUT --upload-file "dump/$f" -H "Authorization: Bearer $token" "$UPLOAD_URL/$day/$f"
          done

The schemas left out are Supabase's own, which a restore recreates; Vault's secrets stay out of the bucket. Run it once with «Run workflow» and look in the bucket.

Restore

Into an empty Supabase project, or any Postgres of the same major version:

sha256sum -c SHA256SUMS
gunzip roles.sql.gz && psql "$DATABASE_URL" -f roles.sql        # the roles that are missing; errors for existing ones are fine
pg_restore --clean --if-exists -d "$DATABASE_URL" app.dump

Restore one into a scratch project now and then: a backup nobody has restored is a guess.

What this doesn't protect

  • main. Whoever can push to main can change what the workflow does with the login. Protect it like production, because it is.
  • Reading the bucket. Only from Cloudflare's dashboard or wrangler r2 object get, with your own account. That is the point: nothing the job holds can read past backups.
  • A broken day. If a run fails, nothing tells you unless you look: turn on GitHub's failure emails at least, or have the last step report each run somewhere you check.

Where we use it

Our apps on Supabase run this every morning. The repository is private: the pieces are small enough to copy, and each app keeps its own ids out of shared code.

whitebear