Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
e62a3b0
feat(db): add mavedb_user_id and mavedb_roles for RLS policies
bencap Nov 17, 2026
6560976
chore(db): drop a dropped table from the RLS registry
bencap Nov 17, 2026
53c36bc
perf(db): index contributor ids and calibration score sets for RLS
bencap Nov 17, 2026
25ac683
feat(db): keep a readable snapshot of the RLS policies in policies.sql
bencap Nov 17, 2026
c109277
feat(db): add RLS policies to the five record tables
bencap Nov 17, 2026
717c3f6
fix(permissions): drop the last modifier from calibration read access
bencap Nov 17, 2026
30df4a0
feat(db): add RLS policies to the tables owned by one record
bencap Nov 17, 2026
805e2c1
fix(score-sets): flush the rename before recording its URN redirect
bencap Nov 17, 2026
fc027b2
feat(db): carry score_set_id on target sequences and accessions
bencap Nov 17, 2026
6da6b4c
feat(db): add RLS policies to target sequences and accessions
bencap Nov 17, 2026
7d5c418
feat(alleles): record when a public score set first links an allele
bencap Nov 17, 2026
4223cc5
feat(db): add RLS policies to the shared tables
bencap Nov 17, 2026
7e474ee
feat(db): make plain views read their tables as the caller
bencap Nov 17, 2026
cdac84a
Merge branch 'feature/bencap/827/database-roles' into feature/bencap/…
bencap Nov 30, 2026
713b7f0
fix(db): leave the dropped event view out of the security_invoker mig…
bencap Nov 30, 2026
6dbf02d
test(export): give the CSV export fixture's target gene an accession
bencap Nov 30, 2026
1fd4b43
Merge branch 'feature/bencap/827/database-roles' into feature/bencap/…
bencap Nov 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/run-tests-on-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 36 additions & 0 deletions alembic/versions/7c1d4e9a2b30_add_rls_principal_helpers.py
Original file line number Diff line number Diff line change
@@ -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()")
36 changes: 36 additions & 0 deletions alembic/versions/8e2f5a0b3c41_index_contributor_ids_for_rls.py
Original file line number Diff line number Diff line change
@@ -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)
105 changes: 105 additions & 0 deletions alembic/versions/9a3b6c1d4e52_add_rls_policies_for_record_tables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
"""add RLS policies to scoresets, experiments, experiment_sets, collections and score_calibrations

Each table gets a business policy (``<table>_rule``) deciding which rows the api sees and writes, and a worker
policy (``<table>_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}")
112 changes: 112 additions & 0 deletions alembic/versions/a4c7d2e5f863_add_rls_policies_for_owned_tables.py
Original file line number Diff line number Diff line change
@@ -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}")
Loading
Loading