forked from mtusi2026/mtusi2026lab7
OpenBao 2.7.3 (raft, TLS 1.3 with client certificates) holds the PostgreSQL role passwords, the Valkey password and the S3 keys; each process logs in with its own mTLS identity, reads only its paths and renews its token in the background. Operator init, unseal, configure and seed go through infra/openbao/bao.py and make bao_*; checks are make bao_check and driver.py openbao-outage. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
476 lines
19 KiB
Python
476 lines
19 KiB
Python
"""Права ролей во временной базе (change `storage-roles`, design, решения 2–5,
|
||
10; спек `storage-access`).
|
||
|
||
Каталог после `alembic upgrade head` = матрица `src/infra/db/roles.py`;
|
||
лишнее право, выданное вручную, снимает повторный `upgrade`; `downgrade -1` и
|
||
снова `upgrade` сводят права; `alembic check` их не трогает; `--sql` печатает
|
||
`GRANT`. Отказы ролей — в откатываемых транзакциях: таблицы и строки не
|
||
меняются. Посторонняя роль кластера к базе не подключается. Правки verify:
|
||
права `PUBLIC` снимает `upgrade` (W1), членство и права на базу — bootstrap
|
||
(W1), откат на несколько ревизий и промежуточная ревизия сводятся (W2), роли
|
||
процессов не входят в служебные базы `postgres` и `template1` (S6).
|
||
"""
|
||
|
||
import uuid
|
||
from collections.abc import AsyncIterator
|
||
|
||
import asyncpg
|
||
import pytest
|
||
|
||
from conftest import (
|
||
ROLE_PASSWORDS,
|
||
TEST_DB,
|
||
_bootstrap_roles,
|
||
admin,
|
||
run_alembic,
|
||
settings,
|
||
)
|
||
from src.infra.db import roles
|
||
from src.infra.tls import build_client_context
|
||
|
||
pytestmark = pytest.mark.anyio
|
||
|
||
# права уровня таблицы, кроме тех, что бывают в матрице: их нет ни у кого
|
||
_FORBIDDEN_TABLE_PRIVILEGES = ("TRUNCATE", "REFERENCES", "TRIGGER")
|
||
|
||
_TABLE_GRANTS_SQL = """
|
||
SELECT c.relname, x.grantee::regrole::text AS grantee, x.privilege_type
|
||
FROM pg_class c
|
||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||
CROSS JOIN LATERAL aclexplode(c.relacl) x
|
||
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'S')
|
||
AND x.grantee <> c.relowner
|
||
"""
|
||
|
||
_COLUMN_GRANTS_SQL = """
|
||
SELECT c.relname, a.attname, x.grantee::regrole::text AS grantee,
|
||
x.privilege_type
|
||
FROM pg_attribute a
|
||
JOIN pg_class c ON c.oid = a.attrelid
|
||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||
CROSS JOIN LATERAL aclexplode(a.attacl) x
|
||
WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p')
|
||
"""
|
||
|
||
|
||
def _alembic(*args: str) -> str:
|
||
"""alembic ролью migrate в процессе теста (секция роли — подстановкой,
|
||
change `openbao-secrets`); вывод `--sql` — текстом."""
|
||
return run_alembic(*args)
|
||
|
||
|
||
async def _connect(role: str, database: str = TEST_DB) -> asyncpg.Connection:
|
||
source = settings.database
|
||
return await asyncpg.connect(
|
||
host=source.host,
|
||
port=source.port,
|
||
user=role,
|
||
password=ROLE_PASSWORDS[role],
|
||
database=database,
|
||
timeout=source.connect_timeout_seconds,
|
||
ssl=build_client_context(settings.client_tls.ca_file),
|
||
)
|
||
|
||
|
||
async def _catalog() -> dict[str, dict[str, roles.TableGrant]]:
|
||
"""Права ролей процессов по каталогу: роль → таблица → права."""
|
||
connection = await admin()
|
||
try:
|
||
table_rows = await connection.fetch(_TABLE_GRANTS_SQL)
|
||
column_rows = await connection.fetch(_COLUMN_GRANTS_SQL)
|
||
finally:
|
||
await connection.close()
|
||
found: dict[str, dict[str, dict[str, object]]] = {}
|
||
for row in table_rows:
|
||
entry = found.setdefault(row["grantee"], {}).setdefault(
|
||
row["relname"],
|
||
{"privileges": set(), "update": set()},
|
||
)
|
||
entry["privileges"].add(row["privilege_type"])
|
||
for row in column_rows:
|
||
entry = found.setdefault(row["grantee"], {}).setdefault(
|
||
row["relname"],
|
||
{"privileges": set(), "update": set()},
|
||
)
|
||
if row["privilege_type"] == "UPDATE":
|
||
entry["update"].add(row["attname"])
|
||
else:
|
||
entry["privileges"].add(f"column {row['privilege_type']}")
|
||
result: dict[str, dict[str, roles.TableGrant]] = {}
|
||
for grantee, tables in found.items():
|
||
for table, entry in tables.items():
|
||
privileges = entry["privileges"]
|
||
unexpected = privileges - {"SELECT", "INSERT", "DELETE"}
|
||
# лишнее право уровня таблицы (UPDATE на всю таблицу и пр.) —
|
||
# отдельной строкой: его в матрице не бывает
|
||
result.setdefault(grantee, {})[table] = roles.TableGrant(
|
||
select="SELECT" in privileges,
|
||
insert="INSERT" in privileges,
|
||
delete="DELETE" in privileges,
|
||
update=frozenset(
|
||
entry["update"] | {f"<{p}>" for p in unexpected},
|
||
),
|
||
)
|
||
return result
|
||
|
||
|
||
def _expected() -> dict[str, dict[str, roles.TableGrant]]:
|
||
return {
|
||
role: {
|
||
table: grant
|
||
for table, grant in roles.MATRIX[role].items()
|
||
if not grant.is_empty
|
||
}
|
||
for role in roles.PROCESS_ROLES
|
||
}
|
||
|
||
|
||
async def _assert_catalog_matches_matrix() -> None:
|
||
catalog = await _catalog()
|
||
# права есть только у ролей процессов (владелец migrate в aclexplode
|
||
# исключён); PUBLIC и прочие роли прав на таблицы не имеют
|
||
assert set(catalog) <= set(roles.PROCESS_ROLES), sorted(catalog)
|
||
actual = {role: catalog.get(role, {}) for role in roles.PROCESS_ROLES}
|
||
assert actual == _expected()
|
||
|
||
|
||
@pytest.fixture
|
||
async def converged() -> AsyncIterator[None]:
|
||
"""Права до и после теста — матрица (тест мог выдать лишнее)."""
|
||
yield
|
||
_alembic("upgrade", "head")
|
||
|
||
|
||
async def test_catalog_matches_matrix() -> None:
|
||
await _assert_catalog_matches_matrix()
|
||
|
||
|
||
async def test_owner_and_attributes() -> None:
|
||
connection = await admin()
|
||
try:
|
||
owners = await connection.fetch(
|
||
"SELECT c.relname, pg_get_userbyid(c.relowner) AS owner "
|
||
"FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||
"WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p', 'i', 'S')",
|
||
)
|
||
schema_owner = await connection.fetchval(roles.SCHEMA_OWNER_SQL)
|
||
attributes = await connection.fetch(
|
||
"SELECT rolname, rolsuper, rolcreatedb, rolcreaterole, "
|
||
"rolreplication, rolbypassrls, rolinherit, rolcanlogin "
|
||
"FROM pg_roles WHERE rolname = ANY($1::text[])",
|
||
list(roles.ALL_ROLES),
|
||
)
|
||
members = await connection.fetch(
|
||
roles.MEMBERSHIP_SQL,
|
||
list(roles.ALL_ROLES),
|
||
)
|
||
privileges = await connection.fetch(
|
||
"SELECT r AS role, "
|
||
"has_database_privilege(r, $1, 'CONNECT') AS can_connect, "
|
||
"has_database_privilege(r, $1, 'CREATE') AS db_create, "
|
||
"has_database_privilege(r, $1, 'TEMP') AS db_temp, "
|
||
"has_schema_privilege(r, 'public', 'CREATE') AS schema_create "
|
||
"FROM unnest($2::text[]) r",
|
||
TEST_DB,
|
||
list(roles.ALL_ROLES),
|
||
)
|
||
public_connect = await connection.fetchval(
|
||
"SELECT count(*) FROM pg_database d, aclexplode(d.datacl) x "
|
||
"WHERE d.datname = $1 AND x.grantee = 0",
|
||
TEST_DB,
|
||
)
|
||
finally:
|
||
await connection.close()
|
||
assert schema_owner == roles.MIGRATE_ROLE
|
||
assert {row["owner"] for row in owners} == {roles.MIGRATE_ROLE}
|
||
assert {row["relname"] for row in owners} >= set(roles.TABLES) | {
|
||
"alembic_version",
|
||
}
|
||
assert len(attributes) == len(roles.ALL_ROLES)
|
||
for row in attributes:
|
||
assert row["rolcanlogin"], row["rolname"]
|
||
assert not any(
|
||
row[name]
|
||
for name in (
|
||
"rolsuper",
|
||
"rolcreatedb",
|
||
"rolcreaterole",
|
||
"rolreplication",
|
||
"rolbypassrls",
|
||
"rolinherit",
|
||
)
|
||
), row["rolname"]
|
||
assert members == []
|
||
by_role = {row["role"]: row for row in privileges}
|
||
for role in roles.ALL_ROLES:
|
||
assert by_role[role]["can_connect"], role
|
||
assert not by_role[role]["db_create"], role
|
||
assert not by_role[role]["db_temp"], role
|
||
assert by_role[role]["schema_create"] is (role == roles.MIGRATE_ROLE)
|
||
assert public_connect == 0
|
||
|
||
|
||
async def test_extra_grant_removed_by_upgrade(converged: None) -> None:
|
||
"""Спек `storage-access`, «Лишнее право снимается миграцией»."""
|
||
connection = await admin()
|
||
try:
|
||
await connection.execute("GRANT INSERT ON public.users TO worker")
|
||
await connection.execute(
|
||
"GRANT UPDATE (filename) ON public.attachments TO worker",
|
||
)
|
||
await connection.execute("GRANT TRUNCATE ON public.messages TO api")
|
||
finally:
|
||
await connection.close()
|
||
catalog = await _catalog()
|
||
assert catalog["worker"]["users"].insert
|
||
assert "filename" in catalog["worker"]["attachments"].update
|
||
# alembic check права не трогает
|
||
_alembic("check")
|
||
assert (await _catalog())["worker"]["users"].insert
|
||
_alembic("upgrade", "head")
|
||
await _assert_catalog_matches_matrix()
|
||
|
||
|
||
async def test_public_grant_removed_by_upgrade(converged: None) -> None:
|
||
"""Verify W1, спек `storage-access`, «Право PUBLIC снимается сведением»:
|
||
права `PUBLIC` на таблицы, колонки и `CREATE` в схеме снимает `upgrade`."""
|
||
connection = await admin()
|
||
try:
|
||
await connection.execute(
|
||
"GRANT UPDATE, DELETE ON public.messages TO PUBLIC",
|
||
)
|
||
await connection.execute("GRANT SELECT ON public.sessions TO PUBLIC")
|
||
await connection.execute(
|
||
"GRANT UPDATE (filename) ON public.attachments TO PUBLIC",
|
||
)
|
||
await connection.execute("GRANT CREATE ON SCHEMA public TO PUBLIC")
|
||
finally:
|
||
await connection.close()
|
||
# права PUBLIC видны в каталоге (grantee 0 — не роль процесса)
|
||
assert set(await _catalog()) - set(roles.PROCESS_ROLES)
|
||
_alembic("upgrade", "head")
|
||
await _assert_catalog_matches_matrix()
|
||
connection = await admin()
|
||
try:
|
||
schema_create = await connection.fetchval(
|
||
"SELECT has_schema_privilege('worker', 'public', 'CREATE')",
|
||
)
|
||
finally:
|
||
await connection.close()
|
||
assert schema_create is False
|
||
|
||
|
||
async def test_bootstrap_removes_membership_and_database_rights() -> None:
|
||
"""Verify W1: членство роли процесса в другой роли — в том числе выданное
|
||
не суперпользователем bootstrap — и права на базу сверх `CONNECT` снимает
|
||
повторный bootstrap ролей."""
|
||
grantor = f"test_uow_grantor_{uuid.uuid4().hex[:8]}"
|
||
connection = await admin()
|
||
try:
|
||
await connection.execute("GRANT pg_read_all_data TO worker")
|
||
await connection.execute(
|
||
f"CREATE ROLE {roles.quote_ident(grantor)} NOLOGIN",
|
||
)
|
||
await connection.execute(
|
||
f"GRANT pg_read_all_data TO {roles.quote_ident(grantor)} "
|
||
"WITH ADMIN OPTION",
|
||
)
|
||
await connection.execute(f"SET ROLE {roles.quote_ident(grantor)}")
|
||
await connection.execute("GRANT pg_read_all_data TO relay")
|
||
await connection.execute("RESET ROLE")
|
||
await connection.execute(
|
||
f'GRANT CREATE, TEMPORARY ON DATABASE "{TEST_DB}" TO worker',
|
||
)
|
||
assert await connection.fetch(
|
||
roles.MEMBERSHIP_SQL,
|
||
list(roles.ALL_ROLES),
|
||
)
|
||
finally:
|
||
await connection.close()
|
||
try:
|
||
await _bootstrap_roles()
|
||
connection = await admin()
|
||
try:
|
||
members = await connection.fetch(
|
||
roles.MEMBERSHIP_SQL,
|
||
list(roles.ALL_ROLES),
|
||
)
|
||
rights = await connection.fetchrow(
|
||
"SELECT has_database_privilege('worker', $1, 'CREATE') AS c, "
|
||
"has_database_privilege('worker', $1, 'TEMP') AS t, "
|
||
"has_database_privilege('worker', $1, 'CONNECT') AS connect",
|
||
TEST_DB,
|
||
)
|
||
finally:
|
||
await connection.close()
|
||
assert [tuple(row) for row in members] == []
|
||
assert not rights["c"]
|
||
assert not rights["t"]
|
||
assert rights["connect"]
|
||
finally:
|
||
# уборка и при красном тесте: отсутствующее членство — WARNING
|
||
connection = await admin()
|
||
try:
|
||
await connection.execute("REVOKE pg_read_all_data FROM worker")
|
||
await connection.execute(
|
||
"REVOKE pg_read_all_data FROM relay GRANTED BY "
|
||
f"{roles.quote_ident(grantor)}",
|
||
)
|
||
await connection.execute(
|
||
f'REVOKE CREATE, TEMPORARY ON DATABASE "{TEST_DB}" FROM worker',
|
||
)
|
||
await connection.execute(f"DROP ROLE {roles.quote_ident(grantor)}")
|
||
finally:
|
||
await connection.close()
|
||
|
||
|
||
async def test_downgrade_and_upgrade_converge(converged: None) -> None:
|
||
_alembic("downgrade", "-1")
|
||
catalog = await _catalog()
|
||
for role in roles.PROCESS_ROLES:
|
||
assert catalog.get(role, {}) == _expected()[role], role
|
||
_alembic("upgrade", "head")
|
||
await _assert_catalog_matches_matrix()
|
||
|
||
|
||
async def test_multi_revision_downgrade_converges(converged: None) -> None:
|
||
"""Verify W2, спек `db-migrations`, «Откат на несколько ревизий»: колонки
|
||
`GRANT UPDATE (…)`, которых на ревизии нет, сведение пропускает."""
|
||
_alembic("downgrade", "-3")
|
||
_alembic("upgrade", "head")
|
||
await _assert_catalog_matches_matrix()
|
||
|
||
|
||
async def test_upgrade_to_intermediate_revision_converges(
|
||
converged: None,
|
||
) -> None:
|
||
"""Verify W2: `upgrade` до промежуточной ревизии (до `attachment_jobs` и
|
||
`attachments.error_code`) — права на то, что есть, код 0."""
|
||
_alembic("downgrade", "base")
|
||
_alembic("upgrade", "5c3e1f0a9b7d")
|
||
catalog = await _catalog()
|
||
assert catalog["api"]["users"].insert
|
||
assert "attachment_jobs" not in catalog.get("worker", {})
|
||
# worker: на этой ревизии нет error_code — UPDATE только status, updated_at
|
||
assert catalog["worker"]["attachments"].update == frozenset(
|
||
{"status", "updated_at"},
|
||
)
|
||
_alembic("upgrade", "head")
|
||
await _assert_catalog_matches_matrix()
|
||
|
||
|
||
@pytest.mark.parametrize("database", ["postgres", "template1"])
|
||
async def test_process_roles_cannot_connect_to_maintenance_databases(
|
||
database: str,
|
||
) -> None:
|
||
"""Verify S6: служебные базы кластера ролям процессов закрыты (bootstrap
|
||
снимает `CONNECT` и `TEMP` у `PUBLIC`)."""
|
||
for role in roles.ALL_ROLES:
|
||
with pytest.raises(asyncpg.InsufficientPrivilegeError):
|
||
connection = await _connect(role, database)
|
||
await connection.close()
|
||
|
||
|
||
def test_offline_sql_prints_grants() -> None:
|
||
output = _alembic("upgrade", "head", "--sql")
|
||
assert 'REVOKE ALL ON ALL TABLES IN SCHEMA "public" FROM' in output
|
||
assert 'GRANT INSERT ON "public"."attachment_job_replays" TO "relay"' in (
|
||
output
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("role", "statement"),
|
||
[
|
||
("api", "CREATE TABLE storage_roles_probe (id int)"),
|
||
("worker", "CREATE TABLE storage_roles_probe (id int)"),
|
||
("relay", "ALTER TABLE attachments ADD COLUMN probe int"),
|
||
("cleaner", "DROP TABLE attachment_variants"),
|
||
("worker", "INSERT INTO users (id) SELECT NULL WHERE false"),
|
||
("worker", "INSERT INTO messages (id) SELECT NULL WHERE false"),
|
||
("worker", "SELECT 1 FROM sessions LIMIT 1"),
|
||
("worker", "UPDATE attachments SET filename = 'x' WHERE false"),
|
||
("api", "SELECT 1 FROM attachment_job_replays LIMIT 1"),
|
||
("api", "DELETE FROM attachments WHERE false"),
|
||
("api", "UPDATE attachment_jobs SET state = 'queued' WHERE false"),
|
||
("cleaner", "SELECT 1 FROM users LIMIT 1"),
|
||
(
|
||
"relay",
|
||
"INSERT INTO attachment_variants (attachment_id) "
|
||
"SELECT NULL WHERE false",
|
||
),
|
||
("api", "SELECT 1 FROM alembic_version"),
|
||
("worker", "SELECT pg_read_file('/etc/hostname')"),
|
||
("worker", "COPY (SELECT 1) TO PROGRAM 'true'"),
|
||
("worker", "CREATE ROLE storage_roles_probe"),
|
||
],
|
||
)
|
||
async def test_role_refused(role: str, statement: str) -> None:
|
||
"""Спек `storage-access`, «DDL только у миграций», «worker не трогает
|
||
данные API», «API не трогает конвейер», «Уборщик и relay в своих
|
||
границах»: 42501 в откатываемой транзакции."""
|
||
connection = await _connect(role)
|
||
try:
|
||
transaction = connection.transaction()
|
||
await transaction.start()
|
||
try:
|
||
with pytest.raises(asyncpg.InsufficientPrivilegeError):
|
||
await connection.execute(statement)
|
||
finally:
|
||
await transaction.rollback()
|
||
finally:
|
||
await connection.close()
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("role", "statement"),
|
||
[
|
||
("migrate", "CREATE TABLE storage_roles_probe (id int)"),
|
||
("worker", "UPDATE attachments SET status = 'ready' WHERE false"),
|
||
("worker", "SELECT 1 FROM attachment_jobs FOR UPDATE SKIP LOCKED"),
|
||
("relay", "SELECT 1 FROM attachments FOR NO KEY UPDATE"),
|
||
("cleaner", "DELETE FROM attachments WHERE false"),
|
||
("api", "SELECT 1 FROM sessions LIMIT 1"),
|
||
],
|
||
)
|
||
async def test_role_allowed(role: str, statement: str) -> None:
|
||
"""Контроль: разрешённое матрицей проходит (откатываемая транзакция)."""
|
||
connection = await _connect(role)
|
||
try:
|
||
transaction = connection.transaction()
|
||
await transaction.start()
|
||
try:
|
||
await connection.execute(statement)
|
||
finally:
|
||
await transaction.rollback()
|
||
finally:
|
||
await connection.close()
|
||
|
||
|
||
async def test_stranger_role_cannot_connect() -> None:
|
||
"""Спек `storage-access`, «Посторонняя роль кластера»."""
|
||
name = f"test_uow_stranger_{uuid.uuid4().hex[:8]}"
|
||
password = uuid.uuid4().hex
|
||
connection = await admin()
|
||
try:
|
||
await connection.execute(
|
||
f"CREATE ROLE {roles.quote_ident(name)} LOGIN PASSWORD "
|
||
f"'{password}'",
|
||
)
|
||
try:
|
||
source = settings.database
|
||
with pytest.raises(asyncpg.InsufficientPrivilegeError):
|
||
await asyncpg.connect(
|
||
host=source.host,
|
||
port=source.port,
|
||
user=name,
|
||
password=password,
|
||
database=TEST_DB,
|
||
timeout=source.connect_timeout_seconds,
|
||
ssl=build_client_context(settings.client_tls.ca_file),
|
||
)
|
||
finally:
|
||
await connection.execute(f"DROP ROLE {roles.quote_ident(name)}")
|
||
finally:
|
||
await connection.close()
|