From bb5d5eb37f9e966d9ac0d4128d4513f7fb8baeef Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 11:41:35 -0800 Subject: [PATCH 1/9] fix(db): leave extensions out of the squashed baseline Production's schema dump carried CREATE EXTENSION pg_stat_statements and its COMMENT, a monitoring extension installed on production, not part of MaveDB's schema. Creating it needs a superuser and commenting on it needs its owner, so mavedb_migrate couldn't replay the baseline into an empty database. bin/build-baseline now drops extension statements, and the current baseline loses the same lines. Production and staging are stamped at the baseline, so nothing changes for them. Expect: agents squashing migrations leave extensions to the master user instead of carrying them into a baseline. --- alembic/baseline/c5e1a9d4b7f2.sql | 12 +----------- bin/build-baseline | 11 +++++++++-- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/alembic/baseline/c5e1a9d4b7f2.sql b/alembic/baseline/c5e1a9d4b7f2.sql index e1666b79e..9a05bec33 100644 --- a/alembic/baseline/c5e1a9d4b7f2.sql +++ b/alembic/baseline/c5e1a9d4b7f2.sql @@ -6,19 +6,9 @@ -- Dumped from database version 15.17 -- Dumped by pg_dump version 15.17 (Homebrew) +-- Extensions purposefully omitted from this schema dump --- --- Name: pg_stat_statements; Type: EXTENSION; Schema: -; Owner: - --- - -CREATE EXTENSION IF NOT EXISTS pg_stat_statements WITH SCHEMA public; - - --- --- Name: EXTENSION pg_stat_statements; Type: COMMENT; Schema: -; Owner: - --- -COMMENT ON EXTENSION pg_stat_statements IS 'track planning and execution statistics of all SQL statements executed'; -- diff --git a/bin/build-baseline b/bin/build-baseline index 407e6eb0c..e4363188d 100755 --- a/bin/build-baseline +++ b/bin/build-baseline @@ -19,8 +19,15 @@ SEED_ROWS = {"mondo_terms": "code = 'MONDO:0000001'"} # pg_dump emits psql meta-commands (``\restrict``) and session settings. Neither can run inside the # migration's transaction without leaking into the rest of the upgrade; every object name in the dump is -# schema-qualified, so the empty ``search_path`` it sets is not needed either. -DROPPED_PREFIXES = ("\\", "SET ", "SELECT pg_catalog.set_config('search_path'") +# schema-qualified, so the empty ``search_path`` it sets is not needed either. Extensions aren't MaveDB's +# schema: creating one needs the master user, while migrations run as ``mavedb_owner`` (#827). +DROPPED_PREFIXES = ( + "\\", + "SET ", + "SELECT pg_catalog.set_config('search_path'", + "CREATE EXTENSION ", + "COMMENT ON EXTENSION ", +) def run(*args: str) -> str: From fce8f881f5900f044e3123abd173a92b2c137d6f Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 11:41:48 -0800 Subject: [PATCH 2/9] feat(db): split database roles into owner, migrate, worker and api Row-level security doesn't apply to a table's owner, and today the api's login owns every table, so no policy could ever bind it. The roles are now mavedb_owner (owns everything, can't log in), mavedb_migrate (runs as the owner), mavedb_worker and mavedb_api, neither of which owns anything or belongs to any role. mavedb.db.rls lists every table, view, materialized view and function in the schema with the access each role gets, and whether a policy decides the api's rows. mavedb.db.bootstrap makes the database's grants match it exactly, and fails closed: anything unlisted gets nothing, and it refuses roles carrying privileges or memberships it didn't give them. Setup (roles, schema grants) runs once per database as the master user, through scripts/bootstrap_roles. alembic/env.py reapplies the grants at the end of every upgrade, in the migration's transaction, so a table can never commit without the grants its entry gives it, and the upgrade stops on a database that was never set up. Migrations may not GRANT or REVOKE. The worker owns nothing, so it refreshes materialized views through mavedb_refresh_mat_views(), a SECURITY DEFINER function only it may run. The api keeps grants on mapped_variants and the legacy keyword tables, which it never reads: deleting a score set or experiment loads them through ORM relationships, which failed as mavedb_api once revoked. Expect: agents add an rls.py entry for every new table, view or function and never grant in a migration; migrations run as mavedb_migrate. --- .claude/rules/rls.md | 20 + alembic/README.md | 29 +- alembic/env.py | 6 + ...8e2c7d1f3a_add_mavedb_refresh_mat_views.py | 57 ++ bin/check-migrations | 10 +- src/mavedb/db/bootstrap.py | 470 ++++++++++ src/mavedb/db/rls.py | 169 ++++ src/mavedb/db/view.py | 86 +- src/mavedb/scripts/bootstrap_roles.py | 49 + tests/bin/test_check_migrations.py | 30 + tests/conftest.py | 82 +- tests/db/test_bootstrap.py | 844 ++++++++++++++++++ tests/db/test_principal.py | 2 +- tests/routers/test_api_role.py | 151 ++++ 14 files changed, 1971 insertions(+), 34 deletions(-) create mode 100644 .claude/rules/rls.md create mode 100644 alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py create mode 100644 src/mavedb/db/bootstrap.py create mode 100644 src/mavedb/db/rls.py create mode 100644 src/mavedb/scripts/bootstrap_roles.py create mode 100644 tests/db/test_bootstrap.py create mode 100644 tests/routers/test_api_role.py diff --git a/.claude/rules/rls.md b/.claude/rules/rls.md new file mode 100644 index 000000000..0a014a3ca --- /dev/null +++ b/.claude/rules/rls.md @@ -0,0 +1,20 @@ +--- +paths: + - "src/mavedb/db/rls.py" + - "src/mavedb/db/bootstrap.py" + - "src/mavedb/models/**" + - "alembic/versions/**" + - "src/mavedb/lib/permissions/**" +--- + +# Row-level security and grants + +Database permissions fail closed (#808). Any database object that nobody made an explicit access decision on should end up with no access, not silent access. A design that can fail open is wrong and undesirable for this project, in all cases. + +- Every table, view, materialized view and function in the schema has an entry in `src/mavedb/db/rls.py`. A new one gets no grants until it has one, and `tests/db/test_bootstrap.py` fails CI while any entry is missing. +- Picking a table's entry is the decision about its row-level security. `GUARDED` means a policy (#809) decides which rows the api sees. `CARVE_OUT` means every caller sees every row, and needs a comment beside it saying why that's safe. `NONE` means the api never reads it. Ask the user if you're unsure which to choose, as this decision has important security implications. +- A view reads its tables as its owner, who skips their policies. A `GUARDED` view must be `WITH (security_invoker = true)`, or the api isn't granted it. A materialized view can never be `GUARDED`: its rows were read as the owner at refresh, and Postgres has no RLS on it. So a materialized view is `CARVE_OUT`, with a reason why every row is safe for everyone, or `NONE`. +- Grants come only from `apply_grants` reading `rls.py`. Never `GRANT` or `REVOKE` in a migration or by hand. The next upgrade revokes it anyway, and a squashed baseline is dumped without privileges, so it would be lost at the next squash too. +- Prefer allow-lists to deny-lists. Prefer a check that raises to code that trusts existing state or quietly repairs it. The bootstrap refuses roles with privileges it didn't give them. +- Name database functions `mavedb_*`, so it's clear in the database that a function comes from MaveDB's own code and not from Postgres or an extension. +- A `SECURITY DEFINER` function runs with the owner's privileges. List it with one executor and a reason, and pin its `search_path`. diff --git a/alembic/README.md b/alembic/README.md index c13e79671..22ce31fcb 100644 --- a/alembic/README.md +++ b/alembic/README.md @@ -40,7 +40,34 @@ At each cycle boundary, once the last release has been stable in production for 4. Check the replay: run `alembic upgrade head` on an empty database, and diff a schema-only dump of it against production's. 5. Re-parent the first migration on each open branch onto the baseline, and add a row to the log below. -Ownership and grants aren't in the baseline. The role bootstrap script applies them (#827). +Ownership and grants aren't in the baseline. The role bootstrap's grants step applies them (#827). + +## Roles + +Migrations run as `mavedb_migrate`, which runs as `mavedb_owner`, so every object a migration creates belongs to the owner. Every upgrade, downgrade or stamp then runs the bootstrap's grants step in the same transaction (`alembic/env.py`). It revokes every grant on the owner's tables, views, sequences and functions, and grants exactly what `src/mavedb/db/rls.py` lists, so the grants never depend on the migration history, and a squash can't lose one. + +So a migration never grants or revokes (`bin/check-migrations` refuses it). A new table, view or function gets no privileges until it has an entry in `rls.py`, which also says whether row-level security decides which rows the api sees. CI fails while anything in the schema has no entry. + +The upgrade stops if the database was never set up for the roles, or if a role has privileges the bootstrap doesn't give it. A new database, including a local one, needs setting up once, as the master user (`postgres` locally): + +```bash +poetry run python -m mavedb.scripts.bootstrap_roles setup --commit +``` + +A migration may create only what `mavedb_owner` can own: tables, views, functions, policies and indexes. Extensions, roles and cluster or database settings need the master user, so they go in the bootstrap's cluster or database part, run before the migration that relies on them. `bin/build-baseline` leaves extensions out of the baseline for the same reason. + +### Restoring a dump + +Loading a data-only dump with `session_replication_role = replica`, which skips foreign key checks and triggers, is a master user's job. None of the four roles may set it. Locally `postgres` is a superuser. On RDS the master user sets it, then borrows the owner to write its tables and returns it afterwards: + +```sql +SET session_replication_role = replica; +GRANT mavedb_owner TO CURRENT_USER; +SET ROLE mavedb_owner; +-- load the dump +RESET ROLE; +REVOKE mavedb_owner FROM CURRENT_USER; +``` ## Squash log diff --git a/alembic/env.py b/alembic/env.py index 9cdc453d4..6c3505ca7 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -8,6 +8,7 @@ # Import model metadata for autogenerate support. # Linters will flag mavedb.models.* as unused, but we must import it. from mavedb.db.base import Base +from mavedb.db.bootstrap import apply_grants from mavedb.models import * # noqa: F401,F403 # this is the Alembic Config object, which provides @@ -79,6 +80,11 @@ def run_migrations_online(): with context.begin_transaction(): context.run_migrations() + # Only commands that move the database to a revision, not ``current`` or ``check``. In the same + # transaction, so a migration never commits without the grants its tables need. + if context.get_context().opts.get("destination_rev") is not None: + apply_grants(connection) + if context.is_offline_mode(): run_migrations_offline() diff --git a/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py b/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py new file mode 100644 index 000000000..09e1aa54c --- /dev/null +++ b/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py @@ -0,0 +1,57 @@ +"""add mavedb_refresh_mat_views, which refreshes materialized views as their owner + +Refreshing a materialized view requires owning it. The worker logs in as ``mavedb_worker``, which owns nothing +(#827), so it calls this ``SECURITY DEFINER`` function instead. Run as ``mavedb_migrate``, the function belongs +to ``mavedb_owner``, whose default privileges keep ``PUBLIC`` from executing it. The role bootstrap's grants +step, which runs in the same transaction, lets ``mavedb_worker`` execute it. Keep the body identical to +``REFRESH_MAT_VIEWS_FUNCTION`` in ``mavedb.db.view``. + +Revision ID: 4b8e2c7d1f3a +Revises: 020b7e003efd +Create Date: 2026-11-06 + +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "4b8e2c7d1f3a" +down_revision = "020b7e003efd" +branch_labels = None +depends_on = None + + +def upgrade(): + op.execute("""CREATE OR REPLACE FUNCTION mavedb_refresh_mat_views(view_name regclass DEFAULT NULL, concurrent boolean DEFAULT true) +RETURNS void +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $$ +DECLARE + mv regclass; + refreshed integer := 0; +BEGIN + FOR mv IN + SELECT c.oid::regclass + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind = 'm' AND n.nspname = 'public' AND (view_name IS NULL OR c.oid = view_name) + ORDER BY c.relname + LOOP + IF concurrent THEN + EXECUTE 'REFRESH MATERIALIZED VIEW CONCURRENTLY ' || mv::text; + ELSE + EXECUTE 'REFRESH MATERIALIZED VIEW ' || mv::text; + END IF; + refreshed := refreshed + 1; + END LOOP; + + IF view_name IS NOT NULL AND refreshed = 0 THEN + RAISE EXCEPTION USING MESSAGE = view_name::text || ' is not a materialized view in the public schema'; + END IF; +END +$$;""") + + +def downgrade(): + op.execute("DROP FUNCTION mavedb_refresh_mat_views(regclass, boolean)") diff --git a/bin/check-migrations b/bin/check-migrations index b7b436bdb..170f3e9e1 100755 --- a/bin/check-migrations +++ b/bin/check-migrations @@ -8,6 +8,7 @@ step for large indexes. """ import ast +import re import sys from pathlib import Path @@ -19,6 +20,10 @@ FORBIDDEN_IMPORTS = { "urllib": "makes network calls", } +# A squashed baseline is dumped without privileges, so a grant made only in a migration would vanish at the next +# squash. The role bootstrap's grants step makes every grant from ``mavedb.db.rls`` instead. +PRIVILEGE_STATEMENT = re.compile(r"\b(GRANT|REVOKE)\b") + def _docstrings(tree: ast.Module) -> set[int]: ids = set() @@ -53,10 +58,13 @@ def check(path: Path) -> list[str]: reason = "commits mid-upgrade" elif isinstance(node, ast.Constant) and isinstance(node.value, str) and id(node) not in docstrings: text = " ".join(node.value.upper().split()) - if "CONCURRENTLY" in text: + # Unlike an index build, a concurrent materialized view refresh runs inside a transaction. + if "CONCURRENTLY" in text.replace("REFRESH MATERIALIZED VIEW CONCURRENTLY", ""): reason = "uses CONCURRENTLY, which can't run inside a transaction" elif "ADD VALUE" in text: reason = "adds an enum value, which the rest of the upgrade's transaction can't use" + elif PRIVILEGE_STATEMENT.search(text): + reason = "grants or revokes privileges; list the object in src/mavedb/db/rls.py instead" if reason: problems.append(f"{path}:{node.lineno}: {reason}") return problems diff --git a/src/mavedb/db/bootstrap.py b/src/mavedb/db/bootstrap.py new file mode 100644 index 000000000..1bd29d88e --- /dev/null +++ b/src/mavedb/db/bootstrap.py @@ -0,0 +1,470 @@ +"""Create the database roles, check they can be trusted, and make their grants match ``mavedb.db.rls`` (#827). + +Three parts, each safe to re-run, and none of which sets or changes a password: + +1. ``bootstrap_cluster``: once per cluster, as the master user. Creates the roles and their settings, then + refuses to go on if any role has privileges the design doesn't give it. +2. ``bootstrap_database``: once per database, as the master user. Schema grants, and new functions closed to + ``PUBLIC``. +3. ``apply_grants``: after every migration. ``alembic/env.py`` runs it at the end of every upgrade, in the same + transaction. Moves anything the api owns to the owner, revokes every grant on the owner's relations, + sequences and functions, then grants exactly what ``mavedb.db.rls`` lists. + +Part 3 is the only thing that grants privileges on the schema's objects; migrations may not GRANT or REVOKE +(``bin/check-migrations``). That's what lets a squashed baseline be dumped without privileges: replaying it +and running part 3 gives the same grants as the migrations it replaced. + +Roles belong to the whole cluster and creating them needs the master user, so parts 1 and 2 can't be +migrations. Run them with ``python -m mavedb.scripts.bootstrap_roles setup``. +""" + +import logging +from collections import defaultdict +from contextlib import contextmanager +from typing import Iterator + +from sqlalchemy import Connection, text +from sqlalchemy.exc import DBAPIError + +from mavedb.db.rls import ( + API_ROLE, + FUNCTIONS, + MIGRATE_ROLE, + OWNER_ROLE, + RELATIONS, + WORKER_ROLE, + ApiAccess, + Relation, +) + +logger = logging.getLogger(__name__) + +# The worker's jobs share one event loop and their database calls are synchronous, so a call waiting on a lock +# stalls every job on the worker, the lock's holder included when it is another job on the same worker. Its jobs +# legitimately run long statements and idle in transactions, so this is its only limit. Change it here and run +# `bootstrap_roles setup` again; a worker picks it up on its next connection. +WORKER_LOCK_TIMEOUT = "60s" + +SETUP_HINT = "Run `python -m mavedb.scripts.bootstrap_roles setup` against this database as the master user." + +# Role attributes that skip grants or RLS, or hand out privileges, none of which these roles should have. +_UNSAFE_ATTRIBUTES = { + "rolsuper": "SUPERUSER", + "rolbypassrls": "BYPASSRLS", + "rolcreaterole": "CREATEROLE", + "rolcreatedb": "CREATEDB", + "rolreplication": "REPLICATION", +} + +_OWNER_OID = "(SELECT oid FROM pg_roles WHERE rolname = :owner)" + +# Relation kinds that hold rows a role can write: tables, partitioned tables and foreign tables. +_TABLE_KINDS = ("r", "p", "f") + + +def _roles() -> list[str]: + return [OWNER_ROLE, MIGRATE_ROLE, WORKER_ROLE, API_ROLE] + + +def _execute(conn: Connection, statement: str) -> None: + logger.info(statement) + conn.execute(text(statement)) + + +@contextmanager +def _privileges_of(conn: Connection, *roles: str) -> Iterator[None]: + """Give the current user the privileges of ``roles`` for the duration of the block. + + On RDS the master user isn't a superuser, so moving or granting another role's objects needs membership in + that role. Membership is granted and revoked again in the caller's transaction, so ``MIGRATE_ROLE`` stays + the only member of ``OWNER_ROLE`` once it commits. PG 15 lets a ``CREATEROLE`` user grant itself any + non-superuser role; PG 16 requires ``ADMIN OPTION`` on the role instead. + """ + if conn.execute(text("SELECT rolsuper FROM pg_roles WHERE rolname = current_user")).scalar_one(): + yield + return + + borrowed = [ + role + for role in roles + if not conn.execute(text("SELECT pg_has_role(current_user, :role, 'USAGE')"), {"role": role}).scalar_one() + ] + if ( + borrowed + and not conn.execute(text("SELECT rolcreaterole FROM pg_roles WHERE rolname = current_user")).scalar_one() + ): + raise RuntimeError(f"This step needs the privileges of {borrowed}. Run it as the master user.") + for role in borrowed: + _execute(conn, f"GRANT {role} TO current_user") + try: + yield + except DBAPIError: + # The transaction is aborted, so a REVOKE would fail and hide this error. Rolling back undoes the GRANT. + raise + except BaseException: + _give_back(conn, borrowed) + raise + _give_back(conn, borrowed) + + +def _give_back(conn: Connection, borrowed: list[str]) -> None: + for role in borrowed: + _execute(conn, f"REVOKE {role} FROM current_user") + + +def role_problems(conn: Connection) -> list[str]: + """Return each way the roles differ from what part 1 sets up, or an empty list when they match. + + None of the roles may skip grants or RLS, create roles or databases, or set any superuser-only parameter, + such as ``session_replication_role``, which turns off foreign key checks; restores set that as the master + user. The owner can't log in. Their one membership, among themselves or with any other role, is the migrate + login in the owner, and the migrate login runs as the owner. + """ + roles = _roles() + columns = ", ".join(_UNSAFE_ATTRIBUTES) + found = { + row.rolname: row + for row in conn.execute( + text(f"SELECT rolname, rolcanlogin, {columns} FROM pg_roles WHERE rolname = ANY(:roles)"), + {"roles": roles}, + ) + } + + problems = [] + for role in roles: + row = found.get(role) + if row is None: + problems.append(f"{role} doesn't exist") + continue + problems += [f"{role} has {name}" for column, name in _UNSAFE_ATTRIBUTES.items() if getattr(row, column)] + if OWNER_ROLE in found and found[OWNER_ROLE].rolcanlogin: + problems.append(f"{OWNER_ROLE} can log in") + + # Any grant on a parameter, to PUBLIC or to one of the roles, lets them change a superuser-only setting. + parameters = conn.execute( + text( + "SELECT coalesce(r.rolname, 'PUBLIC'), p.parname FROM pg_parameter_acl p " + "CROSS JOIN LATERAL aclexplode(p.paracl) a LEFT JOIN pg_roles r ON r.oid = a.grantee " + "WHERE a.grantee = 0 OR r.rolname = ANY(:roles) ORDER BY 1, 2" + ), + {"roles": roles}, + ) + problems += [f"{grantee} can set {parameter}" for grantee, parameter in parameters] + + memberships = [ + tuple(row) + for row in conn.execute( + text( + "SELECT r.rolname, m.rolname FROM pg_auth_members am JOIN pg_roles r ON r.oid = am.roleid " + "JOIN pg_roles m ON m.oid = am.member WHERE r.rolname = ANY(:roles) OR m.rolname = ANY(:roles) " + "ORDER BY 1, 2" + ), + {"roles": roles}, + ) + ] + problems += [ + f"{member} is a member of {role}" + for role, member in memberships + if (role, member) != (OWNER_ROLE, MIGRATE_ROLE) + ] + if OWNER_ROLE in found and MIGRATE_ROLE in found: + if (OWNER_ROLE, MIGRATE_ROLE) not in memberships: + problems.append(f"{MIGRATE_ROLE} isn't a member of {OWNER_ROLE}") + if _role_setting(conn, MIGRATE_ROLE, "role") != OWNER_ROLE: + problems.append(f"{MIGRATE_ROLE} doesn't run as {OWNER_ROLE}") + + return problems + + +def bootstrap_cluster(conn: Connection) -> None: + """Part 1: create the four roles, their one membership and their settings. Run once per cluster as the master user. + + Roles that already exist keep their passwords; a new login role has none until an operator sets one. Each + statement runs only when its effect is missing: roles belong to the whole cluster, and rewriting a role that + is already right still collides with anyone else altering it at the same moment. + + Raises: + RuntimeError: If a role that already existed has a privilege the design doesn't give it, such as + ``BYPASSRLS`` or another role's membership. The bootstrap doesn't strip privileges it didn't grant; + remove them by hand and run it again. + """ + existing = set(conn.execute(text("SELECT rolname FROM pg_roles")).scalars()) + + for role, login in ((OWNER_ROLE, False), (MIGRATE_ROLE, True), (WORKER_ROLE, True), (API_ROLE, True)): + if role not in existing: + _execute(conn, f"CREATE ROLE {role} {'LOGIN' if login else 'NOLOGIN'}") + + if conn.execute(text("SELECT rolcanlogin FROM pg_roles WHERE rolname = :r"), {"r": OWNER_ROLE}).scalar_one(): + _execute(conn, f"ALTER ROLE {OWNER_ROLE} NOLOGIN") + + is_member = conn.execute( + text("SELECT pg_has_role(:member, :role, 'MEMBER')"), {"member": MIGRATE_ROLE, "role": OWNER_ROLE} + ).scalar_one() + if not is_member: + _execute(conn, f"GRANT {OWNER_ROLE} TO {MIGRATE_ROLE}") + + # A new object belongs to the role that created it, not to a role its creator is a member of. Without + # this, every table a migration creates would belong to the migrate login, and the api couldn't read it. + if _role_setting(conn, MIGRATE_ROLE, "role") != OWNER_ROLE: + _execute(conn, f"ALTER ROLE {MIGRATE_ROLE} SET role = {OWNER_ROLE}") + if _role_setting(conn, WORKER_ROLE, "lock_timeout") != WORKER_LOCK_TIMEOUT: + _execute(conn, f"ALTER ROLE {WORKER_ROLE} SET lock_timeout = '{WORKER_LOCK_TIMEOUT}'") + + problems = role_problems(conn) + if problems: + raise RuntimeError( + "These roles have privileges the bootstrap doesn't give them, so it won't trust them: " + f"{'; '.join(problems)}. Remove them by hand and run it again." + ) + + +def _role_setting(conn: Connection, role: str, name: str) -> str | None: + """Return the value ``ALTER ROLE role SET name`` stored for every database, or None if there is none.""" + settings = conn.execute( + text( + "SELECT s.setconfig FROM pg_db_role_setting s JOIN pg_roles r ON r.oid = s.setrole " + "WHERE r.rolname = :role AND s.setdatabase = 0" + ), + {"role": role}, + ).scalar_one_or_none() + for setting in settings or []: + key, _, value = setting.partition("=") + if key == name: + return value + + return None + + +def schema_privilege_problems(conn: Connection) -> list[str]: + """Return each way the api or the worker could create objects in this database, or an empty list. + + An object's owner skips its RLS policies and grants, so a role that can create one can make itself a table + nobody guards. + """ + problems = [] + for role in (API_ROLE, WORKER_ROLE): + can_create = conn.execute( + text( + "SELECT has_schema_privilege(:role, 'public', 'CREATE'), " + "has_database_privilege(:role, current_database(), 'CREATE')" + ), + {"role": role}, + ).one() + if can_create[0]: + problems.append(f"{role} can create objects in schema public") + if can_create[1]: + problems.append(f"{role} can create schemas in this database") + return problems + + +def bootstrap_database(conn: Connection) -> None: + """Part 2: schema grants, and new functions closed to ``PUBLIC``. Run once per database as the master user. + + These belong to each database, not the cluster. A database cloned from a template inherits them. + + Raises: + RuntimeError: If the api or the worker can create objects here through a grant this didn't make. + """ + with _privileges_of(conn, OWNER_ROLE): + _execute(conn, "REVOKE CREATE ON SCHEMA public FROM PUBLIC") + _execute(conn, f"GRANT CREATE, USAGE ON SCHEMA public TO {OWNER_ROLE}") + _execute(conn, f"GRANT USAGE ON SCHEMA public TO {API_ROLE}, {WORKER_ROLE}") + # Postgres lets PUBLIC execute every new function. A SECURITY DEFINER function runs as its owner, so + # until part 3 ran, a new one would lend the owner's privileges to any caller. + _execute(conn, f"ALTER DEFAULT PRIVILEGES FOR ROLE {OWNER_ROLE} REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC") + + problems = schema_privilege_problems(conn) + if problems: + raise RuntimeError(f"{'; '.join(problems)}. Revoke these by hand and run it again.") + + +def setup(conn: Connection) -> None: + """Parts 1 and 2, for a new database. Run as the master user, then migrate as ``mavedb_migrate``.""" + bootstrap_cluster(conn) + bootstrap_database(conn) + + +def _database_is_set_up(conn: Connection) -> bool: + """Return whether part 2 has run here, read from the default privileges it leaves on the owner's functions.""" + return conn.execute( + text( + "SELECT EXISTS (SELECT FROM pg_default_acl d JOIN pg_roles o ON o.oid = d.defaclrole " + "WHERE o.rolname = :owner AND d.defaclnamespace = 0 AND d.defaclobjtype = 'f')" + ), + {"owner": OWNER_ROLE}, + ).scalar_one() + + +def apply_grants(conn: Connection) -> None: + """Part 3: ownership and grants. ``alembic/env.py`` runs this after every upgrade; the test template runs it too. + + Moving ownership away from the api is needed once per database and does nothing afterwards. It needs the + master user, and it locks each table exclusively, so set ``lock_timeout`` on the connection before calling + this against a live database. + + Raises: + RuntimeError: If part 2 hasn't run on this database, if the roles differ from what parts 1 and 2 set up, + if anything in the schema belongs to a role other than the owner, or if the api role owns a database. ``REASSIGN OWNED`` would move that database too, which for the + mapper's ``gene_normalizer`` database changes what its login may do. Change each such database's + owner by hand first. + """ + if not _database_is_set_up(conn): + raise RuntimeError(f"This database has no roles set up. {SETUP_HINT}") + + problems = role_problems(conn) + schema_privilege_problems(conn) + if problems: + raise RuntimeError(f"The roles aren't as the bootstrap sets them up: {'; '.join(problems)}. {SETUP_HINT}") + + owned_databases = list( + conn.execute( + text("SELECT datname FROM pg_database WHERE datdba = (SELECT oid FROM pg_roles WHERE rolname = :role)"), + {"role": API_ROLE}, + ).scalars() + ) + if owned_databases: + raise RuntimeError(f"{API_ROLE} owns databases {owned_databases}; change their owner before running this.") + + api_owns_objects = conn.execute( + text( + "SELECT EXISTS (SELECT FROM pg_shdepend d JOIN pg_database db ON db.oid = d.dbid " + "WHERE db.datname = current_database() AND d.deptype = 'o' " + "AND d.refobjid = (SELECT oid FROM pg_roles WHERE rolname = :role))" + ), + {"role": API_ROLE}, + ).scalar_one() + + with _privileges_of(conn, OWNER_ROLE, *([API_ROLE] if api_owns_objects else [])): + if api_owns_objects: + _execute(conn, f"REASSIGN OWNED BY {API_ROLE} TO {OWNER_ROLE}") + + # The grants below cover only the owner's objects. Anything else in the schema keeps whatever its owner + # gives it, and its owner skips its RLS policies. + strays = _objects_not_owned_by_the_owner(conn) + if strays: + raise RuntimeError( + f"These belong to a role other than {OWNER_ROLE}: {'; '.join(strays)}. Change their owner by hand, " + "or drop them, and run this again." + ) + + _grant_relations(conn) + _grant_functions(conn) + + +def _objects_not_owned_by_the_owner(conn: Connection) -> list[str]: + """Return the relations and functions in ``public`` that the owner doesn't own, skipping extensions' own.""" + return [ + f"{name} (owned by {owner})" + for name, owner in conn.execute( + text( + "SELECT c.oid::regclass::text, c.relowner::regrole::text FROM pg_class c " + "JOIN pg_namespace n ON n.oid = c.relnamespace " + f"WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm', 'S') AND c.relowner <> {_OWNER_OID} " + "AND NOT EXISTS (SELECT FROM pg_depend d WHERE d.classid = 'pg_class'::regclass " + "AND d.objid = c.oid AND d.deptype = 'e') " + "UNION ALL " + "SELECT p.oid::regprocedure::text, p.proowner::regrole::text FROM pg_proc p " + "JOIN pg_namespace n ON n.oid = p.pronamespace " + f"WHERE n.nspname = 'public' AND p.proowner <> {_OWNER_OID} " + "AND NOT EXISTS (SELECT FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass " + "AND d.objid = p.oid AND d.deptype = 'e') " + "ORDER BY 1" + ), + {"owner": OWNER_ROLE}, + ) + ] + + +def _grantees(relation: Relation | None, kind: str = "r", security_invoker: bool = False) -> tuple[str, ...]: + """Return the roles a relation of ``kind`` is granted to, given its entry. + + A guarded view reads its tables as its owner unless it's ``security_invoker``, and a materialized view's rows + were read as the owner, so in either case the api would see rows its policies hide. It isn't granted them. + """ + if relation is None: + return () + api = relation.api is ApiAccess.CARVE_OUT or ( + relation.api is ApiAccess.GUARDED and (kind in _TABLE_KINDS or (kind == "v" and security_invoker)) + ) + return tuple(role for role, granted in ((API_ROLE, api), (WORKER_ROLE, relation.worker)) if granted) + + +def _revoke_all(conn: Connection, kind: str, objects: list[str]) -> None: + if objects: + _execute(conn, f"REVOKE ALL ON {kind} {', '.join(objects)} FROM PUBLIC, {API_ROLE}, {WORKER_ROLE}") + + +def _grant_relations(conn: Connection) -> None: + """Grant each of the owner's relations and sequences to exactly the roles ``RELATIONS`` lists, and no others. + + A relation missing from ``RELATIONS`` gets nothing, and the api gets no guarded view that isn't + ``security_invoker`` and no guarded materialized view. A sequence goes to the roles that can write the table + that owns it, and nowhere if no table does. + """ + relations = conn.execute( + text( + "SELECT c.relname, c.oid::regclass::text, c.relkind, coalesce((SELECT o.option_value::boolean " + "FROM pg_options_to_table(c.reloptions) o WHERE o.option_name = 'security_invoker'), false) " + "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + f"WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm') AND c.relowner = {_OWNER_OID} " + "ORDER BY 1" + ), + {"owner": OWNER_ROLE}, + ).all() + sequences = conn.execute( + text( + "SELECT s.oid::regclass::text, t.relname FROM pg_class s " + "JOIN pg_namespace n ON n.oid = s.relnamespace " + "LEFT JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = s.oid " + "AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i') " + "LEFT JOIN pg_class t ON t.oid = d.refobjid " + f"WHERE n.nspname = 'public' AND s.relkind = 'S' AND s.relowner = {_OWNER_OID} ORDER BY 1" + ), + {"owner": OWNER_ROLE}, + ).all() + + # Grouped by what's granted to whom, so each group is one statement. + grants: dict[tuple[str, str, tuple[str, ...]], list[str]] = defaultdict(list) + for name, relation, kind, security_invoker in relations: + privileges = "SELECT, INSERT, UPDATE, DELETE" if kind in _TABLE_KINDS else "SELECT" + entry = RELATIONS.get(name) + if entry and entry.api is ApiAccess.GUARDED and API_ROLE not in _grantees(entry, kind, security_invoker): + logger.warning(f"Not granting {name} to {API_ROLE}: it's guarded, but its rows skip RLS.") + if grantees := _grantees(entry, kind, security_invoker): + grants[("TABLE", privileges, grantees)].append(relation) + for sequence, table in sequences: + if grantees := _grantees(RELATIONS.get(table)): + grants[("SEQUENCE", "USAGE, SELECT", grantees)].append(sequence) + + _revoke_all(conn, "TABLE", [relation for _, relation, _, _ in relations]) + _revoke_all(conn, "SEQUENCE", [sequence for sequence, _ in sequences]) + for (kind, privileges, grantees), objects in sorted(grants.items()): + _execute(conn, f"GRANT {privileges} ON {kind} {', '.join(objects)} TO {', '.join(grantees)}") + + +def _grant_functions(conn: Connection) -> None: + """Let exactly the roles ``FUNCTIONS`` lists execute each of the owner's functions, and no others. + + A function missing from ``FUNCTIONS`` gets nothing, and so does one whose ``SECURITY DEFINER`` flag differs + from its entry, since it isn't the function that was reviewed. So does a ``SECURITY DEFINER`` function that + doesn't pin its ``search_path``: a caller could put objects of their own ahead of the ones it means, and it + would run them as the owner. Extensions' functions belong to the role that created the extension, so + they're left alone. + """ + functions = conn.execute( + text( + "SELECT p.proname, p.oid::regprocedure::text, p.prosecdef, p.proconfig FROM pg_proc p " + "JOIN pg_namespace n ON n.oid = p.pronamespace " + f"WHERE n.nspname = 'public' AND p.proowner = {_OWNER_OID} ORDER BY 2" + ), + {"owner": OWNER_ROLE}, + ).all() + + _revoke_all(conn, "ROUTINE", [signature for _, signature, _, _ in functions]) + for name, signature, security_definer, config in functions: + function = FUNCTIONS.get(name) + if not function or not function.executors or function.security_definer != security_definer: + continue + if security_definer and not any(setting.startswith("search_path=") for setting in config or []): + logger.warning(f"Not granting {signature}: it's SECURITY DEFINER without a pinned search_path.") + continue + _execute(conn, f"GRANT EXECUTE ON ROUTINE {signature} TO {', '.join(sorted(function.executors))}") diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py new file mode 100644 index 000000000..e6f47ca4f --- /dev/null +++ b/src/mavedb/db/rls.py @@ -0,0 +1,169 @@ +"""Database roles, and what each role may do to every relation and function in the schema (#808, #827). + +The bootstrap (``mavedb.db.bootstrap``) makes the database's grants match these registries exactly, and the CI +and startup checks (#824) read them. Anything missing from a registry gets no grants, so a new table or +function is unreachable until it's listed here. Listing one is a reviewed change: say beside it why its access +is safe, and for a table the api can read, whether row-level security decides which rows. +""" + +from dataclasses import dataclass +from enum import Enum + +OWNER_ROLE = "mavedb_owner" +"""Owns every table and function. No role logs in as it. Migrations run through it via ``MIGRATE_ROLE``.""" + +MIGRATE_ROLE = "mavedb_migrate" +"""The login for migrations and deploy steps. Its only membership is ``OWNER_ROLE``, which it runs as.""" + +WORKER_ROLE = "mavedb_worker" +"""The worker's login. It has only the privileges granted to it here, and belongs to no role.""" + +API_ROLE = "mavedb_api" +"""The api's login, in every environment. It has only the privileges granted to it here, and belongs to no role.""" + + +class ApiAccess(Enum): + GUARDED = "guarded" + """The api is granted the relation, and an RLS policy decides which rows it sees (#809). + + A view reads its tables as its owner, who skips their policies, so a guarded view must be + ``security_invoker``; the api isn't granted one that isn't. A materialized view can't be guarded: its rows + were read as the owner at refresh, and Postgres has no RLS on it. + """ + + CARVE_OUT = "carve_out" + """The api is granted the relation with no policy, so every caller sees every row. Say why that's safe.""" + + NONE = "none" + """The api gets no privileges on the relation.""" + + +@dataclass(frozen=True) +class Function: + executors: frozenset[str] = frozenset() + security_definer: bool = False + + +@dataclass(frozen=True) +class Relation: + api: ApiAccess + worker: bool = True + + +GUARDED = Relation(ApiAccess.GUARDED) +CARVE_OUT = Relation(ApiAccess.CARVE_OUT) +WORKER_ONLY = Relation(ApiAccess.NONE) +UNGRANTED = Relation(ApiAccess.NONE, worker=False) + +# Every table, view and materialized view in the schema. Tables, including foreign tables, get SELECT, INSERT, +# UPDATE and DELETE; views and materialized views get SELECT. A table's sequences go to the roles that can write the table. A name +# that isn't in the database is skipped, so production's leftover tables can be listed here. +RELATIONS: dict[str, Relation] = { + # Records with their own rule (#809). + "scoresets": GUARDED, + "experiments": GUARDED, + "experiment_sets": GUARDED, + "collections": GUARDED, + "score_calibrations": GUARDED, + # Owned rows, visible when the record that owns them is (#809). + "variants": GUARDED, + "target_genes": GUARDED, + "target_sequences": GUARDED, + "target_accessions": GUARDED, + "target_gene_external_identifiers": GUARDED, + "target_gene_mappings": GUARDED, + "mapping_records": GUARDED, + "mapping_record_alleles": GUARDED, + "projection_groups": GUARDED, + "score_calibration_functional_classifications": GUARDED, + "score_calibration_functional_classification_variants": GUARDED, + "score_calibration_publication_identifiers": GUARDED, + "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, + "scoreset_sra_identifiers": GUARDED, + "experiment_sra_identifiers": GUARDED, + "experiment_set_sra_identifiers": GUARDED, + "experiment_controlled_keywords": GUARDED, + "scoreset_meta_analysis_sources": GUARDED, + "collection_score_sets": GUARDED, + "collection_experiments": GUARDED, + "urn_redirects": GUARDED, + "pipelines": GUARDED, + "job_runs": GUARDED, + "job_dependencies": GUARDED, + # Shared rows, visible when a record the caller can see links to them (#809). + "alleles": GUARDED, + "vep_allele_consequences": GUARDED, + "clinvar_allele_links": GUARDED, + "gnomad_allele_links": GUARDED, + "clinvar_controls": GUARDED, + "gnomad_variants": GUARDED, + "variant_translations": GUARDED, + "publication_identifiers": GUARDED, + # Fixed vocabulary, not produced by anyone's work. + "licenses": CARVE_OUT, + "controlled_keywords": CARVE_OUT, + "acmg_classifications": CARVE_OUT, + "mondo_terms": CARVE_OUT, + "genome_identifiers": CARVE_OUT, + "taxonomies": CARVE_OUT, + # Routes look up strangers by ORCID and list users, and the policies read it for the caller's ORCID. The + # sensitive column, email, is returned only to the user and to admins. + "users": CARVE_OUT, + # Read by the parent records' policies; a policy here would loop back through the parent. + "contributors": CARVE_OUT, + "scoreset_contributors": CARVE_OUT, + "experiment_contributors": CARVE_OUT, + "experiment_set_contributors": CARVE_OUT, + # Read by role checks. + "users_roles": CARVE_OUT, + "roles": CARVE_OUT, + # Read by the collections policy. + "collection_user_associations": CARVE_OUT, + # Looked up before the caller is known; the listing route filters by user. The worker resolves no keys. + "access_keys": Relation(ApiAccess.CARVE_OUT, worker=False), + # Holds only published variants, and no record is both private and published (#893). + "published_variants_materialized_view": CARVE_OUT, + # Legacy, and no route reads them, but deleting a score set, experiment or experiment set loads them + # through ORM relationships. The mapped variant tables go with #775; the keyword tables when their + # relationships are removed. + "mapped_variants": CARVE_OUT, + "gnomad_variants_mapped_variants": CARVE_OUT, + "mapped_variants_clinical_controls": CARVE_OUT, + "keywords": CARVE_OUT, + "scoreset_keywords": CARVE_OUT, + "experiment_keywords": CARVE_OUT, + "experiment_set_keywords": CARVE_OUT, + # Only the worker and operator scripts read these. A route that needs one adds a policy and moves it. + "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. + "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, + # Unmodelled tables left over in production, which nothing reads. Dropped by #829. + "mavedb_ldh_records": UNGRANTED, + "mavedb_ldh_records_audit": UNGRANTED, + "mavedb_staging_mapped_clinvar_allele_ids_1": UNGRANTED, + "mavedb_staging_mapped_variants_clinical_controls": UNGRANTED, + "variants_to_sync": UNGRANTED, + "vep_functional_consequence_archive": UNGRANTED, +} + + +# Every function the owner owns in the schema, by name, covering all its overloads. Only the listed roles may +# 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] = { + # 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. + "reset_sequence": Function(), +} diff --git a/src/mavedb/db/view.py b/src/mavedb/db/view.py index 2b2dab231..d3f3f7627 100644 --- a/src/mavedb/db/view.py +++ b/src/mavedb/db/view.py @@ -171,9 +171,9 @@ def refresh_mat_view(session: Session, name: str, concurrently=True): """ Refresh a PostgreSQL materialized view within the current SQLAlchemy session. - This helper issues a REFRESH MATERIALIZED VIEW statement for the specified - materialized view name. It first explicitly flushes the session because - session.execute() bypasses SQLAlchemy's autoflush mechanism; without the flush, + This helper calls ``mavedb_refresh_mat_views``, which issues REFRESH MATERIALIZED VIEW as the view's owner, + since refreshing requires owning the view and the worker owns nothing. It first explicitly flushes the + session because session.execute() bypasses SQLAlchemy's autoflush mechanism; without the flush, pending changes (e.g., newly inserted/updated rows that the view depends on) might not be reflected in the refreshed view. @@ -182,7 +182,7 @@ def refresh_mat_view(session: Session, name: str, concurrently=True): session : sqlalchemy.orm.Session An active SQLAlchemy session bound to a PostgreSQL database. name : str - The exact name (optionally schema-qualified) of the materialized view to refresh. + The exact name (optionally schema-qualified) of a materialized view in the public schema. concurrently : bool, default True If True, uses REFRESH MATERIALIZED VIEW CONCURRENTLY allowing reads during the refresh and requiring a unique index on the materialized view. If False, @@ -208,24 +208,23 @@ def refresh_mat_view(session: Session, name: str, concurrently=True): Examples -------- refresh_mat_view(session, "public.my_materialized_view") - refresh_mat_view(session, "reports.daily_stats", concurrently=False) + refresh_mat_view(session, "my_materialized_view", concurrently=False) """ # since session.execute() bypasses autoflush, must manually flush in order # to include newly-created/modified objects in the refresh session.flush() - _con = "CONCURRENTLY " if concurrently else "" - session.execute(sa.text("REFRESH MATERIALIZED VIEW " + _con + name)) + session.execute( + sa.text("SELECT mavedb_refresh_mat_views(CAST(:name AS regclass), :concurrently)"), + {"name": name, "concurrently": concurrently}, + ) def refresh_all_mat_views(session: Session, concurrently=True): """ - Refreshes all PostgreSQL materialized views visible to the given SQLAlchemy session. + Refreshes every PostgreSQL materialized view in the public schema. - The function inspects the current database connection for registered materialized - views and issues a REFRESH MATERIALIZED VIEW command for each one using the helper - function `refresh_mat_view`. After all refresh operations complete, the session - is committed to persist any transactional side effects of the refresh statements. + Calls ``mavedb_refresh_mat_views``, which refreshes each view as its owner. Parameters ---------- @@ -236,29 +235,58 @@ def refresh_all_mat_views(session: Session, concurrently=True): (only supported when the view has a unique index that satisfies PostgreSQL requirements). If False, a standard blocking refresh is performed. - Behavior - -------- - - If inspection of the connection fails or returns no inspector, the function - exits without performing any work. - - Each materialized view name returned by the inspector is passed to - `refresh_mat_view(session, name, concurrently)`. - Notes ----- - Using CONCURRENTLY allows reads during refresh at the cost of requiring an appropriate unique index and potentially being slower. - - Exceptions raised during individual refresh operations will propagate unless - `refresh_mat_view` handles them internally; in such a case the commit will - not be reached. - Ensure the session is in a clean transactional state if you rely on consistent snapshot semantics. - This function commits no changes; it is the caller's responsibility to commit the session if needed. """ - inspector = sa.inspect(session.connection()) - - if not inspector: - return - - for mv in inspector.get_materialized_view_names(): - refresh_mat_view(session, mv, concurrently) + session.flush() + session.execute(sa.text("SELECT mavedb_refresh_mat_views(NULL, :concurrently)"), {"concurrently": concurrently}) + + +# Refreshing a materialized view requires owning it, and the worker owns nothing, so it refreshes through +# this function, which runs as its owner. Migration 4b8e2c7d1f3a creates it in deployed databases; this +# creates it wherever Base.metadata builds the schema, as the test template does. Keep the two identical. +# +# TODO(#834): Temporary. Once the test template is built from the migrations, delete this copy and the two +# listeners below; nothing else uses create_all or drop_all. +REFRESH_MAT_VIEWS_FUNCTION = sa.DDL(""" +CREATE OR REPLACE FUNCTION mavedb_refresh_mat_views(view_name regclass DEFAULT NULL, concurrent boolean DEFAULT true) +RETURNS void +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path = pg_catalog, pg_temp +AS $$ +DECLARE + mv regclass; + refreshed integer := 0; +BEGIN + FOR mv IN + SELECT c.oid::regclass + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE c.relkind = 'm' AND n.nspname = 'public' AND (view_name IS NULL OR c.oid = view_name) + ORDER BY c.relname + LOOP + IF concurrent THEN + EXECUTE 'REFRESH MATERIALIZED VIEW CONCURRENTLY ' || mv::text; + ELSE + EXECUTE 'REFRESH MATERIALIZED VIEW ' || mv::text; + END IF; + refreshed := refreshed + 1; + END LOOP; + + IF view_name IS NOT NULL AND refreshed = 0 THEN + RAISE EXCEPTION USING MESSAGE = view_name::text || ' is not a materialized view in the public schema'; + END IF; +END +$$; +""") + +sa.event.listen(Base.metadata, "after_create", REFRESH_MAT_VIEWS_FUNCTION) +sa.event.listen( + Base.metadata, "before_drop", sa.DDL("DROP FUNCTION IF EXISTS mavedb_refresh_mat_views(regclass, boolean)") +) diff --git a/src/mavedb/scripts/bootstrap_roles.py b/src/mavedb/scripts/bootstrap_roles.py new file mode 100644 index 000000000..fe4b77e0f --- /dev/null +++ b/src/mavedb/scripts/bootstrap_roles.py @@ -0,0 +1,49 @@ +"""Set up the database roles, or reapply their grants (#827). Dry run unless ``--commit``. + +Connects with the ``DB_*`` environment variables. + +- ``setup``: once for each new database, as the master user. Creates the roles if the cluster lacks them, + checks the ones it finds, then sets up this database for them. +- ``grants``: reapplies ownership and grants. Every ``alembic upgrade`` already does this, so it's needed by + hand only the first time, as the master user, to move the tables the api's login owns. + +None of it sets a password. A new environment runs:: + + DB_USERNAME= ... python -m mavedb.scripts.bootstrap_roles setup --commit + DB_USERNAME=mavedb_migrate ... alembic upgrade head +""" + +import logging + +import asyncclick as click +from sqlalchemy import text +from sqlalchemy.orm import Session + +from mavedb.db.bootstrap import apply_grants, setup +from mavedb.scripts.environment import script_environment, with_database_session + +logger = logging.getLogger(__name__) + + +@script_environment.command() +@with_database_session +@click.argument("part", type=click.Choice(["setup", "grants"])) +@click.option( + "--lock-timeout", + default="5s", + show_default=True, + help="How long to wait for each table's lock. Moving ownership locks every table; on a timeout, re-run.", +) +def bootstrap_roles(db: Session, part: str, lock_timeout: str) -> None: + conn = db.connection() + conn.execute(text("SELECT set_config('lock_timeout', :timeout, true)"), {"timeout": lock_timeout}) + logger.info(f"Running {part!r} as {conn.execute(text('SELECT current_user')).scalar_one()}") + + if part == "setup": + setup(conn) + else: + apply_grants(conn) + + +if __name__ == "__main__": + bootstrap_roles() diff --git a/tests/bin/test_check_migrations.py b/tests/bin/test_check_migrations.py index bda6be59a..a3e60cb23 100644 --- a/tests/bin/test_check_migrations.py +++ b/tests/bin/test_check_migrations.py @@ -32,6 +32,12 @@ def problems_in(tmp_path: Path, source: str) -> list[str]: ("def upgrade():\n op.execute('CREATE INDEX concurrently ix ON t (c)')\n", "CONCURRENTLY"), ("def upgrade():\n op.get_bind().commit()\n", "commits mid-upgrade"), ("def upgrade():\n op.execute(\"ALTER TYPE state ADD value 'done'\")\n", "adds an enum value"), + ("def upgrade():\n op.execute('grant select on t to mavedb_api')\n", "grants or revokes"), + ("def upgrade():\n op.execute('REVOKE EXECUTE ON FUNCTION f() FROM PUBLIC')\n", "grants or revokes"), + ( + "def upgrade():\n op.execute('ALTER DEFAULT PRIVILEGES REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC')\n", + "grants or revokes", + ), ], ids=[ "mavedb-from-import", @@ -42,6 +48,9 @@ def problems_in(tmp_path: Path, source: str) -> list[str]: "concurrently", "commit", "enum-add-value", + "grant", + "revoke", + "default-privileges", ], ) def test_check_forbidden_pattern_reports_one_problem(tmp_path, source, reason): @@ -63,6 +72,20 @@ def test_check_concurrently_in_docstrings_passes(tmp_path): assert problems_in(tmp_path, source) == [] +@pytest.mark.unit +def test_check_concurrent_mat_view_refresh_passes(tmp_path): + source = "def upgrade():\n op.execute('REFRESH MATERIALIZED VIEW concurrently mv')\n" + + assert problems_in(tmp_path, source) == [] + + +@pytest.mark.unit +def test_check_concurrent_index_beside_mat_view_refresh_reports_one_problem(tmp_path): + source = "def upgrade():\n op.execute('REFRESH MATERIALIZED VIEW CONCURRENTLY mv; DROP INDEX CONCURRENTLY ix')\n" + + assert len(problems_in(tmp_path, source)) == 1 + + @pytest.mark.unit def test_check_alembic_and_sqlalchemy_core_imports_pass(tmp_path): source = "import sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.dialects import postgresql\n" @@ -73,3 +96,10 @@ def test_check_alembic_and_sqlalchemy_core_imports_pass(tmp_path): @pytest.mark.unit def test_main_current_migrations_pass(): assert check_migrations.main([]) == 0 + + +@pytest.mark.unit +def test_check_grant_inside_an_identifier_passes(tmp_path): + source = "def upgrade():\n op.execute('ALTER TABLE t ADD COLUMN grant_id integer')\n" + + assert problems_in(tmp_path, source) == [] diff --git a/tests/conftest.py b/tests/conftest.py index 0019f4231..c9877e5e5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,6 +1,7 @@ import logging # noqa: F401 import os import sys +import time from contextlib import contextmanager from datetime import datetime from unittest import mock @@ -11,6 +12,7 @@ import pytest_socket from pytest_postgresql import factories from sqlalchemy import URL, create_engine, text +from sqlalchemy.exc import DBAPIError from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import NullPool @@ -19,6 +21,8 @@ os.environ.setdefault("CLINGEN_CACHE_BACKEND", "memory") from mavedb.db.base import Base +from mavedb.db.bootstrap import apply_grants, bootstrap_cluster, bootstrap_database +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 from mavedb.models.experiment import Experiment @@ -66,13 +70,60 @@ email_validator.TEST_ENVIRONMENT = True +# Lets tests log in as each role over a real connection. The bootstrap never sets a password, so the test +# harness does, on the test cluster only. +TEST_ROLE_PASSWORD = "mavedb-test-only" + + +def _bootstrap_cluster(engine): + """ + Bootstrap the PostgreSQL cluster with the necessary roles and grants. + + This function attempts to create or alter the required roles for the MaveDB cluster, + retrying up to 5 times in case of concurrent modifications by other test runs. + + Parameters + ---------- + engine : sqlalchemy.engine.Engine + An SQLAlchemy engine connected to the PostgreSQL cluster. + + Raises + ------ + sqlalchemy.exc.DBAPIError + If the role creation or alteration fails after 5 attempts. + """ + for attempt in range(5): + try: + with engine.begin() as conn: + bootstrap_cluster(conn) + unset = conn.execute( + text("SELECT rolname FROM pg_authid WHERE rolname = ANY(:roles) AND rolpassword IS NULL"), + {"roles": [OWNER_ROLE, MIGRATE_ROLE, WORKER_ROLE, API_ROLE]}, + ).scalars() + for role in unset: + conn.execute(text(f"ALTER ROLE {role} PASSWORD '{TEST_ROLE_PASSWORD}'")) + return + except DBAPIError: + if attempt == 4: + raise + time.sleep(0.2 * (attempt + 1)) + + def _load_schema(host, port, user, dbname, password): - """Build the schema once into the server's template database, which each test's database is cloned from.""" + """Build the schema once into the server's template database, which each test's database is cloned from. + + The roles and grants are applied as they are in a deployed database, with the schema built as the owner, + as a migration would. Clones inherit the grants and default privileges. + """ engine = create_engine( URL.create("postgresql+psycopg2", username=user, password=password, host=host, port=port, database=dbname), poolclass=NullPool, ) - Base.metadata.create_all(bind=engine) + _bootstrap_cluster(engine) + with engine.begin() as conn: + bootstrap_database(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + Base.metadata.create_all(bind=conn) # Create a unique index for the published_variants_materialized_view to # enforce uniqueness on (variant_id, mapping_record_id, score_set_id). This @@ -82,6 +133,8 @@ def _load_schema(host, port, user, dbname, password): text("""CREATE UNIQUE INDEX IF NOT EXISTS published_variants_mv_unique_idx ON published_variants_materialized_view (variant_id, mapping_record_id, score_set_id)"""), ) + apply_grants(conn) + engine.dispose() @@ -155,6 +208,31 @@ def session(postgresql): engine.dispose() +@pytest.fixture +def login_as(postgresql): + """Return a factory for engines that log in to the test database as a given role, on real connections.""" + engines = [] + + def _login(role: str, database: str | None = None): + engine = create_engine( + URL.create( + "postgresql+psycopg2", + username=role, + password=TEST_ROLE_PASSWORD, + host=postgresql.info.host, + port=postgresql.info.port, + database=database or postgresql.info.dbname, + ), + poolclass=NullPool, + ) + engines.append(engine) + return engine + + yield _login + for engine in engines: + engine.dispose() + + @pytest.fixture def db_session_fixture(session): @contextmanager diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py new file mode 100644 index 000000000..e6fb9a164 --- /dev/null +++ b/tests/db/test_bootstrap.py @@ -0,0 +1,844 @@ +# ruff: noqa: E402 + +import os +import subprocess +import sys +import uuid +from pathlib import Path + +import pytest + +pytest.importorskip("psycopg2") + +from sqlalchemy import URL, create_engine, text +from sqlalchemy.exc import OperationalError, ProgrammingError +from sqlalchemy.orm import Session +from sqlalchemy.pool import NullPool + +from mavedb.db import bootstrap +from mavedb.db.bootstrap import apply_grants, bootstrap_cluster, bootstrap_database, role_problems, setup +from mavedb.db.rls import ( + API_ROLE, + FUNCTIONS, + GUARDED, + MIGRATE_ROLE, + OWNER_ROLE, + RELATIONS, + WORKER_ROLE, + ApiAccess, +) +from mavedb.db.view import REFRESH_MAT_VIEWS_FUNCTION, refresh_all_mat_views +from tests.conftest import TEST_ROLE_PASSWORD + +API_ROOT = Path(__file__).resolve().parents[2] + +TABLE_PRIVILEGES = {"SELECT", "INSERT", "UPDATE", "DELETE"} + +# What each part may change, read back as plain values so two snapshots compare equal when nothing changed. +CATALOG_QUERIES = { + "roles": "SELECT rolname, rolcanlogin, rolsuper, rolinherit, rolcreaterole, rolbypassrls FROM pg_roles " + "WHERE rolname = ANY(:roles) ORDER BY 1", + "memberships": "SELECT r.rolname, m.rolname, am.admin_option FROM pg_auth_members am " + "JOIN pg_roles r ON r.oid = am.roleid JOIN pg_roles m ON m.oid = am.member " + "WHERE r.rolname = ANY(:roles) OR m.rolname = ANY(:roles) ORDER BY 1, 2", + "role_settings": "SELECT r.rolname, s.setdatabase, s.setconfig FROM pg_db_role_setting s " + "JOIN pg_roles r ON r.oid = s.setrole WHERE r.rolname = ANY(:roles) ORDER BY 1, 2", + "parameter_acls": "SELECT p.parname, r.rolname, a.privilege_type FROM pg_parameter_acl p " + "CROSS JOIN LATERAL aclexplode(p.paracl) a JOIN pg_roles r ON r.oid = a.grantee " + "WHERE r.rolname = ANY(:roles) ORDER BY 1, 2, 3", + "schema_acl": "SELECT nspowner::regrole::text, nspacl::text FROM pg_namespace WHERE nspname = 'public'", + "default_acls": "SELECT defaclrole::regrole::text, defaclobjtype, defaclacl::text FROM pg_default_acl ORDER BY 1, 2", + "relations": "SELECT c.relname, c.relowner::regrole::text, c.relacl::text FROM pg_class c " + "JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm', 'S') " + "ORDER BY 1", + "functions": "SELECT p.oid::regprocedure::text, p.proowner::regrole::text, p.proacl::text FROM pg_proc p " + "JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public' ORDER BY 1", +} + +# Every grant on the schema's relations and sequences to anyone but their owner, with a missing ACL read as +# Postgres's default. +RELATION_GRANTS = """ +SELECT c.relname, coalesce(g.rolname, 'PUBLIC'), a.privilege_type + FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace + CROSS JOIN LATERAL aclexplode( + coalesce(c.relacl, acldefault((CASE c.relkind WHEN 'S' THEN 's' ELSE 'r' END)::"char", c.relowner))) a + LEFT JOIN pg_roles g ON g.oid = a.grantee + WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm', 'S') AND a.grantee <> c.relowner +""" + +FUNCTION_GRANTS = """ +SELECT p.proname, coalesce(g.rolname, 'PUBLIC'), a.privilege_type + FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace + CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f'::"char", p.proowner))) a + LEFT JOIN pg_roles g ON g.oid = a.grantee + WHERE n.nspname = 'public' AND a.grantee <> p.proowner +""" + + +def _has_privileges(conn, role: str, table: str, privileges: list[str]) -> bool: + return all( + conn.execute(text("SELECT has_table_privilege(:r, :t, :p)"), {"r": role, "t": table, "p": p}).scalar_one() + for p in privileges + ) + + +def _grants(conn, query: str = RELATION_GRANTS) -> dict[str, set[tuple[str, str]]]: + grants: dict[str, set[tuple[str, str]]] = {} + for name, grantee, privilege in conn.execute(text(query)): + grants.setdefault(name, set()).add((grantee, privilege)) + return grants + + +def _expected_grantees(name: str) -> list[str]: + relation = RELATIONS.get(name) + if relation is None: + return [] + return [API_ROLE] * (relation.api is not ApiAccess.NONE) + [WORKER_ROLE] * relation.worker + + +def _snapshot(engine, api_role: str) -> dict[str, list]: + # Only these roles: concurrent tests on the same cluster create and drop roles of their own. + roles = [OWNER_ROLE, MIGRATE_ROLE, WORKER_ROLE, api_role] + with engine.connect() as conn: + return { + name: [tuple(row) for row in conn.execute(text(query), {"roles": roles})] + for name, query in CATALOG_QUERIES.items() + } + + +def _url(postgresql, database: str, username: str | None = None, password: str | None = None) -> URL: + return URL.create( + "postgresql+psycopg2", + username=username or postgresql.info.user, + password=password or postgresql.info.password or None, + host=postgresql.info.host, + port=postgresql.info.port, + database=database, + ) + + +def _drop_role(conn, role: str) -> None: + if conn.execute(text("SELECT EXISTS (SELECT FROM pg_roles WHERE rolname = :r)"), {"r": role}).scalar_one(): + # Also revokes its cluster-wide grants, such as on parameters, which would otherwise block the drop. + conn.execute(text(f"DROP OWNED BY {role}")) + conn.execute(text(f"DROP ROLE {role}")) + + +@pytest.fixture +def superuser(postgresql): + engine = create_engine(_url(postgresql, postgresql.info.dbname), poolclass=NullPool) + yield engine + engine.dispose() + + +@pytest.fixture +def fresh_role(superuser): + """Return a factory for roles no other test uses, dropped afterwards.""" + created = [] + + def _create(prefix: str = "mavedb_test") -> str: + role = f"{prefix}_{uuid.uuid4().hex[:8]}" + created.append(role) + return role + + yield _create + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + for role in reversed(created): + _drop_role(conn, role) + + +@pytest.fixture +def fresh_api_role(fresh_role, monkeypatch): + """Stand a role no other test uses in for the api's, so a test can change it without touching the cluster's. + + The api role is shared by every run against the same cluster, and these tests give it objects, databases, + attributes and memberships. + """ + role = fresh_role("mavedb_test_api") + monkeypatch.setattr(bootstrap, "API_ROLE", role) + return role + + +@pytest.fixture +def fresh_database(postgresql, superuser, fresh_api_role): + """Return a factory for an empty database on the test cluster, as on a new deployment. + + Depends on ``fresh_api_role`` so its databases are dropped before the role, which has grants in them. + """ + created = [] + + def _create(owner: str | None = None) -> str: + name = f"{postgresql.info.dbname}_fresh_{len(created)}" + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f"CREATE DATABASE {name} TEMPLATE template0" + (f" OWNER {owner}" if owner else ""))) + created.append(name) + return name + + yield _create + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + for name in created: + conn.execute(text(f"DROP DATABASE IF EXISTS {name} WITH (FORCE)")) + + +def _run_all_parts(engine) -> None: + with engine.begin() as conn: + bootstrap_cluster(conn) + with engine.begin() as conn: + bootstrap_database(conn) + with engine.begin() as conn: + apply_grants(conn) + + +@pytest.mark.integration +class TestBootstrapParts: + def test_each_part_on_a_fresh_database_second_run_changes_nothing(self, postgresql, fresh_database, fresh_api_role): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + _run_all_parts(engine) + with engine.begin() as conn: + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute(text("CREATE TABLE widgets (id serial PRIMARY KEY)")) + conn.execute(text(REFRESH_MAT_VIEWS_FUNCTION.statement)) + + _run_all_parts(engine) + first = _snapshot(engine, fresh_api_role) + parts = {"cluster": bootstrap_cluster, "database": bootstrap_database, "grants": apply_grants} + for name, part in parts.items(): + with engine.begin() as conn: + part(conn) + assert _snapshot(engine, fresh_api_role) == first, name + + engine.dispose() + + def test_bootstrap_cluster_new_role_has_no_password_and_existing_password_is_kept(self, superuser, fresh_api_role): + with superuser.begin() as conn: + bootstrap_cluster(conn) + with superuser.begin() as conn: + assert ( + conn.execute( + text("SELECT rolpassword FROM pg_authid WHERE rolname = :r"), {"r": fresh_api_role} + ).scalar_one() + is None + ) + conn.execute(text(f"ALTER ROLE {fresh_api_role} PASSWORD 'kept'")) + password = conn.execute( + text("SELECT rolpassword FROM pg_authid WHERE rolname = :r"), {"r": fresh_api_role} + ).scalar_one() + + with superuser.begin() as conn: + bootstrap_cluster(conn) + with superuser.connect() as conn: + assert ( + conn.execute( + text("SELECT rolpassword FROM pg_authid WHERE rolname = :r"), {"r": fresh_api_role} + ).scalar_one() + == password + ) + + @pytest.mark.parametrize("attribute", ["SUPERUSER", "BYPASSRLS", "CREATEROLE", "CREATEDB", "REPLICATION"]) + def test_bootstrap_cluster_existing_role_with_unsafe_attribute_raises(self, superuser, fresh_api_role, attribute): + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {fresh_api_role} LOGIN {attribute}")) + + with superuser.begin() as conn, pytest.raises(RuntimeError, match=f"{fresh_api_role} has {attribute}"): + bootstrap_cluster(conn) + + def test_bootstrap_cluster_existing_role_in_another_role_raises(self, superuser, fresh_api_role): + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {fresh_api_role} LOGIN")) + conn.execute(text(f"GRANT pg_read_all_data TO {fresh_api_role}")) + + with ( + superuser.begin() as conn, + pytest.raises(RuntimeError, match=f"{fresh_api_role} is a member of pg_read_all_data"), + ): + bootstrap_cluster(conn) + + def test_bootstrap_cluster_another_role_in_an_existing_role_raises(self, superuser, fresh_role, fresh_api_role): + stranger = fresh_role("mavedb_test_stranger") + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {fresh_api_role} LOGIN")) + conn.execute(text(f"CREATE ROLE {stranger} LOGIN IN ROLE {fresh_api_role}")) + + with ( + superuser.begin() as conn, + pytest.raises(RuntimeError, match=f"{stranger} is a member of {fresh_api_role}"), + ): + bootstrap_cluster(conn) + + @pytest.mark.parametrize("parameter", ["session_replication_role", "log_statement"]) + def test_bootstrap_cluster_existing_role_that_can_set_a_superuser_parameter_raises( + self, superuser, fresh_api_role, parameter + ): + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {fresh_api_role} LOGIN")) + conn.execute(text(f"GRANT SET ON PARAMETER {parameter} TO {fresh_api_role}")) + + with superuser.begin() as conn, pytest.raises(RuntimeError, match=f"{fresh_api_role} can set {parameter}"): + bootstrap_cluster(conn) + + def test_bootstrap_database_api_able_to_create_in_public_raises(self, postgresql, fresh_database, fresh_api_role): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + bootstrap_cluster(conn) + conn.execute(text(f"GRANT CREATE ON SCHEMA public TO {fresh_api_role}")) + + with ( + engine.begin() as conn, + pytest.raises(RuntimeError, match=f"{fresh_api_role} can create objects in schema public"), + ): + bootstrap_database(conn) + engine.dispose() + + @pytest.mark.parametrize( + "grant, problem", + [ + ("GRANT CREATE ON SCHEMA public TO {role}", "can create objects in schema public"), + ("GRANT CREATE ON DATABASE {database} TO {role}", "can create schemas in this database"), + ], + ids=["schema", "database"], + ) + def test_apply_grants_api_able_to_create_objects_raises( + self, postgresql, fresh_database, fresh_api_role, grant, problem + ): + database = fresh_database() + engine = create_engine(_url(postgresql, database), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(grant.format(role=fresh_api_role, database=database))) + + with engine.begin() as conn, pytest.raises(RuntimeError, match=f"{fresh_api_role} {problem}"): + apply_grants(conn) + engine.dispose() + + @pytest.mark.parametrize( + "statement", + ["CREATE TABLE widgets (id int)", "CREATE FUNCTION unlisted() RETURNS int LANGUAGE sql AS 'SELECT 1'"], + ids=["table", "function"], + ) + def test_apply_grants_object_owned_by_another_role_raises(self, postgresql, fresh_database, statement): + # Made by hand as the superuser, so the grants step can't govern it and its owner skips its policies. + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(statement)) + + with engine.begin() as conn, pytest.raises(RuntimeError, match=f"belong to a role other than {OWNER_ROLE}"): + apply_grants(conn) + engine.dispose() + + def test_apply_grants_role_given_a_membership_after_setup_raises(self, postgresql, fresh_database, fresh_api_role): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"GRANT pg_read_all_data TO {fresh_api_role}")) + + with engine.begin() as conn, pytest.raises(RuntimeError, match="aren't as the bootstrap sets them up"): + apply_grants(conn) + engine.dispose() + + def test_apply_grants_api_role_owning_objects_moves_them_to_the_owner( + self, postgresql, fresh_database, fresh_api_role + ): + # As on staging and production before this change, where the api's login owns every table. + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + bootstrap_cluster(conn) + conn.execute(text("CREATE TABLE licenses (id serial PRIMARY KEY)")) + conn.execute(text(f"ALTER TABLE licenses OWNER TO {fresh_api_role}")) + with engine.begin() as conn: + bootstrap_database(conn) + with engine.begin() as conn: + apply_grants(conn) + + with engine.connect() as conn: + owners = conn.execute( + text( + "SELECT relname, relowner::regrole::text FROM pg_class " + "WHERE relname IN ('licenses', 'licenses_id_seq') ORDER BY 1" + ) + ).all() + assert [tuple(row) for row in owners] == [("licenses", OWNER_ROLE), ("licenses_id_seq", OWNER_ROLE)] + assert _has_privileges(conn, fresh_api_role, "licenses", sorted(TABLE_PRIVILEGES)) + engine.dispose() + + def test_apply_grants_leaves_exactly_the_listed_grants(self, postgresql, fresh_database, fresh_api_role): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute(text("CREATE TABLE licenses (id serial PRIMARY KEY)")) + conn.execute(text("CREATE TABLE annotation_event (id serial PRIMARY KEY)")) + conn.execute(text("CREATE TABLE widgets (id serial PRIMARY KEY)")) + conn.execute(text("CREATE FUNCTION unlisted() RETURNS int LANGUAGE sql AS 'SELECT 1'")) + # Stray grants, as a migration or an operator could leave them. + conn.execute(text("GRANT SELECT ON widgets TO PUBLIC")) + conn.execute(text(f"GRANT ALL ON annotation_event TO {fresh_api_role}")) + conn.execute(text(f"GRANT TRUNCATE ON licenses TO {WORKER_ROLE}")) + conn.execute(text(f"GRANT EXECUTE ON FUNCTION unlisted() TO PUBLIC, {fresh_api_role}")) + with engine.begin() as conn: + apply_grants(conn) + + with engine.connect() as conn: + grants = _grants(conn) + function_grants = _grants(conn, FUNCTION_GRANTS) + engine.dispose() + + dml = {(role, p) for role in (fresh_api_role, WORKER_ROLE) for p in TABLE_PRIVILEGES} + assert grants["licenses"] == dml + assert grants["licenses_id_seq"] == {(r, p) for r in (fresh_api_role, WORKER_ROLE) for p in ("USAGE", "SELECT")} + assert grants["annotation_event"] == {(WORKER_ROLE, p) for p in TABLE_PRIVILEGES} + assert "widgets" not in grants + assert "widgets_id_seq" not in grants + assert "unlisted" not in function_grants + + def test_apply_grants_function_unlike_its_entry_gets_no_executors(self, postgresql, fresh_database, fresh_api_role): + # Listed as SECURITY DEFINER for the worker; one that isn't is not the function that was reviewed. + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute( + text( + "CREATE FUNCTION mavedb_refresh_mat_views(view_name regclass, concurrent boolean) RETURNS void " + "LANGUAGE sql AS ''" + ) + ) + with engine.begin() as conn: + apply_grants(conn) + assert "mavedb_refresh_mat_views" not in _grants(conn, FUNCTION_GRANTS) + engine.dispose() + + def test_apply_grants_definer_function_without_pinned_search_path_gets_no_executors( + self, postgresql, fresh_database, fresh_api_role + ): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute( + text( + "CREATE FUNCTION mavedb_refresh_mat_views(view_name regclass, concurrent boolean) RETURNS void " + "LANGUAGE sql SECURITY DEFINER AS ''" + ) + ) + with engine.begin() as conn: + apply_grants(conn) + assert "mavedb_refresh_mat_views" not in _grants(conn, FUNCTION_GRANTS) + engine.dispose() + + @pytest.mark.parametrize( + "create, api_granted", + [ + ("CREATE VIEW guarded_relation AS SELECT 1 AS id", False), + ("CREATE VIEW guarded_relation WITH (security_invoker = true) AS SELECT 1 AS id", True), + ("CREATE MATERIALIZED VIEW guarded_relation AS SELECT 1 AS id", False), + ], + ids=["view", "security-invoker-view", "materialized-view"], + ) + def test_apply_grants_guarded_view_reaches_the_api_only_when_it_reads_as_the_caller( + self, postgresql, fresh_database, fresh_api_role, monkeypatch, create, api_granted + ): + monkeypatch.setitem(RELATIONS, "guarded_relation", GUARDED) + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute(text(create)) + with engine.begin() as conn: + apply_grants(conn) + grants = _grants(conn).get("guarded_relation", set()) + engine.dispose() + + assert ((fresh_api_role, "SELECT") in grants) is api_granted + assert (WORKER_ROLE, "SELECT") in grants + + def test_apply_grants_foreign_table_gets_exactly_the_listed_grants( + self, postgresql, fresh_database, fresh_api_role + ): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + # A wrapper with no handler: enough to create a foreign table, not to read one. + conn.execute(text("CREATE FOREIGN DATA WRAPPER test_fdw")) + conn.execute(text("CREATE SERVER test_server FOREIGN DATA WRAPPER test_fdw")) + conn.execute(text("CREATE FOREIGN TABLE licenses (id int) SERVER test_server")) + conn.execute(text(f"ALTER FOREIGN TABLE licenses OWNER TO {OWNER_ROLE}")) + conn.execute(text("GRANT SELECT ON licenses TO PUBLIC")) + with engine.begin() as conn: + apply_grants(conn) + grants = _grants(conn) + engine.dispose() + + assert grants["licenses"] == {(role, p) for role in (fresh_api_role, WORKER_ROLE) for p in TABLE_PRIVILEGES} + + def test_bootstrap_database_new_function_is_closed_to_public(self, postgresql, fresh_database): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) + conn.execute(text("CREATE FUNCTION unlisted() RETURNS int LANGUAGE sql AS 'SELECT 1'")) + assert "unlisted" not in _grants(conn, FUNCTION_GRANTS) + engine.dispose() + + def test_apply_grants_api_role_owning_a_database_raises(self, postgresql, fresh_database, fresh_api_role): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + fresh_database(owner=fresh_api_role) + + with engine.begin() as conn, pytest.raises(RuntimeError, match="owns databases"): + apply_grants(conn) + engine.dispose() + + def test_apply_grants_without_setup_raises(self, postgresql, fresh_database): + engine = create_engine(_url(postgresql, fresh_database()), poolclass=NullPool) + with engine.begin() as conn, pytest.raises(RuntimeError, match="no roles set up"): + apply_grants(conn) + engine.dispose() + + def test_parts_as_a_non_superuser_master_leave_no_borrowed_memberships( + self, postgresql, superuser, fresh_role, fresh_database, fresh_api_role + ): + # RDS's master user can create roles but isn't a superuser, so it has to borrow the owner's and the + # api's privileges to change their objects. It must give them back. + master = fresh_role("mavedb_test_master") + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {master} LOGIN CREATEROLE PASSWORD '{TEST_ROLE_PASSWORD}'")) + bootstrap_cluster(conn) + database = fresh_database(owner=master) + with create_engine(_url(postgresql, database), poolclass=NullPool).begin() as conn: + conn.execute(text("CREATE TABLE widgets (id serial PRIMARY KEY)")) + conn.execute(text(f"ALTER TABLE widgets OWNER TO {fresh_api_role}")) + + engine = create_engine(_url(postgresql, database, master, TEST_ROLE_PASSWORD), poolclass=NullPool) + try: + with engine.begin() as conn: + bootstrap_database(conn) + with engine.begin() as conn: + apply_grants(conn) + + with engine.connect() as conn: + owner = conn.execute(text("SELECT relowner::regrole::text FROM pg_class WHERE relname = 'widgets'")) + assert owner.scalar_one() == OWNER_ROLE + memberships = conn.execute( + text( + "SELECT count(*) FROM pg_auth_members WHERE member = (SELECT oid FROM pg_roles WHERE rolname = :m)" + ), + {"m": master}, + ) + assert memberships.scalar_one() == 0 + finally: + engine.dispose() + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f"DROP DATABASE IF EXISTS {database} WITH (FORCE)")) + + def test_privileges_of_python_error_gives_the_borrowed_role_back( + self, postgresql, superuser, fresh_role, fresh_database + ): + # The transaction still works after an error that isn't the database's, so a caller could commit it. + master = fresh_role("mavedb_test_master") + with superuser.begin() as conn: + conn.execute(text(f"CREATE ROLE {master} LOGIN CREATEROLE PASSWORD '{TEST_ROLE_PASSWORD}'")) + bootstrap_cluster(conn) + engine = create_engine(_url(postgresql, fresh_database(), master, TEST_ROLE_PASSWORD), poolclass=NullPool) + + with engine.begin() as conn: + with pytest.raises(ValueError), bootstrap._privileges_of(conn, OWNER_ROLE): + raise ValueError("not the database's") + with engine.connect() as conn: + assert not conn.execute( + text("SELECT pg_has_role(:m, :o, 'MEMBER')"), {"m": master, "o": OWNER_ROLE} + ).scalar_one() + engine.dispose() + + +@pytest.mark.integration +class TestRoles: + def test_role_problems_on_the_test_cluster_finds_none(self, session): + assert role_problems(session.connection()) == [] + + def test_roles_only_membership_is_migrate_in_owner(self, session): + memberships = session.execute( + text( + "SELECT r.rolname, m.rolname FROM pg_auth_members am JOIN pg_roles r ON r.oid = am.roleid " + "JOIN pg_roles m ON m.oid = am.member WHERE r.rolname = ANY(:roles) OR m.rolname = ANY(:roles)" + ), + {"roles": [OWNER_ROLE, MIGRATE_ROLE, WORKER_ROLE, API_ROLE]}, + ).all() + + assert [tuple(m) for m in memberships] == [(OWNER_ROLE, MIGRATE_ROLE)] + + def test_owner_cannot_log_in(self, login_as): + with pytest.raises(OperationalError, match="not permitted to log in"): + login_as(OWNER_ROLE).connect() + + def test_migrate_runs_as_owner(self, login_as): + with login_as(MIGRATE_ROLE).connect() as conn: + assert conn.execute(text("SELECT current_user")).scalar_one() == OWNER_ROLE + + def test_worker_lock_timeout_comes_from_its_role(self, login_as): + with login_as(WORKER_ROLE).connect() as conn: + assert conn.execute(text("SHOW lock_timeout")).scalar_one() == "1min" + assert conn.execute(text("SHOW statement_timeout")).scalar_one() == "0" + + def test_table_created_by_migrate_is_owned_by_owner_and_closed_until_listed(self, login_as): + with login_as(MIGRATE_ROLE).begin() as conn: + conn.execute(text("CREATE TABLE widgets (id serial PRIMARY KEY, name text)")) + assert ( + conn.execute( + text("SELECT relowner::regrole::text FROM pg_class WHERE relname = 'widgets'") + ).scalar_one() + == OWNER_ROLE + ) + + for role in (API_ROLE, WORKER_ROLE): + with login_as(role).connect() as conn, pytest.raises(ProgrammingError, match="permission denied"): + conn.execute(text("SELECT name FROM widgets")) + + @pytest.mark.parametrize("role", [API_ROLE, WORKER_ROLE]) + @pytest.mark.parametrize( + "statement", + ["CREATE TABLE intruder (id int)", f"SET ROLE {OWNER_ROLE}", "SET session_replication_role = replica"], + ids=["create", "set-role", "replication-role"], + ) + def test_api_and_worker_cannot_escalate(self, login_as, role, statement): + with login_as(role).connect() as conn, pytest.raises(ProgrammingError): + conn.execute(text(statement)) + + def test_migrate_cannot_set_session_replication_role(self, login_as): + # It turns off foreign key checks; restores set it as the master user. + with login_as(MIGRATE_ROLE).connect() as conn, pytest.raises(ProgrammingError, match="permission denied"): + conn.execute(text("SET session_replication_role = replica")) + + def test_worker_has_no_privileges_on_access_keys(self, session, login_as): + privileges = session.execute( + text( + "SELECT privilege_type FROM information_schema.role_table_grants WHERE table_name = 'access_keys' AND grantee = :r" + ), + {"r": WORKER_ROLE}, + ).all() + assert privileges == [] + + with login_as(WORKER_ROLE).connect() as conn, pytest.raises(ProgrammingError, match="permission denied"): + conn.execute(text("SELECT 1 FROM access_keys")) + + def test_api_has_no_privileges_on_relations_listed_without_api_access(self, session): + ungranted = sorted(name for name, relation in RELATIONS.items() if relation.api is ApiAccess.NONE) + granted = ( + session.execute( + text( + "SELECT DISTINCT table_name FROM information_schema.role_table_grants WHERE grantee = :r AND table_name = ANY(:t)" + ), + {"r": API_ROLE, "t": ungranted}, + ) + .scalars() + .all() + ) + + assert granted == [] + + def test_api_keeps_grants_on_tables_score_set_delete_cascades_through(self, session): + # Score set delete loads these collections in the ORM, so revoking them would break it (#827, G1). + for table in ( + "mapped_variants", + "gnomad_variants_mapped_variants", + "mapped_variants_clinical_controls", + "target_gene_mappings", + "keywords", + "scoreset_keywords", + "experiment_keywords", + "experiment_set_keywords", + ): + assert _has_privileges(session, API_ROLE, table, ["SELECT", "DELETE"]), table + + +@pytest.mark.integration +class TestRefreshMatViews: + def test_worker_refreshes_through_the_function(self, login_as): + with Session(login_as(WORKER_ROLE)) as session: + refresh_all_mat_views(session) + refresh_all_mat_views(session, concurrently=False) + session.commit() + + def test_worker_cannot_refresh_directly(self, login_as): + with login_as(WORKER_ROLE).connect() as conn, pytest.raises(ProgrammingError, match="must be owner"): + conn.execute(text("REFRESH MATERIALIZED VIEW published_variants_materialized_view")) + + def test_api_cannot_execute_the_function(self, login_as): + with Session(login_as(API_ROLE)) as session, pytest.raises(ProgrammingError, match="permission denied"): + refresh_all_mat_views(session) + + def test_function_given_a_table_raises(self, login_as): + with Session(login_as(WORKER_ROLE)) as session, pytest.raises(Exception, match="not a materialized view"): + session.execute(text("SELECT mavedb_refresh_mat_views('scoresets'::regclass)")) + + def test_migration_creates_the_function_the_template_does(self): + migration = (API_ROOT / "alembic" / "versions" / "4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py").read_text() + + assert REFRESH_MAT_VIEWS_FUNCTION.statement.strip() in migration + + +@pytest.fixture +def replayed_database(postgresql, superuser): + """Return an engine on a new database set up for the roles and upgraded to head as the migrate login.""" + database = f"{postgresql.info.dbname}_replayed" + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f"CREATE DATABASE {database} TEMPLATE template0")) + engine = create_engine(_url(postgresql, database), poolclass=NullPool) + with engine.begin() as conn: + setup(conn) + + env = { + **os.environ, + "DB_HOST": postgresql.info.host, + "DB_PORT": str(postgresql.info.port), + "DB_DATABASE_NAME": database, + "DB_USERNAME": MIGRATE_ROLE, + "DB_PASSWORD": TEST_ROLE_PASSWORD, + } + subprocess.run([sys.executable, "-m", "alembic", "upgrade", "head"], cwd=API_ROOT, env=env, check=True) + + yield engine + engine.dispose() + with superuser.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + conn.execute(text(f"DROP DATABASE IF EXISTS {database} WITH (FORCE)")) + + +@pytest.mark.integration +class TestMigrationReplay: + def test_upgrade_leaves_owner_owned_schema_and_worker_only_function(self, replayed_database, login_as): + with replayed_database.connect() as conn: + owners = ( + conn.execute( + text( + "SELECT DISTINCT relowner::regrole::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm', 'S')" + ) + ) + .scalars() + .all() + ) + executors = ( + conn.execute( + text( + "SELECT r FROM unnest(ARRAY['public', :api, :worker]) r " + "WHERE has_function_privilege(r, 'mavedb_refresh_mat_views(regclass, boolean)', 'EXECUTE')" + ), + {"api": API_ROLE, "worker": WORKER_ROLE}, + ) + .scalars() + .all() + ) + function_owner = conn.execute( + text("SELECT proowner::regrole::text FROM pg_proc WHERE proname = 'mavedb_refresh_mat_views'") + ).scalar_one() + database = conn.execute(text("SELECT current_database()")).scalar_one() + + assert owners == [OWNER_ROLE] + assert function_owner == OWNER_ROLE + assert executors == [WORKER_ROLE] + with Session(login_as(WORKER_ROLE, database)) as session: + refresh_all_mat_views(session) + + def test_upgrade_every_relation_and_function_is_listed(self, replayed_database): + # A new table, view or function fails here until rls.py says who may use it. + with replayed_database.connect() as conn: + relations = 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', 'v', 'm')" + ) + ).scalars() + ) + functions = conn.execute( + text( + "SELECT p.proname, p.prosecdef FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + "WHERE n.nspname = 'public'" + ) + ).all() + + assert sorted(relations - RELATIONS.keys()) == [] + assert sorted(name for name, _ in functions if name not in FUNCTIONS) == [] + assert ( + sorted( + name for name, definer in functions if name in FUNCTIONS and FUNCTIONS[name].security_definer != definer + ) + == [] + ) + + def test_upgrade_guarded_relations_read_as_the_caller_and_definers_pin_search_path(self, replayed_database): + # A guarded view that reads as its owner, or a guarded materialized view, would skip the policies the + # entry promises; a SECURITY DEFINER function with an open search_path runs whatever a caller plants. + with replayed_database.connect() as conn: + relations = conn.execute( + text( + "SELECT c.relname, c.relkind, coalesce((SELECT o.option_value::boolean " + "FROM pg_options_to_table(c.reloptions) o WHERE o.option_name = 'security_invoker'), false) " + "FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND c.relkind IN ('v', 'm')" + ) + ).all() + definers = conn.execute( + text( + "SELECT p.proname, p.proconfig FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace " + "WHERE n.nspname = 'public' AND p.prosecdef" + ) + ).all() + + guarded = {name for name, relation in RELATIONS.items() if relation.api is ApiAccess.GUARDED} + assert ( + sorted(name for name, kind, invoker in relations if name in guarded and (kind == "m" or not invoker)) == [] + ) + assert ( + sorted(name for name, config in definers if not any(c.startswith("search_path=") for c in config or [])) + == [] + ) + + 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. + with replayed_database.connect() as conn: + kinds = dict( + conn.execute( + text( + "SELECT c.relname, c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'f', 'v', 'm')" + ) + ).all() + ) + sequence_tables = dict( + conn.execute( + text( + "SELECT s.relname, t.relname FROM pg_class s JOIN pg_namespace n ON n.oid = s.relnamespace " + "LEFT JOIN pg_depend d ON d.classid = 'pg_class'::regclass AND d.objid = s.oid " + "AND d.refclassid = 'pg_class'::regclass AND d.deptype IN ('a', 'i') " + "LEFT JOIN pg_class t ON t.oid = d.refobjid WHERE n.nspname = 'public' AND s.relkind = 'S'" + ) + ).all() + ) + function_names = set( + conn.execute( + text( + "SELECT p.proname FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'public'" + ) + ).scalars() + ) + grants = _grants(conn) + function_grants = _grants(conn, FUNCTION_GRANTS) + + expected = {} + for name, kind in kinds.items(): + privileges = TABLE_PRIVILEGES if kind in ("r", "p", "f") else {"SELECT"} + expected[name] = {(role, p) for role in _expected_grantees(name) for p in privileges} + for sequence, table in sequence_tables.items(): + expected[sequence] = {(role, p) for role in _expected_grantees(table) for p in ("USAGE", "SELECT")} + expected_functions = { + name: {(role, "EXECUTE") for role in FUNCTIONS[name].executors} + for name in function_names & FUNCTIONS.keys() + } + + assert {name: grants.get(name, set()) for name in expected} == expected + assert {name: function_grants.get(name, set()) for name in function_names} == { + name: expected_functions.get(name, set()) for name in function_names + } diff --git a/tests/db/test_principal.py b/tests/db/test_principal.py index 61c55d690..3c9251691 100644 --- a/tests/db/test_principal.py +++ b/tests/db/test_principal.py @@ -24,7 +24,7 @@ from tests.helpers.constants import ADMIN_USER, TEST_USER from tests.helpers.util.access_key import create_api_key_for_user -# What #809's app_user_id() and app_roles() will read. A connection that has carried a transaction-local value +# What #809's mavedb_user_id() and mavedb_roles() will read. A connection that has carried a transaction-local value # reads '' afterwards, which these casts must turn into NULL rather than an error. _READ_PRINCIPAL = text( "SELECT current_setting('app.user_id', true) AS user_id," diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py new file mode 100644 index 000000000..e327ed99c --- /dev/null +++ b/tests/routers/test_api_role.py @@ -0,0 +1,151 @@ +# ruff: noqa: E402 + +"""Routes whose writes reach tables the api's grants treat specially, run as the api's own login (#827). + +The rest of the suite connects as a superuser. Fixture helpers that stand in for the worker keep that session; +only the app's own database session logs in as ``mavedb_api``. +""" + +import json + +import pytest +from sqlalchemy import select +from sqlalchemy.orm import Session + +arq = pytest.importorskip("arq") +cdot = pytest.importorskip("cdot") +fastapi = pytest.importorskip("fastapi") + +from mavedb.db.rls import API_ROLE +from mavedb.deps import get_db +from mavedb.lib.authentication import UserData, get_current_user +from mavedb.lib.authorization import require_current_user +from mavedb.models.annotation_event import AnnotationEvent +from mavedb.models.enums.annotation_type import AnnotationType +from mavedb.models.enums.disposition import Disposition +from mavedb.models.enums.sequence_level import SequenceLevel +from mavedb.models.experiment import Experiment as ExperimentDbModel +from mavedb.models.legacy_keyword import LegacyKeyword +from mavedb.models.mapped_variant import MappedVariant +from mavedb.models.score_set import ScoreSet as ScoreSetDbModel +from mavedb.models.target_gene import TargetGene +from mavedb.models.target_gene_mapping import TargetGeneMapping +from mavedb.models.user import User +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 + + +@pytest.fixture +def api_role_client(app_, client, login_as): + """The test client, with the app's database session logged in as the api role.""" + api_session = Session(login_as(API_ROLE)) + + def override_get_db(): + try: + yield api_session + finally: + api_session.close() + + def override_user(): + user = api_session.scalars(select(User).where(User.username == TEST_USER["username"])).one() + yield UserData(user, user.roles) + + app_.dependency_overrides[get_db] = override_get_db + app_.dependency_overrides[get_current_user] = override_user + app_.dependency_overrides[require_current_user] = override_user + yield client + api_session.close() + + +def _add_legacy_keyword(session, record) -> None: + keyword = LegacyKeyword(text=f"legacy-{record.urn}") + record.legacy_keyword_objs = [keyword] + session.commit() + + +def _add_target_gene_mapping(session, score_set_urn: str) -> None: + score_set = session.scalars(select(ScoreSetDbModel).where(ScoreSetDbModel.urn == score_set_urn)).one() + for target_gene in score_set.target_genes: + session.add( + TargetGeneMapping(target_gene_id=target_gene.id, alignment_level=SequenceLevel.cdna, tool_version="test") + ) + session.commit() + + +@pytest.mark.integration +def test_delete_score_set_as_api_role_deletes_through_its_cascades( + session, data_provider, api_role_client, setup_router_db, data_files +): + experiment = create_experiment(api_role_client) + score_set = create_seq_score_set_with_mapped_variants( + api_role_client, session, data_provider, experiment["urn"], data_files / "scores.csv" + ) + _add_target_gene_mapping(session, score_set["urn"]) + db_score_set = session.scalars(select(ScoreSetDbModel).where(ScoreSetDbModel.urn == score_set["urn"])).one() + variant_ids = [variant.id for variant in db_score_set.variants] + session.add( + AnnotationEvent( + annotation_type=AnnotationType.VRS_MAPPING, + variant_id=variant_ids[0], + disposition=Disposition.PRESENT, + reason="mapped", + ) + ) + session.commit() + _add_legacy_keyword(session, db_score_set) + + response = api_role_client.delete(f"/api/v1/score-sets/{score_set['urn']}") + + assert response.status_code == 200 + session.expire_all() + assert not session.scalars(select(Variant).where(Variant.id.in_(variant_ids))).first() + assert not session.scalars(select(MappedVariant).where(MappedVariant.variant_id.in_(variant_ids))).first() + assert not session.scalars(select(AnnotationEvent).where(AnnotationEvent.variant_id.in_(variant_ids))).first() + + +@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_removes_old_targets( + session, api_role_client, setup_router_db, mock_publication_fetch +): + experiment = create_experiment(api_role_client) + score_set = create_seq_score_set(api_role_client, experiment["urn"]) + _add_target_gene_mapping(session, score_set["urn"]) + old_target_ids = [ + target.id + for target in session.scalars(select(ScoreSetDbModel).where(ScoreSetDbModel.urn == score_set["urn"])) + .one() + .target_genes + ] + + 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 + session.expire_all() + assert not session.scalars(select(TargetGene).where(TargetGene.id.in_(old_target_ids))).first() + assert not session.scalars( + select(TargetGeneMapping).where(TargetGeneMapping.target_gene_id.in_(old_target_ids)) + ).first() + + +@pytest.mark.integration +def test_read_and_delete_experiment_with_legacy_keywords_as_api_role(session, api_role_client, setup_router_db): + experiment = create_experiment(api_role_client) + db_experiment = session.scalars(select(ExperimentDbModel).where(ExperimentDbModel.urn == experiment["urn"])).one() + _add_legacy_keyword(session, db_experiment) + + assert api_role_client.get(f"/api/v1/experiments/{experiment['urn']}").status_code == 200 + response = api_role_client.delete(f"/api/v1/experiments/{experiment['urn']}") + + assert response.status_code == 200 + session.expire_all() + assert not session.scalars(select(ExperimentDbModel).where(ExperimentDbModel.urn == experiment["urn"])).first() From 00c9c15d02fe4ed3aba267eab7997559d57b7129 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 11:41:56 -0800 Subject: [PATCH 3/9] feat(worker): set the worker's lock timeout on its role The worker set lock_timeout on every connection it opened, because it shared a login with the api. It has its own login now, so the limit lives on the role (ALTER ROLE mavedb_worker SET lock_timeout, from the role bootstrap), and the on-connect SET and DB_WORKER_LOCK_TIMEOUT_SECONDS go. --- src/mavedb/db/timeouts.py | 38 +++++++------------------ src/mavedb/worker/settings/lifecycle.py | 3 -- tests/db/test_timeouts.py | 14 --------- 3 files changed, 10 insertions(+), 45 deletions(-) diff --git a/src/mavedb/db/timeouts.py b/src/mavedb/db/timeouts.py index 43ae8c7cd..c650b6ed5 100644 --- a/src/mavedb/db/timeouts.py +++ b/src/mavedb/db/timeouts.py @@ -1,8 +1,9 @@ -"""Database timeouts for the API and the worker. +"""Database timeouts for the API. -Each process sets its limits on each connection it opens, so scripts and migrations, which share the same login +The API sets its limits on each connection it opens, so scripts and migrations, which share the same login and legitimately run long statements, are unaffected. Prod connects to RDS directly; behind RDS -Proxy these session-level ``SET``s would pin every connection and belong on the login instead. +Proxy these session-level ``SET``s would pin every connection and belong on the login instead. The worker has +a login of its own, so its limit is set on the login (``mavedb.db.bootstrap``). """ import logging @@ -17,20 +18,20 @@ logger = logging.getLogger(__name__) -# Each limit is in seconds and can be overridden from the environment; 0 disables it, as in Postgres. -# The prod API load balancer's idle timeout is 60s. A statement's limit plus the 10s pool wait stays under it. +# All limits are in seconds and may be overridden from the environment. 0 disables the limit. API_STATEMENT_TIMEOUT_SECONDS = int(os.getenv("DB_STATEMENT_TIMEOUT_SECONDS", "30")) +"""The statement timeout in seconds for regular API queries.""" CSV_STATEMENT_TIMEOUT_SECONDS = int(os.getenv("DB_CSV_STATEMENT_TIMEOUT_SECONDS", "45")) +"""The statement timeout in seconds for CSV exports.""" # Below the statement timeout, so API writes queued behind a worker's bulk write fail fast. API_LOCK_TIMEOUT_SECONDS = int(os.getenv("DB_LOCK_TIMEOUT_SECONDS", "5")) +"""The lock timeout in seconds for regular API queries.""" # Above the longest legitimate gap between statements inside one request's transaction. API_IDLE_IN_TRANSACTION_TIMEOUT_SECONDS = int(os.getenv("DB_IDLE_IN_TRANSACTION_TIMEOUT_SECONDS", "60")) -# The worker's jobs share one event loop and their database calls are synchronous, so a call waiting on a lock -# stalls every job on the worker, the lock's holder included when it is another job on the same worker. The -# worker sets only this limit, since its jobs legitimately run long statements and idle in transactions. -WORKER_LOCK_TIMEOUT_SECONDS = int(os.getenv("DB_WORKER_LOCK_TIMEOUT_SECONDS", "60")) +"""The idle-in-transaction timeout in seconds for regular API queries.""" # Not a limit: statements slower than this are logged so the limits above can be tuned from real data. SLOW_STATEMENT_SECONDS = float(os.getenv("DB_SLOW_STATEMENT_SECONDS", "5")) +"""The threshold in seconds for logging slow statements.""" _STARTED_AT_ATTR = "_mavedb_statement_started_at" _SLOW_STATEMENT_LOG_LENGTH = 200 @@ -58,25 +59,6 @@ def apply_api_timeouts(engine: Engine) -> None: event.listen(engine, "connect", _set_api_timeouts) -def _set_worker_timeouts(dbapi_connection, _connection_record) -> None: - cursor = dbapi_connection.cursor() - try: - cursor.execute(f"SET lock_timeout = '{WORKER_LOCK_TIMEOUT_SECONDS}s'") - finally: - cursor.close() - - dbapi_connection.commit() - - -def apply_worker_timeouts(engine: Engine) -> None: - """Apply the worker's lock timeout to every new connection of ``engine``. Safe to call repeatedly. - - Call this before the first connection is opened: connections already in the pool are not touched. - """ - if not event.contains(engine, "connect", _set_worker_timeouts): - event.listen(engine, "connect", _set_worker_timeouts) - - def allow_long_statements(db: Session, seconds: int = CSV_STATEMENT_TIMEOUT_SECONDS) -> None: """Raise ``statement_timeout`` for the rest of the current transaction. diff --git a/src/mavedb/worker/settings/lifecycle.py b/src/mavedb/worker/settings/lifecycle.py index 6c5c2fe75..5cfc81558 100644 --- a/src/mavedb/worker/settings/lifecycle.py +++ b/src/mavedb/worker/settings/lifecycle.py @@ -10,8 +10,6 @@ from concurrent import futures from mavedb.data_providers.services import cdot_rest, seqrepo_data_proxy -from mavedb.db.session import engine -from mavedb.db.timeouts import apply_worker_timeouts from mavedb.worker.settings.constants import MAX_JOBS @@ -47,7 +45,6 @@ def standalone_ctx(): async def startup(ctx): - apply_worker_timeouts(engine) ctx["pool"] = process_pool() diff --git a/tests/db/test_timeouts.py b/tests/db/test_timeouts.py index a645c37a2..1e16003e7 100644 --- a/tests/db/test_timeouts.py +++ b/tests/db/test_timeouts.py @@ -16,7 +16,6 @@ CSV_STATEMENT_TIMEOUT_SECONDS, allow_long_statements, apply_api_timeouts, - apply_worker_timeouts, observe_statements, ) from mavedb.lib.logging.context import logging_context, logging_context_scope @@ -76,19 +75,6 @@ def test_other_engines_are_unbounded(self, engine): assert _show(conn, "statement_timeout") == "0" -@pytest.mark.unit -class TestApplyWorkerTimeouts: - def test_apply_worker_timeouts_new_connections_bound_only_lock_waits(self, engine): - worker_engine = create_engine(engine.url, poolclass=NullPool) - apply_worker_timeouts(worker_engine) - apply_worker_timeouts(worker_engine) # idempotent - - with worker_engine.connect() as conn: - assert _show(conn, "lock_timeout") == "1min" - assert _show(conn, "statement_timeout") == "0" - assert _show(conn, "idle_in_transaction_session_timeout") == "0" - - @pytest.mark.unit class TestObserveStatements: def test_logs_a_slow_statement_without_its_parameters(self, session, engine, caplog): From a06fbd1edc880dc38b86504be0c13e88e19facf9 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 11:41:58 -0800 Subject: [PATCH 4/9] ci: replay migrations as mavedb_migrate after role setup The replay job sets the database up as the master user, then migrates as mavedb_migrate, as a new deployment does. A migration that needs more than the owner's rights, or a database left without its roles, now fails here instead of at deploy. --- .github/workflows/run-tests-on-push.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/run-tests-on-push.yml b/.github/workflows/run-tests-on-push.yml index 3eb003fdb..aea72a56e 100644 --- a/.github/workflows/run-tests-on-push.yml +++ b/.github/workflows/run-tests-on-push.yml @@ -63,7 +63,13 @@ jobs: - run: pip install --upgrade pip - run: pip install poetry - run: poetry install --with dev --extras server + # As a new deployment does: set the database up as the master user, migrate as mavedb_migrate, and upgrade. + - run: poetry run python -m mavedb.scripts.bootstrap_roles setup --commit + - run: psql "postgresql://postgres:postgres@localhost:5432/mavedb" -c "ALTER ROLE mavedb_migrate PASSWORD 'migrate'" - run: poetry run alembic upgrade head + env: + DB_USERNAME: mavedb_migrate + DB_PASSWORD: migrate - name: Check there is exactly one head run: test "$(poetry run alembic heads | wc -l)" -eq 1 From e009047d7b02769b93af5f4c20fc85f43617cb1d Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 12:01:46 -0800 Subject: [PATCH 5/9] docs(db): restore dumps without switching to the owner The restore steps set session_replication_role, then SET ROLE mavedb_owner. The public dump sets session_replication_role itself, and after the switch Postgres checks that against the owner, which may not set it, so the load failed before writing anything. The master user now borrows the owner's privileges by membership and loads as itself. --- alembic/README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/alembic/README.md b/alembic/README.md index 22ce31fcb..fa9e625a5 100644 --- a/alembic/README.md +++ b/alembic/README.md @@ -58,17 +58,16 @@ A migration may create only what `mavedb_owner` can own: tables, views, function ### Restoring a dump -Loading a data-only dump with `session_replication_role = replica`, which skips foreign key checks and triggers, is a master user's job. None of the four roles may set it. Locally `postgres` is a superuser. On RDS the master user sets it, then borrows the owner to write its tables and returns it afterwards: +Loading a data-only dump with `session_replication_role = replica`, which skips foreign key checks and triggers, is a master user's job. None of the four roles may set it. Locally `postgres` is a superuser. On RDS the master user borrows the owner's privileges by membership to write its tables, loads the dump as itself, then gives the owner back: ```sql -SET session_replication_role = replica; GRANT mavedb_owner TO CURRENT_USER; -SET ROLE mavedb_owner; --- load the dump -RESET ROLE; +-- load the dump, which sets session_replication_role itself REVOKE mavedb_owner FROM CURRENT_USER; ``` +Don't `SET ROLE mavedb_owner` for the load. `session_replication_role` is checked against the current role, so a dump setting it after the switch is refused. Revoke even if the load fails: the next upgrade refuses a database where the master user still belongs to the owner. The commands are in `mavedb-deployment`'s `docs/database-dumps.md`. + ## Squash log | Baseline revision | Release | Squashed on | From 1c6a507441137b5379074c8f4d433c823bcab2b0 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Thu, 12 Nov 2026 12:23:20 -0800 Subject: [PATCH 6/9] ci: run the test suite on Postgres 15, as production does The pytest jobs started a server from the runner's own Postgres binaries, now 17, while production, the replay job and bin/test-db run 15. Role and privilege rules changed between those versions: from 16 a CREATEROLE user needs ADMIN OPTION to grant itself a role, and 17 checks MAINTAIN, not ownership, before a materialized view refresh. The bootstrap tests failed on behavior production doesn't have. bin/test-db pins the server to 15, and bin/t already uses it when it's running. --- .github/workflows/run-tests-on-push.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/run-tests-on-push.yml b/.github/workflows/run-tests-on-push.yml index aea72a56e..9636b5586 100644 --- a/.github/workflows/run-tests-on-push.yml +++ b/.github/workflows/run-tests-on-push.yml @@ -85,6 +85,9 @@ jobs: - run: pip install --upgrade pip - run: pip install poetry - run: poetry install --with dev + # Postgres 15, as in production, rather than the runner's own newer server: role and privilege rules + # differ between major versions, and bin/t picks the container up. + - run: bin/test-db up - name: Run fast tests on PRs if: github.event_name == 'pull_request' run: bin/t tests/ -n logical -m "not network and not slow" @@ -104,6 +107,7 @@ jobs: - run: pip install --upgrade pip - run: pip install poetry - run: poetry install --with dev + - run: bin/test-db up - name: Run fast tests on PRs if: github.event_name == 'pull_request' run: bin/t tests/ -n logical -m "not network and not slow" @@ -125,6 +129,7 @@ jobs: - run: pip install --upgrade pip - run: pip install poetry - run: poetry install --with dev --extras server + - run: bin/test-db up - name: Run fast tests with coverage on PRs if: github.event_name == 'pull_request' run: | From ee1f6c4aedb62503622655ebc6d65bb685b6a2e8 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Mon, 30 Nov 2026 10:31:09 -0800 Subject: [PATCH 7/9] fix(db): chain the refresh function migration after the annotation_event drop It revised 020b7e003efd, which annotation_status (9a73f37ec1bc) and the annotation_event drop (4cb129146996) have since built on, leaving two heads once this branch took in integration/rls-baseline. --- alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py b/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py index 09e1aa54c..e9ebc1caf 100644 --- a/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py +++ b/alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py @@ -7,7 +7,7 @@ ``REFRESH_MAT_VIEWS_FUNCTION`` in ``mavedb.db.view``. Revision ID: 4b8e2c7d1f3a -Revises: 020b7e003efd +Revises: 4cb129146996 Create Date: 2026-11-06 """ @@ -16,7 +16,7 @@ # revision identifiers, used by Alembic. revision = "4b8e2c7d1f3a" -down_revision = "020b7e003efd" +down_revision = "4cb129146996" branch_labels = None depends_on = None From ae36d33177bdf69094fdd7195ad7c03d6a7009a4 Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Mon, 30 Nov 2026 10:31:10 -0800 Subject: [PATCH 8/9] fix(db): list annotation_status in the grants registry in place of annotation_event The cutover dropped annotation_event and v_current_annotation_events. annotation_status and v_annotation_status_current take the same entry: only the worker and operator scripts read them, so the api gets no grant. The api-role delete test now plants an annotation_status row, so it still proves a score set delete reaches the worker-only table through the foreign key and not through the api's own session. --- src/mavedb/db/rls.py | 4 ++-- tests/db/test_bootstrap.py | 6 +++--- tests/routers/test_api_role.py | 8 +++++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/mavedb/db/rls.py b/src/mavedb/db/rls.py index e6f47ca4f..f5a0d22df 100644 --- a/src/mavedb/db/rls.py +++ b/src/mavedb/db/rls.py @@ -140,9 +140,9 @@ class Relation: "experiment_keywords": CARVE_OUT, "experiment_set_keywords": CARVE_OUT, # Only the worker and operator scripts read these. A route that needs one adds a policy and moves it. - "annotation_event": WORKER_ONLY, + "annotation_status": WORKER_ONLY, "variant_annotation_status": WORKER_ONLY, - "v_current_annotation_events": WORKER_ONLY, + "v_annotation_status_current": 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. "v_variant_annotations": WORKER_ONLY, diff --git a/tests/db/test_bootstrap.py b/tests/db/test_bootstrap.py index e6fb9a164..047b0e611 100644 --- a/tests/db/test_bootstrap.py +++ b/tests/db/test_bootstrap.py @@ -367,12 +367,12 @@ def test_apply_grants_leaves_exactly_the_listed_grants(self, postgresql, fresh_d setup(conn) conn.execute(text(f"SET LOCAL ROLE {OWNER_ROLE}")) conn.execute(text("CREATE TABLE licenses (id serial PRIMARY KEY)")) - conn.execute(text("CREATE TABLE annotation_event (id serial PRIMARY KEY)")) + conn.execute(text("CREATE TABLE annotation_status (id serial PRIMARY KEY)")) conn.execute(text("CREATE TABLE widgets (id serial PRIMARY KEY)")) conn.execute(text("CREATE FUNCTION unlisted() RETURNS int LANGUAGE sql AS 'SELECT 1'")) # Stray grants, as a migration or an operator could leave them. conn.execute(text("GRANT SELECT ON widgets TO PUBLIC")) - conn.execute(text(f"GRANT ALL ON annotation_event TO {fresh_api_role}")) + conn.execute(text(f"GRANT ALL ON annotation_status TO {fresh_api_role}")) conn.execute(text(f"GRANT TRUNCATE ON licenses TO {WORKER_ROLE}")) conn.execute(text(f"GRANT EXECUTE ON FUNCTION unlisted() TO PUBLIC, {fresh_api_role}")) with engine.begin() as conn: @@ -386,7 +386,7 @@ def test_apply_grants_leaves_exactly_the_listed_grants(self, postgresql, fresh_d dml = {(role, p) for role in (fresh_api_role, WORKER_ROLE) for p in TABLE_PRIVILEGES} assert grants["licenses"] == dml assert grants["licenses_id_seq"] == {(r, p) for r in (fresh_api_role, WORKER_ROLE) for p in ("USAGE", "SELECT")} - assert grants["annotation_event"] == {(WORKER_ROLE, p) for p in TABLE_PRIVILEGES} + assert grants["annotation_status"] == {(WORKER_ROLE, p) for p in TABLE_PRIVILEGES} assert "widgets" not in grants assert "widgets_id_seq" not in grants assert "unlisted" not in function_grants diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py index e327ed99c..c7cde72fd 100644 --- a/tests/routers/test_api_role.py +++ b/tests/routers/test_api_role.py @@ -20,10 +20,11 @@ from mavedb.deps import get_db from mavedb.lib.authentication import UserData, get_current_user from mavedb.lib.authorization import require_current_user -from mavedb.models.annotation_event import AnnotationEvent +from mavedb.models.annotation_status import AnnotationStatus from mavedb.models.enums.annotation_type import AnnotationType from mavedb.models.enums.disposition import Disposition from mavedb.models.enums.sequence_level import SequenceLevel +from mavedb.models.enums.status_kind import StatusKind from mavedb.models.experiment import Experiment as ExperimentDbModel from mavedb.models.legacy_keyword import LegacyKeyword from mavedb.models.mapped_variant import MappedVariant @@ -86,8 +87,9 @@ def test_delete_score_set_as_api_role_deletes_through_its_cascades( db_score_set = session.scalars(select(ScoreSetDbModel).where(ScoreSetDbModel.urn == score_set["urn"])).one() variant_ids = [variant.id for variant in db_score_set.variants] session.add( - AnnotationEvent( + AnnotationStatus( annotation_type=AnnotationType.VRS_MAPPING, + kind=StatusKind.OUTCOME, variant_id=variant_ids[0], disposition=Disposition.PRESENT, reason="mapped", @@ -102,7 +104,7 @@ def test_delete_score_set_as_api_role_deletes_through_its_cascades( session.expire_all() assert not session.scalars(select(Variant).where(Variant.id.in_(variant_ids))).first() assert not session.scalars(select(MappedVariant).where(MappedVariant.variant_id.in_(variant_ids))).first() - assert not session.scalars(select(AnnotationEvent).where(AnnotationEvent.variant_id.in_(variant_ids))).first() + assert not session.scalars(select(AnnotationStatus).where(AnnotationStatus.variant_id.in_(variant_ids))).first() @pytest.mark.integration From f10a077756ff391e5956167ceacc12de9bf47e9e Mon Sep 17 00:00:00 2001 From: Benjamin Capodanno Date: Mon, 30 Nov 2026 11:04:34 -0800 Subject: [PATCH 9/9] test(db): take the api-role client's stand-ins off the app at teardown api_role_client put its own session and user on the shared app and never took them off. The app fixture re-installs its own stand-ins for each test, which hid the leak, but any test that signs in for real would have been answered by the stale user, bound to a closed session. --- tests/routers/test_api_role.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/routers/test_api_role.py b/tests/routers/test_api_role.py index c7cde72fd..be9da3c06 100644 --- a/tests/routers/test_api_role.py +++ b/tests/routers/test_api_role.py @@ -58,6 +58,9 @@ def override_user(): app_.dependency_overrides[require_current_user] = override_user yield client api_session.close() + # Every test shares the app, so a stand-in left here would sign later tests in through a closed session. + for dependency in (get_db, get_current_user, require_current_user): + app_.dependency_overrides.pop(dependency, None) def _add_legacy_keyword(session, record) -> None: