Repository navigation
Conversation
3 tasks done
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.
Coverage Report for CI Build 46492355712Warning No base build found for commit Coverage: 91.401%Details
Uncovered Changes
Coverage RegressionsRequires a base build to compare against. How to fix this → Coverage Stats
💛 - Coveralls |
bencap
force-pushed
the
feature/bencap/827/database-roles
branch
from
November 17, 2026 21:20
572ba08 to
1c6a507
Compare
bencap
force-pushed
the
feature/bencap/809/rls-policies
branch
from
November 17, 2026 21:20
a3bfeb8 to
7e474ee
Compare
…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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
mavedb_user_id()andmavedb_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 inFUNCTIONSfor the api and the worker.GUARDEDtables gets<table>_rule, deciding which rows the api sees and writes, and<table>_worker, showingmavedb_workerevery row. A replay test requires exactly those two on every guarded table and none elsewhere.{admin,mapper}. An experiment or experiment set is also visible through a visible child (Let contributors to a score set see its experiment and experiment set #564). Collections are visible to their members and{admin}. A calibration carries its own rule, and is visible only if its score set is.IN (SELECT id FROM scoresets)only onvariantsandtarget_genes, and a correlatedEXISTSeverywhere else, as Work out which tables need RLS policies, and what they'll cost #832 measured; a replay test keepsINout of the rest.WITH CHECKistrue, because the api stores a publication before anything cites it (Reference publications by their identifier so citations can be written under RLS #945).score_set_id: the api inserts a sequence or accession before the gene that points at it, so their policy readsscoresetsinstead oftarget_genes. Abefore_flushlistener sets the key.target_genes_one_targetand composite foreign keys keep the key from drifting and stop two genes sharing a target, which the ORM'ssingle_parentnever did.alleles.first_published_at: set by triggers when a public score set first links an allele, and never cleared, so theallelespolicy skips itsEXISTSfor 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.v_variant_annotationsandv_current_annotation_eventsaresecurity_invoker, and the view helper creates every plain view that way.src/mavedb/db/policies.sqlis the readable copy of every policy, helper and trigger, generated withpython -m mavedb.scripts.write_policy_snapshotfrom 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.contributor_idon the three contributor tables, andscore_calibrations.score_set_id.record_urn_redirectflushes 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
EXISTSagainstINfor 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:
The
first_published_atbackfill 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.pyenables RLS in the test's own database and logs in asmavedb_api:INSERT ... RETURNINGof 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.first_published_attriggers set the column on link and on publish, including asmavedb_api, never overwrite it, and the drift check catches a wrong value.tests/routers/test_api_role.py, asmavedb_apiwith 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_clientnow binds the principal, as the realget_current_userdoes.tests/routers/test_publication_rls.pyruns against the real role and policy instead of its stand-ins, with the same assertions.tests/db/test_bootstrap.pyreplay checks: the snapshot matches, policies read the principal only through the helpers, no table has RLS enabled,INonly where allowed, every guarded table's two policies, the target constraints, and no plain view reading as its owner.bin/checkand the PR test set (5,848 passed).Checklist
release-<year>.<n>.0branch otherwise; nevermain(stacked on feat(db): split database roles into owner, migrate, worker and api #976 until it merges)mavedb-uiPR regeneratessrc/schema/openapi.d.ts(no API schema change)