Who Can See This Row? A Hands-On Guide to PostgreSQL Row-Level Security

I wanted to see what happens when a query in a shared notes app forgets its workspace filter. Let’s give Mira access to one workspace, put notes from two workspaces in the same PostgreSQL table, and run this as the app:

SELECT body FROM whose_row.notes;

Mira gets one row back, Harbor launch checklist. There’s also a note in Orchard, but Mira only belongs to Harbor. PostgreSQL’s row-level security (RLS) checks her membership even though the query never mentions a workspace.

I put the schema, seed data, and checks in the whose-row repository. We’ll use the same table to try a read, an update, and an insert. The interesting bit is what PostgreSQL tells us when Mira tries something she doesn’t have permission to do.

Run the example

With Docker running, clone the whose-row repository and run the checks from its root.

git clone https://github.com/antt001/whose-row.git
cd whose-row
./verify

The script starts a disposable PostgreSQL 17.12 container, loads two notes, and removes the container when it’s done. All 19 checks passed on December 2, 2026. Here’s the setup they exercise.

User Harbor Orchard
Mira Viewer No access
Eli Editor No access
Noa Editor Editor
Sam No access No access

A viewer can read notes. An editor can also add a note and change its body. The app has a separate database role for managing memberships, so editing a note doesn’t give Eli a way to make himself an editor in Orchard.

How does PostgreSQL know it’s Mira?

Everyone using the app shares the same database login, whose_row_runtime. Our backend authenticates Mira, checks out a connection, and sets her user ID for the transaction. In psql we can try it with a literal:

BEGIN;
SET LOCAL whose_row.user_id = 'mira';
SELECT body FROM whose_row.notes;
COMMIT;

The LOCAL matters here. A plain SET survives a commit. If the pool gives that connection to Sam next, the database could still be checking Mira’s membership. With SET LOCAL, the next transaction starts without Mira’s identity.

In Node.js I want to pass the authenticated ID as a query parameter. PostgreSQL’s set_config accepts the value as a parameter and gives it transaction scope when the third argument is true. Here’s the same read with a pg pool. The page still asks for a particular workspace, and every query uses the same checked-out client. node-postgres transactions

async function listNotes(pool, authenticatedUserId, workspaceId) {
  const client = await pool.connect();
  let discard = false;
  try {
    await client.query('BEGIN');
    await client.query("SELECT set_config('whose_row.user_id', $1, true)", [authenticatedUserId]);
    const { rows } = await client.query(
      'SELECT body FROM whose_row.notes WHERE workspace_id = $1', [workspaceId]);
    await client.query('COMMIT');
    return rows;
  } catch (error) {
    await client.query('ROLLBACK').catch(() => { discard = true; });
    throw error;
  } finally {
    client.release(discard);
  }
}

If rollback fails, we discard the connection and let the caller see the original error. Releasing a pooled client

The backend has to supply the ID from authentication. Anyone with arbitrary SQL access as the runtime role can set that value themselves. What we’re protecting against here is an application query that leaves out a workspace filter or passes the wrong workspace ID.

Give the app access to the right rows

First we grant the app the operations it needs. It can read notes, insert a workspace ID and body, and update the body. It has no delete grant.

GRANT SELECT ON whose_row.notes TO whose_row_runtime;
GRANT INSERT (workspace_id, body), UPDATE (body) ON whose_row.notes TO whose_row_runtime;

ALTER TABLE whose_row.notes ENABLE ROW LEVEL SECURITY;

With RLS enabled, the runtime role also needs a policy that allows the row. Here’s the read policy:

CREATE POLICY notes_select ON whose_row.notes
    FOR SELECT TO whose_row_runtime
    USING (whose_row.has_membership(workspace_id, false));

For each candidate note, has_membership checks the workspace on the row against the user ID for this transaction. Passing false means a viewer membership is enough. Mira’s Harbor membership matches the checklist. There’s no match for the Orchard note.

CREATE FUNCTION whose_row.has_membership(target_workspace integer, editor_required boolean)
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
SET search_path = pg_catalog, pg_temp
AS $$
    SELECT EXISTS (
        SELECT 1
        FROM whose_row.memberships AS membership
        WHERE membership.workspace_id = target_workspace
          AND membership.user_id = current_setting('whose_row.user_id', true)
          AND (NOT editor_required OR membership.access = 'editor')
    );
$$;

Why use SECURITY DEFINER here? I want the runtime role to be able to ask whether the current user belongs to a workspace. The function reads the memberships table with the owner’s privileges and returns a boolean. The runtime role has no direct access to that table. The table name is schema-qualified, the function fixes its search path, and setup.sql revokes the default execute grant from PUBLIC in the transaction that creates the function. PostgreSQL’s guidance on security-definer functions

Why does an update change zero rows while an insert raises an error?

Let’s try editing the Harbor checklist as Mira. She can read it, and the runtime role has permission to update the body column. Now look at the first condition in the update policy:

CREATE POLICY notes_update ON whose_row.notes
    FOR UPDATE TO whose_row_runtime
    USING (whose_row.has_membership(workspace_id, true))
    WITH CHECK (whose_row.has_membership(workspace_id, true));

For an update, USING decides which existing rows we can change. It asks for an editor membership this time. Mira is a viewer, so her update finds no eligible row and finishes with UPDATE 0.

An insert gives PostgreSQL a proposed row to check. The insert policy uses WITH CHECK to require editor access to its workspace. When Mira tries to add a Harbor note, that check fails and she gets an error. Here are the results side by side with the reads:

NOTICE:  PASS missing identity: 0 notes
NOTICE:  PASS viewer read without a workspace filter: Harbor launch checklist
NOTICE:  PASS cross-workspace read: 0 notes
NOTICE:  PASS viewer update: UPDATE 0
NOTICE:  PASS viewer insert: new row violates row-level security policy for table "notes" [42501]
NOTICE:  PASS workspace ID change: permission denied for table notes [42501]

Eli can insert a Harbor note and edit its body. On update, his existing row passes USING, and the edited row still belongs to Harbor, so it passes WITH CHECK too. Noa is an editor in both workspaces. Even so, she gets a permission error if she tries to move a note between them. The grant only allows updates to body. If we ever allow updates to workspace_id, the policy will still check editor access to the destination.

Try the same query as the owner

Here’s a detail that’s easy to miss if you try the example using the login that created the tables. The check sets Sam’s request identity and runs the read as the table owner:

NOTICE:  PASS user without membership: 0 notes
NOTICE:  PASS table owner with Sam's identity: 2 notes
NOTICE:  PASS table owner with FORCE ROW LEVEL SECURITY: 0 notes

Sam belongs to neither workspace. The owner normally bypasses RLS and sees both notes. With FORCE ROW LEVEL SECURITY, the owner is subject to RLS too. The policies grant access only to the runtime role, so the owner sees zero rows. The check rolls back that change. Superusers and roles with BYPASSRLS still bypass the policies under FORCE. PostgreSQL row security policies

What I’d check in the app

Keep the workspace filter on a page that needs one workspace. The membership lookup in this example uses a primary key on (workspace_id, user_id). For a larger table I’d measure the query with representative data under the app’s actual database role. I’d check migration and admin jobs separately since their roles may bypass these policies.

This example uses shared tables. A schema per tenant gives each tenant its own namespace. If tenants need independent restores, a database per tenant may fit better. Both approaches add migration work, and separate databases also add connections to manage.

If you’re debugging an empty result, check the database role and the request ID inside the transaction. A row filtered by the policy looks the same to the caller as a row that doesn’t exist.

The check I’d keep alongside the permissions tests is the one that reuses Mira’s connection. We commit, start a second transaction on that same connection, and read the notes again before setting a user ID:

NOTICE:  PASS set_config identity: Harbor launch checklist
NOTICE:  PASS transaction-local identity after commit: 0 notes

That’s the result I want when the next request gets a connection from the pool.

Categories: Security