Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .claude/rules/rls.md
Original file line number Diff line number Diff line change
@@ -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`.
11 changes: 11 additions & 0 deletions .github/workflows/run-tests-on-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -79,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"
Expand All @@ -98,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"
Expand All @@ -119,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: |
Expand Down
28 changes: 27 additions & 1 deletion alembic/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,33 @@ 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 borrows the owner's privileges by membership to write its tables, loads the dump as itself, then gives the owner back:

```sql
GRANT mavedb_owner TO CURRENT_USER;
-- 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

Expand Down
12 changes: 1 addition & 11 deletions alembic/baseline/c5e1a9d4b7f2.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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';


--
Expand Down
6 changes: 6 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
57 changes: 57 additions & 0 deletions alembic/versions/4b8e2c7d1f3a_add_mavedb_refresh_mat_views.py
Original file line number Diff line number Diff line change
@@ -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: 4cb129146996
Create Date: 2026-11-06

"""

from alembic import op

# revision identifiers, used by Alembic.
revision = "4b8e2c7d1f3a"
down_revision = "4cb129146996"
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)")
11 changes: 9 additions & 2 deletions bin/build-baseline
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 9 additions & 1 deletion bin/check-migrations
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ step for large indexes.
"""

import ast
import re
import sys
from pathlib import Path

Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading