Skip to content

feat(db): add RLS policies for every guarded table - #1004

Draft
bencap wants to merge 17 commits into
feature/bencap/827/database-rolesfrom
feature/bencap/809/rls-policies
Draft

bencap wants to merge 17 commits into
feature/bencap/827/database-rolesfrom
feature/bencap/809/rls-policies

Conversation

@bencap

@bencap bencap commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

Writes the RLS policies for every guarded table as migrations. Nothing is enforced yet: a policy does nothing until its table is enabled, which #825 and #878 do, so behavior changes only where noted below. Stacked on #976. The 13 commits are ordered to be read one at a time.

  • Helpers: mavedb_user_id() and mavedb_roles() read the principal Tell Postgres who is asking, on every transaction in a request #823 sends. They're plain SQL that Postgres inlines into each policy, and they're listed in FUNCTIONS for the api and the worker.
  • Policies: each of the 42 GUARDED tables gets <table>_rule, deciding which rows the api sees and writes, and <table>_worker, showing mavedb_worker every row. A replay test requires exactly those two on every guarded table and none elsewhere.
  • Target tables carry score_set_id: the api inserts a sequence or accession before the gene that points at it, so their policy reads scoresets instead of target_genes. A before_flush listener sets the key. target_genes_one_target and composite foreign keys keep the key from drifting and stop two genes sharing a target, which the ORM's single_parent never did.
  • alleles.first_published_at: set by triggers when a public score set first links an allele, and never cleared, so the alleles policy skips its EXISTS for public alleles. It assumes publication can't be reversed (Enforce publication invariants with database constraints #893). first_published_at_drift() recomputes it from the links.
  • Views: v_variant_annotations and v_current_annotation_events are security_invoker, and the view helper creates every plain view that way.
  • Snapshot: src/mavedb/db/policies.sql is the readable copy of every policy, helper and trigger, generated with python -m mavedb.scripts.write_policy_snapshot from a database at head. The replay CI job and a replay test fail when it's stale. The test template loads it, since the test schema is built from the models until Run tests and local development under the production database roles #834.
  • Indexes: contributor_id on the three contributor tables, and score_calibrations.score_set_id.
  • Behavior changes, both small:
    • A score set's last modifier no longer counts as a contributor for its calibrations. That only mattered after they lost the score set, when it kept their access to its private calibrations. The same flag gates calibration update and delete.
    • record_urn_redirect flushes the rename before staging the redirect, which the redirect's policy needs.

Refs #809. It doesn't close it: the full-RT re-measure, including EXISTS against IN for the classification variants, waits on a staging dump.

No API schema change.

Outside the diff

  • The target-table migration changes data, and its downgrade can't undo it. It copies any sequence or accession shared between target genes, so each gene gets its own, and deletes any that no target gene points at. On the 2026-11-05 production dump that copies one sequence three times (four PAX6 targets of one experiment, inserted by hand) and deletes 208 sequences and 6 accessions. Check production's counts before deploying:

    SELECT num_nonnulls(target_sequence_id, accession_id) AS targets, count(*) FROM target_genes GROUP BY 1;
    SELECT count(*) FROM (SELECT target_sequence_id FROM target_genes WHERE target_sequence_id IS NOT NULL GROUP BY 1 HAVING count(*) > 1) s;
    SELECT count(*) FROM target_sequences t WHERE NOT EXISTS (SELECT 1 FROM target_genes g WHERE g.target_sequence_id = t.id);
    SELECT count(*) FROM target_accessions t WHERE NOT EXISTS (SELECT 1 FROM target_genes g WHERE g.accession_id = t.id);
  • The first_published_at backfill updates about 1.5M alleles with row locks only. Stop the worker during the deploy.

  • Deploys only where Split database roles into owner, migrate, worker and api #827's roles exist, since the worker policies name mavedb_worker.

Tests

  • tests/db/test_rls_policies.py enables RLS in the test's own database and logs in as mavedb_api:
    • Records across seven personas (anonymous, stranger, owner, ORCID contributor, mapper, admin, admin without the role), plus the worker. A stale principal reads as anonymous. INSERT ... RETURNING of one's own record works, and a forged owner is refused. A contributor removed from a score set sees neither it nor the calibration they added.
    • Owned, target and shared rows under visible and hidden parents.
    • The database rejects a target gene with both or neither target, or whose target carries another score set.
    • The first_published_at triggers set the column on link and on publish, including as mavedb_api, never overwrite it, and the drift check catches a wrong value.
  • tests/routers/test_api_role.py, as mavedb_api with RLS on: creating a score set with a sequence target and with an accession target, replacing its targets, and publishing. The publish test failed before the redirect fix, and the create test fails without the principal. api_role_client now binds the principal, as the real get_current_user does.
  • tests/routers/test_publication_rls.py runs against the real role and policy instead of its stand-ins, with the same assertions.
  • tests/db/test_bootstrap.py replay checks: the snapshot matches, policies read the principal only through the helpers, no table has RLS enabled, IN only where allowed, every guarded table's two policies, the target constraints, and no plain view reading as its owner.
  • Two existing tests seeded a target gene with no target or with both; they now seed exactly one, with the same assertions.
  • The target repair ran on the local copy of the 2026-11-05 dump in a rolled-back transaction: 3,743 target genes, each with exactly one target.
  • bin/check and the PR test set (5,848 passed).

Checklist

  • Targets the open patch branch if this is a small, non-breaking change, or the cycle's release-<year>.<n>.0 branch otherwise; never main (stacked on feat(db): split database roles into owner, migrate, worker and api #976 until it merges)
  • API schema change? A matching mavedb-ui PR regenerates src/schema/openapi.d.ts (no API schema change)
  • Docs and instruction files touched by this change are updated

@bencap bencap added the app: backend Task implementation touches the backend label Nov 17, 2026
The RLS policies (#809) read the request's principal only through these
two functions. nullif turns the empty value a pooled connection keeps
after a transaction-local setting ends into "nobody", where a bare cast
would raise. They're plain SQL, not SECURITY DEFINER, so Postgres
inlines them into each policy and they bypass nothing. Both the api and
the worker can execute them, since policies apply to both.
#960 dropped experiment_set_publication_identifiers, so its entry named
nothing. Missing names are skipped, but the registry should list only
what the schema has.
The record policies (#809) find the records a caller contributes to by
contributor_id, but each contributor table's primary key leads with the
parent's id, so that lookup couldn't use it. The calibration policy
joins on score_calibrations.score_set_id. All four tables are small, so
the indexes build in the migration without CONCURRENTLY.
Policies live in migrations, so a table's current rule would otherwise
be spread across the history. write_policy_snapshot renders the policy
helpers and every table's RLS state and policies from a database at
alembic head into src/mavedb/db/policies.sql, sorted so an unchanged
schema renders identically. The replay CI job and a replay test both
fail when the committed file differs, so a policy change is reviewed as
a diff of one file.

The test schema is built from the models, which can't declare
policies, so the test template loads the snapshot to get them until
#834 builds it from the migrations. Two more replay checks: policies
read the principal only through the helpers, and no table has RLS
enabled yet, since enabling is #825's and #878's job.
scoresets, experiments, experiment_sets, collections and
score_calibrations each get <table>_rule, deciding which rows the api
sees and writes, and <table>_worker, showing mavedb_worker every row.
Nothing is enforced until a table is enabled (#825, #878).

Contributors are matched by ORCID, through users. An experiment is
also visible when one of its score sets is, and an experiment set when
one of its experiments is (#564); no child policy reads its parent, so
the policies don't recurse. A calibration carries its own rule rather
than delegating, since a public score set can hold a private
calibration, and it's visible only if its score set is, so a
contributor removed from a score set loses the calibrations they added
to it.

The tests enable RLS in their own database and log in as mavedb_api
across seven personas, since the rest of the suite runs as a superuser
and skips every policy.
Only the owner, contributors and admins may modify a score set, so
matching modified_by_id granted nothing while they still held that
status. Its only effect was to keep a former contributor's access to the
score set's private investigator-provided calibrations after they lost
the score set. The calibration RLS policy (#809) matches owners and
contributors only; the Python rule now agrees. The same flag gates
calibration updates and deletes, which narrow the same way.
27 tables whose rows belong to one record get <table>_rule and
<table>_worker. An owned row is visible exactly when its owner is: each
rule reads the parent table, whose own policy filters the subquery, so
a record's rule lives in one place. Link tables check both sides, so a
caller can't learn that a private collection holds a public record.
URN redirects follow the record they name, and job runs follow their
pipeline, with ad hoc runs admin-only.

variants and target_genes use IN (SELECT id FROM scoresets), which
Postgres hashes once. Every other table uses a correlated EXISTS: below
variants, IN either can't be hashed in work_mem or is mispriced per
lookup and scans whole tables (#832). A replay test keeps IN out of the
owned and shared tables.
Publishing renames a record and stages a redirect from its old URN. A
later query autoflushed both, and nothing ordered the redirect after the
rename, so the redirect could be inserted while no record carried
new_urn yet. Under the urn_redirects RLS policy (#809) that insert
fails, because inserting returns the row's id and the row must pass the
read rule. record_urn_redirect now flushes pending changes first.

api_role_client now binds the principal as the real get_current_user
does, so tests run through it act as the caller at the database. The
new test publishes as mavedb_api with RLS on for every table that has a
policy and that publishing touches; it failed before this change.
The api inserts a target sequence or accession, returning its id,
before the target gene that points at it, so a policy reading
target_genes would refuse the insert under RLS (#809). Each row belongs
to one target gene, so it carries that gene's score set instead, set by
a before_flush listener from the gene, so no creator has to.

target_genes now refers to each by (id, score_set_id), so the carried
key can't drift from the gene's; these composite keys replace the
single-column ones. target_genes_one_target requires exactly one of a
sequence and an accession. The ORM's single_parent never stopped two
genes sharing a sequence, and deleting one sharer's score set would
delete the sequence and null the other gene's target.

The migration repairs existing rows first. A shared sequence or
accession is copied so each gene has its own, and one no gene points at
is deleted: nothing can reach it and it has no score set to carry. On
the 2026-11-05 dump that copies one sequence three times and deletes 214
rows. The downgrade can't restore either.

Two tests seeded a target gene with no target or with both; they now
seed exactly one, with their assertions unchanged.
A sequence or accession is visible exactly when the score set it
carries is. The score set row is written before its targets, so a new
target passes the policy when it's inserted, as INSERT ... RETURNING
requires.

Creating a score set with a sequence target and with an accession
target, and replacing its targets, now pass as mavedb_api with RLS on
for the target tables and the records above them. Without the caller's
principal the same create is refused, so the tests do exercise the
policies.
The alleles RLS policy (#809) shows an allele when a visible mapping
link points at it, and that EXISTS costs 3-10x on per-score-set reads
after reverse translation (#832). About 85% of alleles are linked from a
public score set, for which the check is wasted. first_published_at lets
the policy skip it.

Two triggers set it: when links to a public score set are inserted, and
when a score set goes public, for the alleles it already links. It's
write-once: once a public score set links an allele, the allele's
existence no longer says what anyone is working on. That holds only
while publication can't be reversed (#893). The triggers are plain
functions, run as whoever writes the link or publishes, who can see the
alleles involved.

first_published_at_drift recomputes the column from the links, and the
tests check it after each way of setting it. The policy snapshot now
includes the trigger functions and their triggers, so the test template
gets them too. The backfill updates about 1.5M rows in production with
row locks only; stop the worker during the deploy.
A shared row belongs to no one record and is visible when a record the
caller can see links to it: its presence can say what someone is
working on. Alleles follow their mapping links, retired ones included,
or first_published_at. VEP consequences and ClinVar and gnomAD links
follow their allele; ClinVar controls and gnomAD variants follow their
links; a variant translation needs both of its alleles. A publication
follows its citations, by natural key (#945).

Every rule's WITH CHECK is its read rule except the publications': the
api stores a publication before anything cites it, so the new row could
never pass. Its WITH CHECK is true; a written row discloses nothing, and
an update still reaches only rows the caller can see.

test_publication_rls now runs as mavedb_api against the real policy, as
its docstring said #809 would, with the same assertions. The publish
test enables alleles too. A replay test now requires every GUARDED
table to have exactly its _rule and _worker policies, and no other
table to have any.
A view reads its tables as its owner unless it's security_invoker, and
the owner skips every RLS policy, so anyone granted the view would see
rows the tables' policies hide. v_variant_annotations and
v_current_annotation_events become security_invoker, and the view
helper creates every new plain view that way, so the test schema
matches. Only the worker and scripts read either view today, so nothing
changes now, but a route granted one later reads through the policies.
A replay test fails on any plain view that reads as its owner.
@coveralls

coveralls commented Nov 17, 2026 •

Copy link
Copy Markdown

Coverage Report for CI Build 46492355712

Warning

No base build found for commit f10a077 on feature/bencap/827/database-roles.
Coverage changes can't be calculated without a base build.
If a base build is processing, this comment will update automatically when it completes.

Coverage: 91.401%

Details

  • Patch coverage: 1 uncovered change across 1 file (63 of 64 lines covered, 98.44%).

Uncovered Changes

File Changed Covered %
src/mavedb/db/policy_snapshot.py 28 27 96.43%
Total (8 files) 64 63 98.44%

Coverage Regressions

Requires a base build to compare against. How to fix this →


Coverage Stats

Coverage Status
Relevant Lines: 20292
Covered Lines: 18547
Line Coverage: 91.4%
Coverage Strength: 0.91 hits per line

💛 - Coveralls

@bencap
bencap force-pushed the feature/bencap/827/database-roles branch from 572ba08 to 1c6a507 Compare November 17, 2026 21:20
@bencap
bencap force-pushed the feature/bencap/809/rls-policies branch from a3bfeb8 to 7e474ee Compare November 17, 2026 21:20
…809/rls-policies

# Conflicts:
#	src/mavedb/db/rls.py
#	tests/conftest.py
…ration

The annotation_event cutover dropped v_current_annotation_events, so
altering it would fail the upgrade. Its replacement,
v_annotation_status_current, is created security_invoker, which leaves
v_variant_annotations as the only view to change.
seed_csv_export_score_set arrived with the 2026.3.4 export refactor and
creates a target gene with neither a sequence nor an accession, which
target_genes_one_target now rejects.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: backend Task implementation touches the backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants