Files
mtusi2026lab7/student-tests/unit/test_db_roles.py
T

604 lines
25 KiB
Python

"""Лаба 7: роли PostgreSQL процессов и ACL Valkey (перенос storage-roles).
Без стенда. Матрица `src/db_roles.py` сверяется:
- со схемой (`src/storage/tables.py`): строка на каждую таблицу, колонки
`UPDATE` есть в таблице;
- с SQL хранилища: `METHOD_NEEDS` — что делает SQL каждого метода
`PostgresStorage` и `PostgresPipeline` (S — SELECT, I — INSERT, D — DELETE, U
— UPDATE колонок, L — блокировка строки); у нового метода нет строки — тест
красный. Записи (`update(…).values(…)`, `insert`, `delete`, `ON CONFLICT DO
UPDATE`, `with_for_update`) таблица сверяет с исходным кодом метода сама
(AST), чтения — вручную;
- с процессами: какие методы зовёт процесс, тест находит в его модулях (AST
вызовов `storage.` / `pipeline.`), и права роли должны быть **равны**
объединению потребностей этих методов — недостающее и лишнее право красные.
Ещё: построители SQL (кавычки, имена базы, верификатор), SCRAM-верификатор,
проверка настроек bootstrap (имена без значений), клиент Valkey (пользователь
ACL, без `CLIENT SETINFO`) и учётные данные сервисов в `compose.yaml` — каждому
своя роль, суперпользователь только у `postgres` и `postgres-bootstrap`.
Права на настоящем PostgreSQL — `make storage-roles-check` на стенде и
`make test-isolated` / `make failure-checks` (журнал без «permission denied»).
"""
import ast
import inspect
import os
import re
import subprocess
import sys
import textwrap
from pathlib import Path
import pytest
from src import db_roles
from src.cache import create_cache
from src.config import Cache, Settings
from src.db_bootstrap import settings_problems
from src.storage.pipeline import PostgresPipeline
from src.storage.postgres import PostgresStorage
from src.storage.tables import metadata
pytestmark = pytest.mark.unit
ROOT = Path(__file__).resolve().parents[2]
def need(
*,
s: bool = False,
i: bool = False,
d: bool = False,
u: tuple[str, ...] = (),
lock: bool = False,
) -> dict:
return {"S": s, "I": i, "D": d, "U": frozenset(u), "L": lock}
_JOB_RETRY = ("state", "lease_until", "published_at", "next_attempt_at", "last_error")
# метод хранилища → таблица → что делает его SQL
METHOD_NEEDS: dict[str, dict[str, dict]] = {
# --- PostgresStorage: API ---
"ping": {},
"create_user": {"users": need(s=True, i=True)},
"get_credentials": {"users": need(s=True)},
"create_session": {"sessions": need(i=True)},
"create_session_with_rehash": {
"users": need(s=True, u=("password_hash",)),
"sessions": need(i=True),
},
"get_identity": {"sessions": need(s=True), "users": need(s=True)},
"delete_session": {"sessions": need(s=True, d=True)},
"create_chat": {
"users": need(s=True),
"chats": need(i=True),
"chat_members": need(i=True),
},
"get_chat": {"chats": need(s=True), "chat_members": need(s=True)},
"list_chats_of": {"chats": need(s=True), "chat_members": need(s=True)},
"create_message": {
"attachments": need(s=True),
"idempotency_keys": need(
s=True, i=True, u=("request_hash", "message_id", "created_at")
),
"messages": need(s=True, i=True),
"message_attachments": need(s=True, i=True),
},
"list_messages": {"messages": need(s=True), "message_attachments": need(s=True)},
"create_pending_attachment": {"attachments": need(i=True)},
"queue_attachment": {
"attachments": need(s=True, u=("status", "updated_at")),
"attachment_jobs": need(i=True),
},
"count_unfinished_jobs": {"attachment_jobs": need(s=True)},
"get_attachment": {
"attachments": need(s=True),
"attachment_variants": need(s=True),
},
# --- PostgresStorage: уборщик и сверка ---
"list_stale_pending": {"attachments": need(s=True)},
"mark_pending_removing": {
"attachments": need(s=True, u=("updated_at",), lock=True)
},
"remove_stale_pending": {"attachments": need(s=True, d=True, lock=True)},
"list_staging_done": {"attachments": need(s=True)},
"clear_staging": {"attachments": need(s=True, u=("staging_key",), lock=True)},
"attachments_by_ids": {"attachments": need(s=True)},
"attachment_references": {"attachments": need(s=True)},
"ready_page": {"attachments": need(s=True)},
"mark_attachment_lost": {"attachments": need(s=True, u=("lost_at",))},
"clear_attachment_lost": {"attachments": need(s=True, u=("lost_at",))},
# --- PostgresPipeline: worker ---
"claim_job": {
"attachment_jobs": need(
s=True, u=("state", "lease_until", "updated_at"), lock=True
),
"attachments": need(s=True, u=("status", "updated_at")),
},
"finish_job": {
"attachment_jobs": need(
s=True, u=("state", "lease_until", "last_error", "updated_at"), lock=True
),
# ON CONFLICT (ключ эффекта) DO NOTHING читает цель конфликта
"attachment_variants": need(s=True, i=True),
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
},
"retry_job": {
"attachment_jobs": need(s=True, u=(*_JOB_RETRY, "updated_at"), lock=True),
"attachments": need(s=True, u=("status", "updated_at")),
},
"fail_job": {
"attachment_jobs": need(
s=True, u=("state", "lease_until", "last_error", "updated_at"), lock=True
),
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
},
# --- PostgresPipeline: relay и replay ---
"publish_due": {
"attachment_jobs": need(
s=True, u=("attempt", "published_at", "updated_at"), lock=True
)
},
"recover_leases": {
"attachment_jobs": need(s=True, u=(*_JOB_RETRY, "updated_at"), lock=True),
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
},
"republish_lost": {
"attachment_jobs": need(s=True, u=("published_at", "updated_at"), lock=True)
},
"list_failed": {"attachment_jobs": need(s=True), "attachments": need(s=True)},
"replay_job": {
"attachment_jobs": need(
s=True, u=(*_JOB_RETRY, "attempt_base", "updated_at"), lock=True
),
"attachments": need(
s=True, u=("status", "error_code", "updated_at"), lock=True
),
"attachment_job_replays": need(i=True),
},
"pipeline_counts": {"attachment_jobs": need(s=True)},
}
# модули процесса: в них тест ищет вызовы методов хранилища
PROCESS_MODULES = {
"api": (
"src/services/users.py",
"src/services/sessions.py",
"src/services/chats.py",
"src/services/messages.py",
"src/services/attachments.py",
"src/services/access.py",
"src/api/routes/health.py",
),
"worker": ("src/services/processing.py", "src/worker/main.py"),
"relay": ("src/services/relay.py", "src/services/replay.py", "src/relay/main.py"),
"cleaner": (
"src/services/cleanup.py",
"src/services/reconcile.py",
"src/cleaner/main.py",
),
}
# имена, через которые процессы держат хранилище
_HOLDERS = {"storage", "_storage", "pipeline", "_pipeline"}
_STORAGE_CLASSES = (PostgresStorage, PostgresPipeline)
def _storage_methods() -> set[str]:
return {
name
for cls in _STORAGE_CLASSES
for name, member in vars(cls).items()
if not name.startswith("_") and inspect.iscoroutinefunction(member)
}
def _called_methods(path: str) -> set[str]:
"""`<…>.storage.<метод>(` и т. п. в модуле процесса."""
tree = ast.parse((ROOT / path).read_text(encoding="utf-8"))
found = set()
for node in ast.walk(tree):
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
continue
holder = node.func.value
name = (
holder.attr
if isinstance(holder, ast.Attribute)
else getattr(holder, "id", None)
)
if name in _HOLDERS:
found.add(node.func.attr)
return found
def _process_methods(process: str) -> set[str]:
methods = set()
for path in PROCESS_MODULES[process]:
methods |= _called_methods(path)
return methods & _storage_methods()
def _grant_of(needs: list[dict]) -> db_roles.TableGrant:
update: set[str] = set()
for item in needs:
update |= item["U"]
return db_roles.TableGrant(
select=any(item["S"] for item in needs),
insert=any(item["I"] for item in needs),
delete=any(item["D"] for item in needs),
update=frozenset(update),
)
def test_matrix_covers_schema() -> None:
assert set(db_roles.TABLES) == set(metadata.tables)
for role, tables in db_roles.MATRIX.items():
assert set(tables) == set(db_roles.TABLES), role
for table, grant in tables.items():
columns = set(metadata.tables[table].c.keys())
assert grant.update <= columns, (role, table, grant.update - columns)
def test_every_storage_method_has_needs() -> None:
assert _storage_methods() == set(METHOD_NEEDS)
for method, tables in METHOD_NEEDS.items():
for table, item in tables.items():
assert table in metadata.tables, (method, table)
assert item["U"] <= set(metadata.tables[table].c.keys()), (method, table)
# имена таблиц в исходном коде хранилища (переменные tables.py)
_TABLE_NAMES = set(metadata.tables)
def _method_tree(method: str) -> ast.Module:
"""Исходный код метода вместе с вспомогательными `self._x(…)` класса и
`_x(…)` модуля (`_new_session`, `_stale_lock`, `_fenced`): запрос часто
строит помощник."""
cls = next(c for c in _STORAGE_CLASSES if method in vars(c))
module = sys.modules[cls.__module__]
seen: set[str] = set()
bodies: list[ast.stmt] = []
queue = [vars(cls)[method]]
while queue:
func = queue.pop()
tree = ast.parse(textwrap.dedent(inspect.getsource(func)))
bodies.extend(tree.body)
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
name, helper = None, None
if isinstance(node.func, ast.Attribute) and isinstance(
node.func.value, ast.Name
):
if node.func.value.id == "self" and node.func.attr.startswith("_"):
name = node.func.attr
helper = vars(cls).get(name)
elif isinstance(node.func, ast.Name) and node.func.id.startswith("_"):
name = node.func.id
helper = getattr(module, name, None)
if name and name not in seen and inspect.isfunction(helper):
seen.add(name)
queue.append(helper)
return ast.Module(body=bodies, type_ignores=[])
def _method_writes(method: str) -> dict[str, dict]:
"""Записи метода по его исходному коду: таблица → I / D / U колонок, и
есть ли в нём блокировка строки (`with_for_update`)."""
tree = _method_tree(method)
writes: dict[str, dict] = {}
def table(node: ast.AST) -> str | None:
return (
node.id if isinstance(node, ast.Name) and node.id in _TABLE_NAMES else None
)
def base_table(call: ast.AST) -> str | None:
# update(t).where(…).values(…): спуститься по цепочке до update(t)
while isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute):
call = call.func.value
if (
isinstance(call, ast.Call)
and isinstance(call.func, ast.Name)
and call.func.id == "update"
and call.args
):
return table(call.args[0])
return None
def insert_table(call: ast.AST) -> str | None:
# pg_insert(t).values(…).on_conflict_…(…): до pg_insert(t)
while isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute):
call = call.func.value
if (
isinstance(call, ast.Call)
and isinstance(call.func, ast.Name)
and call.func.id in ("insert", "pg_insert")
and call.args
):
return table(call.args[0])
return None
def entry(name: str) -> dict:
return writes.setdefault(name, {"I": False, "D": False, "U": set(), "S": False})
lock = False
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
func = node.func
if isinstance(func, ast.Name) and func.id in (
"insert",
"pg_insert",
"sa_delete",
):
name = table(node.args[0]) if node.args else None
if name:
entry(name)["D" if func.id == "sa_delete" else "I"] = True
if isinstance(func, ast.Attribute):
if func.attr == "insert" and table(func.value):
entry(func.value.id)["I"] = True
if func.attr == "values":
name = base_table(func.value)
if name:
entry(name)["U"] |= {kw.arg for kw in node.keywords if kw.arg}
if func.attr == "on_conflict_do_update":
for kw in node.keywords:
if kw.arg == "set_" and isinstance(kw.value, ast.Dict):
keys = {
k.value
for k in kw.value.keys
if isinstance(k, ast.Constant)
}
writes.setdefault("on_conflict", {"U": set()})["U"] |= keys
# ON CONFLICT (цель) читает колонки цели: нужен SELECT (на стенде
# без него — «permission denied for table attachment_variants»)
if func.attr in ("on_conflict_do_nothing", "on_conflict_do_update") and any(
kw.arg == "index_elements" for kw in node.keywords
):
name = insert_table(func.value)
if name:
entry(name)["S"] = True
if func.attr == "with_for_update":
lock = True
writes["lock"] = {"L": lock}
return writes
@pytest.mark.parametrize("method", sorted(METHOD_NEEDS))
def test_method_needs_match_source_writes(method: str) -> None:
writes = _method_writes(method)
needs = METHOD_NEEDS[method]
assert writes.pop("lock")["L"] == any(item["L"] for item in needs.values())
conflict = writes.pop("on_conflict", {"U": set()})["U"]
if conflict:
assert any(conflict <= item["U"] and item["I"] for item in needs.values())
for name, write in writes.items():
item = needs.get(name)
assert item is not None, (method, name)
assert write["I"] == item["I"], (method, name, "INSERT")
assert write["D"] == item["D"], (method, name, "DELETE")
assert write["U"] <= item["U"], (method, name, write["U"] - item["U"])
if write["S"]:
assert item["S"], (method, name, "SELECT for ON CONFLICT")
for name, item in needs.items():
if item["I"] or item["D"]:
assert name in writes, (method, name)
def test_processes_use_only_their_storage() -> None:
storage = {name for name in vars(PostgresStorage) if not name.startswith("_")}
pipeline = {name for name in vars(PostgresPipeline) if not name.startswith("_")}
assert _process_methods("api") <= storage
assert _process_methods("cleaner") <= storage
assert _process_methods("worker") <= pipeline
assert _process_methods("relay") <= pipeline
# каждый метод хранилища зовёт хоть один процесс (иначе матрица неполна)
used = set().union(*(_process_methods(p) for p in PROCESS_MODULES))
assert used == set(METHOD_NEEDS)
@pytest.mark.parametrize("role", db_roles.PROCESS_ROLES)
def test_role_grants_equal_needs_of_its_queries(role: str) -> None:
methods = _process_methods(role)
assert methods, role
for table in db_roles.TABLES:
needs = [METHOD_NEEDS[m][table] for m in methods if table in METHOD_NEEDS[m]]
expected = _grant_of(needs) if needs else db_roles.NO_GRANT
assert db_roles.MATRIX[role][table] == expected, (role, table)
# блокировке строки (FOR UPDATE / NO KEY UPDATE) нужен UPDATE хотя бы
# одной колонки этой таблицы у роли
if any(item["L"] for item in needs):
assert db_roles.MATRIX[role][table].update, (role, table)
def test_privilege_statements() -> None:
full = db_roles.privilege_statements()
assert full[0] == (
'REVOKE ALL ON ALL TABLES IN SCHEMA "public" FROM PUBLIC, "api", '
'"worker", "relay", "cleaner"'
)
assert any(s.startswith('REVOKE CREATE ON SCHEMA "public"') for s in full[:3])
assert 'GRANT SELECT, INSERT, DELETE ON "public"."sessions" TO "api"' in full
assert 'GRANT UPDATE ("password_hash") ON "public"."users" TO "api"' in full
assert not any('"migrate"' in s for s in full)
# на ревизии ниже head: только существующие таблицы и колонки
partial = db_roles.privilege_statements(
{"users": {"id", "password_hash"}, "attachments": {"id", "status"}}
)
assert not any('"sessions"' in s for s in partial)
assert 'GRANT UPDATE ("status") ON "public"."attachments" TO "api"' in partial
assert not any("updated_at" in s for s in partial)
def test_sql_builders_reject_bad_input() -> None:
assert db_roles.quote_ident('a"b') == '"a""b"'
with pytest.raises(ValueError, match="must match"):
db_roles.check_database_name("messenger; DROP")
with pytest.raises(ValueError, match="must match"):
db_roles.database_access_sql("Bad-Name")
with pytest.raises(ValueError, match="not a SCRAM"):
db_roles.set_password_sql("api", "plain password")
with pytest.raises(ValueError, match="unknown object kind"):
db_roles.object_owner_sql("FUNCTION", "f")
with pytest.raises(ValueError, match="not a maintenance"):
db_roles.maintenance_database_sql("messenger")
with pytest.raises(ValueError, match="printable ASCII"):
db_roles.check_role_password("")
with pytest.raises(ValueError, match="printable ASCII"):
db_roles.check_role_password("пароль")
assert db_roles.revoke_membership_sql("relay", "pg_read_all_data", "boss") == (
'REVOKE "pg_read_all_data" FROM "relay" GRANTED BY "boss"'
)
assert "NOINHERIT" in db_roles.create_role_sql("api")
assert "NOSUPERUSER" in db_roles.alter_role_sql("api")
assert db_roles.QUIET_SESSION_SQL[0] == "SET search_path = pg_catalog"
def test_scram_verifier() -> None:
verifier = db_roles.scram_verifier("s3cret pass", salt=b"0123456789abcdef")
assert re.fullmatch(db_roles.SCRAM_VERIFIER_PATTERN, verifier)
assert verifier.startswith("SCRAM-SHA-256$4096:MDEyMzQ1Njc4OWFiY2RlZg==$")
assert db_roles.verifier_matches(verifier, "s3cret pass")
assert not db_roles.verifier_matches(verifier, "other")
assert not db_roles.verifier_matches(None, "s3cret pass")
assert not db_roles.verifier_matches("md5abc", "s3cret pass")
# соль случайная: два верификатора одного пароля разные
assert db_roles.scram_verifier("x") != db_roles.scram_verifier("x")
assert "s3cret" not in db_roles.set_password_sql("api", verifier)
_ROLE_ENV = {
f"DB_ROLE_{role.upper()}_PASSWORD": f"{role}-password"
for role in db_roles.ALL_ROLES
}
def test_bootstrap_settings_problems_name_variables_only() -> None:
good = Settings.from_env(
{
**_ROLE_ENV,
"DB_USER": "messenger",
"DB_PASSWORD": "x",
"DB_NAME": "messenger",
}
)
assert settings_problems(good) == []
assert "api-password" not in repr(good)
bad = Settings.from_env(
{
**_ROLE_ENV,
"DB_ROLE_API_PASSWORD": "",
"DB_ROLE_WORKER_PASSWORD": "пароль",
"DB_USER": "api",
"DB_NAME": "Bad",
}
)
assert settings_problems(bad) == [
"DB_ROLE_API_PASSWORD",
"DB_ROLE_WORKER_PASSWORD",
"DB_NAME",
"DB_USER",
"DB_PASSWORD",
]
def test_bootstrap_exits_2_without_values() -> None:
env = {
"PATH": os.environ.get("PATH", ""),
**_ROLE_ENV,
"DB_ROLE_RELAY_PASSWORD": "",
"DB_PASSWORD": "superuser-secret",
}
done = subprocess.run(
[sys.executable, "-m", "src.db_bootstrap"],
cwd=ROOT,
env=env,
capture_output=True,
text=True,
timeout=60,
check=False,
)
assert done.returncode == 2
assert "DB_ROLE_RELAY_PASSWORD" in done.stderr
assert "password" not in done.stderr.replace("_PASSWORD", "")
assert "superuser-secret" not in done.stdout + done.stderr
def test_cache_user_and_no_client_setinfo() -> None:
settings = Settings.from_env({"CACHE_USER": "api", "CACHE_PASSWORD": "pw"})
assert settings.cache.user == "api"
assert Cache().user == ""
ca = ROOT / ".pki" / "stand" / "ca.crt"
if not ca.is_file():
pytest.skip("no stand CA (make pki-stand) to build the TLS context")
cache = create_cache(settings.cache, namespace="messenger", ca_file=str(ca))
kwargs = cache._client.connection_pool.connection_kwargs
assert kwargs["username"] == "api"
assert kwargs["driver_info"] is None
def _compose_services() -> dict[str, str]:
"""Блоки сервисов compose.yaml текстом (отступ в два пробела)."""
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
body = text.split("\nservices:\n", 1)[1].split("\nnetworks:\n", 1)[0]
blocks: dict[str, str] = {}
name = ""
for line in body.splitlines():
found = re.match(r"^ ([a-z0-9-]+):$", line)
if found:
name = found.group(1)
blocks[name] = ""
elif name:
blocks[name] += line + "\n"
return blocks
def test_compose_credentials_per_service() -> None:
blocks = _compose_services()
for role, service in (
("api", "api"),
("worker", "worker"),
("relay", "relay"),
("cleaner", "cleaner"),
("migrate", "migrate"),
):
block = blocks[service]
assert f"DB_USER: {role}\n" in block, service
# пароля роли в окружении нет ни своего, ни чужого: процесс читает его из
# OpenBao (перенос openbao-secrets, test_openbao_config.py)
assert "DB_PASSWORD" not in block, service
for other in db_roles.ALL_ROLES:
assert f"POSTGRES_{other.upper()}_PASSWORD" not in block, (service, other)
with_superuser = {
name for name, block in blocks.items() if "${POSTGRES_PASSWORD:" in block
}
assert with_superuser == {"postgres", "postgres-bootstrap"}
with_operator = {
name for name, block in blocks.items() if "VALKEY_OPERATOR_PASSWORD" in block
}
assert with_operator == {"valkey"}
assert "CACHE_USER: api" in (ROOT / "compose.yaml").read_text(encoding="utf-8")
assert (
"postgres-bootstrap:\n condition: service_completed_successfully"
in (blocks["migrate"])
)
def test_valkey_acl_script() -> None:
script = (ROOT / "infra" / "valkey" / "start.sh").read_text(encoding="utf-8")
assert "user default off" in script
assert "+get +set +eval +evalsha +ttl +expire +incr +decr +del" in script
# ключи api — префикс кэша и счётчиков входа своей базы (src/constants.py)
from src.constants import CACHE_KEY_PREFIX
assert f'CACHE_KEY_PREFIX="{CACHE_KEY_PREFIX}"' in script
assert "+@all" not in script.split("user api", 1)[1].split("\n", 1)[0]
done = subprocess.run(
["sh", "-n", str(ROOT / "infra" / "valkey" / "start.sh")], check=False
)
assert done.returncode == 0