Site icon NexGismo

RLS Policy Privilege Escalation: Lessons From Dosu’s Breach

RLS Policy Privilege Escalation: Lessons From Dosu's Breach
TL;DR
  • What: One missing check in an RLS policy on org invitations let a free user make themselves owner of Dosu’s internal org.
  • Why it matters: That single row-level bug chained into integration secrets, the database, CI and the cloud project.
  • What to do: Make every INSERT policy prove authority over the target resource, and keep production credentials out of PR pipelines.
  • Key stat: The attacker went from a new account to Dosu’s cloud project in under two hours.

An RLS policy privilege escalation happens when a row-level security policy checks who is writing a row but not whether they control the resource the row points to. In Dosu’s November 2026 breach, an invitation policy let any signed-in user invite themselves as owner of any org. The fix is a WITH CHECK that verifies ownership of the target org.

RLS policy privilege escalation is an authorization flaw in PostgreSQL row-level security where a policy lets a user insert or update rows that grant them more access than they hold. It usually comes from a WITH CHECK expression that validates the row’s author but not the author’s rights over the row’s target, such as an org, team or project.

An RLS policy privilege escalation is the kind of bug that passes code review because the policy looks correct. On November 2, 2026, an attacker used exactly that kind of flaw at Dosu, the AI documentation platform. Dosu’s own post-mortem says the attacker signed up for a free account, abused “an incorrect RLS policy check” on org invitations, and became owner of Dosu’s internal org.

From there the chain moved fast: integration credentials, database tokens, a pull request that leaked cloud keys from CI, and a backdoor service. The main intrusion ran from 04:11 to 07:59 UTC, per the same report.

If you build multi-tenant apps on Supabase, Postgres or any “invite a teammate” flow in Node.js, Next.js or Django, this post-mortem is a checklist in disguise. Below, I walk through the attack chain, reproduce the invitation-policy bug in a real Postgres engine, show the fixed policy, and cover the two CI and integration lessons that turned one bad row into a full breach.

What happened in the Dosu breach, step by step?

The attacker chained seven steps, each using access gained in the step before. All times below come from Dosu’s published timeline.

  1. Recon (Oct 31 to Nov 2): two IP addresses scanned public APIs and tried forged tokens. Every forged token was rejected.
  2. Sign-up (05:59 UTC): a free Dosu account via Slack sign-in.
  3. Org takeover (06:21 to 07:00): the flawed invitation policy let the attacker invite themselves as owner of Dosu’s internal org and one open-source org.
  4. Integration credentials (06:42): as owner, they changed the integration server URL to a Cloudflare Quick Tunnel. Dosu then sent the integrations’ credentials to it.
  5. Database (06:51 to 07:57): a read-only DB token led to further credentials and command execution.
  6. CI (07:50): with the bot’s GitHub token they opened a pull request. CI ran an infrastructure preview with production cloud credentials, and the PR’s code sent them out.
  7. Cloud (07:52 to 07:59): a small backdoor service was deployed. An org policy blocked every attempt to make it public.

Supabase detected the activity and alerted Dosu at 08:17 UTC. Dosu was unavailable until 11:28, shipped the invitation fix at 15:35, and finished rotating every production secret by 16:53, according to the incident timeline.

Why did an RLS policy privilege escalation work on an invitation table?

It worked because invitation rows grant access to a different resource than the row itself. Dosu has not published the exact policy. It describes “one missing check in one access policy written years ago,” which let the attacker create an invitation to any org.

Here is the trap. The standard ownership pattern in Supabase’s RLS guide is with check ((select auth.uid()) = user_id). It ensures “a user cannot create a row that belongs to someone else.” That is right for a profile or a todo. It is wrong for an invitation, because the dangerous column is org_id, not the author column.

The broken shape

-- BROKEN: proves who wrote the row, not that they may invite into org_id
CREATE POLICY invite_insert ON org_invitations
  FOR INSERT TO authenticated
  WITH CHECK (invited_by = auth.uid());

This policy reads well in review. It also lets any signed-in user insert {org_id: <victim org>, invitee_id: <me>, role: 'owner'}. If accepting an invitation then creates a membership, the attacker owns the org.

The fixed shape

CREATE SCHEMA IF NOT EXISTS private;

CREATE FUNCTION private.is_org_owner(target_org uuid)
RETURNS boolean
LANGUAGE sql STABLE SECURITY DEFINER
SET search_path = ''
AS $$
  SELECT EXISTS (
    SELECT 1 FROM public.org_members
    WHERE org_id = target_org
      AND user_id = (SELECT auth.uid())
      AND role = 'owner'
  )
$$;

-- FIXED: the inviter must own the target org, and cannot invite themselves
CREATE POLICY invite_insert ON org_invitations
  FOR INSERT TO authenticated
  WITH CHECK (
    invited_by = (SELECT auth.uid())
    AND (SELECT private.is_org_owner(org_id))
    AND invitee_id <> (SELECT auth.uid())
  );

The helper follows Supabase’s documented rules: a security definer function must set search_path = '' and must never live in an exposed schema, or it becomes callable over the Data API with the creator’s privileges.

Can you reproduce an RLS policy privilege escalation locally?

Yes, and you should, because a policy test catches an RLS policy privilege escalation in seconds. We ran the broken and fixed policies against PGlite 0.5.17, which reports itself as PostgreSQL 18.7, on Node.js v22.23.4 in our sandbox. The script mimics Supabase with an authenticated role and an auth.uid() function backed by a session setting.

// rls_test.mjs — npm i @electric-sql/pglite
import { PGlite } from '@electric-sql/pglite';

const ORG = '00000000-0000-0000-0000-00000000000a';
const OWNER = '00000000-0000-0000-0000-000000000001';
const ATTACKER = '00000000-0000-0000-0000-0000000000ff';

async function run(label, check) {
  const db = new PGlite();
  await db.exec(`
    CREATE SCHEMA auth;
    CREATE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE
      AS $$ SELECT current_setting('app.user_id', true)::uuid $$;
    CREATE ROLE authenticated NOLOGIN;
    GRANT USAGE ON SCHEMA auth TO authenticated;
    CREATE TABLE orgs (id uuid PRIMARY KEY, name text);
    CREATE TABLE org_members (org_id uuid, user_id uuid, role text,
      PRIMARY KEY (org_id, user_id));
    CREATE TABLE org_invitations (id serial PRIMARY KEY, org_id uuid,
      invitee_id uuid, role text, invited_by uuid);
    ALTER TABLE org_invitations ENABLE ROW LEVEL SECURITY;
    GRANT SELECT, INSERT ON org_invitations TO authenticated;
    GRANT USAGE ON SEQUENCE org_invitations_id_seq TO authenticated;
    CREATE FUNCTION is_org_owner(o uuid) RETURNS boolean
      LANGUAGE sql STABLE SECURITY DEFINER AS $$
      SELECT EXISTS (SELECT 1 FROM org_members
        WHERE org_id = o AND user_id = auth.uid() AND role = 'owner') $$;
    CREATE POLICY invite_insert ON org_invitations FOR INSERT
      TO authenticated WITH CHECK (${check});
    INSERT INTO orgs VALUES ('${ORG}', 'internal-org');
    INSERT INTO org_members VALUES ('${ORG}', '${OWNER}', 'owner');
  `);
  await db.exec(`SET ROLE authenticated; SET app.user_id = '${ATTACKER}';`);
  try {
    await db.query(`INSERT INTO org_invitations (org_id, invitee_id, role, invited_by)
      VALUES ('${ORG}', '${ATTACKER}', 'owner', '${ATTACKER}')`);
    console.log(`${label}: attacker INSERT succeeded`);
  } catch (e) {
    console.log(`${label}: attacker INSERT rejected -> ${e.message}`);
  }
  await db.close();
}

await run('BROKEN', `invited_by = auth.uid()`);
await run('FIXED ', `invited_by = auth.uid() AND is_org_owner(org_id)
                     AND invitee_id <> auth.uid()`);

Raw output from our run (the full script also checks that the real owner can still invite a teammate):

BROKEN: attacker INSERT succeeded -> self-invite as owner of internal-org
BROKEN: real owner INSERT succeeded
FIXED : attacker INSERT rejected -> new row violates row-level security policy for table "org_invitations"
FIXED : real owner INSERT succeeded

Two details matter. First, we tested as a non-superuser role, because superusers and Supabase’s service_role bypass RLS entirely. Second, the PostgreSQL CREATE POLICY docs confirm that a failed WITH CHECK raises an error and aborts the whole command, so the negative test is a clean assertion.

Which checks prevent RLS policy privilege escalation?

Every write policy should answer “does this user have authority over every resource this row references?” Postgres gives you the tools, but the semantics have sharp edges. According to the official CREATE POLICY reference:

That last point is the overlooked one. If someone later adds a broad “members can insert” permissive policy, it ORs with your careful owner check. Add a RESTRICTIVE policy for invariants that must always hold, such as “only owners can create owner-role invitations.” Restrictive policies are ANDed, per the same docs.

For accept-invite flows, also re-check on UPDATE: the invitee should only be able to flip accepted_at, never change org_id or role. Column-level GRANT UPDATE (accepted_at) handles that more reliably than a policy.

How did a pull request leak production cloud credentials?

Dosu’s CI ran an infrastructure preview on pull requests with access to production cloud credentials. The attacker’s PR, opened with the bot’s stolen GitHub token, sent those credentials out at 07:50 UTC. Note the nuance: this PR came from a token with repo write access, not a fork, so fork protections would not have helped.

GitHub’s guide on securely using pull_request_target calls the general pattern a “pwn request”: a privileged job runs code from the PR. It also notes that execution “does not require an obvious build step.” Commands like npm install run attacker-controlled scripts too.

# RISKY: PR code runs in a job that holds long-lived prod keys
on: pull_request
jobs:
  preview:
    runs-on: ubuntu-latest
    env:
      AWS_ACCESS_KEY_ID: ${{ secrets.PROD_AWS_KEY }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.PROD_AWS_SECRET }}
    steps:
      - uses: actions/checkout@v6
      - run: npm ci && npx cdk diff
# SAFER: no stored keys; OIDC role scoped to a preview account,
# and a protected environment for anything touching prod
on: pull_request
permissions:
  id-token: write
  contents: read
jobs:
  preview:
    runs-on: ubuntu-latest
    environment: preview   # require reviewers for a separate 'prod' environment
    steps:
      - uses: actions/checkout@v6
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::<PREVIEW_ACCOUNT_ID>:role/pr-preview-readonly
          aws-region: us-east-1
      - run: npm ci --ignore-scripts && npx cdk diff

With GitHub’s OIDC integration, the cloud provider issues “a short-lived access token that is only valid for a single job.” Dosu made the same move after the incident: deployments now use short-lived credentials instead of stored keys. Also note a deadline: GitHub will enforce its default pull_request_target block on December 2, 2026 for affected public repositories.

Why is “change the integration URL” a credential-exfiltration risk?

Because the server sends secrets to whatever URL an owner configures. Once the attacker was owner, they pointed the integration’s server URL at a Quick Tunnel, and Dosu sent the integration’s credentials to it. That included a database token and a GitHub bot token.

My recommendation for Node.js, Next.js or Django backends: treat any setting that changes where credentials are sent like a password change.

// Express/Next.js route handler sketch (illustrative, not from Dosu)
const ALLOWED_HOSTS = new Set(['api.github.com', 'slack.com']);

export async function updateIntegrationUrl(req, res) {
  const { integrationId, serverUrl } = req.body;
  const url = new URL(serverUrl);

  if (url.protocol !== 'https:' || !ALLOWED_HOSTS.has(url.hostname)) {
    return res.status(400).json({ error: 'Host not allowed' });
  }
  if (!req.session.recentlyReauthenticated) {
    return res.status(403).json({ error: 'Re-authentication required' });
  }
  await db.integrations.update(integrationId, { serverUrl: url.toString() });
  await revokeAndReissueCredentials(integrationId); // never replay old secrets
  await notifyOrgOwners(integrationId, 'Integration endpoint changed');
  return res.json({ ok: true });
}

The same rule applies to webhooks and custom LLM base URLs in AI apps. If a user can redirect your outbound call, they can collect whatever header you attach to it.

What does this breach say about AI-driven attacks?

It shows how fast automated scanners now find authorization bugs. Dosu reports the attacker used the ARTEX penetration testing framework, which sent more than 80,000 requests in 90 minutes and found the flaw within hours. Multiple earlier penetration tests, including one the week before, had missed it.

Dosu’s conclusion is blunt: “All code that a frontier model hasn’t reviewed is at risk.” That echoes what we covered in Project Glasswing and AI vulnerability discovery. The defensive side worked too: Dosu’s own agent refused every prompt-injected request for credentials. Volume this high is also a reason to revisit rate limiting with token buckets and sliding windows on sign-up and API surfaces.

RLS policy privilege escalation: which controls would have broken the chain?

Dosu attack steps mapped to controls (source: Dosu post-mortem, PostgreSQL and GitHub docs)
Attack step (UTC) What failed Control that breaks it Primary reference
Org takeover, 06:21–07:00 Invitation INSERT policy lacked target-org check WITH CHECK owner check + RESTRICTIVE invariant + policy tests PostgreSQL CREATE POLICY
Integration creds, 06:42 Owner could redirect where secrets are sent Host allowlist, re-auth, rotate on change, owner alerts Dosu post-mortem
Database, 06:51–07:57 A DB token sat behind an integration Least-privilege, short-lived DB credentials Supabase RLS guide
CI creds, 07:50 PR preview had prod cloud credentials OIDC, separate preview account, protected environments GitHub OIDC
Cloud backdoor, 07:52–07:59 Contained: org policy blocked public exposure Keep org-level deny policies Dosu post-mortem

Dosu also got two things right that limited damage: integration credentials were encrypted and API keys were hashed, so the attacker reached those tables but not usable secrets. For the frontend side of tenant auth, see our Next.js 16 auth security mistakes guide, and for the dependency side, npm supply chain defense layers.

The NexGismo verdict: The Dosu breach is not a Supabase problem; it is an authorization-modelling problem that RLS makes easy to write and easy to miss. I’d require a negative policy test for every table that grants access to another resource, and I’d treat any CI job that runs PR code with production credentials as already compromised. Fix those two and this chain stops at step three.

Frequently Asked Questions

What is the difference between USING and WITH CHECK in RLS?

USING filters which existing rows a user can see, update or delete. WITH CHECK validates new rows created by INSERT or UPDATE, and raises an error if the check fails. INSERT policies accept only WITH CHECK, so any rule about the target org or project must live there.

Does the service_role key bypass RLS in Supabase?

Yes. Supabase documents that service_role has full access and bypasses Row Level Security, so it must stay server-side. Superuser roles like postgres also bypass RLS, which is why policy tests must run as the authenticated or anon role to mean anything.

Is RLS enough to secure a multi-tenant Supabase app?

RLS is necessary but not sufficient. Policies must check authority over every referenced resource, grants must be minimal, views need security_invoker, and server-side code using service_role needs its own authorization. Dosu’s breach also spread through integrations and CI, which RLS does not cover.

Why is pull_request_target dangerous in GitHub Actions?

It runs with the base repository’s secrets and a privileged token. If the workflow checks out and runs pull request code, an attacker’s build script executes with those secrets. GitHub calls this a pwn request and will enforce a default block for affected public repositories on December 2, 2026.

How do you test RLS policies?

Switch to a non-superuser role, set the user identity, and assert both allowed and denied operations for each table. Supabase recommends SQL tests under supabase/tests/ covering select, insert, update and delete. An in-process engine like PGlite also works for fast Node.js unit tests.

The Dosu post-mortem is worth reading in full because it is honest about a small mistake with a large blast radius. To prevent an RLS policy privilege escalation in your own stack, the action list is short. Grep your migrations for every FOR INSERT policy on tables named like invitations, members, roles or grants. Add a negative test for each, as shown above. Then audit which CI jobs can see production credentials when a pull request runs, and move them to OIDC.

If you run multi-tenant apps on Postgres, start with your invitation table today. It is the one attackers will try first. Have a policy pattern you’d like reviewed? Share it in the comments and we may cover it in a follow-up.

Sources

Exit mobile version