From e62a3b0b3abaff08a4c876ae809380c2e057bd1d Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:39:56 -0800 Subject: [PATCH 01/15] feat(db): add mavedb_user_id and mavedb_roles for RLS policies 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. --- .../7c1d4e9a2b30_add_rls_principal_helpers.py | 36 +++++++++++++++++++ src/mavedb/db/rls.py | 4 +++ 2 files changed, 40 insertions(+) create mode 100644 alembic/versions/7c1d4e9a2b30_add_rls_principal_helpers.py diff --git a/alembic/versions/7c1d4e9a2b30_add_rls_principal_helpers.py b/alembic/versions/7c1d4e9a2b30_add_rls_principal_helpers.py new file mode 100644 index 00000000..1b75f68a --- /dev/null +++ b/alembic/versions/7c1d4e9a2b30_add_rls_principal_helpers.py @@ -0,0 +1,36 @@ +"""add mavedb_user_id and mavedb_roles, which read the request's principal for RLS policies + +The api sends ``app.user_id`` and ``app.active_roles`` into every transaction (``mavedb.db.principal``). Policies +read them only through these two functions. ``nullif`` turns the empty value a pooled connection keeps after a +transaction-local setting ends into "nobody", instead of a cast error. Both are plain SQL functions, not +``SECURITY DEFINER``, so Postgres inlines them into each policy and they bypass nothing. + +Revision ID: 7c1d4e9a2b30 +Revises: 4b8e2c7d1f3a +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "7c1d4e9a2b30" +down_revision = "4b8e2c7d1f3a" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute( + """CREATE FUNCTION mavedb_user_id() RETURNS integer LANGUAGE sql STABLE PARALLEL SAFE +AS $$ SELECT nullif(current_setting('app.user_id', true), '')::integer $$""" + ) + op.execute( + """CREATE FUNCTION mavedb_roles() RETURNS text[] LANGUAGE sql STABLE PARALLEL SAFE +AS $$ SELECT coalesce(nullif(current_setting('app.active_roles', true), '')::text[], '{}') $$""" + ) + + +def downgrade(): + op.execute("DROP FUNCTION mavedb_roles()") + op.execute("DROP FUNCTION mavedb_user_id()") diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py index e6f47ca4..7c3d516f 100644 --- a/src/mavedb/db/rls.py +++ b/src/mavedb/db/rls.py @@ -162,6 +162,10 @@ class Relation: # execute one. A SECURITY DEFINER function runs as the owner, so it gets one executor and a reason, and pins its # search_path; one that doesn't pin it gets no executors. FUNCTIONS: dict[str, Function] = { + # Read the request's principal for the RLS policies (#809). Plain SQL that Postgres inlines into each policy, + # so they bypass nothing. Any role a policy applies to must be able to run them. + "mavedb_user_id": Function(frozenset({API_ROLE, WORKER_ROLE})), + "mavedb_roles": Function(frozenset({API_ROLE, WORKER_ROLE})), # Refreshing a materialized view requires owning it, and the worker owns nothing. "mavedb_refresh_mat_views": Function(frozenset({WORKER_ROLE}), security_definer=True), # From the 2026.3.0 baseline. Nothing calls it. From 6560976ae16f82adb4a483a332364c4c8cb1ce93 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:43:26 -0800 Subject: [PATCH 02/15] chore(db): drop a dropped table from the RLS registry #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. --- src/mavedb/db/rls.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py index 7c3d516f..eeeee751 100644 --- a/src/mavedb/db/rls.py +++ b/src/mavedb/db/rls.py @@ -81,7 +81,6 @@ class Relation: "calibration_controls": GUARDED, "scoreset_publication_identifiers": GUARDED, "experiment_publication_identifiers": GUARDED, - "experiment_set_publication_identifiers": GUARDED, "scoreset_doi_identifiers": GUARDED, "experiment_doi_identifiers": GUARDED, "experiment_set_doi_identifiers": GUARDED, From 53c36bce97ef531eae6c056e96a91b18f96aabf2 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:40:08 -0800 Subject: [PATCH 03/15] perf(db): index contributor ids and calibration score sets for RLS 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. --- ...f5a0b3c41_index_contributor_ids_for_rls.py | 36 +++++++++++++++++++ src/mavedb/models/experiment.py | 2 +- src/mavedb/models/experiment_set.py | 2 +- src/mavedb/models/score_calibration.py | 2 +- src/mavedb/models/score_set.py | 2 +- 5 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 alembic/versions/8e2f5a0b3c41_index_contributor_ids_for_rls.py diff --git a/alembic/versions/8e2f5a0b3c41_index_contributor_ids_for_rls.py b/alembic/versions/8e2f5a0b3c41_index_contributor_ids_for_rls.py new file mode 100644 index 00000000..f01aabfc --- /dev/null +++ b/alembic/versions/8e2f5a0b3c41_index_contributor_ids_for_rls.py @@ -0,0 +1,36 @@ +"""index contributor_id on the three contributor tables and score_set_id on score_calibrations + +The RLS policies (#809) look up the records a caller contributes to by ``contributor_id``, but each contributor +table's primary key leads with the parent's id, so the lookup can't use it. The calibration policy joins on +``score_calibrations.score_set_id``. All four tables are small, so the indexes build without ``CONCURRENTLY``. + +Revision ID: 8e2f5a0b3c41 +Revises: 7c1d4e9a2b30 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "8e2f5a0b3c41" +down_revision = "7c1d4e9a2b30" +branch_labels = None +depends_on = None + +INDEXES = [ + ("ix_scoreset_contributors_contributor_id", "scoreset_contributors", "contributor_id"), + ("ix_experiment_contributors_contributor_id", "experiment_contributors", "contributor_id"), + ("ix_experiment_set_contributors_contributor_id", "experiment_set_contributors", "contributor_id"), + ("ix_score_calibrations_score_set_id", "score_calibrations", "score_set_id"), +] + + +def upgrade(): + for name, table, column in INDEXES: + op.create_index(name, table, [column]) + + +def downgrade(): + for name, table, _ in reversed(INDEXES): + op.drop_index(name, table_name=table) diff --git a/src/mavedb/models/experiment.py b/src/mavedb/models/experiment.py index 7e7e40bb..557f69b4 100644 --- a/src/mavedb/models/experiment.py +++ b/src/mavedb/models/experiment.py @@ -33,7 +33,7 @@ "experiment_contributors", Base.metadata, Column("experiment_id", ForeignKey("experiments.id"), primary_key=True), - Column("contributor_id", ForeignKey("contributors.id"), primary_key=True), + Column("contributor_id", ForeignKey("contributors.id"), primary_key=True, index=True), ) experiments_legacy_keywords_association_table = Table( diff --git a/src/mavedb/models/experiment_set.py b/src/mavedb/models/experiment_set.py index 43bdca6c..86a367ee 100644 --- a/src/mavedb/models/experiment_set.py +++ b/src/mavedb/models/experiment_set.py @@ -22,7 +22,7 @@ "experiment_set_contributors", Base.metadata, Column("experiment_set_id", ForeignKey("experiment_sets.id"), primary_key=True), - Column("contributor_id", ForeignKey("contributors.id"), primary_key=True), + Column("contributor_id", ForeignKey("contributors.id"), primary_key=True, index=True), ) diff --git a/src/mavedb/models/score_calibration.py b/src/mavedb/models/score_calibration.py index f3e82dff..37c1a9ee 100644 --- a/src/mavedb/models/score_calibration.py +++ b/src/mavedb/models/score_calibration.py @@ -70,7 +70,7 @@ class ScoreCalibration(Base): id: Mapped[int] = Column(Integer, primary_key=True) urn = Column(String(64), nullable=True, default=generate_calibration_urn, unique=True, index=True) - score_set_id = Column(Integer, ForeignKey("scoresets.id"), nullable=False) + score_set_id = Column(Integer, ForeignKey("scoresets.id"), index=True, nullable=False) score_set: Mapped["ScoreSet"] = relationship("ScoreSet", back_populates="score_calibrations") title = Column(String, nullable=False) diff --git a/src/mavedb/models/score_set.py b/src/mavedb/models/score_set.py index 0c9941da..06f31c5b 100644 --- a/src/mavedb/models/score_set.py +++ b/src/mavedb/models/score_set.py @@ -33,7 +33,7 @@ "scoreset_contributors", Base.metadata, Column("scoreset_id", ForeignKey("scoresets.id"), primary_key=True), - Column("contributor_id", ForeignKey("contributors.id"), primary_key=True), + Column("contributor_id", ForeignKey("contributors.id"), primary_key=True, index=True), ) From 25ac683cd93f5a0a491017f519cffef6199d3384 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:41:18 -0800 Subject: [PATCH 04/15] feat(db): keep a readable snapshot of the RLS policies in policies.sql 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. --- .github/workflows/run-tests-on-push.yml | 4 ++ src/mavedb/db/policies.sql | 16 +++++ src/mavedb/db/policy_snapshot.py | 76 +++++++++++++++++++++ src/mavedb/scripts/write_policy_snapshot.py | 28 ++++++++ tests/conftest.py | 4 ++ tests/db/test_bootstrap.py | 34 +++++++++ 6 files changed, 162 insertions(+) create mode 100644 src/mavedb/db/policies.sql create mode 100644 src/mavedb/db/policy_snapshot.py create mode 100644 src/mavedb/scripts/write_policy_snapshot.py diff --git a/.github/workflows/run-tests-on-push.yml b/.github/workflows/run-tests-on-push.yml index 9636b558..338e4db4 100644 --- a/.github/workflows/run-tests-on-push.yml +++ b/.github/workflows/run-tests-on-push.yml @@ -72,6 +72,10 @@ jobs: DB_PASSWORD: migrate - name: Check there is exactly one head run: test "$(poetry run alembic heads | wc -l)" -eq 1 + - name: Check the policy snapshot matches the migrations + run: | + poetry run python -m mavedb.scripts.write_policy_snapshot + git diff --exit-code src/mavedb/db/policies.sql run-tests-3_11-core-dependencies: runs-on: ubuntu-latest diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql new file mode 100644 index 00000000..4d1ce550 --- /dev/null +++ b/src/mavedb/db/policies.sql @@ -0,0 +1,16 @@ +-- Row-level security in the public schema: the functions it relies on, then each table's RLS state and +-- policies. +-- Generated from a database at alembic head by `python -m mavedb.scripts.write_policy_snapshot`. Don't edit +-- by hand: change policies in a migration and regenerate this file. + +CREATE OR REPLACE FUNCTION public.mavedb_roles() + RETURNS text[] + LANGUAGE sql + STABLE PARALLEL SAFE +AS $function$ SELECT coalesce(nullif(current_setting('app.active_roles', true), '')::text[], '{}') $function$; + +CREATE OR REPLACE FUNCTION public.mavedb_user_id() + RETURNS integer + LANGUAGE sql + STABLE PARALLEL SAFE +AS $function$ SELECT nullif(current_setting('app.user_id', true), '')::integer $function$; diff --git a/src/mavedb/db/policy_snapshot.py b/src/mavedb/db/policy_snapshot.py new file mode 100644 index 00000000..6aeba27f --- /dev/null +++ b/src/mavedb/db/policy_snapshot.py @@ -0,0 +1,76 @@ +"""Write the database's row-level security rules as one readable SQL file (#809). + +Policies live in migrations, so the current rule for a table is spread across the history. The snapshot, +``src/mavedb/db/policies.sql``, is the readable copy, generated from a database built by ``alembic upgrade +head`` and never edited by hand. A test replays the migrations and fails when the committed file differs, so a +change to a policy is reviewed as a diff of this file. + +The test schema is built from the models, which can't declare policies, so the test template loads this file +to get them. +""" + +from pathlib import Path + +from sqlalchemy import Connection, text + +SNAPSHOT_PATH = Path(__file__).parent / "policies.sql" + +# Every function a policy calls. Policy bodies call nothing else. +RLS_FUNCTIONS = ("mavedb_user_id", "mavedb_roles") + +_HEADER = """\ +-- Row-level security in the public schema: the functions it relies on, then each table's RLS state and +-- policies. +-- Generated from a database at alembic head by `python -m mavedb.scripts.write_policy_snapshot`. Don't edit +-- by hand: change policies in a migration and regenerate this file. +""" + + +def render_policy_snapshot(conn: Connection) -> str: + """Return the snapshot of ``conn``'s database, sorted so an unchanged schema renders identically.""" + functions = conn.execute( + text( + "SELECT pg_get_functiondef(p.oid) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + "WHERE n.nspname = 'public' AND p.proname = ANY(:names) ORDER BY p.proname, p.oid::regprocedure::text" + ), + {"names": list(RLS_FUNCTIONS)}, + ).scalars() + triggers = conn.execute( + text( + "SELECT pg_get_triggerdef(t.oid) FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid " + "WHERE NOT t.tgisinternal AND p.proname = ANY(:names) ORDER BY t.tgrelid::regclass::text, t.tgname" + ), + {"names": list(RLS_FUNCTIONS)}, + ).scalars() + tables = conn.execute( + text( + "SELECT c.relname, c.relrowsecurity FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND (c.relrowsecurity OR EXISTS (SELECT FROM pg_policy p WHERE p.polrelid = c.oid)) " + "ORDER BY c.relname" + ) + ).all() + policies = conn.execute( + text( + "SELECT tablename, policyname, permissive, roles::text[], cmd, qual, with_check FROM pg_policies " + "WHERE schemaname = 'public' ORDER BY tablename, policyname" + ) + ).all() + + sections = [_HEADER] + sections.extend(f"{definition.strip()};\n" for definition in functions) + if trigger_lines := "".join(f"{trigger};\n" for trigger in triggers): + sections.append(trigger_lines) + for table, enabled in tables: + state = "ENABLED" if enabled else "not enabled" + lines = [f"-- {table}: row-level security {state}"] + if enabled: + lines.append(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY;") + for _, name, permissive, roles, command, using, check in (p for p in policies if p.tablename == table): + statement = f"CREATE POLICY {name} ON {table} AS {permissive} FOR {command} TO {', '.join(sorted(roles))}" + if using is not None: + statement += f"\n USING ({using})" + if check is not None: + statement += f"\n WITH CHECK ({check})" + lines.append(statement + ";") + sections.append("\n".join(lines) + "\n") + return "\n".join(sections) diff --git a/src/mavedb/scripts/write_policy_snapshot.py b/src/mavedb/scripts/write_policy_snapshot.py new file mode 100644 index 00000000..d17de0ba --- /dev/null +++ b/src/mavedb/scripts/write_policy_snapshot.py @@ -0,0 +1,28 @@ +"""Write ``src/mavedb/db/policies.sql`` from a database at alembic head (#809). + +Connects with the ``DB_*`` environment variables and only reads. Run it after a migration that changes a policy, +against a database upgraded to head, and commit the result:: + + poetry run alembic upgrade head + poetry run python -m mavedb.scripts.write_policy_snapshot +""" + +import logging + +from sqlalchemy.orm import Session + +from mavedb.db.policy_snapshot import SNAPSHOT_PATH, render_policy_snapshot +from mavedb.scripts.environment import script_environment, with_database_session + +logger = logging.getLogger(__name__) + + +@script_environment.command() +@with_database_session +def write_policy_snapshot(db: Session) -> None: + SNAPSHOT_PATH.write_text(render_policy_snapshot(db.connection())) + logger.info(f"Wrote {SNAPSHOT_PATH}") + + +if __name__ == "__main__": + write_policy_snapshot() diff --git a/tests/conftest.py b/tests/conftest.py index c9877e5e..fb4a46da 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,6 +22,7 @@ from mavedb.db.base import Base from mavedb.db.bootstrap import apply_grants, bootstrap_cluster, bootstrap_database +from mavedb.db.policy_snapshot import SNAPSHOT_PATH from mavedb.db.rls import API_ROLE, MIGRATE_ROLE, OWNER_ROLE, WORKER_ROLE from mavedb.lib.logging.context import set_strict_collisions from mavedb.models import * # noqa: F403 @@ -124,6 +125,9 @@ def _load_schema(host, port, user, dbname, password): bootstrap_database(conn) conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) Base.metadata.create_all(bind=conn) + # The models can't declare policies. The snapshot holds the ones the migrations create, and a test + # checks it against a replay of them. + conn.exec_driver_sql(SNAPSHOT_PATH.read_text()) # Create a unique index for the published_variants_materialized_view to # enforce uniqueness on (variant_id, mapping_record_id, score_set_id). This diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index e6fb9a16..3147aacc 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -17,6 +17,7 @@ from mavedb.db import bootstrap from mavedb.db.bootstrap import apply_grants, bootstrap_cluster, bootstrap_database, role_problems, setup +from mavedb.db.policy_snapshot import SNAPSHOT_PATH, render_policy_snapshot from mavedb.db.rls import ( API_ROLE, FUNCTIONS, @@ -795,6 +796,39 @@ def test_upgrade_guarded_relations_read_as_the_caller_and_definers_pin_search_pa == [] ) + def test_upgrade_policies_match_the_committed_snapshot(self, replayed_database): + # A migration that changes a policy commits the regenerated snapshot, so review sees the whole rule. + with replayed_database.connect() as conn: + snapshot = render_policy_snapshot(conn) + + assert snapshot == SNAPSHOT_PATH.read_text(), ( + "src/mavedb/db/policies.sql is out of date; run `python -m mavedb.scripts.write_policy_snapshot` " + "against a database at alembic head" + ) + + def test_upgrade_policies_read_the_principal_only_through_the_helpers(self, replayed_database): + with replayed_database.connect() as conn: + policies = conn.execute( + text( + "SELECT tablename || '.' || policyname FROM pg_policies WHERE schemaname = 'public' " + "AND (coalesce(qual, '') ~ 'current_setting|app\\.' OR coalesce(with_check, '') ~ 'current_setting|app\\.')" + ) + ).scalars() + + assert sorted(policies) == [] + + def test_upgrade_enables_row_level_security_on_no_table(self, replayed_database): + # Enabling is the pilot's and the rollout's job (#825, #878), each in a release of its own. + with replayed_database.connect() as conn: + enabled = conn.execute( + text( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND (c.relrowsecurity OR c.relforcerowsecurity)" + ) + ).scalars() + + assert sorted(enabled) == [] + def test_upgrade_grants_match_the_registry(self, replayed_database): # The baseline is dumped without privileges, so these grants have to come from rls.py alone. A grant # anything else made would differ here, and be lost at the next squash. From c109277c0a7aeab6c468253140910ef3779a3076 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:42:51 -0800 Subject: [PATCH 05/15] feat(db): add RLS policies to the five record tables scoresets, experiments, experiment_sets, collections and score_calibrations each get _rule, deciding which rows the api sees and writes, and
_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. --- ...4e52_add_rls_policies_for_record_tables.py | 105 ++++++ src/mavedb/db/policies.sql | 88 +++++ tests/db/test_rls_policies.py | 347 ++++++++++++++++++ 3 files changed, 540 insertions(+) create mode 100644 alembic/versions/9a3b6c1d4e52_add_rls_policies_for_record_tables.py create mode 100644 tests/db/test_rls_policies.py diff --git a/alembic/versions/9a3b6c1d4e52_add_rls_policies_for_record_tables.py b/alembic/versions/9a3b6c1d4e52_add_rls_policies_for_record_tables.py new file mode 100644 index 00000000..3d7f4c48 --- /dev/null +++ b/alembic/versions/9a3b6c1d4e52_add_rls_policies_for_record_tables.py @@ -0,0 +1,105 @@ +"""add RLS policies to scoresets, experiments, experiment_sets, collections and score_calibrations + +Each table gets a business policy (``
_rule``) deciding which rows the api sees and writes, and a worker +policy (``
_worker``) showing ``mavedb_worker`` every row. Nothing is enforced until a table's row-level +security is enabled (#825, #878), so this changes no behavior. + +A contributor is matched by ORCID: contributor rows hold an ORCID, not a user id, so each rule looks up the +caller's ORCID in ``users``. An experiment is also visible when one of its score sets is, and an experiment set +when one of its experiments is (#564). Those subqueries are filtered by the child table's own policy, and no child +policy reads its parent, so the policies don't recurse. + +A calibration carries its own rule instead of delegating, because a public score set can hold a private +calibration, and it's visible only if its score set is. + +Revision ID: 9a3b6c1d4e52 +Revises: 8e2f5a0b3c41 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "9a3b6c1d4e52" +down_revision = "8e2f5a0b3c41" +branch_labels = None +depends_on = None + +SCORESETS = """ + private = false + OR created_by_id = mavedb_user_id() + OR mavedb_roles() && '{admin,mapper}' + OR id IN (SELECT sc.scoreset_id FROM scoreset_contributors sc + JOIN contributors c ON c.id = sc.contributor_id + JOIN users u ON u.username = c.orcid_id + WHERE u.id = mavedb_user_id()) +""" + +EXPERIMENTS = """ + private = false + OR created_by_id = mavedb_user_id() + OR mavedb_roles() && '{admin,mapper}' + OR id IN (SELECT ec.experiment_id FROM experiment_contributors ec + JOIN contributors c ON c.id = ec.contributor_id + JOIN users u ON u.username = c.orcid_id + WHERE u.id = mavedb_user_id()) + OR id IN (SELECT experiment_id FROM scoresets) +""" + +EXPERIMENT_SETS = """ + private = false + OR created_by_id = mavedb_user_id() + OR mavedb_roles() && '{admin,mapper}' + OR id IN (SELECT esc.experiment_set_id FROM experiment_set_contributors esc + JOIN contributors c ON c.id = esc.contributor_id + JOIN users u ON u.username = c.orcid_id + WHERE u.id = mavedb_user_id()) + OR id IN (SELECT experiment_set_id FROM experiments) +""" + +COLLECTIONS = """ + private = false + OR created_by_id = mavedb_user_id() + OR mavedb_roles() && '{admin}' + OR id IN (SELECT cua.collection_id FROM collection_user_associations cua + WHERE cua.user_id = mavedb_user_id() + AND cua.contribution_role IN ('admin', 'editor', 'viewer')) +""" + +SCORE_CALIBRATIONS = """ + EXISTS (SELECT 1 FROM scoresets s WHERE s.id = score_calibrations.score_set_id) + AND ( + private = false + OR created_by_id = mavedb_user_id() + OR mavedb_roles() && '{admin}' + OR (investigator_provided AND EXISTS ( + SELECT 1 FROM scoresets ss + WHERE ss.id = score_calibrations.score_set_id + AND (ss.created_by_id = mavedb_user_id() + OR ss.id IN (SELECT sc.scoreset_id FROM scoreset_contributors sc + JOIN contributors c ON c.id = sc.contributor_id + JOIN users u ON u.username = c.orcid_id + WHERE u.id = mavedb_user_id())))) + ) +""" + +RULES = { + "scoresets": SCORESETS, + "experiments": EXPERIMENTS, + "experiment_sets": EXPERIMENT_SETS, + "collections": COLLECTIONS, + "score_calibrations": SCORE_CALIBRATIONS, +} + + +def upgrade(): + for table, predicate in RULES.items(): + op.execute(f"CREATE POLICY {table}_rule ON {table} FOR ALL USING ({predicate}) WITH CHECK ({predicate})") + op.execute(f"CREATE POLICY {table}_worker ON {table} FOR ALL TO mavedb_worker USING (true) WITH CHECK (true)") + + +def downgrade(): + for table in reversed(RULES): + op.execute(f"DROP POLICY {table}_worker ON {table}") + op.execute(f"DROP POLICY {table}_rule ON {table}") diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql index 4d1ce550..94025f98 100644 --- a/src/mavedb/db/policies.sql +++ b/src/mavedb/db/policies.sql @@ -14,3 +14,91 @@ CREATE OR REPLACE FUNCTION public.mavedb_user_id() LANGUAGE sql STABLE PARALLEL SAFE AS $function$ SELECT nullif(current_setting('app.user_id', true), '')::integer $function$; + +-- collections: row-level security not enabled +CREATE POLICY collections_rule ON collections AS PERMISSIVE FOR ALL TO public + USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]) OR (id IN ( SELECT cua.collection_id + FROM collection_user_associations cua + WHERE ((cua.user_id = mavedb_user_id()) AND ((cua.contribution_role)::text = ANY ((ARRAY['admin'::character varying, 'editor'::character varying, 'viewer'::character varying])::text[]))))))) + WITH CHECK (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]) OR (id IN ( SELECT cua.collection_id + FROM collection_user_associations cua + WHERE ((cua.user_id = mavedb_user_id()) AND ((cua.contribution_role)::text = ANY ((ARRAY['admin'::character varying, 'editor'::character varying, 'viewer'::character varying])::text[]))))))); +CREATE POLICY collections_worker ON collections AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiment_sets: row-level security not enabled +CREATE POLICY experiment_sets_rule ON experiment_sets AS PERMISSIVE FOR ALL TO public + USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT esc.experiment_set_id + FROM ((experiment_set_contributors esc + JOIN contributors c ON ((c.id = esc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))) OR (id IN ( SELECT experiments.experiment_set_id + FROM experiments)))) + WITH CHECK (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT esc.experiment_set_id + FROM ((experiment_set_contributors esc + JOIN contributors c ON ((c.id = esc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))) OR (id IN ( SELECT experiments.experiment_set_id + FROM experiments)))); +CREATE POLICY experiment_sets_worker ON experiment_sets AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiments: row-level security not enabled +CREATE POLICY experiments_rule ON experiments AS PERMISSIVE FOR ALL TO public + USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT ec.experiment_id + FROM ((experiment_contributors ec + JOIN contributors c ON ((c.id = ec.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))) OR (id IN ( SELECT scoresets.experiment_id + FROM scoresets)))) + WITH CHECK (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT ec.experiment_id + FROM ((experiment_contributors ec + JOIN contributors c ON ((c.id = ec.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))) OR (id IN ( SELECT scoresets.experiment_id + FROM scoresets)))); +CREATE POLICY experiments_worker ON experiments AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- score_calibrations: row-level security not enabled +CREATE POLICY score_calibrations_rule ON score_calibrations AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM scoresets s + WHERE (s.id = score_calibrations.score_set_id))) AND ((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]) OR (investigator_provided AND (EXISTS ( SELECT 1 + FROM scoresets ss + WHERE ((ss.id = score_calibrations.score_set_id) AND ((ss.created_by_id = mavedb_user_id()) OR (ss.id IN ( SELECT sc.scoreset_id + FROM ((scoreset_contributors sc + JOIN contributors c ON ((c.id = sc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))))))))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM scoresets s + WHERE (s.id = score_calibrations.score_set_id))) AND ((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]) OR (investigator_provided AND (EXISTS ( SELECT 1 + FROM scoresets ss + WHERE ((ss.id = score_calibrations.score_set_id) AND ((ss.created_by_id = mavedb_user_id()) OR (ss.id IN ( SELECT sc.scoreset_id + FROM ((scoreset_contributors sc + JOIN contributors c ON ((c.id = sc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))))))))))); +CREATE POLICY score_calibrations_worker ON score_calibrations AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- scoresets: row-level security not enabled +CREATE POLICY scoresets_rule ON scoresets AS PERMISSIVE FOR ALL TO public + USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT sc.scoreset_id + FROM ((scoreset_contributors sc + JOIN contributors c ON ((c.id = sc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))))) + WITH CHECK (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT sc.scoreset_id + FROM ((scoreset_contributors sc + JOIN contributors c ON ((c.id = sc.contributor_id))) + JOIN users u ON (((u.username)::text = (c.orcid_id)::text))) + WHERE (u.id = mavedb_user_id()))))); +CREATE POLICY scoresets_worker ON scoresets AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py new file mode 100644 index 00000000..2c9ed0ba --- /dev/null +++ b/tests/db/test_rls_policies.py @@ -0,0 +1,347 @@ +"""The RLS policies (#809), checked as the api's login with row-level security enabled. + +The rest of the suite runs as a superuser, which skips every policy, so these tests enable RLS on the tables +they read, in the test's own database, and log in as ``mavedb_api`` with the principal sent the way +``mavedb.db.principal`` sends it. Rows are seeded as the superuser and named, and each test compares the names a +persona can see with the names it should. +""" + +from collections import defaultdict +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Optional + +import pytest + +pytest.importorskip("psycopg2") + +from sqlalchemy import text +from sqlalchemy.exc import ProgrammingError + +from mavedb.db.rls import API_ROLE, WORKER_ROLE + +pytestmark = pytest.mark.integration + +RECORD_TABLES = ("scoresets", "experiments", "experiment_sets", "score_calibrations", "collections") + +# How a row is identified, for tables without an id column. +ROW_KEYS: dict[str, str] = {} + +DATES = {"creation_date": "2026-01-01", "modification_date": "2026-01-01"} + + +@dataclass(frozen=True) +class Persona: + user: Optional[str] + roles: str = "{}" + + +PERSONAS = { + "anonymous": Persona(None), + "stranger": Persona("stranger"), + "owner": Persona("owner"), + "contributor": Persona("contributor"), + "mapper": Persona("mapper", "{mapper}"), + "admin": Persona("admin", "{admin}"), + "admin_without_role": Persona("admin"), +} + + +class Seed: + """Rows inserted as the superuser, by name, and the table each belongs to.""" + + def __init__(self, session): + self.session = session + self.ids: dict[str, object] = {} + self.rows: dict[str, set[str]] = defaultdict(set) + + def add(self, table: str, label: Optional[str] = None, /, **values) -> object: + columns = ", ".join(f'"{column}"' for column in values) + params = ", ".join(f":{column}" for column in values) + key = self.session.execute( + text(f"INSERT INTO {table} ({columns}) VALUES ({params}) RETURNING {ROW_KEYS.get(table, 'id')}"), values + ).scalar_one() + if label is not None: + self.ids[label] = key + self.rows[table].add(label) + return key + + def __getitem__(self, name: str): + return self.ids[name] + + def enable(self, *tables: str) -> None: + for table in tables: + self.session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) + self.session.commit() + + def principal(self, persona: Persona) -> dict: + return {"user_id": "" if persona.user is None else str(self[persona.user]), "roles": persona.roles} + + +def _send(conn, seed: Seed, persona: Persona) -> None: + conn.execute( + text("SELECT set_config('app.user_id', :user_id, true), set_config('app.active_roles', :roles, true)"), + seed.principal(persona), + ) + + +def _visible(conn, seed: Seed, table: str) -> set[str]: + visible = set(conn.execute(text(f"SELECT {ROW_KEYS.get(table, 'id')} FROM {table}")).scalars()) + return {name for name in seed.rows[table] if seed[name] in visible} + + +@contextmanager +def _as(login_as, seed: Seed, persona: Persona, role: str = API_ROLE): + with login_as(role).begin() as conn: + if persona.user is not None: + _send(conn, seed, persona) + yield conn + + +@pytest.fixture +def records(session): + """Public and private records of each kind, owned by ``owner``.""" + seed = Seed(session) + for name in ("owner", "contributor", "stranger", "mapper", "admin"): + seed.ids[name] = seed.add( + "users", + username=f"0000-0000-0000-{len(seed.ids):04d}", + is_superuser=False, + is_staff=False, + is_active=True, + is_first_login=False, + ) + orcid = session.execute(text("SELECT username FROM users WHERE id = :id"), {"id": seed["contributor"]}) + seed.ids["contributor_row"] = seed.add("contributors", orcid_id=orcid.scalar_one()) + license_id = seed.add("licenses", long_name="l", short_name="l", text="l", active=True, **DATES) + seed.ids["disease"] = seed.add("mondo_terms", code="MONDO:0000001", system="MONDO", label="d", **DATES) + + for visibility, private in (("public", False), ("private", True)): + seed.add( + "experiment_sets", + f"es_{visibility}", + extra_metadata="{}", + private=private, + approved=False, + num_experiments=1, + created_by_id=seed["owner"], + urn=f"urn:mavedb:es-{visibility}", + **DATES, + ) + seed.add( + "experiments", + f"e_{visibility}", + title="t", + short_description="s", + abstract_text="a", + method_text="m", + extra_metadata="{}", + private=private, + approved=False, + num_scoresets=1, + experiment_set_id=seed[f"es_{visibility}"], + external_links="{}", + created_by_id=seed["owner"], + urn=f"urn:mavedb:e-{visibility}", + **DATES, + ) + seed.add( + "scoresets", + f"s_{visibility}", + title="t", + method_text="m", + abstract_text="a", + short_description="s", + extra_metadata="{}", + dataset_columns="{}", + normalised=False, + private=private, + approved=False, + num_variants=0, + experiment_id=seed[f"e_{visibility}"], + licence_id=license_id, + external_links="{}", + created_by_id=seed["owner"], + urn=f"urn:mavedb:s-{visibility}", + **DATES, + ) + # Listed on the score set only: the experiment and experiment set reach them through it (#564). + session.execute( + text("INSERT INTO scoreset_contributors (scoreset_id, contributor_id) VALUES (:s, :c)"), + {"s": seed["s_private"], "c": seed["contributor_row"]}, + ) + + for name, score_set, private, investigator_provided, creator in ( + ("c_public_on_public", "s_public", False, False, "stranger"), + ("c_investigator_private_on_public", "s_public", True, True, "owner"), + ("c_community_private_on_public", "s_public", True, False, "stranger"), + ("c_public_on_private", "s_private", False, False, "owner"), + ("c_investigator_private_on_private", "s_private", True, True, "owner"), + ): + seed.add( + "score_calibrations", + name, + score_set_id=seed[score_set], + title=name, + research_use_only=False, + primary=False, + investigator_provided=investigator_provided, + private=private, + created_by_id=seed[creator], + modified_by_id=seed[creator], + disease_term_id=seed["disease"], + **DATES, + ) + + seed.add("collections", "col_public", name="p", private=False, created_by_id=seed["stranger"], **DATES) + seed.add("collections", "col_private", name="q", private=True, created_by_id=seed["owner"], **DATES) + session.execute( + text( + "INSERT INTO collection_user_associations (collection_id, user_id, contribution_role) " + "VALUES (:c, :u, 'viewer')" + ), + {"c": seed["col_private"], "u": seed["contributor"]}, + ) + session.commit() + return seed + + +ALL_CALIBRATIONS = { + "c_public_on_public", + "c_investigator_private_on_public", + "c_community_private_on_public", + "c_public_on_private", + "c_investigator_private_on_private", +} +PUBLIC_ONLY = { + "scoresets": {"s_public"}, + "experiments": {"e_public"}, + "experiment_sets": {"es_public"}, + "score_calibrations": {"c_public_on_public"}, + "collections": {"col_public"}, +} +BOTH_RECORDS = { + "scoresets": {"s_public", "s_private"}, + "experiments": {"e_public", "e_private"}, + "experiment_sets": {"es_public", "es_private"}, +} + +RECORDS_EXPECTED = { + "anonymous": PUBLIC_ONLY, + "stranger": {**PUBLIC_ONLY, "score_calibrations": {"c_public_on_public", "c_community_private_on_public"}}, + "owner": { + **BOTH_RECORDS, + "score_calibrations": ALL_CALIBRATIONS - {"c_community_private_on_public"}, + "collections": {"col_public", "col_private"}, + }, + "contributor": { + **BOTH_RECORDS, + "score_calibrations": {"c_public_on_public", "c_public_on_private", "c_investigator_private_on_private"}, + "collections": {"col_public", "col_private"}, + }, + "mapper": { + **BOTH_RECORDS, + "score_calibrations": {"c_public_on_public", "c_public_on_private"}, + "collections": {"col_public"}, + }, + "admin": {**BOTH_RECORDS, "score_calibrations": ALL_CALIBRATIONS, "collections": {"col_public", "col_private"}}, + "admin_without_role": PUBLIC_ONLY, +} + + +@pytest.fixture +def records_enforcing(records): + """Row-level security on for the record tables.""" + records.enable(*RECORD_TABLES) + + +@pytest.mark.usefixtures("records_enforcing") +@pytest.mark.parametrize("table", RECORD_TABLES) +@pytest.mark.parametrize("persona", PERSONAS) +def test_record_policy_persona_sees_exactly_their_rows(records, login_as, persona, table): + with _as(login_as, records, PERSONAS[persona]) as conn: + assert _visible(conn, records, table) == RECORDS_EXPECTED[persona][table] + + +@pytest.mark.usefixtures("records_enforcing") +@pytest.mark.parametrize("table", RECORD_TABLES) +def test_record_policy_worker_sees_every_row(records, login_as, table): + with _as(login_as, records, PERSONAS["anonymous"], WORKER_ROLE) as conn: + assert _visible(conn, records, table) == records.rows[table] + + +@pytest.mark.usefixtures("records_enforcing") +def test_record_policy_principal_left_empty_by_a_previous_transaction_reads_as_anonymous(records, login_as): + with login_as(API_ROLE).connect() as conn: + with conn.begin(): + _send(conn, records, PERSONAS["admin"]) + with conn.begin(): + assert _visible(conn, records, "scoresets") == {"s_public"} + + +@pytest.mark.usefixtures("records_enforcing") +def test_record_policy_insert_returning_own_private_record_succeeds(records, login_as): + with _as(login_as, records, PERSONAS["stranger"]) as conn: + row = conn.execute( + text( + "INSERT INTO experiment_sets (extra_metadata, private, approved, num_experiments, created_by_id, " + "creation_date, modification_date) VALUES ('{}', true, false, 0, :me, now(), now()) RETURNING id" + ), + {"me": records["stranger"]}, + ).scalar_one() + + assert row is not None + + +@pytest.mark.usefixtures("records_enforcing") +def test_record_policy_insert_on_behalf_of_another_user_is_refused(records, login_as): + with _as(login_as, records, PERSONAS["stranger"]) as conn: + with pytest.raises(ProgrammingError, match="row-level security"): + conn.execute( + text( + "INSERT INTO experiment_sets (extra_metadata, private, approved, num_experiments, " + "created_by_id, creation_date, modification_date) " + "VALUES ('{}', true, false, 0, :owner, now(), now())" + ), + {"owner": records["owner"]}, + ) + + +@pytest.mark.usefixtures("records_enforcing") +def test_record_policy_update_of_a_hidden_row_changes_nothing(records, login_as, session): + with _as(login_as, records, PERSONAS["stranger"]) as conn: + updated = conn.execute(text("UPDATE scoresets SET title = 'x' WHERE id = :id"), {"id": records["s_private"]}) + + assert updated.rowcount == 0 + title = session.execute(text("SELECT title FROM scoresets WHERE id = :id"), {"id": records["s_private"]}) + assert title.scalar_one() == "t" + + +@pytest.mark.usefixtures("records_enforcing") +def test_calibration_policy_contributor_removed_from_score_set_sees_neither_it_nor_their_calibration( + records, login_as, session +): + calibration = records.add( + "score_calibrations", + score_set_id=records["s_private"], + title="added by the contributor", + research_use_only=False, + primary=False, + investigator_provided=True, + private=True, + created_by_id=records["contributor"], + modified_by_id=records["contributor"], + disease_term_id=records["disease"], + **DATES, + ) + session.execute( + text("DELETE FROM scoreset_contributors WHERE contributor_id = :c"), {"c": records["contributor_row"]} + ) + session.commit() + + with _as(login_as, records, PERSONAS["contributor"]) as conn: + score_sets = set(conn.execute(text("SELECT id FROM scoresets")).scalars()) + calibrations = set(conn.execute(text("SELECT id FROM score_calibrations")).scalars()) + + assert records["s_private"] not in score_sets + assert calibration not in calibrations From 717c3f671d9ccc180fdd81bb2262ccb63c9a3cd1 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:43:03 -0800 Subject: [PATCH 06/15] fix(permissions): drop the last modifier from calibration read access 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. --- src/mavedb/lib/permissions/score_calibration.py | 5 ++--- tests/lib/permissions/test_score_calibration.py | 13 +++++++++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/mavedb/lib/permissions/score_calibration.py b/src/mavedb/lib/permissions/score_calibration.py index d852764d..ac116635 100644 --- a/src/mavedb/lib/permissions/score_calibration.py +++ b/src/mavedb/lib/permissions/score_calibration.py @@ -38,12 +38,11 @@ def has_permission(user_data: Optional[UserData], entity: ScoreCalibration, acti active_roles = [] if user_data is not None: user_is_owner = entity.created_by_id == user_data.user.id - # Contributor status is determined by matching the user's username (ORCID ID) against the contributors' ORCID IDs, - # as well as by matching the user's ID against the created_by_id and modified_by_id fields of the ScoreSet. + # The score set's owner and contributors, as the RLS policy matches them (#809). Its last modifier isn't + # included: that would keep their access to private calibrations after they lost the score set. user_is_contributor_to_score_set = ( user_data.user.username in [c.orcid_id for c in entity.score_set.contributors] or user_data.user.id == entity.score_set.created_by_id - or user_data.user.id == entity.score_set.modified_by_id ) active_roles = user_data.active_roles diff --git a/tests/lib/permissions/test_score_calibration.py b/tests/lib/permissions/test_score_calibration.py index 8c1c23df..26c1e097 100644 --- a/tests/lib/permissions/test_score_calibration.py +++ b/tests/lib/permissions/test_score_calibration.py @@ -285,6 +285,19 @@ def test_owner_who_cannot_read_the_score_set_cannot_read_their_calibration( assert not result.permitted assert result.http_code == 404 + def test_has_permission_score_set_last_modifier_without_ownership_cannot_read_private_calibration( + self, entity_helper: EntityTestHelper + ) -> None: + score_calibration = entity_helper.create_score_calibration( + "private", investigator_provided=True, score_set_state="published" + ) + score_calibration.score_set.modified_by_id = 4 + + result = has_permission(entity_helper.create_user_data("other_user"), score_calibration, Action.READ) + + assert not result.permitted + assert result.http_code == 404 + class TestScoreCalibrationUpdateActionHandler: """Test the _handle_update_action helper function directly.""" From 30df4a0e57c89e54bfd405a98089f48371971af1 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:44:23 -0800 Subject: [PATCH 07/15] feat(db): add RLS policies to the tables owned by one record 27 tables whose rows belong to one record get
_rule and
_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. --- ...5f863_add_rls_policies_for_owned_tables.py | 112 ++++++ src/mavedb/db/policies.sql | 336 ++++++++++++++++++ tests/db/test_bootstrap.py | 15 + tests/db/test_rls_policies.py | 196 +++++++++- 4 files changed, 658 insertions(+), 1 deletion(-) create mode 100644 alembic/versions/a4c7d2e5f863_add_rls_policies_for_owned_tables.py diff --git a/alembic/versions/a4c7d2e5f863_add_rls_policies_for_owned_tables.py b/alembic/versions/a4c7d2e5f863_add_rls_policies_for_owned_tables.py new file mode 100644 index 00000000..76e92684 --- /dev/null +++ b/alembic/versions/a4c7d2e5f863_add_rls_policies_for_owned_tables.py @@ -0,0 +1,112 @@ +"""add RLS policies to the tables whose rows belong to one record + +An owned row is visible exactly when the record that owns it is. Each policy reads its parent table, whose own +policy filters the subquery, so the rule for a record lives in one place. Each table also gets a worker policy +showing ``mavedb_worker`` every row. Nothing is enforced until row-level security is enabled (#825, #878). + +``variants`` and ``target_genes`` use ``IN (SELECT id FROM scoresets)``, where Postgres hashes the visible score +set ids once. Every other table uses a correlated ``EXISTS``: below ``variants`` the planner can't hash the +visible ids or misprices the hashed subplan per lookup, and scans whole tables instead (#832). + +Revision ID: a4c7d2e5f863 +Revises: 9a3b6c1d4e52 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "a4c7d2e5f863" +down_revision = "9a3b6c1d4e52" +branch_labels = None +depends_on = None + + +def _exists(parent: str, key: str, table: str, column: str) -> str: + return f"EXISTS (SELECT 1 FROM {parent} p WHERE p.{key} = {table}.{column})" + + +def _owned_by(parent: str, table: str, column: str) -> str: + return _exists(parent, "id", table, column) + + +RULES = { + "variants": "scoreset_id IN (SELECT id FROM scoresets)", + "target_genes": "scoreset_id IN (SELECT id FROM scoresets)", + "mapping_records": _owned_by("scoresets", "mapping_records", "score_set_id"), + "mapping_record_alleles": _owned_by("scoresets", "mapping_record_alleles", "score_set_id"), + "projection_groups": _owned_by("scoresets", "projection_groups", "score_set_id"), + "target_gene_external_identifiers": _owned_by("target_genes", "target_gene_external_identifiers", "target_gene_id"), + "target_gene_mappings": _owned_by("target_genes", "target_gene_mappings", "target_gene_id"), + "score_calibration_functional_classifications": _owned_by( + "score_calibrations", "score_calibration_functional_classifications", "calibration_id" + ), + "score_calibration_publication_identifiers": _owned_by( + "score_calibrations", "score_calibration_publication_identifiers", "score_calibration_id" + ), + "calibration_controls": _owned_by("score_calibrations", "calibration_controls", "calibration_id"), + # Measured against IN (SELECT id FROM score_calibration_functional_classifications) before #809 merges. + "score_calibration_functional_classification_variants": _owned_by( + "score_calibration_functional_classifications", + "score_calibration_functional_classification_variants", + "functional_classification_id", + ), + "scoreset_publication_identifiers": _owned_by("scoresets", "scoreset_publication_identifiers", "scoreset_id"), + "experiment_publication_identifiers": _owned_by( + "experiments", "experiment_publication_identifiers", "experiment_id" + ), + "scoreset_doi_identifiers": _owned_by("scoresets", "scoreset_doi_identifiers", "scoreset_id"), + "experiment_doi_identifiers": _owned_by("experiments", "experiment_doi_identifiers", "experiment_id"), + "experiment_set_doi_identifiers": _owned_by( + "experiment_sets", "experiment_set_doi_identifiers", "experiment_set_id" + ), + "scoreset_sra_identifiers": _owned_by("scoresets", "scoreset_sra_identifiers", "scoreset_id"), + "experiment_sra_identifiers": _owned_by("experiments", "experiment_sra_identifiers", "experiment_id"), + "experiment_set_sra_identifiers": _owned_by( + "experiment_sets", "experiment_set_sra_identifiers", "experiment_set_id" + ), + "experiment_controlled_keywords": _owned_by("experiments", "experiment_controlled_keywords", "experiment_id"), + # Both sides, so neither record discloses the other. + "scoreset_meta_analysis_sources": ( + _owned_by("scoresets", "scoreset_meta_analysis_sources", "source_scoreset_id") + + " AND " + + _owned_by("scoresets", "scoreset_meta_analysis_sources", "meta_analysis_scoreset_id") + ), + # Both sides, so a caller can't learn that a private collection holds a public record. + "collection_score_sets": ( + _owned_by("collections", "collection_score_sets", "collection_id") + + " AND " + + _owned_by("scoresets", "collection_score_sets", "score_set_id") + ), + "collection_experiments": ( + _owned_by("collections", "collection_experiments", "collection_id") + + " AND " + + _owned_by("experiments", "collection_experiments", "experiment_id") + ), + # Publication writes the row onto the record it's making public, and requests are forwarded before + # authentication, so a redirect is visible when the record it names is. + "urn_redirects": ( + _exists("scoresets", "urn", "urn_redirects", "new_urn") + + " OR " + + _exists("experiments", "urn", "urn_redirects", "new_urn") + + " OR " + + _exists("experiment_sets", "urn", "urn_redirects", "new_urn") + ), + "pipelines": "created_by_user_id = mavedb_user_id() OR mavedb_roles() && '{admin}'", + # A run with no pipeline, an ad hoc run, has no creator to show it to, so only admins see it. + "job_runs": _owned_by("pipelines", "job_runs", "pipeline_id") + " OR mavedb_roles() && '{admin}'", + "job_dependencies": _owned_by("job_runs", "job_dependencies", "id"), +} + + +def upgrade(): + for table, predicate in RULES.items(): + op.execute(f"CREATE POLICY {table}_rule ON {table} FOR ALL USING ({predicate}) WITH CHECK ({predicate})") + op.execute(f"CREATE POLICY {table}_worker ON {table} FOR ALL TO mavedb_worker USING (true) WITH CHECK (true)") + + +def downgrade(): + for table in reversed(RULES): + op.execute(f"DROP POLICY {table}_worker ON {table}") + op.execute(f"DROP POLICY {table}_rule ON {table}") diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql index 94025f98..c883f7e0 100644 --- a/src/mavedb/db/policies.sql +++ b/src/mavedb/db/policies.sql @@ -15,6 +15,50 @@ CREATE OR REPLACE FUNCTION public.mavedb_user_id() STABLE PARALLEL SAFE AS $function$ SELECT nullif(current_setting('app.user_id', true), '')::integer $function$; +-- calibration_controls: row-level security not enabled +CREATE POLICY calibration_controls_rule ON calibration_controls AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = calibration_controls.calibration_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = calibration_controls.calibration_id)))); +CREATE POLICY calibration_controls_worker ON calibration_controls AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- collection_experiments: row-level security not enabled +CREATE POLICY collection_experiments_rule ON collection_experiments AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM collections p + WHERE (p.id = collection_experiments.collection_id))) AND (EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = collection_experiments.experiment_id))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM collections p + WHERE (p.id = collection_experiments.collection_id))) AND (EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = collection_experiments.experiment_id))))); +CREATE POLICY collection_experiments_worker ON collection_experiments AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- collection_score_sets: row-level security not enabled +CREATE POLICY collection_score_sets_rule ON collection_score_sets AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM collections p + WHERE (p.id = collection_score_sets.collection_id))) AND (EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = collection_score_sets.score_set_id))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM collections p + WHERE (p.id = collection_score_sets.collection_id))) AND (EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = collection_score_sets.score_set_id))))); +CREATE POLICY collection_score_sets_worker ON collection_score_sets AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- collections: row-level security not enabled CREATE POLICY collections_rule ON collections AS PERMISSIVE FOR ALL TO public USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]) OR (id IN ( SELECT cua.collection_id @@ -27,6 +71,66 @@ CREATE POLICY collections_worker ON collections AS PERMISSIVE FOR ALL TO mavedb_ USING (true) WITH CHECK (true); +-- experiment_controlled_keywords: row-level security not enabled +CREATE POLICY experiment_controlled_keywords_rule ON experiment_controlled_keywords AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_controlled_keywords.experiment_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_controlled_keywords.experiment_id)))); +CREATE POLICY experiment_controlled_keywords_worker ON experiment_controlled_keywords AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiment_doi_identifiers: row-level security not enabled +CREATE POLICY experiment_doi_identifiers_rule ON experiment_doi_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_doi_identifiers.experiment_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_doi_identifiers.experiment_id)))); +CREATE POLICY experiment_doi_identifiers_worker ON experiment_doi_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiment_publication_identifiers: row-level security not enabled +CREATE POLICY experiment_publication_identifiers_rule ON experiment_publication_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_publication_identifiers.experiment_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_publication_identifiers.experiment_id)))); +CREATE POLICY experiment_publication_identifiers_worker ON experiment_publication_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiment_set_doi_identifiers: row-level security not enabled +CREATE POLICY experiment_set_doi_identifiers_rule ON experiment_set_doi_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE (p.id = experiment_set_doi_identifiers.experiment_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE (p.id = experiment_set_doi_identifiers.experiment_set_id)))); +CREATE POLICY experiment_set_doi_identifiers_worker ON experiment_set_doi_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- experiment_set_sra_identifiers: row-level security not enabled +CREATE POLICY experiment_set_sra_identifiers_rule ON experiment_set_sra_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE (p.id = experiment_set_sra_identifiers.experiment_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE (p.id = experiment_set_sra_identifiers.experiment_set_id)))); +CREATE POLICY experiment_set_sra_identifiers_worker ON experiment_set_sra_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- experiment_sets: row-level security not enabled CREATE POLICY experiment_sets_rule ON experiment_sets AS PERMISSIVE FOR ALL TO public USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT esc.experiment_set_id @@ -45,6 +149,18 @@ CREATE POLICY experiment_sets_worker ON experiment_sets AS PERMISSIVE FOR ALL TO USING (true) WITH CHECK (true); +-- experiment_sra_identifiers: row-level security not enabled +CREATE POLICY experiment_sra_identifiers_rule ON experiment_sra_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_sra_identifiers.experiment_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM experiments p + WHERE (p.id = experiment_sra_identifiers.experiment_id)))); +CREATE POLICY experiment_sra_identifiers_worker ON experiment_sra_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- experiments: row-level security not enabled CREATE POLICY experiments_rule ON experiments AS PERMISSIVE FOR ALL TO public USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT ec.experiment_id @@ -63,6 +179,110 @@ CREATE POLICY experiments_worker ON experiments AS PERMISSIVE FOR ALL TO mavedb_ USING (true) WITH CHECK (true); +-- job_dependencies: row-level security not enabled +CREATE POLICY job_dependencies_rule ON job_dependencies AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM job_runs p + WHERE (p.id = job_dependencies.id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM job_runs p + WHERE (p.id = job_dependencies.id)))); +CREATE POLICY job_dependencies_worker ON job_dependencies AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- job_runs: row-level security not enabled +CREATE POLICY job_runs_rule ON job_runs AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM pipelines p + WHERE (p.id = job_runs.pipeline_id))) OR (mavedb_roles() && '{admin}'::text[]))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM pipelines p + WHERE (p.id = job_runs.pipeline_id))) OR (mavedb_roles() && '{admin}'::text[]))); +CREATE POLICY job_runs_worker ON job_runs AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- mapping_record_alleles: row-level security not enabled +CREATE POLICY mapping_record_alleles_rule ON mapping_record_alleles AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = mapping_record_alleles.score_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = mapping_record_alleles.score_set_id)))); +CREATE POLICY mapping_record_alleles_worker ON mapping_record_alleles AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- mapping_records: row-level security not enabled +CREATE POLICY mapping_records_rule ON mapping_records AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = mapping_records.score_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = mapping_records.score_set_id)))); +CREATE POLICY mapping_records_worker ON mapping_records AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- pipelines: row-level security not enabled +CREATE POLICY pipelines_rule ON pipelines AS PERMISSIVE FOR ALL TO public + USING (((created_by_user_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]))) + WITH CHECK (((created_by_user_id = mavedb_user_id()) OR (mavedb_roles() && '{admin}'::text[]))); +CREATE POLICY pipelines_worker ON pipelines AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- projection_groups: row-level security not enabled +CREATE POLICY projection_groups_rule ON projection_groups AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = projection_groups.score_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = projection_groups.score_set_id)))); +CREATE POLICY projection_groups_worker ON projection_groups AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- score_calibration_functional_classification_variants: row-level security not enabled +CREATE POLICY score_calibration_functional_classification_variants_rule ON score_calibration_functional_classification_variants AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM score_calibration_functional_classifications p + WHERE (p.id = score_calibration_functional_classification_variants.functional_classification_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM score_calibration_functional_classifications p + WHERE (p.id = score_calibration_functional_classification_variants.functional_classification_id)))); +CREATE POLICY score_calibration_functional_classification_variants_worker ON score_calibration_functional_classification_variants AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- score_calibration_functional_classifications: row-level security not enabled +CREATE POLICY score_calibration_functional_classifications_rule ON score_calibration_functional_classifications AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = score_calibration_functional_classifications.calibration_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = score_calibration_functional_classifications.calibration_id)))); +CREATE POLICY score_calibration_functional_classifications_worker ON score_calibration_functional_classifications AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- score_calibration_publication_identifiers: row-level security not enabled +CREATE POLICY score_calibration_publication_identifiers_rule ON score_calibration_publication_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = score_calibration_publication_identifiers.score_calibration_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM score_calibrations p + WHERE (p.id = score_calibration_publication_identifiers.score_calibration_id)))); +CREATE POLICY score_calibration_publication_identifiers_worker ON score_calibration_publication_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- score_calibrations: row-level security not enabled CREATE POLICY score_calibrations_rule ON score_calibrations AS PERMISSIVE FOR ALL TO public USING (((EXISTS ( SELECT 1 @@ -87,6 +307,58 @@ CREATE POLICY score_calibrations_worker ON score_calibrations AS PERMISSIVE FOR USING (true) WITH CHECK (true); +-- scoreset_doi_identifiers: row-level security not enabled +CREATE POLICY scoreset_doi_identifiers_rule ON scoreset_doi_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_doi_identifiers.scoreset_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_doi_identifiers.scoreset_id)))); +CREATE POLICY scoreset_doi_identifiers_worker ON scoreset_doi_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- scoreset_meta_analysis_sources: row-level security not enabled +CREATE POLICY scoreset_meta_analysis_sources_rule ON scoreset_meta_analysis_sources AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_meta_analysis_sources.source_scoreset_id))) AND (EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_meta_analysis_sources.meta_analysis_scoreset_id))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_meta_analysis_sources.source_scoreset_id))) AND (EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_meta_analysis_sources.meta_analysis_scoreset_id))))); +CREATE POLICY scoreset_meta_analysis_sources_worker ON scoreset_meta_analysis_sources AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- scoreset_publication_identifiers: row-level security not enabled +CREATE POLICY scoreset_publication_identifiers_rule ON scoreset_publication_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_publication_identifiers.scoreset_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_publication_identifiers.scoreset_id)))); +CREATE POLICY scoreset_publication_identifiers_worker ON scoreset_publication_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- scoreset_sra_identifiers: row-level security not enabled +CREATE POLICY scoreset_sra_identifiers_rule ON scoreset_sra_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_sra_identifiers.scoreset_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = scoreset_sra_identifiers.scoreset_id)))); +CREATE POLICY scoreset_sra_identifiers_worker ON scoreset_sra_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- scoresets: row-level security not enabled CREATE POLICY scoresets_rule ON scoresets AS PERMISSIVE FOR ALL TO public USING (((private = false) OR (created_by_id = mavedb_user_id()) OR (mavedb_roles() && '{admin,mapper}'::text[]) OR (id IN ( SELECT sc.scoreset_id @@ -102,3 +374,67 @@ CREATE POLICY scoresets_rule ON scoresets AS PERMISSIVE FOR ALL TO public CREATE POLICY scoresets_worker ON scoresets AS PERMISSIVE FOR ALL TO mavedb_worker USING (true) WITH CHECK (true); + +-- target_gene_external_identifiers: row-level security not enabled +CREATE POLICY target_gene_external_identifiers_rule ON target_gene_external_identifiers AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM target_genes p + WHERE (p.id = target_gene_external_identifiers.target_gene_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM target_genes p + WHERE (p.id = target_gene_external_identifiers.target_gene_id)))); +CREATE POLICY target_gene_external_identifiers_worker ON target_gene_external_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- target_gene_mappings: row-level security not enabled +CREATE POLICY target_gene_mappings_rule ON target_gene_mappings AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM target_genes p + WHERE (p.id = target_gene_mappings.target_gene_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM target_genes p + WHERE (p.id = target_gene_mappings.target_gene_id)))); +CREATE POLICY target_gene_mappings_worker ON target_gene_mappings AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- target_genes: row-level security not enabled +CREATE POLICY target_genes_rule ON target_genes AS PERMISSIVE FOR ALL TO public + USING ((scoreset_id IN ( SELECT scoresets.id + FROM scoresets))) + WITH CHECK ((scoreset_id IN ( SELECT scoresets.id + FROM scoresets))); +CREATE POLICY target_genes_worker ON target_genes AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- urn_redirects: row-level security not enabled +CREATE POLICY urn_redirects_rule ON urn_redirects AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM scoresets p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))) OR (EXISTS ( SELECT 1 + FROM experiments p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))) OR (EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM scoresets p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))) OR (EXISTS ( SELECT 1 + FROM experiments p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))) OR (EXISTS ( SELECT 1 + FROM experiment_sets p + WHERE ((p.urn)::text = (urn_redirects.new_urn)::text))))); +CREATE POLICY urn_redirects_worker ON urn_redirects AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- variants: row-level security not enabled +CREATE POLICY variants_rule ON variants AS PERMISSIVE FOR ALL TO public + USING ((scoreset_id IN ( SELECT scoresets.id + FROM scoresets))) + WITH CHECK ((scoreset_id IN ( SELECT scoresets.id + FROM scoresets))); +CREATE POLICY variants_worker ON variants AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index 3147aacc..666be965 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -817,6 +817,21 @@ def test_upgrade_policies_read_the_principal_only_through_the_helpers(self, repl assert sorted(policies) == [] + def test_upgrade_policies_below_the_records_use_in_only_on_variants_and_target_genes(self, replayed_database): + # Below them, IN over a large parent can't be hashed or is mispriced per lookup; EXISTS is priced + # correctly (#832). The record tables' own rules use IN over small contributor lists. + allowed = {"scoresets", "experiments", "experiment_sets", "collections", "score_calibrations"} + allowed |= {"variants", "target_genes", "score_calibration_functional_classification_variants"} + with replayed_database.connect() as conn: + policies = conn.execute( + text( + "SELECT tablename, policyname FROM pg_policies WHERE schemaname = 'public' " + "AND (coalesce(qual, '') ~ ' IN \\( SELECT' OR coalesce(with_check, '') ~ ' IN \\( SELECT')" + ) + ).all() + + assert sorted(f"{table}.{name}" for table, name in policies if table not in allowed) == [] + def test_upgrade_enables_row_level_security_on_no_table(self, replayed_database): # Enabling is the pilot's and the rollout's job (#825, #878), each in a release of its own. with replayed_database.connect() as conn: diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py index 2c9ed0ba..48fd3650 100644 --- a/tests/db/test_rls_policies.py +++ b/tests/db/test_rls_policies.py @@ -25,7 +25,10 @@ RECORD_TABLES = ("scoresets", "experiments", "experiment_sets", "score_calibrations", "collections") # How a row is identified, for tables without an id column. -ROW_KEYS: dict[str, str] = {} +ROW_KEYS = { + "collection_score_sets": "collection_id || ':' || score_set_id", + "collection_experiments": "collection_id || ':' || experiment_id", +} DATES = {"creation_date": "2026-01-01", "modification_date": "2026-01-01"} @@ -345,3 +348,194 @@ def test_calibration_policy_contributor_removed_from_score_set_sees_neither_it_n assert records["s_private"] not in score_sets assert calibration not in calibrations + + +@pytest.fixture +def owned(records): + """Rows owned by the records, one under a visible parent and one under a hidden one where it applies.""" + seed = records + for visibility in ("public", "private"): + variant = seed.add( + "variants", + f"v_{visibility}", + data="{}", + scoreset_id=seed[f"s_{visibility}"], + urn=f"urn:mavedb:s-{visibility}#1", + **DATES, + ) + seed.add( + "mapping_records", + f"mr_{visibility}", + variant_id=variant, + score_set_id=seed[f"s_{visibility}"], + assay_level="genomic", + mapping_api_version="1", + mapped_date="2026-01-01", + valid_from="2026-01-01", + ) + + # Under a public calibration and a private one, both on the public score set. + for name, calibration in (("public", "c_public_on_public"), ("hidden", "c_investigator_private_on_public")): + seed.add( + "calibration_controls", + f"cc_{name}", + calibration_id=seed[calibration], + variant_id=seed["v_public"], + clinical_status="benign", + created_by_id=seed["owner"], + modified_by_id=seed["owner"], + **DATES, + ) + seed.add( + "score_calibration_functional_classifications", + f"fc_{name}", + calibration_id=seed[calibration], + label="l", + functional_classification="normal", + ) + + for collection, record in (("col_public", "public"), ("col_private", "public"), ("col_public", "private")): + seed.add( + "collection_score_sets", + f"css_{collection}_{record}", + collection_id=seed[collection], + score_set_id=seed[f"s_{record}"], + position=0, + ) + seed.add( + "collection_experiments", + f"ce_{collection}_{record}", + collection_id=seed[collection], + experiment_id=seed[f"e_{record}"], + position=0, + ) + + for kind in ("s", "e", "es"): + for visibility in ("public", "private"): + seed.add( + "urn_redirects", + f"ur_{kind}_{visibility}", + old_urn=f"tmp:{kind}-{visibility}", + new_urn=f"urn:mavedb:{kind}-{visibility}", + created_at="2026-01-01", + ) + + pipeline = seed.add( + "pipelines", "p_owner", name="p", status="created", metadata="{}", created_by_user_id=seed["owner"] + ) + runs = {} + for name, pipeline_id in (("jr_owner", pipeline), ("jr_ad_hoc", None)): + runs[name] = seed.add( + "job_runs", + name, + job_type="t", + job_function="f", + status="pending", + max_retries=0, + retry_count=0, + pipeline_id=pipeline_id, + metadata="{}", + ) + seed.add( + "job_dependencies", + "jd_owner", + id=runs["jr_owner"], + depends_on_job_id=runs["jr_ad_hoc"], + dependency_type="success_required", + ) + seed.add( + "job_dependencies", + "jd_ad_hoc", + id=runs["jr_ad_hoc"], + depends_on_job_id=runs["jr_owner"], + dependency_type="success_required", + ) + seed.session.commit() + return seed + + +OWNED_TABLES = ( + "variants", + "mapping_records", + "calibration_controls", + "score_calibration_functional_classifications", + "collection_score_sets", + "collection_experiments", + "urn_redirects", + "pipelines", + "job_runs", + "job_dependencies", +) + +OWNED_EXPECTED = { + "anonymous": { + "variants": {"v_public"}, + "mapping_records": {"mr_public"}, + "calibration_controls": {"cc_public"}, + "score_calibration_functional_classifications": {"fc_public"}, + "collection_score_sets": {"css_col_public_public"}, + "collection_experiments": {"ce_col_public_public"}, + "urn_redirects": {"ur_s_public", "ur_e_public", "ur_es_public"}, + "pipelines": set(), + "job_runs": set(), + "job_dependencies": set(), + }, + "owner": { + "variants": {"v_public", "v_private"}, + "mapping_records": {"mr_public", "mr_private"}, + "calibration_controls": {"cc_public", "cc_hidden"}, + "score_calibration_functional_classifications": {"fc_public", "fc_hidden"}, + "collection_score_sets": {"css_col_public_public", "css_col_private_public", "css_col_public_private"}, + "collection_experiments": {"ce_col_public_public", "ce_col_private_public", "ce_col_public_private"}, + "urn_redirects": {f"ur_{kind}_{v}" for kind in ("s", "e", "es") for v in ("public", "private")}, + "pipelines": {"p_owner"}, + "job_runs": {"jr_owner"}, + "job_dependencies": {"jd_owner"}, + }, + "admin": { + "variants": {"v_public", "v_private"}, + "mapping_records": {"mr_public", "mr_private"}, + "calibration_controls": {"cc_public", "cc_hidden"}, + "score_calibration_functional_classifications": {"fc_public", "fc_hidden"}, + "collection_score_sets": {"css_col_public_public", "css_col_private_public", "css_col_public_private"}, + "collection_experiments": {"ce_col_public_public", "ce_col_private_public", "ce_col_public_private"}, + "urn_redirects": {f"ur_{kind}_{v}" for kind in ("s", "e", "es") for v in ("public", "private")}, + "pipelines": {"p_owner"}, + "job_runs": {"jr_owner", "jr_ad_hoc"}, + "job_dependencies": {"jd_owner", "jd_ad_hoc"}, + }, +} + + +@pytest.fixture +def owned_enforcing(owned): + """Row-level security on for the record tables and the tables they own.""" + owned.enable(*RECORD_TABLES, *OWNED_TABLES) + + +@pytest.mark.usefixtures("owned_enforcing") +@pytest.mark.parametrize("table", OWNED_TABLES) +@pytest.mark.parametrize("persona", OWNED_EXPECTED) +def test_owned_policy_row_visible_exactly_when_its_owner_is(owned, login_as, persona, table): + with _as(login_as, owned, PERSONAS[persona]) as conn: + assert _visible(conn, owned, table) == OWNED_EXPECTED[persona][table] + + +@pytest.mark.usefixtures("owned_enforcing") +@pytest.mark.parametrize("table", OWNED_TABLES) +def test_owned_policy_worker_sees_every_row(owned, login_as, table): + with _as(login_as, owned, PERSONAS["anonymous"], WORKER_ROLE) as conn: + assert _visible(conn, owned, table) == owned.rows[table] + + +@pytest.mark.usefixtures("owned_enforcing") +def test_owned_policy_insert_under_a_hidden_parent_is_refused(owned, login_as): + with _as(login_as, owned, PERSONAS["stranger"]) as conn: + with pytest.raises(ProgrammingError, match="row-level security"): + conn.execute( + text( + "INSERT INTO variants (data, scoreset_id, creation_date, modification_date) " + "VALUES ('{}', :s, now(), now())" + ), + {"s": owned["s_private"]}, + ) From 805e2c1bf422d0be879ca8c92b7399801ec3a4a9 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:45:14 -0800 Subject: [PATCH 08/15] fix(score-sets): flush the rename before recording its URN redirect 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. --- src/mavedb/lib/urn_redirects.py | 3 +++ tests/routers/test_api_role.py | 44 ++++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/src/mavedb/lib/urn_redirects.py b/src/mavedb/lib/urn_redirects.py index d131d38a..5aadf03c 100644 --- a/src/mavedb/lib/urn_redirects.py +++ b/src/mavedb/lib/urn_redirects.py @@ -67,6 +67,9 @@ def record_urn_redirect(db: Session, old_urn: Optional[str], new_urn: str) -> No if not old_urn or old_urn == new_urn: return + # The redirect's RLS policy shows it only once a record carries new_urn, and inserting it returns its id, so + # the rename has to reach the database first. Nothing orders the two inserts otherwise (#809). + db.flush() db.add(UrnRedirect(old_urn=old_urn, new_urn=new_urn)) # type: ignore[call-arg] diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py index e327ed99..cdce337b 100644 --- a/tests/routers/test_api_role.py +++ b/tests/routers/test_api_role.py @@ -7,15 +7,17 @@ """ import json +from unittest.mock import patch import pytest -from sqlalchemy import select +from sqlalchemy import select, text from sqlalchemy.orm import Session arq = pytest.importorskip("arq") cdot = pytest.importorskip("cdot") fastapi = pytest.importorskip("fastapi") +from mavedb.db.principal import bind_principal from mavedb.db.rls import API_ROLE from mavedb.deps import get_db from mavedb.lib.authentication import UserData, get_current_user @@ -34,7 +36,12 @@ from mavedb.models.variant import Variant from tests.helpers.constants import TEST_MINIMAL_ACC_SCORESET, TEST_USER from tests.helpers.util.experiment import create_experiment -from tests.helpers.util.score_set import create_seq_score_set, create_seq_score_set_with_mapped_variants +from tests.helpers.util.score_set import ( + create_seq_score_set, + create_seq_score_set_with_mapped_variants, + publish_score_set, +) +from tests.helpers.util.variant import mock_worker_variant_insertion @pytest.fixture @@ -50,7 +57,9 @@ def override_get_db(): def override_user(): user = api_session.scalars(select(User).where(User.username == TEST_USER["username"])).one() - yield UserData(user, user.roles) + user_data = UserData(user, user.roles) + bind_principal(api_session, user_data) + yield user_data app_.dependency_overrides[get_db] = override_get_db app_.dependency_overrides[get_current_user] = override_user @@ -149,3 +158,32 @@ def test_read_and_delete_experiment_with_legacy_keywords_as_api_role(session, ap assert response.status_code == 200 session.expire_all() assert not session.scalars(select(ExperimentDbModel).where(ExperimentDbModel.urn == experiment["urn"])).first() + + +@pytest.mark.integration +def test_publish_score_set_as_api_role_with_rls_enabled_records_its_redirects( + session, data_provider, api_role_client, setup_router_db, data_files +): + for table in ( + "experiment_sets", + "experiments", + "scoresets", + "target_genes", + "variants", + "urn_redirects", + "mapping_records", + "mapping_record_alleles", + ): + session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) + session.commit() + experiment = create_experiment(api_role_client) + score_set = create_seq_score_set(api_role_client, experiment["urn"]) + score_set = mock_worker_variant_insertion( + api_role_client, session, data_provider, score_set, data_files / "scores.csv" + ) + + with patch.object(arq.ArqRedis, "enqueue_job", return_value=None): + published = publish_score_set(api_role_client, score_set["urn"]) + + redirects = session.execute(text("SELECT old_urn, new_urn FROM urn_redirects")).all() + assert (score_set["urn"], published["urn"]) in redirects From fc027b257fef37c6aa825cdb77662d3ae6980047 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:46:10 -0800 Subject: [PATCH 09/15] feat(db): carry score_set_id on target sequences and accessions 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. --- ...t_id_on_target_sequences_and_accessions.py | 102 ++++++++++++++++++ src/mavedb/models/target_accession.py | 15 ++- src/mavedb/models/target_gene.py | 48 ++++++++- src/mavedb/models/target_sequence.py | 17 ++- tests/db/test_bootstrap.py | 20 ++++ tests/db/test_rls_policies.py | 64 ++++++++++- tests/lib/csv/test_variant.py | 10 +- .../test_reverse_translation.py | 2 + 8 files changed, 268 insertions(+), 10 deletions(-) create mode 100644 alembic/versions/b5d8e3f6a974_carry_score_set_id_on_target_sequences_and_accessions.py diff --git a/alembic/versions/b5d8e3f6a974_carry_score_set_id_on_target_sequences_and_accessions.py b/alembic/versions/b5d8e3f6a974_carry_score_set_id_on_target_sequences_and_accessions.py new file mode 100644 index 00000000..fa2e4287 --- /dev/null +++ b/alembic/versions/b5d8e3f6a974_carry_score_set_id_on_target_sequences_and_accessions.py @@ -0,0 +1,102 @@ +"""carry score_set_id on target_sequences and target_accessions, with one target per gene + +The api inserts a target sequence or accession, with ``RETURNING 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, and its policy reads ``scoresets``. + +- ``score_set_id`` is backfilled from ``target_genes`` and made ``NOT NULL``. +- ``target_genes`` refers to each by ``(id, score_set_id)``, so the carried key can't differ from the gene's. + These composite foreign keys replace the single-column ones. +- ``target_genes_one_target`` requires exactly one of a sequence and an accession. + +Existing rows are repaired first, so the constraints hold: + +- A sequence or accession shared by several target genes is copied, so each gene gets its own. The lowest + target gene id keeps the original. The ORM permits sharing, and deleting one sharer's score set would delete + the shared row and leave the others with no target. +- A sequence or accession no target gene points at is deleted. Nothing can reach it, and it has no score set to + carry. The downgrade can't restore these rows or merge the copies. + +Revision ID: b5d8e3f6a974 +Revises: a4c7d2e5f863 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "b5d8e3f6a974" +down_revision = "a4c7d2e5f863" +branch_labels = None +depends_on = None + +# (table, the target_genes column pointing at it, its columns other than id and score_set_id, the foreign key +# it replaces, and the composite one replacing it) +TARGETS = [ + ( + "target_sequences", + "target_sequence_id", + "sequence_type, sequence, creation_date, modification_date, label, taxonomy_id", + "target_genes_wt_sequence_id_fkey", + "target_genes_target_sequence_score_set_fkey", + ), + ( + "target_accessions", + "accession_id", + "assembly, accession, creation_date, modification_date, gene, is_base_editor", + "target_genes_accession_id_fkey", + "target_genes_accession_score_set_fkey", + ), +] + + +def upgrade(): + for table, column, copied, old_fkey, new_fkey in TARGETS: + op.execute(f""" +DO $$ +DECLARE + gene record; + copy_id integer; +BEGIN + FOR gene IN + SELECT tg.id, tg.{column} AS target_id FROM target_genes tg + WHERE tg.{column} IS NOT NULL + AND EXISTS (SELECT 1 FROM target_genes o WHERE o.{column} = tg.{column} AND o.id < tg.id) + ORDER BY tg.id + LOOP + INSERT INTO {table} ({copied}) SELECT {copied} FROM {table} WHERE id = gene.target_id RETURNING id INTO copy_id; + UPDATE target_genes SET {column} = copy_id WHERE id = gene.id; + END LOOP; +END +$$""") + op.execute(f"DELETE FROM {table} t WHERE NOT EXISTS (SELECT 1 FROM target_genes tg WHERE tg.{column} = t.id)") + + op.execute(f"ALTER TABLE {table} ADD COLUMN score_set_id integer") + op.execute(f"UPDATE {table} t SET score_set_id = tg.scoreset_id FROM target_genes tg WHERE tg.{column} = t.id") + op.execute(f"ALTER TABLE {table} ALTER COLUMN score_set_id SET NOT NULL") + op.execute( + f"ALTER TABLE {table} ADD CONSTRAINT {table}_score_set_id_fkey " + "FOREIGN KEY (score_set_id) REFERENCES scoresets (id)" + ) + op.execute(f"CREATE INDEX ix_{table}_score_set_id ON {table} (score_set_id)") + op.execute(f"ALTER TABLE {table} ADD CONSTRAINT uq_{table}_id_score_set_id UNIQUE (id, score_set_id)") + + op.execute(f"ALTER TABLE target_genes DROP CONSTRAINT {old_fkey}") + op.execute( + f"ALTER TABLE target_genes ADD CONSTRAINT {new_fkey} " + f"FOREIGN KEY ({column}, scoreset_id) REFERENCES {table} (id, score_set_id)" + ) + + op.execute( + "ALTER TABLE target_genes ADD CONSTRAINT target_genes_one_target " + "CHECK (num_nonnulls(target_sequence_id, accession_id) = 1)" + ) + + +def downgrade(): + op.execute("ALTER TABLE target_genes DROP CONSTRAINT target_genes_one_target") + for table, column, _, old_fkey, new_fkey in reversed(TARGETS): + op.execute(f"ALTER TABLE target_genes DROP CONSTRAINT {new_fkey}") + op.execute(f"ALTER TABLE target_genes ADD CONSTRAINT {old_fkey} FOREIGN KEY ({column}) REFERENCES {table} (id)") + op.execute(f"ALTER TABLE {table} DROP COLUMN score_set_id") diff --git a/src/mavedb/models/target_accession.py b/src/mavedb/models/target_accession.py index 9e176888..bb74c321 100644 --- a/src/mavedb/models/target_accession.py +++ b/src/mavedb/models/target_accession.py @@ -1,12 +1,19 @@ from datetime import date +from typing import TYPE_CHECKING -from sqlalchemy import Boolean, Column, Date, Integer, String +from sqlalchemy import Boolean, Column, Date, ForeignKey, Integer, String, UniqueConstraint +from sqlalchemy.orm import Mapped, relationship from mavedb.db.base import Base +if TYPE_CHECKING: + from mavedb.models.score_set import ScoreSet + class TargetAccession(Base): __tablename__ = "target_accessions" + # The target gene's foreign key includes score_set_id, so the key carried here can't drift from it (#809). + __table_args__ = (UniqueConstraint("id", "score_set_id", name="uq_target_accessions_id_score_set_id"),) id = Column(Integer, primary_key=True) assembly = Column(String, nullable=True) @@ -15,3 +22,9 @@ class TargetAccession(Base): creation_date = Column(Date, nullable=False, default=date.today) modification_date = Column(Date, nullable=False, default=date.today, onupdate=date.today) is_base_editor = Column(Boolean, nullable=False, default=False) + + # The score set of the target gene that owns this accession, carried so the RLS policy can check it without + # reading target_genes: the api inserts an accession before any target gene points at it (#809). Set from the + # target gene when the accession is created (``mavedb.models.target_gene``). + score_set_id = Column(Integer, ForeignKey("scoresets.id"), index=True, nullable=False) + score_set: Mapped["ScoreSet"] = relationship("ScoreSet") diff --git a/src/mavedb/models/target_gene.py b/src/mavedb/models/target_gene.py index 36c399f9..301a1d35 100644 --- a/src/mavedb/models/target_gene.py +++ b/src/mavedb/models/target_gene.py @@ -1,9 +1,9 @@ from datetime import date from typing import TYPE_CHECKING -from sqlalchemy import Column, Date, Enum, ForeignKey, Integer, String +from sqlalchemy import CheckConstraint, Column, Date, Enum, ForeignKey, ForeignKeyConstraint, Integer, String, event from sqlalchemy.dialects.postgresql import JSONB -from sqlalchemy.orm import Mapped, backref, relationship +from sqlalchemy.orm import Mapped, Session, backref, relationship from mavedb.db.base import Base from mavedb.models.enums.target_category import TargetCategory @@ -20,6 +20,21 @@ class TargetGene(Base): __tablename__ = "target_genes" + __table_args__ = ( + # A target is a sequence or an accession. Each is owned by one target gene and carries its score set. + # These keys prevent the carried score set differing from the gene's (#809). + CheckConstraint("num_nonnulls(target_sequence_id, accession_id) = 1", name="target_genes_one_target"), + ForeignKeyConstraint( + ["target_sequence_id", "scoreset_id"], + ["target_sequences.id", "target_sequences.score_set_id"], + name="target_genes_target_sequence_score_set_fkey", + ), + ForeignKeyConstraint( + ["accession_id", "scoreset_id"], + ["target_accessions.id", "target_accessions.score_set_id"], + name="target_genes_accession_score_set_fkey", + ), + ) id: Mapped[int] = Column(Integer, primary_key=True) @@ -32,16 +47,22 @@ class TargetGene(Base): score_set_id = Column("scoreset_id", Integer, ForeignKey("scoresets.id"), index=True, nullable=False) score_set: Mapped[ScoreSet] = relationship(back_populates="target_genes", single_parent=True, uselist=True) - target_sequence_id = Column(Integer, ForeignKey("target_sequences.id"), index=True, nullable=True) - accession_id = Column(Integer, ForeignKey("target_accessions.id"), index=True, nullable=True) + target_sequence_id = Column(Integer, index=True, nullable=True) + accession_id = Column(Integer, index=True, nullable=True) target_sequence: Mapped[TargetSequence] = relationship( - back_populates="target_genes", cascade="all,delete-orphan", single_parent=True + back_populates="target_genes", + cascade="all,delete-orphan", + single_parent=True, + primaryjoin="TargetGene.target_sequence_id == TargetSequence.id", + foreign_keys=[target_sequence_id], ) target_accession: Mapped[TargetAccession] = relationship( "TargetAccession", backref=backref("target_genes", single_parent=True, uselist=True), cascade="all,delete-orphan", single_parent=True, + primaryjoin="TargetGene.accession_id == TargetAccession.id", + foreign_keys=[accession_id], ) pre_mapped_metadata: Mapped[JSONB] = Column("pre_mapped_metadata", JSONB, nullable=True) @@ -63,3 +84,20 @@ class TargetGene(Base): back_populates="target_gene", cascade="all, delete-orphan", ) + + +@event.listens_for(Session, "before_flush") +def _carry_score_set_to_new_targets(session: Session, flush_context, instances) -> None: + """Give each new target sequence or accession its target gene's score set before it's inserted.""" + for target_gene in [*session.new, *session.dirty]: + if not isinstance(target_gene, TargetGene): + continue + for target in (target_gene.target_sequence, target_gene.target_accession): + if target is None or target not in session.new or target.score_set_id is not None: + continue + if target_gene.score_set_id is not None: + target.score_set_id = target_gene.score_set_id + # A score set created in the same flush has no id yet; the relationship orders the inserts. + else: + score_set = target_gene.score_set + target.score_set = score_set[0] if isinstance(score_set, list) else score_set diff --git a/src/mavedb/models/target_sequence.py b/src/mavedb/models/target_sequence.py index 763a28ee..e878aa4f 100644 --- a/src/mavedb/models/target_sequence.py +++ b/src/mavedb/models/target_sequence.py @@ -1,7 +1,7 @@ from datetime import date from typing import TYPE_CHECKING, List -from sqlalchemy import Column, Date, ForeignKey, Integer, String +from sqlalchemy import Column, Date, ForeignKey, Integer, String, UniqueConstraint from sqlalchemy.orm import Mapped, backref, relationship from mavedb.db.base import Base @@ -9,11 +9,14 @@ from .taxonomy import Taxonomy if TYPE_CHECKING: + from mavedb.models.score_set import ScoreSet from mavedb.models.target_gene import TargetGene class TargetSequence(Base): __tablename__ = "target_sequences" + # The target gene's foreign key includes score_set_id, so the key carried here can't drift from it (#809). + __table_args__ = (UniqueConstraint("id", "score_set_id", name="uq_target_sequences_id_score_set_id"),) id = Column(Integer, primary_key=True) sequence_type = Column(String, nullable=False) @@ -27,4 +30,14 @@ class TargetSequence(Base): creation_date = Column(Date, nullable=False, default=date.today) modification_date = Column(Date, nullable=False, default=date.today, onupdate=date.today) - target_genes: Mapped[List["TargetGene"]] = relationship(back_populates="target_sequence") + # The score set of the target gene that owns this sequence, carried so the RLS policy can check it without + # reading target_genes: the api inserts a sequence before any target gene points at it (#809). Set from the + # target gene when the sequence is created (``mavedb.models.target_gene``). + score_set_id = Column(Integer, ForeignKey("scoresets.id"), index=True, nullable=False) + score_set: Mapped["ScoreSet"] = relationship("ScoreSet") + + target_genes: Mapped[List["TargetGene"]] = relationship( + back_populates="target_sequence", + primaryjoin="TargetGene.target_sequence_id == TargetSequence.id", + foreign_keys="TargetGene.target_sequence_id", + ) diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index 666be965..4a073353 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -832,6 +832,26 @@ def test_upgrade_policies_below_the_records_use_in_only_on_variants_and_target_g assert sorted(f"{table}.{name}" for table, name in policies if table not in allowed) == [] + def test_upgrade_target_genes_have_one_target_carrying_their_score_set(self, replayed_database): + # The models declare these too, but the test template is built from the models, not the migrations. + with replayed_database.connect() as conn: + constraints = set( + conn.execute( + text( + "SELECT conname FROM pg_constraint WHERE conrelid IN " + "('target_genes'::regclass, 'target_sequences'::regclass, 'target_accessions'::regclass)" + ) + ).scalars() + ) + + assert { + "target_genes_one_target", + "target_genes_target_sequence_score_set_fkey", + "target_genes_accession_score_set_fkey", + "uq_target_sequences_id_score_set_id", + "uq_target_accessions_id_score_set_id", + } <= constraints + def test_upgrade_enables_row_level_security_on_no_table(self, replayed_database): # Enabling is the pilot's and the rollout's job (#825, #878), each in a release of its own. with replayed_database.connect() as conn: diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py index 48fd3650..cc723a8f 100644 --- a/tests/db/test_rls_policies.py +++ b/tests/db/test_rls_policies.py @@ -16,7 +16,7 @@ pytest.importorskip("psycopg2") from sqlalchemy import text -from sqlalchemy.exc import ProgrammingError +from sqlalchemy.exc import IntegrityError, ProgrammingError from mavedb.db.rls import API_ROLE, WORKER_ROLE @@ -350,6 +350,43 @@ def test_calibration_policy_contributor_removed_from_score_set_sees_neither_it_n assert calibration not in calibrations +@pytest.fixture +def targets(records): + """A sequence and an accession under each score set, with no target gene yet.""" + seed = records + for visibility in ("public", "private"): + seed.add( + "target_sequences", + f"ts_{visibility}", + sequence_type="dna", + sequence="ATG", + score_set_id=seed[f"s_{visibility}"], + **DATES, + ) + seed.add( + "target_accessions", + f"ta_{visibility}", + accession="NM_000001.1", + is_base_editor=False, + score_set_id=seed[f"s_{visibility}"], + **DATES, + ) + seed.session.commit() + return seed + + +def _add_public_target_gene(seed: Seed, **target_names: str) -> None: + seed.add( + "target_genes", + name="g", + category="protein_coding", + scoreset_id=seed["s_public"], + **DATES, + **{column: seed[name] for column, name in target_names.items()}, + ) + seed.session.commit() + + @pytest.fixture def owned(records): """Rows owned by the records, one under a visible parent and one under a hidden one where it applies.""" @@ -539,3 +576,28 @@ def test_owned_policy_insert_under_a_hidden_parent_is_refused(owned, login_as): ), {"s": owned["s_private"]}, ) + + +@pytest.mark.parametrize( + "target_names", + [{}, {"target_sequence_id": "ts_public", "accession_id": "ta_public"}], + ids=["neither", "both"], +) +def test_target_gene_without_exactly_one_target_is_rejected(targets, target_names): + with pytest.raises(IntegrityError, match="target_genes_one_target"): + _add_public_target_gene(targets, **target_names) + + +@pytest.mark.parametrize( + "column, name", + [("target_sequence_id", "ts_private"), ("accession_id", "ta_private")], + ids=["sequence", "accession"], +) +def test_target_gene_whose_target_carries_another_score_set_is_rejected(targets, column, name): + with pytest.raises(IntegrityError, match="score_set_fkey"): + _add_public_target_gene(targets, **{column: name}) + + +@pytest.mark.parametrize("column, name", [("target_sequence_id", "ts_public"), ("accession_id", "ta_public")]) +def test_target_gene_with_one_target_under_its_own_score_set_is_accepted(targets, column, name): + _add_public_target_gene(targets, **{column: name}) diff --git a/tests/lib/csv/test_variant.py b/tests/lib/csv/test_variant.py index 6059bd29..3367e104 100644 --- a/tests/lib/csv/test_variant.py +++ b/tests/lib/csv/test_variant.py @@ -40,6 +40,7 @@ from mavedb.models.score_calibration import ScoreCalibration from mavedb.models.score_calibration_functional_classification import ScoreCalibrationFunctionalClassification from mavedb.models.score_set import ScoreSet +from mavedb.models.target_accession import TargetAccession from mavedb.models.target_gene import TargetGene from mavedb.models.variant import Variant from tests.helpers.constants import ( @@ -742,7 +743,14 @@ def test_non_clinvar_control_is_not_reported(self, session, setup_lib_db_with_ma def test_provenance_columns(self, session, setup_lib_db_with_mapped_variant): variant = setup_lib_db_with_mapped_variant.variant - session.add(TargetGene(score_set_id=variant.score_set.id, name="PTEN", category="protein_coding")) + session.add( + TargetGene( + score_set_id=variant.score_set.id, + name="PTEN", + category="protein_coding", + target_accession=TargetAccession(accession="NM_000314.8"), + ) + ) session.commit() rows = _parse_csv(get_variant_csv(session, variant.urn)) diff --git a/tests/worker/jobs/variant_processing/test_reverse_translation.py b/tests/worker/jobs/variant_processing/test_reverse_translation.py index 99774334..b281b6ca 100644 --- a/tests/worker/jobs/variant_processing/test_reverse_translation.py +++ b/tests/worker/jobs/variant_processing/test_reverse_translation.py @@ -672,6 +672,8 @@ async def test_genomic_only_target_falls_back_to_its_transcript_accession_then_m # Protein records pass no genomic HGVS and keep their NP_→NM_ lookup. assert resolve(*key, None) is None + # A target is a sequence or an accession, never both. + target_gene.target_sequence = None target_gene.target_accession = TargetAccession(accession="NM_999999.3", assembly="GRCh38", gene="GENE") session.commit() coordinates = FakeCoordinates(mane="NM_888888.2") From 6da6b4c04bfcd097c76207f9452709bc32f87d2d Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:46:52 -0800 Subject: [PATCH 10/15] feat(db): add RLS policies to target sequences and accessions 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. --- ...ies_for_target_sequences_and_accessions.py | 34 +++++++++++ src/mavedb/db/policies.sql | 24 ++++++++ tests/db/test_rls_policies.py | 12 +++- tests/routers/test_api_role.py | 60 ++++++++++++++++--- 4 files changed, 120 insertions(+), 10 deletions(-) create mode 100644 alembic/versions/c6e9f4a7b085_add_rls_policies_for_target_sequences_and_accessions.py diff --git a/alembic/versions/c6e9f4a7b085_add_rls_policies_for_target_sequences_and_accessions.py b/alembic/versions/c6e9f4a7b085_add_rls_policies_for_target_sequences_and_accessions.py new file mode 100644 index 00000000..d7b29a25 --- /dev/null +++ b/alembic/versions/c6e9f4a7b085_add_rls_policies_for_target_sequences_and_accessions.py @@ -0,0 +1,34 @@ +"""add RLS policies to target_sequences and target_accessions, by the score set they carry + +A sequence or accession is visible exactly when its score set is. The score set row is written before its +targets, so a new one passes the policy when it's inserted, as ``INSERT ... RETURNING`` requires. Each table also +gets a worker policy. Nothing is enforced until row-level security is enabled (#825, #878). + +Revision ID: c6e9f4a7b085 +Revises: b5d8e3f6a974 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "c6e9f4a7b085" +down_revision = "b5d8e3f6a974" +branch_labels = None +depends_on = None + +TABLES = ("target_sequences", "target_accessions") + + +def upgrade(): + for table in TABLES: + predicate = f"EXISTS (SELECT 1 FROM scoresets p WHERE p.id = {table}.score_set_id)" + op.execute(f"CREATE POLICY {table}_rule ON {table} FOR ALL USING ({predicate}) WITH CHECK ({predicate})") + op.execute(f"CREATE POLICY {table}_worker ON {table} FOR ALL TO mavedb_worker USING (true) WITH CHECK (true)") + + +def downgrade(): + for table in reversed(TABLES): + op.execute(f"DROP POLICY {table}_worker ON {table}") + op.execute(f"DROP POLICY {table}_rule ON {table}") diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql index c883f7e0..40dcebf0 100644 --- a/src/mavedb/db/policies.sql +++ b/src/mavedb/db/policies.sql @@ -375,6 +375,18 @@ CREATE POLICY scoresets_worker ON scoresets AS PERMISSIVE FOR ALL TO mavedb_work USING (true) WITH CHECK (true); +-- target_accessions: row-level security not enabled +CREATE POLICY target_accessions_rule ON target_accessions AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = target_accessions.score_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = target_accessions.score_set_id)))); +CREATE POLICY target_accessions_worker ON target_accessions AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- target_gene_external_identifiers: row-level security not enabled CREATE POLICY target_gene_external_identifiers_rule ON target_gene_external_identifiers AS PERMISSIVE FOR ALL TO public USING ((EXISTS ( SELECT 1 @@ -409,6 +421,18 @@ CREATE POLICY target_genes_worker ON target_genes AS PERMISSIVE FOR ALL TO maved USING (true) WITH CHECK (true); +-- target_sequences: row-level security not enabled +CREATE POLICY target_sequences_rule ON target_sequences AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = target_sequences.score_set_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM scoresets p + WHERE (p.id = target_sequences.score_set_id)))); +CREATE POLICY target_sequences_worker ON target_sequences AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- urn_redirects: row-level security not enabled CREATE POLICY urn_redirects_rule ON urn_redirects AS PERMISSIVE FOR ALL TO public USING (((EXISTS ( SELECT 1 diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py index cc723a8f..5ab40481 100644 --- a/tests/db/test_rls_policies.py +++ b/tests/db/test_rls_policies.py @@ -388,9 +388,9 @@ def _add_public_target_gene(seed: Seed, **target_names: str) -> None: @pytest.fixture -def owned(records): +def owned(targets): """Rows owned by the records, one under a visible parent and one under a hidden one where it applies.""" - seed = records + seed = targets for visibility in ("public", "private"): variant = seed.add( "variants", @@ -493,6 +493,8 @@ def owned(records): OWNED_TABLES = ( "variants", + "target_sequences", + "target_accessions", "mapping_records", "calibration_controls", "score_calibration_functional_classifications", @@ -507,6 +509,8 @@ def owned(records): OWNED_EXPECTED = { "anonymous": { "variants": {"v_public"}, + "target_sequences": {"ts_public"}, + "target_accessions": {"ta_public"}, "mapping_records": {"mr_public"}, "calibration_controls": {"cc_public"}, "score_calibration_functional_classifications": {"fc_public"}, @@ -519,6 +523,8 @@ def owned(records): }, "owner": { "variants": {"v_public", "v_private"}, + "target_sequences": {"ts_public", "ts_private"}, + "target_accessions": {"ta_public", "ta_private"}, "mapping_records": {"mr_public", "mr_private"}, "calibration_controls": {"cc_public", "cc_hidden"}, "score_calibration_functional_classifications": {"fc_public", "fc_hidden"}, @@ -531,6 +537,8 @@ def owned(records): }, "admin": { "variants": {"v_public", "v_private"}, + "target_sequences": {"ts_public", "ts_private"}, + "target_accessions": {"ta_public", "ta_private"}, "mapping_records": {"mr_public", "mr_private"}, "calibration_controls": {"cc_public", "cc_hidden"}, "score_calibration_functional_classifications": {"fc_public", "fc_hidden"}, diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py index cdce337b..b0606227 100644 --- a/tests/routers/test_api_role.py +++ b/tests/routers/test_api_role.py @@ -37,6 +37,7 @@ from tests.helpers.constants import TEST_MINIMAL_ACC_SCORESET, TEST_USER from tests.helpers.util.experiment import create_experiment from tests.helpers.util.score_set import ( + create_acc_score_set, create_seq_score_set, create_seq_score_set_with_mapped_variants, publish_score_set, @@ -160,22 +161,65 @@ def test_read_and_delete_experiment_with_legacy_keywords_as_api_role(session, ap assert not session.scalars(select(ExperimentDbModel).where(ExperimentDbModel.urn == experiment["urn"])).first() -@pytest.mark.integration -def test_publish_score_set_as_api_role_with_rls_enabled_records_its_redirects( - session, data_provider, api_role_client, setup_router_db, data_files -): +@pytest.fixture +def target_tables_enforcing(session): + """Row-level security on for the target tables and the records above them, in this test's database (#809). + + The target tables' policies read ``scoresets``, which has to enforce too, or every score set passes. + """ for table in ( "experiment_sets", "experiments", "scoresets", "target_genes", - "variants", - "urn_redirects", - "mapping_records", - "mapping_record_alleles", + "target_sequences", + "target_accessions", ): session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) session.commit() + + +@pytest.mark.integration +@pytest.mark.parametrize("create", [create_seq_score_set, create_acc_score_set], ids=["sequence", "accession"]) +def test_create_score_set_as_api_role_with_target_rls_enabled_succeeds( + session, api_role_client, setup_router_db, target_tables_enforcing, create +): + experiment = create_experiment(api_role_client) + + score_set = create(api_role_client, experiment["urn"]) + + target = score_set["targetGenes"][0] + assert target.get("targetSequence") or target.get("targetAccession") + + +@pytest.mark.integration +@pytest.mark.parametrize( + "mock_publication_fetch", + [({"dbName": "PubMed", "identifier": "20711194"})], + indirect=["mock_publication_fetch"], +) +def test_replace_score_set_targets_as_api_role_with_target_rls_enabled_succeeds( + session, api_role_client, setup_router_db, target_tables_enforcing, mock_publication_fetch +): + experiment = create_experiment(api_role_client) + score_set = create_seq_score_set(api_role_client, experiment["urn"]) + + response = api_role_client.patch( + f"/api/v1/score-sets-with-variants/{score_set['urn']}", + data={"target_genes": json.dumps(TEST_MINIMAL_ACC_SCORESET["targetGenes"])}, + ) + + assert response.status_code == 200 + assert response.json()["targetGenes"][0]["targetAccession"] + + +@pytest.mark.integration +def test_publish_score_set_as_api_role_with_rls_enabled_records_its_redirects( + session, data_provider, api_role_client, setup_router_db, target_tables_enforcing, data_files +): + for table in ("variants", "urn_redirects", "mapping_records", "mapping_record_alleles"): + session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) + session.commit() experiment = create_experiment(api_role_client) score_set = create_seq_score_set(api_role_client, experiment["urn"]) score_set = mock_worker_variant_insertion( From 7d5c4189d338e069bb39fef159a8c2b1723084d0 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:48:33 -0800 Subject: [PATCH 11/15] feat(alleles): record when a public score set first links an allele 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. --- ...05b8c196_add_alleles_first_published_at.py | 89 ++++++++++ src/mavedb/db/policies.sql | 38 ++++- src/mavedb/db/policy_snapshot.py | 13 +- src/mavedb/db/rls.py | 4 + src/mavedb/lib/alleles.py | 22 ++- src/mavedb/models/allele.py | 6 +- tests/db/test_rls_policies.py | 157 ++++++++++++++++++ 7 files changed, 321 insertions(+), 8 deletions(-) create mode 100644 alembic/versions/d7fa05b8c196_add_alleles_first_published_at.py diff --git a/alembic/versions/d7fa05b8c196_add_alleles_first_published_at.py b/alembic/versions/d7fa05b8c196_add_alleles_first_published_at.py new file mode 100644 index 00000000..c06e7d16 --- /dev/null +++ b/alembic/versions/d7fa05b8c196_add_alleles_first_published_at.py @@ -0,0 +1,89 @@ +"""add alleles.first_published_at, set by trigger once a public score set links the allele + +The ``alleles`` RLS policy shows an allele when a visible mapping link points at it. About 85% of alleles are +linked from a public score set, and for those that ``EXISTS`` is wasted work, costing 3-10x on per-score-set +reads after reverse translation (#832). This column lets the policy skip it. + +- It's write-once: it only goes from null to set. 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); a change that allows it, such as unpublishing or an embargo, has to revisit this column. +- ``mavedb_mark_alleles_published_by_links`` sets it when links to a public score set are inserted, and + ``mavedb_mark_alleles_published_by_score_set`` when a score set goes public, for the alleles it already links. + Links aren't re-pointed after insert (retiring one updates only its ``valid_to``), so inserts are enough. +- The value is the date the linking score set was published. + +Both functions are plain, not ``SECURITY DEFINER``. They run as whoever writes the link or publishes, who can see +the alleles involved. + +The backfill updates about 1.5M rows in production. It takes row locks only, so reads go on, but stop the worker +during the deploy so it doesn't wait on them. + +Revision ID: d7fa05b8c196 +Revises: c6e9f4a7b085 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "d7fa05b8c196" +down_revision = "c6e9f4a7b085" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute("ALTER TABLE alleles ADD COLUMN first_published_at date") + + op.execute("""CREATE FUNCTION mavedb_mark_alleles_published_by_links() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE alleles a + SET first_published_at = coalesce(s.published_date, current_date) + FROM new_links l + JOIN scoresets s ON s.id = l.score_set_id + WHERE a.id = l.allele_id + AND NOT s.private + AND a.first_published_at IS NULL; + RETURN NULL; +END +$$""") + op.execute( + "CREATE TRIGGER mapping_record_alleles_mark_alleles_published AFTER INSERT ON mapping_record_alleles " + "REFERENCING NEW TABLE AS new_links FOR EACH STATEMENT " + "EXECUTE FUNCTION mavedb_mark_alleles_published_by_links()" + ) + + op.execute("""CREATE FUNCTION mavedb_mark_alleles_published_by_score_set() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE alleles a + SET first_published_at = coalesce(NEW.published_date, current_date) + FROM mapping_record_alleles m + WHERE m.score_set_id = NEW.id + AND a.id = m.allele_id + AND a.first_published_at IS NULL; + RETURN NULL; +END +$$""") + op.execute( + "CREATE TRIGGER scoresets_mark_alleles_published AFTER UPDATE OF private ON scoresets " + "FOR EACH ROW WHEN (OLD.private AND NOT NEW.private) " + "EXECUTE FUNCTION mavedb_mark_alleles_published_by_score_set()" + ) + + op.execute("""UPDATE alleles a + SET first_published_at = p.published + FROM (SELECT m.allele_id, min(coalesce(s.published_date, s.creation_date)) AS published + FROM mapping_record_alleles m + JOIN scoresets s ON s.id = m.score_set_id + WHERE NOT s.private + GROUP BY m.allele_id) p + WHERE a.id = p.allele_id""") + + +def downgrade(): + op.execute("DROP TRIGGER scoresets_mark_alleles_published ON scoresets") + op.execute("DROP FUNCTION mavedb_mark_alleles_published_by_score_set()") + op.execute("DROP TRIGGER mapping_record_alleles_mark_alleles_published ON mapping_record_alleles") + op.execute("DROP FUNCTION mavedb_mark_alleles_published_by_links()") + op.execute("ALTER TABLE alleles DROP COLUMN first_published_at") diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql index 40dcebf0..ffcf1478 100644 --- a/src/mavedb/db/policies.sql +++ b/src/mavedb/db/policies.sql @@ -1,8 +1,39 @@ --- Row-level security in the public schema: the functions it relies on, then each table's RLS state and --- policies. +-- Row-level security in the public schema: the functions and triggers it relies on, then each table's RLS +-- state and policies. -- Generated from a database at alembic head by `python -m mavedb.scripts.write_policy_snapshot`. Don't edit -- by hand: change policies in a migration and regenerate this file. +CREATE OR REPLACE FUNCTION public.mavedb_mark_alleles_published_by_links() + RETURNS trigger + LANGUAGE plpgsql +AS $function$ +BEGIN + UPDATE alleles a + SET first_published_at = coalesce(s.published_date, current_date) + FROM new_links l + JOIN scoresets s ON s.id = l.score_set_id + WHERE a.id = l.allele_id + AND NOT s.private + AND a.first_published_at IS NULL; + RETURN NULL; +END +$function$; + +CREATE OR REPLACE FUNCTION public.mavedb_mark_alleles_published_by_score_set() + RETURNS trigger + LANGUAGE plpgsql +AS $function$ +BEGIN + UPDATE alleles a + SET first_published_at = coalesce(NEW.published_date, current_date) + FROM mapping_record_alleles m + WHERE m.score_set_id = NEW.id + AND a.id = m.allele_id + AND a.first_published_at IS NULL; + RETURN NULL; +END +$function$; + CREATE OR REPLACE FUNCTION public.mavedb_roles() RETURNS text[] LANGUAGE sql @@ -15,6 +46,9 @@ CREATE OR REPLACE FUNCTION public.mavedb_user_id() STABLE PARALLEL SAFE AS $function$ SELECT nullif(current_setting('app.user_id', true), '')::integer $function$; +CREATE TRIGGER mapping_record_alleles_mark_alleles_published AFTER INSERT ON public.mapping_record_alleles REFERENCING NEW TABLE AS new_links FOR EACH STATEMENT EXECUTE FUNCTION mavedb_mark_alleles_published_by_links(); +CREATE TRIGGER scoresets_mark_alleles_published AFTER UPDATE OF private ON public.scoresets FOR EACH ROW WHEN ((old.private AND (NOT new.private))) EXECUTE FUNCTION mavedb_mark_alleles_published_by_score_set(); + -- calibration_controls: row-level security not enabled CREATE POLICY calibration_controls_rule ON calibration_controls AS PERMISSIVE FOR ALL TO public USING ((EXISTS ( SELECT 1 diff --git a/src/mavedb/db/policy_snapshot.py b/src/mavedb/db/policy_snapshot.py index 6aeba27f..8ce3bec5 100644 --- a/src/mavedb/db/policy_snapshot.py +++ b/src/mavedb/db/policy_snapshot.py @@ -15,12 +15,17 @@ SNAPSHOT_PATH = Path(__file__).parent / "policies.sql" -# Every function a policy calls. Policy bodies call nothing else. -RLS_FUNCTIONS = ("mavedb_user_id", "mavedb_roles") +# Every function a policy calls, and the trigger functions that maintain a column a policy reads. +RLS_FUNCTIONS = ( + "mavedb_user_id", + "mavedb_roles", + "mavedb_mark_alleles_published_by_links", + "mavedb_mark_alleles_published_by_score_set", +) _HEADER = """\ --- Row-level security in the public schema: the functions it relies on, then each table's RLS state and --- policies. +-- Row-level security in the public schema: the functions and triggers it relies on, then each table's RLS +-- state and policies. -- Generated from a database at alembic head by `python -m mavedb.scripts.write_policy_snapshot`. Don't edit -- by hand: change policies in a migration and regenerate this file. """ diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py index eeeee751..bb7d425b 100644 --- a/src/mavedb/db/rls.py +++ b/src/mavedb/db/rls.py @@ -165,6 +165,10 @@ class Relation: # so they bypass nothing. Any role a policy applies to must be able to run them. "mavedb_user_id": Function(frozenset({API_ROLE, WORKER_ROLE})), "mavedb_roles": Function(frozenset({API_ROLE, WORKER_ROLE})), + # Trigger functions that set alleles.first_published_at (#809). A trigger runs its function whoever fires it, + # so nobody needs to call them. + "mavedb_mark_alleles_published_by_links": Function(), + "mavedb_mark_alleles_published_by_score_set": Function(), # Refreshing a materialized view requires owning it, and the worker owns nothing. "mavedb_refresh_mat_views": Function(frozenset({WORKER_ROLE}), security_definer=True), # From the 2026.3.0 baseline. Nothing calls it. diff --git a/src/mavedb/lib/alleles.py b/src/mavedb/lib/alleles.py index c66e069f..63d566d7 100644 --- a/src/mavedb/lib/alleles.py +++ b/src/mavedb/lib/alleles.py @@ -13,7 +13,7 @@ from datetime import datetime from typing import Optional, TypeVar -from sqlalchemy import and_, select +from sqlalchemy import and_, exists, select from sqlalchemy.orm import Session, joinedload from mavedb.lib.permissions import Action, has_permission @@ -231,3 +231,23 @@ def get_allele_translations( .distinct() ).all() ) + + +def first_published_at_drift(db: Session) -> list[int]: + """Return the ids of alleles whose ``first_published_at`` disagrees with their links (#809). + + The column should be set exactly when a public score set links the allele, retired links included. The RLS + policy shows a set allele to everyone, so one set too early would disclose an allele only private score sets + produced. Triggers maintain it; this recomputes it from the links to check them. + """ + linked_from_public = exists( + select(1) + .select_from(MappingRecordAllele) + .join(ScoreSet, ScoreSet.id == MappingRecordAllele.score_set_id) + .where(MappingRecordAllele.allele_id == Allele.id, ScoreSet.private.is_(False)) + ) + return list( + db.scalars( + select(Allele.id).where(Allele.first_published_at.is_not(None) != linked_from_public).order_by(Allele.id) + ) + ) diff --git a/src/mavedb/models/allele.py b/src/mavedb/models/allele.py index 379cdd56..3fa8cffd 100644 --- a/src/mavedb/models/allele.py +++ b/src/mavedb/models/allele.py @@ -4,7 +4,7 @@ from sqlalchemy import Column, Date, Index, Integer, String, UniqueConstraint, func from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.hybrid import hybrid_property -from sqlalchemy.orm import Mapped, relationship +from sqlalchemy.orm import Mapped, mapped_column, relationship from mavedb.db.base import Base from mavedb.lib.hgvs import extract_accession @@ -33,6 +33,10 @@ class Allele(Base): clingen_allele_id = Column(String, nullable=True) post_mapped: Mapped[Optional[Any]] = Column(JSONB(none_as_null=True), nullable=True) + # When a public score set first linked this allele, set by database triggers and never cleared (#809). The + # RLS policy shows a set allele to everyone without checking its links. + first_published_at: Mapped[Optional[date]] = mapped_column(Date, nullable=True) + created_at: Mapped[date] = Column(Date, nullable=False, default=date.today) updated_at: Mapped[date] = Column(Date, nullable=False, default=date.today, onupdate=date.today) diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py index 5ab40481..28618930 100644 --- a/tests/db/test_rls_policies.py +++ b/tests/db/test_rls_policies.py @@ -19,6 +19,7 @@ from sqlalchemy.exc import IntegrityError, ProgrammingError from mavedb.db.rls import API_ROLE, WORKER_ROLE +from mavedb.lib.alleles import first_published_at_drift pytestmark = pytest.mark.integration @@ -26,6 +27,8 @@ # How a row is identified, for tables without an id column. ROW_KEYS = { + "variant_translations": "aa_clingen_id || ':' || nt_clingen_id", + "scoreset_publication_identifiers": "db_name || ':' || identifier || ':' || scoreset_id", "collection_score_sets": "collection_id || ':' || score_set_id", "collection_experiments": "collection_id || ':' || experiment_id", } @@ -609,3 +612,157 @@ def test_target_gene_whose_target_carries_another_score_set_is_rejected(targets, @pytest.mark.parametrize("column, name", [("target_sequence_id", "ts_public"), ("accession_id", "ta_public")]) def test_target_gene_with_one_target_under_its_own_score_set_is_accepted(targets, column, name): _add_public_target_gene(targets, **{column: name}) + + +@pytest.fixture +def shared(owned): + """Shared rows, each reached from the public score set's records or only from the private one's.""" + seed = owned + for visibility in ("public", "private"): + allele = seed.add( + "alleles", + f"a_{visibility}", + vrs_digest=f"digest-{visibility}", + level="genomic", + clingen_allele_id=f"CA-{visibility}", + **{"created_at": "2026-01-01", "updated_at": "2026-01-01"}, + ) + seed.add( + "mapping_record_alleles", + f"mra_{visibility}", + mapping_record_id=seed[f"mr_{visibility}"], + allele_id=allele, + score_set_id=seed[f"s_{visibility}"], + is_authoritative=True, + valid_from="2026-01-01", + ) + seed.add( + "vep_allele_consequences", + f"vep_{visibility}", + allele_id=allele, + source_version="1", + access_date="2026-01-01", + valid_from="2026-01-01", + ) + control = seed.add( + "clinvar_controls", + f"cvc_{visibility}", + db_identifier=f"cv-{visibility}", + gene_symbol="G", + clinical_significance="benign", + clinical_review_status="r", + db_version="1", + db_name="ClinVar", + **DATES, + ) + seed.add( + "clinvar_allele_links", + f"cal_{visibility}", + allele_id=allele, + clinvar_control_id=control, + valid_from="2026-01-01", + ) + gnomad = seed.add( + "gnomad_variants", + f"gv_{visibility}", + db_name="gnomAD", + db_identifier=f"gv-{visibility}", + db_version="1", + allele_count=1, + allele_number=1, + allele_frequency=1.0, + **DATES, + ) + seed.add( + "gnomad_allele_links", + f"gal_{visibility}", + allele_id=allele, + gnomad_variant_id=gnomad, + valid_from="2026-01-01", + ) + seed.add( + "publication_identifiers", + f"pub_{visibility}", + identifier=f"pub-{visibility}", + db_name="PubMed", + title="t", + authors="[]", + **DATES, + ) + seed.add( + "scoreset_publication_identifiers", + f"spi_{visibility}", + scoreset_id=seed[f"s_{visibility}"], + db_name="PubMed", + identifier=f"pub-{visibility}", + primary=False, + ) + seed.add("variant_translations", "vt_public", aa_clingen_id="CA-public", nt_clingen_id="CA-public", **DATES) + seed.add("variant_translations", "vt_mixed", aa_clingen_id="CA-public", nt_clingen_id="CA-private", **DATES) + seed.session.commit() + return seed + + +def _first_published(session, seed: Seed, name: str): + session.expire_all() + return session.execute( + text("SELECT first_published_at FROM alleles WHERE id = :id"), {"id": seed[name]} + ).scalar_one() + + +def test_first_published_at_link_from_public_score_set_sets_it_and_private_leaves_it_null(shared, session): + assert _first_published(session, shared, "a_public") is not None + assert _first_published(session, shared, "a_private") is None + assert first_published_at_drift(session) == [] + + +def test_first_published_at_publishing_a_score_set_sets_it_for_alleles_it_links(shared, session): + session.execute( + text("UPDATE scoresets SET private = false, published_date = '2026-02-02' WHERE id = :id"), + {"id": shared["s_private"]}, + ) + session.commit() + + assert str(_first_published(session, shared, "a_private")) == "2026-02-02" + assert first_published_at_drift(session) == [] + + +def test_first_published_at_is_never_overwritten(shared, session): + before = _first_published(session, shared, "a_public") + session.execute( + text( + "INSERT INTO mapping_record_alleles (mapping_record_id, allele_id, score_set_id, is_authoritative, " + "valid_from) VALUES (:mr, :a, :s, false, now())" + ), + {"mr": shared["mr_private"], "a": shared["a_public"], "s": shared["s_private"]}, + ) + session.execute( + text("UPDATE scoresets SET private = false, published_date = '2030-01-01' WHERE id = :id"), + {"id": shared["s_private"]}, + ) + session.commit() + + assert _first_published(session, shared, "a_public") == before + + +def test_first_published_at_link_to_an_already_public_score_set_sets_it(shared, session): + session.execute( + text( + "INSERT INTO mapping_record_alleles (mapping_record_id, allele_id, score_set_id, is_authoritative, " + "valid_from) VALUES (:mr, :a, :s, false, now())" + ), + {"mr": shared["mr_public"], "a": shared["a_private"], "s": shared["s_public"]}, + ) + session.commit() + + assert _first_published(session, shared, "a_private") is not None + assert first_published_at_drift(session) == [] + + +def test_first_published_at_drift_reports_an_allele_set_without_a_public_link(shared, session): + session.execute( + text("UPDATE alleles SET first_published_at = '2026-01-01' WHERE id = :id"), {"id": shared["a_private"]} + ) + session.commit() + + assert first_published_at_drift(session) == [shared["a_private"]] From 4223cc55c31171e359e7e769aa8beffc4042cdfb Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:49:20 -0800 Subject: [PATCH 12/15] feat(db): add RLS policies to the shared tables 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. --- ...d2a7_add_rls_policies_for_shared_tables.py | 82 ++++++++++++++ src/mavedb/db/policies.sql | 102 ++++++++++++++++++ tests/db/test_bootstrap.py | 30 ++++++ tests/db/test_rls_policies.py | 84 +++++++++++++++ tests/routers/test_api_role.py | 2 +- tests/routers/test_publication_rls.py | 62 ++++------- 6 files changed, 319 insertions(+), 43 deletions(-) create mode 100644 alembic/versions/e8ab16c9d2a7_add_rls_policies_for_shared_tables.py diff --git a/alembic/versions/e8ab16c9d2a7_add_rls_policies_for_shared_tables.py b/alembic/versions/e8ab16c9d2a7_add_rls_policies_for_shared_tables.py new file mode 100644 index 00000000..c8dba6bd --- /dev/null +++ b/alembic/versions/e8ab16c9d2a7_add_rls_policies_for_shared_tables.py @@ -0,0 +1,82 @@ +"""add RLS policies to the tables whose rows any record can link to + +A shared row belongs to no one record. It's visible when a record the caller can see links to it: its presence +can say what someone is working on, so these aren't public reference data. Each policy reads its link table, +whose own policy filters the subquery. Each table also gets a worker policy. Nothing is enforced until row-level +security is enabled (#825, #878). + +- ``alleles``: a link from a visible score set, retired links included, or ``first_published_at``, which a + public score set's link has already set. +- The rows fetched for alleles (VEP consequences, ClinVar and gnomAD links) follow their allele; ClinVar controls + and gnomAD variants follow their links; a variant translation needs both of its alleles. +- ``publication_identifiers``: a citation from a visible record, by natural key (#945). Its ``WITH CHECK`` is + ``true``: the api stores a publication before anything cites it (``INSERT ... ON CONFLICT DO NOTHING``, no + ``RETURNING``), so the new row couldn't pass the read rule. Accepting any written row discloses nothing, and an + update still reaches only the rows the caller can see. + +Every policy is a correlated ``EXISTS``: ``IN`` over alleles can't be hashed in memory (#832). + +Revision ID: e8ab16c9d2a7 +Revises: d7fa05b8c196 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "e8ab16c9d2a7" +down_revision = "d7fa05b8c196" +branch_labels = None +depends_on = None + + +def _cited_by(table: str) -> str: + return ( + f"EXISTS (SELECT 1 FROM {table} c WHERE c.db_name = publication_identifiers.db_name " + "AND c.identifier = publication_identifiers.identifier)" + ) + + +RULES = { + "alleles": ( + "first_published_at IS NOT NULL " + "OR EXISTS (SELECT 1 FROM mapping_record_alleles m WHERE m.allele_id = alleles.id)" + ), + "vep_allele_consequences": "EXISTS (SELECT 1 FROM alleles a WHERE a.id = vep_allele_consequences.allele_id)", + "clinvar_allele_links": "EXISTS (SELECT 1 FROM alleles a WHERE a.id = clinvar_allele_links.allele_id)", + "gnomad_allele_links": "EXISTS (SELECT 1 FROM alleles a WHERE a.id = gnomad_allele_links.allele_id)", + "clinvar_controls": ( + "EXISTS (SELECT 1 FROM clinvar_allele_links l WHERE l.clinvar_control_id = clinvar_controls.id)" + ), + "gnomad_variants": "EXISTS (SELECT 1 FROM gnomad_allele_links l WHERE l.gnomad_variant_id = gnomad_variants.id)", + "variant_translations": ( + "EXISTS (SELECT 1 FROM alleles a WHERE a.clingen_allele_id = variant_translations.aa_clingen_id) " + "AND EXISTS (SELECT 1 FROM alleles a WHERE a.clingen_allele_id = variant_translations.nt_clingen_id)" + ), + "publication_identifiers": " OR ".join( + _cited_by(table) + for table in ( + "scoreset_publication_identifiers", + "experiment_publication_identifiers", + "score_calibration_publication_identifiers", + ) + ), +} + + +# Tables whose written rows needn't pass the read rule. +CHECKS = {"publication_identifiers": "true"} + + +def upgrade(): + for table, predicate in RULES.items(): + check = CHECKS.get(table, predicate) + op.execute(f"CREATE POLICY {table}_rule ON {table} FOR ALL USING ({predicate}) WITH CHECK ({check})") + op.execute(f"CREATE POLICY {table}_worker ON {table} FOR ALL TO mavedb_worker USING (true) WITH CHECK (true)") + + +def downgrade(): + for table in reversed(RULES): + op.execute(f"DROP POLICY {table}_worker ON {table}") + op.execute(f"DROP POLICY {table}_rule ON {table}") diff --git a/src/mavedb/db/policies.sql b/src/mavedb/db/policies.sql index ffcf1478..8ca5918c 100644 --- a/src/mavedb/db/policies.sql +++ b/src/mavedb/db/policies.sql @@ -49,6 +49,18 @@ AS $function$ SELECT nullif(current_setting('app.user_id', true), '')::integer $ CREATE TRIGGER mapping_record_alleles_mark_alleles_published AFTER INSERT ON public.mapping_record_alleles REFERENCING NEW TABLE AS new_links FOR EACH STATEMENT EXECUTE FUNCTION mavedb_mark_alleles_published_by_links(); CREATE TRIGGER scoresets_mark_alleles_published AFTER UPDATE OF private ON public.scoresets FOR EACH ROW WHEN ((old.private AND (NOT new.private))) EXECUTE FUNCTION mavedb_mark_alleles_published_by_score_set(); +-- alleles: row-level security not enabled +CREATE POLICY alleles_rule ON alleles AS PERMISSIVE FOR ALL TO public + USING (((first_published_at IS NOT NULL) OR (EXISTS ( SELECT 1 + FROM mapping_record_alleles m + WHERE (m.allele_id = alleles.id))))) + WITH CHECK (((first_published_at IS NOT NULL) OR (EXISTS ( SELECT 1 + FROM mapping_record_alleles m + WHERE (m.allele_id = alleles.id))))); +CREATE POLICY alleles_worker ON alleles AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- calibration_controls: row-level security not enabled CREATE POLICY calibration_controls_rule ON calibration_controls AS PERMISSIVE FOR ALL TO public USING ((EXISTS ( SELECT 1 @@ -61,6 +73,30 @@ CREATE POLICY calibration_controls_worker ON calibration_controls AS PERMISSIVE USING (true) WITH CHECK (true); +-- clinvar_allele_links: row-level security not enabled +CREATE POLICY clinvar_allele_links_rule ON clinvar_allele_links AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = clinvar_allele_links.allele_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = clinvar_allele_links.allele_id)))); +CREATE POLICY clinvar_allele_links_worker ON clinvar_allele_links AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- clinvar_controls: row-level security not enabled +CREATE POLICY clinvar_controls_rule ON clinvar_controls AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM clinvar_allele_links l + WHERE (l.clinvar_control_id = clinvar_controls.id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM clinvar_allele_links l + WHERE (l.clinvar_control_id = clinvar_controls.id)))); +CREATE POLICY clinvar_controls_worker ON clinvar_controls AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- collection_experiments: row-level security not enabled CREATE POLICY collection_experiments_rule ON collection_experiments AS PERMISSIVE FOR ALL TO public USING (((EXISTS ( SELECT 1 @@ -213,6 +249,30 @@ CREATE POLICY experiments_worker ON experiments AS PERMISSIVE FOR ALL TO mavedb_ USING (true) WITH CHECK (true); +-- gnomad_allele_links: row-level security not enabled +CREATE POLICY gnomad_allele_links_rule ON gnomad_allele_links AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = gnomad_allele_links.allele_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = gnomad_allele_links.allele_id)))); +CREATE POLICY gnomad_allele_links_worker ON gnomad_allele_links AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + +-- gnomad_variants: row-level security not enabled +CREATE POLICY gnomad_variants_rule ON gnomad_variants AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM gnomad_allele_links l + WHERE (l.gnomad_variant_id = gnomad_variants.id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM gnomad_allele_links l + WHERE (l.gnomad_variant_id = gnomad_variants.id)))); +CREATE POLICY gnomad_variants_worker ON gnomad_variants AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- job_dependencies: row-level security not enabled CREATE POLICY job_dependencies_rule ON job_dependencies AS PERMISSIVE FOR ALL TO public USING ((EXISTS ( SELECT 1 @@ -281,6 +341,20 @@ CREATE POLICY projection_groups_worker ON projection_groups AS PERMISSIVE FOR AL USING (true) WITH CHECK (true); +-- publication_identifiers: row-level security not enabled +CREATE POLICY publication_identifiers_rule ON publication_identifiers AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM scoreset_publication_identifiers c + WHERE (((c.db_name)::text = (publication_identifiers.db_name)::text) AND ((c.identifier)::text = (publication_identifiers.identifier)::text)))) OR (EXISTS ( SELECT 1 + FROM experiment_publication_identifiers c + WHERE (((c.db_name)::text = (publication_identifiers.db_name)::text) AND ((c.identifier)::text = (publication_identifiers.identifier)::text)))) OR (EXISTS ( SELECT 1 + FROM score_calibration_publication_identifiers c + WHERE (((c.db_name)::text = (publication_identifiers.db_name)::text) AND ((c.identifier)::text = (publication_identifiers.identifier)::text)))))) + WITH CHECK (true); +CREATE POLICY publication_identifiers_worker ON publication_identifiers AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- score_calibration_functional_classification_variants: row-level security not enabled CREATE POLICY score_calibration_functional_classification_variants_rule ON score_calibration_functional_classification_variants AS PERMISSIVE FOR ALL TO public USING ((EXISTS ( SELECT 1 @@ -487,6 +561,22 @@ CREATE POLICY urn_redirects_worker ON urn_redirects AS PERMISSIVE FOR ALL TO mav USING (true) WITH CHECK (true); +-- variant_translations: row-level security not enabled +CREATE POLICY variant_translations_rule ON variant_translations AS PERMISSIVE FOR ALL TO public + USING (((EXISTS ( SELECT 1 + FROM alleles a + WHERE ((a.clingen_allele_id)::text = (variant_translations.aa_clingen_id)::text))) AND (EXISTS ( SELECT 1 + FROM alleles a + WHERE ((a.clingen_allele_id)::text = (variant_translations.nt_clingen_id)::text))))) + WITH CHECK (((EXISTS ( SELECT 1 + FROM alleles a + WHERE ((a.clingen_allele_id)::text = (variant_translations.aa_clingen_id)::text))) AND (EXISTS ( SELECT 1 + FROM alleles a + WHERE ((a.clingen_allele_id)::text = (variant_translations.nt_clingen_id)::text))))); +CREATE POLICY variant_translations_worker ON variant_translations AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); + -- variants: row-level security not enabled CREATE POLICY variants_rule ON variants AS PERMISSIVE FOR ALL TO public USING ((scoreset_id IN ( SELECT scoresets.id @@ -496,3 +586,15 @@ CREATE POLICY variants_rule ON variants AS PERMISSIVE FOR ALL TO public CREATE POLICY variants_worker ON variants AS PERMISSIVE FOR ALL TO mavedb_worker USING (true) WITH CHECK (true); + +-- vep_allele_consequences: row-level security not enabled +CREATE POLICY vep_allele_consequences_rule ON vep_allele_consequences AS PERMISSIVE FOR ALL TO public + USING ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = vep_allele_consequences.allele_id)))) + WITH CHECK ((EXISTS ( SELECT 1 + FROM alleles a + WHERE (a.id = vep_allele_consequences.allele_id)))); +CREATE POLICY vep_allele_consequences_worker ON vep_allele_consequences AS PERMISSIVE FOR ALL TO mavedb_worker + USING (true) + WITH CHECK (true); diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index 4a073353..02611ec2 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -796,6 +796,36 @@ def test_upgrade_guarded_relations_read_as_the_caller_and_definers_pin_search_pa == [] ) + def test_upgrade_every_guarded_table_has_its_rule_and_worker_policies_and_no_other_table_has_any( + self, replayed_database + ): + with replayed_database.connect() as conn: + tables = set( + conn.execute( + text( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f')" + ) + ).scalars() + ) + policies = conn.execute( + text( + "SELECT tablename, policyname, roles::text[], qual, with_check FROM pg_policies " + "WHERE schemaname = 'public'" + ) + ).all() + + guarded = {name for name, relation in RELATIONS.items() if relation.api is ApiAccess.GUARDED} & tables + names = {(table, name) for table, name, *_ in policies} + worker_policies = {(table, name) for table, name, roles, using, check in policies if roles == [WORKER_ROLE]} + assert sorted({table for table, _ in names} - guarded) == [] + assert sorted(names) == sorted((table, f"{table}_{kind}") for table in guarded for kind in ("rule", "worker")) + assert { + (table, name, using, check) + for table, name, roles, using, check in policies + if (table, name) in worker_policies + } == {(table, f"{table}_worker", "true", "true") for table in guarded} + def test_upgrade_policies_match_the_committed_snapshot(self, replayed_database): # A migration that changes a policy commits the regenerated snapshot, so review sees the whole rule. with replayed_database.connect() as conn: diff --git a/tests/db/test_rls_policies.py b/tests/db/test_rls_policies.py index 28618930..733b646a 100644 --- a/tests/db/test_rls_policies.py +++ b/tests/db/test_rls_policies.py @@ -703,6 +703,78 @@ def shared(owned): return seed +SHARED_TABLES = ( + "alleles", + "mapping_record_alleles", + "vep_allele_consequences", + "clinvar_allele_links", + "clinvar_controls", + "gnomad_allele_links", + "gnomad_variants", + "variant_translations", + "publication_identifiers", + "scoreset_publication_identifiers", +) + + +def _shared_expected(*visibilities: str) -> dict[str, set[str]]: + prefixes = { + "alleles": "a", + "mapping_record_alleles": "mra", + "vep_allele_consequences": "vep", + "clinvar_allele_links": "cal", + "clinvar_controls": "cvc", + "gnomad_allele_links": "gal", + "gnomad_variants": "gv", + "publication_identifiers": "pub", + "scoreset_publication_identifiers": "spi", + } + expected = {table: {f"{prefix}_{v}" for v in visibilities} for table, prefix in prefixes.items()} + expected["variant_translations"] = {"vt_public", "vt_mixed"} if "private" in visibilities else {"vt_public"} + return expected + + +SHARED_EXPECTED = { + "anonymous": _shared_expected("public"), + "stranger": _shared_expected("public"), + "owner": _shared_expected("public", "private"), + "mapper": _shared_expected("public", "private"), +} + + +@pytest.fixture +def shared_enforcing(shared): + """Row-level security on for every table the shared tables' policies read, and the shared tables.""" + shared.enable(*RECORD_TABLES, *OWNED_TABLES, *SHARED_TABLES) + + +@pytest.mark.usefixtures("shared_enforcing") +@pytest.mark.parametrize("table", SHARED_TABLES) +@pytest.mark.parametrize("persona", SHARED_EXPECTED) +def test_shared_policy_row_visible_exactly_when_a_visible_record_links_it(shared, login_as, persona, table): + with _as(login_as, shared, PERSONAS[persona]) as conn: + assert _visible(conn, shared, table) == SHARED_EXPECTED[persona][table] + + +@pytest.mark.usefixtures("shared_enforcing") +@pytest.mark.parametrize("table", SHARED_TABLES) +def test_shared_policy_worker_sees_every_row(shared, login_as, table): + with _as(login_as, shared, PERSONAS["anonymous"], WORKER_ROLE) as conn: + assert _visible(conn, shared, table) == shared.rows[table] + + +@pytest.mark.usefixtures("shared_enforcing") +def test_alleles_policy_allele_with_first_published_at_is_visible_without_a_visible_link(shared, login_as, session): + session.execute( + text("UPDATE alleles SET first_published_at = '2026-01-01' WHERE id = :id"), {"id": shared["a_private"]} + ) + session.commit() + + with _as(login_as, shared, PERSONAS["anonymous"]) as conn: + assert _visible(conn, shared, "alleles") == {"a_public", "a_private"} + assert _visible(conn, shared, "mapping_record_alleles") == {"mra_public"} + + def _first_published(session, seed: Seed, name: str): session.expire_all() return session.execute( @@ -766,3 +838,15 @@ def test_first_published_at_drift_reports_an_allele_set_without_a_public_link(sh session.commit() assert first_published_at_drift(session) == [shared["a_private"]] + + +def test_first_published_at_publishing_as_the_api_role_sets_it(shared, session, login_as): + shared.enable(*RECORD_TABLES, *OWNED_TABLES, *SHARED_TABLES) + + with _as(login_as, shared, PERSONAS["owner"]) as conn: + conn.execute( + text("UPDATE scoresets SET private = false, published_date = '2026-02-02' WHERE id = :id"), + {"id": shared["s_private"]}, + ) + + assert str(_first_published(session, shared, "a_private")) == "2026-02-02" diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py index b0606227..750273a9 100644 --- a/tests/routers/test_api_role.py +++ b/tests/routers/test_api_role.py @@ -217,7 +217,7 @@ def test_replace_score_set_targets_as_api_role_with_target_rls_enabled_succeeds( def test_publish_score_set_as_api_role_with_rls_enabled_records_its_redirects( session, data_provider, api_role_client, setup_router_db, target_tables_enforcing, data_files ): - for table in ("variants", "urn_redirects", "mapping_records", "mapping_record_alleles"): + for table in ("variants", "urn_redirects", "mapping_records", "mapping_record_alleles", "alleles"): session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) session.commit() experiment = create_experiment(api_role_client) diff --git a/tests/routers/test_publication_rls.py b/tests/routers/test_publication_rls.py index a4efb52b..ab629fb3 100644 --- a/tests/routers/test_publication_rls.py +++ b/tests/routers/test_publication_rls.py @@ -1,11 +1,10 @@ # ruff: noqa: E402 -"""Citing publications under a row-level security read policy on ``publication_identifiers`` (#945). +"""Citing publications under the row-level security policy on ``publication_identifiers`` (#945, #809). -The api's roles (#827) and the real policy (#809) don't exist yet, so these tests stand them in: a role without -login rights that isn't a superuser and doesn't own the tables, and a policy that shows a publication only when a -record the caller can see cites it. "Can see" is reduced to public or created by the caller. #809 replaces this -fixture with the real policy. +The requests run as the api's login with the caller's principal, and RLS enabled on the publications, the +citation tables and the records they read, so a publication is visible only when a record the caller can see +cites it. """ from contextlib import contextmanager @@ -17,6 +16,7 @@ cdot = pytest.importorskip("cdot") fastapi = pytest.importorskip("fastapi") +from mavedb.db.rls import API_ROLE from mavedb.models.publication_identifier import PublicationIdentifier from mavedb.models.score_set import ScoreSet from mavedb.models.user import User @@ -25,54 +25,32 @@ from tests.helpers.util.score_set import create_seq_score_set from tests.helpers.util.user import change_ownership -API_ROLE = "mavedb_test_rls_api" - -# A record makes a publication visible when it cites it and the caller can see the record. -VISIBLE_CITATION = """ - EXISTS ( - SELECT 1 FROM {citations} c JOIN {owners} o ON o.id = c.{owner_id} - WHERE c.db_name = publication_identifiers.db_name AND c.identifier = publication_identifiers.identifier - AND (NOT o.private OR o.created_by_id = current_setting('mavedb_test.user_id')::int) - ) -""" -READ_POLICY = " OR ".join( - VISIBLE_CITATION.format(citations=citations, owners=owners, owner_id=owner_id) - for citations, owners, owner_id in [ - ("scoreset_publication_identifiers", "scoresets", "scoreset_id"), - ("experiment_publication_identifiers", "experiments", "experiment_id"), - ("score_calibration_publication_identifiers", "score_calibrations", "score_calibration_id"), - ] +# The publications, everything that cites them, and the records the citations' policies read. +ENFORCING = ( + "publication_identifiers", + "scoreset_publication_identifiers", + "experiment_publication_identifiers", + "score_calibration_publication_identifiers", + "scoresets", + "experiments", + "experiment_sets", + "score_calibrations", ) @pytest.fixture def as_api_role(session, setup_router_db): - """Enable the read policy, and return a context manager that runs the requests inside it as the api role.""" - session.execute( - text( - f""" - DO $$ - BEGIN - CREATE ROLE {API_ROLE} NOLOGIN; - -- Roles span the cluster, which parallel test databases share. - EXCEPTION WHEN duplicate_object OR unique_violation THEN NULL; - END $$ - """ - ) - ) - session.execute(text(f"GRANT USAGE ON SCHEMA public TO {API_ROLE}")) - session.execute(text(f"GRANT ALL ON ALL TABLES IN SCHEMA public TO {API_ROLE}")) - session.execute(text(f"GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO {API_ROLE}")) - session.execute(text("ALTER TABLE publication_identifiers ENABLE ROW LEVEL SECURITY")) - session.execute(text(f"CREATE POLICY read_cited ON publication_identifiers FOR SELECT USING ({READ_POLICY})")) - session.execute(text("CREATE POLICY write_any ON publication_identifiers FOR INSERT WITH CHECK (true)")) + """Enable RLS, and return a context manager that runs the requests inside it as the api role.""" + for table in ENFORCING: + session.execute(text(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")) session.commit() caller_id = session.scalars(select(User.id).filter_by(username=TEST_USER["username"])).one() def switch_role(session, transaction, connection): connection.exec_driver_sql( - f"SET LOCAL ROLE {API_ROLE}; SELECT set_config('mavedb_test.user_id', '{caller_id}', true)" + f"SET LOCAL ROLE {API_ROLE}; SELECT set_config('app.user_id', '{caller_id}', true), " + "set_config('app.active_roles', '{}', true)" ) @contextmanager From 7e474ee89b5cad2d603179f8d915470245334cf3 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Tue, 17 Nov 2026 12:50:10 -0800 Subject: [PATCH 13/15] feat(db): make plain views read their tables as the caller 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. --- ..._make_annotation_views_security_invoker.py | 31 +++++++++++++++++++ src/mavedb/db/rls.py | 3 +- src/mavedb/db/view.py | 4 ++- tests/db/test_bootstrap.py | 13 ++++++++ 4 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py diff --git a/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py b/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py new file mode 100644 index 00000000..ad2c43af --- /dev/null +++ b/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py @@ -0,0 +1,31 @@ +"""make v_variant_annotations and v_current_annotation_events read their tables as the caller + +A view reads its tables as its owner unless it's ``security_invoker``, and the owner skips every policy, so a +caller granted the view would see rows the tables' policies hide. Only the worker and scripts read these two +today (``rls.py``), so nothing changes, but a route granted one later reads through the policies. + +Revision ID: f9bc27dae3b8 +Revises: e8ab16c9d2a7 +Create Date: 2026-11-12 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "f9bc27dae3b8" +down_revision = "e8ab16c9d2a7" +branch_labels = None +depends_on = None + +VIEWS = ("v_variant_annotations", "v_current_annotation_events") + + +def upgrade(): + for view in VIEWS: + op.execute(f"ALTER VIEW {view} SET (security_invoker = true)") + + +def downgrade(): + for view in VIEWS: + op.execute(f"ALTER VIEW {view} RESET (security_invoker)") diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py index bb7d425b..a9f185a0 100644 --- a/src/mavedb/db/rls.py +++ b/src/mavedb/db/rls.py @@ -142,8 +142,7 @@ class Relation: "annotation_event": WORKER_ONLY, "variant_annotation_status": WORKER_ONLY, "v_current_annotation_events": WORKER_ONLY, - # No route reads it yet. It can become GUARDED once #809 makes it security_invoker; until then it would - # read its tables as the owner, past their policies. + # No route reads it yet. It's security_invoker (#809), so a route that needs it can make it GUARDED. "v_variant_annotations": WORKER_ONLY, # Alembic's record of the schema's revision. Only migrations, running as the owner, read or write it. "alembic_version": UNGRANTED, diff --git a/src/mavedb/db/view.py b/src/mavedb/db/view.py index d3f3f762..7a60ff8b 100644 --- a/src/mavedb/db/view.py +++ b/src/mavedb/db/view.py @@ -84,9 +84,11 @@ def refresh(cls, connection, concurrently=True): @compiler.compiles(CreateView) def _create_view(element: CreateView, compiler, **kw): + # A plain view reads its tables as the caller, so their RLS policies apply to it (#809). A materialized view + # can't: its rows were read as the owner at refresh. return "CREATE %s %s AS %s" % ( "MATERIALIZED VIEW" if element.materialized else "VIEW", - element.name, + element.name if element.materialized else f"{element.name} WITH (security_invoker = true)", compiler.sql_compiler.process(element.selectable, literal_binds=True), ) diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index 02611ec2..12606074 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -882,6 +882,19 @@ def test_upgrade_target_genes_have_one_target_carrying_their_score_set(self, rep "uq_target_accessions_id_score_set_id", } <= constraints + def test_upgrade_plain_views_read_their_tables_as_the_caller(self, replayed_database): + # A view that reads as its owner skips every policy on its tables, whoever it's granted to. + with replayed_database.connect() as conn: + owner_views = conn.execute( + text( + "SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND c.relkind = 'v' AND NOT coalesce((SELECT o.option_value::boolean " + "FROM pg_options_to_table(c.reloptions) o WHERE o.option_name = 'security_invoker'), false)" + ) + ).scalars() + + assert sorted(owner_views) == [] + def test_upgrade_enables_row_level_security_on_no_table(self, replayed_database): # Enabling is the pilot's and the rollout's job (#825, #878), each in a release of its own. with replayed_database.connect() as conn: From 713b7f0e81c1992df484332673fd56ebcbb9a514 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Mon, 30 Nov 2026 10:32:15 -0800 Subject: [PATCH 14/15] fix(db): leave the dropped event view out of the security_invoker migration 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. --- ...9bc27dae3b8_make_annotation_views_security_invoker.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py b/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py index ad2c43af..b65a2a96 100644 --- a/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py +++ b/alembic/versions/f9bc27dae3b8_make_annotation_views_security_invoker.py @@ -1,8 +1,9 @@ -"""make v_variant_annotations and v_current_annotation_events read their tables as the caller +"""make v_variant_annotations read its tables as the caller A view reads its tables as its owner unless it's ``security_invoker``, and the owner skips every policy, so a -caller granted the view would see rows the tables' policies hide. Only the worker and scripts read these two -today (``rls.py``), so nothing changes, but a route granted one later reads through the policies. +caller granted the view would see rows the tables' policies hide. Only the worker and scripts read it today +(``rls.py``), so nothing changes, but a route granted it later reads through the policies. +``v_annotation_status_current`` was created ``security_invoker`` (9a73f37ec1bc) and needs nothing here. Revision ID: f9bc27dae3b8 Revises: e8ab16c9d2a7 @@ -18,7 +19,7 @@ branch_labels = None depends_on = None -VIEWS = ("v_variant_annotations", "v_current_annotation_events") +VIEWS = ("v_variant_annotations",) def upgrade(): From 6dbf02d8d0e48dcfe7267cd78b13b52db2cb592b Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Mon, 30 Nov 2026 10:44:47 -0800 Subject: [PATCH 15/15] test(export): give the CSV export fixture's target gene an accession 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. --- tests/helpers/util/csv_export.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/helpers/util/csv_export.py b/tests/helpers/util/csv_export.py index 06121b60..6fd23d46 100644 --- a/tests/helpers/util/csv_export.py +++ b/tests/helpers/util/csv_export.py @@ -16,6 +16,7 @@ from mavedb.models.mapping_record_allele import MappingRecordAllele from mavedb.models.projection_group import ProjectionGroup from mavedb.models.score_set import ScoreSet +from mavedb.models.target_accession import TargetAccession from mavedb.models.target_gene import TargetGene from mavedb.models.variant import Variant from tests.helpers.constants import TEST_GNOMAD_VARIANT @@ -71,7 +72,14 @@ def seed_csv_export_score_set(session, mapped) -> CsvExportScoreSet: score_set = mapped.variant.score_set score_set.dataset_columns = {"score_columns": ["score", "se"], "count_columns": ["c_0"]} session.add(score_set) - session.add(TargetGene(name="PTEN", category=TargetCategory.protein_coding, score_set_id=score_set.id)) + session.add( + TargetGene( + name="PTEN", + category=TargetCategory.protein_coding, + score_set_id=score_set.id, + target_accession=TargetAccession(accession="NM_000314.8"), + ) + ) session.commit() session.execute(