forked from mtusi2026/mtusi2026lab7
feat: separate PostgreSQL roles and Valkey ACL per service
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -252,6 +252,8 @@ ENTRYPOINTS = {
|
||||
"relay": (["-m", "src.relay"], "relay"),
|
||||
"cleaner": (["-m", "src.cleaner", "--once"], "cleaner"),
|
||||
"migrations": (["-m", "alembic", "upgrade", "head"], "migrations"),
|
||||
# bootstrap ролей (change storage-roles): та же проверка до подключения
|
||||
"db_bootstrap": (["-m", "src.db_bootstrap"], "db_bootstrap"),
|
||||
}
|
||||
|
||||
|
||||
@@ -339,11 +341,117 @@ def test_entrypoint_refuses_before_connecting(
|
||||
assert str(tmp_path) not in json.dumps(records)
|
||||
|
||||
|
||||
_ROLE_PASSWORDS = {
|
||||
f"DB_ROLES__{role.upper()}_PASSWORD": f"{role}-secret-value"
|
||||
for role in ("migrate", "api", "worker", "relay", "cleaner")
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("env", "fields"),
|
||||
[
|
||||
(
|
||||
{"DB_ROLES__WORKER_PASSWORD": ""},
|
||||
["db_roles.worker_password"],
|
||||
),
|
||||
(
|
||||
{"DB_ROLES__API_PASSWORD": "пароль"},
|
||||
["db_roles.api_password"],
|
||||
),
|
||||
(
|
||||
{"DATABASE__USER": "api", "DATABASE__NAME": "Bad-Name"},
|
||||
["database.name", "database.user"],
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_db_bootstrap_refuses_settings(
|
||||
pki: Path,
|
||||
env: dict[str, str],
|
||||
fields: list[str],
|
||||
) -> None:
|
||||
"""Спек `storage-access`, «Пустой пароль роли» (change `storage-roles`):
|
||||
код 2 до подключения (порт 1 закрыт: подключение дало бы код 1), запись
|
||||
называет поля, значений паролей в выводе нет."""
|
||||
base = {
|
||||
"CLIENT_TLS__CA_FILE": str(pki / "stand" / "ca.crt"),
|
||||
"DATABASE__PORT": "1",
|
||||
"DATABASE__USER": "messenger",
|
||||
"DATABASE__PASSWORD": "superuser-secret-value",
|
||||
"DATABASE__NAME": "messenger",
|
||||
}
|
||||
code, records = _run_entrypoint(
|
||||
"db_bootstrap",
|
||||
pki,
|
||||
**{**base, **_ROLE_PASSWORDS, **env},
|
||||
)
|
||||
assert code == 2, records
|
||||
refusal = [
|
||||
r for r in records if r["event"] == "Invalid database roles settings"
|
||||
]
|
||||
assert len(refusal) == 1, records
|
||||
assert refusal[0]["fields"] == fields
|
||||
assert refusal[0]["module"] == "db_bootstrap"
|
||||
assert "secret-value" not in json.dumps(records)
|
||||
assert "пароль" not in json.dumps(records, ensure_ascii=False)
|
||||
assert not [r for r in records if r["event"] == "Applying database roles"]
|
||||
|
||||
|
||||
def test_db_bootstrap_unreachable_database_is_code_1(pki: Path) -> None:
|
||||
"""Отказ PostgreSQL (закрытый порт) — код 1 и запись без паролей."""
|
||||
code, records = _run_entrypoint(
|
||||
"db_bootstrap",
|
||||
pki,
|
||||
CLIENT_TLS__CA_FILE=str(pki / "stand" / "ca.crt"),
|
||||
DATABASE__PORT="1",
|
||||
DATABASE__USER="messenger",
|
||||
DATABASE__PASSWORD="superuser-secret-value",
|
||||
DATABASE__NAME="messenger",
|
||||
DATABASE__CONNECT_TIMEOUT_SECONDS="1",
|
||||
**_ROLE_PASSWORDS,
|
||||
)
|
||||
assert code == 1, records
|
||||
assert [
|
||||
r for r in records if r["event"] == "Database roles bootstrap failed"
|
||||
]
|
||||
assert "secret-value" not in json.dumps(records)
|
||||
|
||||
|
||||
def test_cache_pool_user_without_client_setinfo(pki: Path) -> None:
|
||||
"""Пул клиента кэша (change `storage-roles`, design, решение 9):
|
||||
пользователь ACL из `[cache] username`, без `CLIENT SETINFO` — у
|
||||
пользователя `api` этой команды нет."""
|
||||
cache = create_cache(
|
||||
Cache(host="valkey", username="api"),
|
||||
namespace="db",
|
||||
ca_file=str(pki / "stand" / "ca.crt"),
|
||||
)
|
||||
pool = cache._client.connection_pool
|
||||
assert pool.connection_kwargs["username"] == "api"
|
||||
connection = pool.make_connection()
|
||||
assert connection.username == "api"
|
||||
assert connection.driver_info is None
|
||||
# пустой username — пользователь default (на стенде выключен)
|
||||
default = create_cache(
|
||||
Cache(host="valkey"),
|
||||
namespace="db",
|
||||
ca_file=str(pki / "stand" / "ca.crt"),
|
||||
)
|
||||
assert (
|
||||
default._client.connection_pool.connection_kwargs["username"] is None
|
||||
)
|
||||
|
||||
|
||||
# имена команд, которые получил сервер RESP (без аргументов: в AUTH пароль)
|
||||
_RESP_COMMANDS: list[str] = []
|
||||
|
||||
|
||||
async def _resp_session(
|
||||
reader: asyncio.StreamReader,
|
||||
writer: asyncio.StreamWriter,
|
||||
) -> None:
|
||||
"""Сервер RESP из двух ответов: `GET` — значение, прочее — `+OK`."""
|
||||
"""Сервер RESP: `GET` — значение; вход пользователем `default` (на стенде
|
||||
выключен; redis-py 8 входит `HELLO 3 AUTH <пользователь> <пароль>`) —
|
||||
`WRONGPASS`, другим — карта RESP3 `HELLO`; прочее — `+OK`."""
|
||||
with contextlib.suppress(Exception):
|
||||
while line := await reader.readline():
|
||||
count = int(line[1:])
|
||||
@@ -351,8 +459,26 @@ async def _resp_session(
|
||||
for _ in range(count):
|
||||
size = int((await reader.readline())[1:])
|
||||
parts.append((await reader.readexactly(size + 2))[:-2])
|
||||
if parts[0].upper() == b"GET":
|
||||
command = parts[0].upper()
|
||||
if command == b"CLIENT":
|
||||
name = " ".join(p.decode().upper() for p in parts[:2])
|
||||
elif command == b"HELLO" and b"AUTH" in parts:
|
||||
user = parts[parts.index(b"AUTH") + 1].decode()
|
||||
name = f"HELLO AUTH {user}"
|
||||
else:
|
||||
name = command.decode()
|
||||
_RESP_COMMANDS.append(name)
|
||||
if command == b"GET":
|
||||
writer.write(b"$5\r\nvalue\r\n")
|
||||
elif name == "HELLO AUTH default" or (
|
||||
command == b"AUTH" and len(parts) == 2 # noqa: PLR2004
|
||||
):
|
||||
writer.write(
|
||||
b"-WRONGPASS invalid username-password pair or user is "
|
||||
b"disabled.\r\n",
|
||||
)
|
||||
elif command == b"HELLO":
|
||||
writer.write(b"%1\r\n+proto\r\n:3\r\n")
|
||||
else:
|
||||
writer.write(b"+OK\r\n")
|
||||
await writer.drain()
|
||||
@@ -423,3 +549,54 @@ async def test_cache_handshake(
|
||||
assert "CERTIFICATE_VERIFY_FAILED" in recorder.records[0][1]["error"]
|
||||
else:
|
||||
assert events == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("username", "expected"),
|
||||
[("api", "value"), ("", None)],
|
||||
)
|
||||
async def test_cache_acl_user(
|
||||
pki: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
username: str,
|
||||
expected: str | None,
|
||||
) -> None:
|
||||
"""Спек `service-configuration`, «Неверный пользователь — обход кэша»
|
||||
(change `storage-roles`): `api` — вход пользователем `api` и ответ, без
|
||||
`CLIENT SETINFO`; пустой username — вход пользователем `default`, отказ
|
||||
— промах и одна запись «Cache is unavailable» без пароля."""
|
||||
recorder = _Recorder()
|
||||
monkeypatch.setattr(cache_client, "logger", recorder)
|
||||
_RESP_COMMANDS.clear()
|
||||
async with _valkey_tls(pki) as port:
|
||||
cache = create_cache(
|
||||
Cache(
|
||||
host="localhost",
|
||||
port=port,
|
||||
timeout_seconds=2,
|
||||
username=username,
|
||||
password="cache-secret-value",
|
||||
),
|
||||
namespace="db",
|
||||
ca_file=str(pki / "stand" / "ca.crt"),
|
||||
)
|
||||
try:
|
||||
assert await cache.get("key") == expected
|
||||
finally:
|
||||
await cache.aclose()
|
||||
assert not [c for c in _RESP_COMMANDS if c.startswith("CLIENT SETINFO")]
|
||||
if expected is None:
|
||||
assert _RESP_COMMANDS[0] == "HELLO AUTH default"
|
||||
assert [event for event, _ in recorder.records] == [
|
||||
"Cache is unavailable",
|
||||
]
|
||||
assert recorder.records[0][1]["error_type"] == "AuthenticationError"
|
||||
assert "cache-secret-value" not in repr(recorder.records)
|
||||
else:
|
||||
# CLIENT MAINT_NOTIFICATIONS redis-py шлёт в режиме auto и отказ
|
||||
# пропускает; Valkey 9.1 такой подкоманды не знает, в ACL LOG её нет
|
||||
# (проверка стенда — evidence/security/storage-roles.md)
|
||||
assert [
|
||||
c for c in _RESP_COMMANDS if c != "CLIENT MAINT_NOTIFICATIONS"
|
||||
] == ["HELLO AUTH api", "GET"]
|
||||
assert recorder.records == []
|
||||
|
||||
@@ -0,0 +1,474 @@
|
||||
"""Матрица прав ролей PostgreSQL (change `storage-roles`, design, решения 4,
|
||||
13; спек `storage-access`, «Права процессов по матрице»).
|
||||
|
||||
Три сверки без базы:
|
||||
|
||||
- матрица покрывает каждую таблицу моделей у каждой роли процесса, колонки
|
||||
`UPDATE` есть в модели;
|
||||
- матрица роли процесса **ровно** равна объединению потребностей методов
|
||||
repo, которые вызывают сервисы его точки входа (`uow.<repo>.<метод>` по
|
||||
AST): недостающее право — красный тест с процессом, repo и таблицей,
|
||||
лишнее — тоже (least privilege);
|
||||
- потребности каждого вызываемого метода описаны в `METHOD_NEEDS`: новый
|
||||
метод repo без строки — красный тест (правило `repo-layer.md`).
|
||||
|
||||
`METHOD_NEEDS` — что делает SQL метода (`src/core/repos/`): S — `SELECT`
|
||||
(чтение, `WHERE`, `RETURNING`), I — `INSERT`, D — `DELETE`, U — `UPDATE`
|
||||
колонок, L — блокировка строки (`FOR UPDATE` / `FOR NO KEY UPDATE`: хотя бы
|
||||
одна колонка `UPDATE`). Права в каталоге настоящей базы —
|
||||
`service-tests/db/test_db_privileges.py`.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config.settings import BASE_DIR
|
||||
from src.infra.db import roles
|
||||
from src.infra.db.models import Base
|
||||
|
||||
SERVICES_DIR = BASE_DIR / "src" / "core" / "services"
|
||||
SERVICES_PACKAGE = "src.core.services"
|
||||
|
||||
# точки входа процессов: сервисы, которые они создают
|
||||
PROCESS_ENTRY_POINTS = {
|
||||
roles.API_ROLE: BASE_DIR / "src" / "api" / "dependencies.py",
|
||||
roles.WORKER_ROLE: BASE_DIR / "src" / "worker" / "main.py",
|
||||
roles.RELAY_ROLE: BASE_DIR / "src" / "relay" / "main.py",
|
||||
roles.CLEANER_ROLE: BASE_DIR / "src" / "cleaner" / "main.py",
|
||||
}
|
||||
|
||||
_JOB_RETRY = (
|
||||
"state",
|
||||
"last_error_code",
|
||||
"next_attempt_at",
|
||||
"lease_expires_at",
|
||||
"published_at",
|
||||
"updated_at",
|
||||
)
|
||||
|
||||
# (repo, метод) → таблица → потребность; запись: "S", "S,I", "S,L",
|
||||
# "S,U(колонка колонка)"
|
||||
METHOD_NEEDS: dict[tuple[str, str], dict[str, str]] = {
|
||||
("users", "insert_user"): {"users": "S,I"},
|
||||
("users", "get_user_credentials"): {"users": "S"},
|
||||
("users", "update_password_hash"): {"users": "S,U(password_hash)"},
|
||||
("users", "get_existing_user_ids"): {"users": "S"},
|
||||
("sessions", "insert_session"): {"sessions": "I"},
|
||||
("sessions", "get_current_session"): {"sessions": "S", "users": "S"},
|
||||
("sessions", "delete_session"): {"sessions": "S,D"},
|
||||
("chats", "insert_chat"): {"chats": "I"},
|
||||
("chats", "insert_chat_members"): {"chat_members": "I"},
|
||||
("chats", "get_chat"): {"chats": "S", "chat_members": "S"},
|
||||
("chats", "get_user_chats_page"): {"chats": "S", "chat_members": "S"},
|
||||
("messages", "insert_message"): {"messages": "I"},
|
||||
("messages", "insert_message_attachments"): {"message_attachments": "I"},
|
||||
("messages", "get_chat_messages_page"): {
|
||||
"messages": "S",
|
||||
"message_attachments": "S",
|
||||
},
|
||||
("idempotency", "claim_key"): {
|
||||
"idempotency_keys": "S,I,U(request_hash message_id created_at)",
|
||||
},
|
||||
("idempotency", "get_key_result"): {
|
||||
"idempotency_keys": "S",
|
||||
"messages": "S",
|
||||
"message_attachments": "S",
|
||||
},
|
||||
("attachments", "insert_attachment"): {"attachments": "I"},
|
||||
("attachments", "mark_queued"): {"attachments": "S,U(status updated_at)"},
|
||||
("attachments", "mark_processing"): {
|
||||
"attachments": "S,U(status updated_at)",
|
||||
},
|
||||
("attachments", "return_to_queued"): {
|
||||
"attachments": "S,U(status updated_at)",
|
||||
},
|
||||
("attachments", "return_group_to_queued"): {
|
||||
"attachments": "S,U(status updated_at)",
|
||||
},
|
||||
("attachments", "replay_failed"): {
|
||||
"attachments": "S,U(status error_code updated_at)",
|
||||
},
|
||||
("attachments", "lock_attachment"): {"attachments": "S,L"},
|
||||
("attachments", "get_staging_candidates"): {"attachments": "S"},
|
||||
("attachments", "lock_staging_candidate"): {"attachments": "S,L"},
|
||||
("attachments", "clear_staging_key"): {
|
||||
"attachments": "S,U(staging_key)",
|
||||
},
|
||||
("attachments", "commit_ready"): {
|
||||
"attachments": "S,U(status updated_at)",
|
||||
},
|
||||
("attachments", "commit_failed"): {
|
||||
"attachments": "S,U(status error_code updated_at)",
|
||||
},
|
||||
("attachments", "get_attachment"): {"attachments": "S"},
|
||||
("attachments", "get_attachments"): {"attachments": "S"},
|
||||
("attachments", "get_stale_pending"): {"attachments": "S"},
|
||||
("attachments", "lock_stale_pending"): {"attachments": "S,L"},
|
||||
("attachments", "mark_removing"): {"attachments": "S,U(updated_at)"},
|
||||
("attachments", "delete_attachment"): {"attachments": "S,D"},
|
||||
("attachments", "get_attachments_for_objects"): {"attachments": "S"},
|
||||
("attachments", "get_ready_page"): {"attachments": "S"},
|
||||
("attachments", "find_attachment_reference"): {"attachments": "S"},
|
||||
("attachments", "mark_lost"): {"attachments": "S,U(lost_at)"},
|
||||
("attachments", "clear_lost"): {"attachments": "S,U(lost_at)"},
|
||||
("jobs", "insert_job"): {"attachment_jobs": "I"},
|
||||
("jobs", "lock_job"): {"attachment_jobs": "S,L"},
|
||||
("jobs", "get_job"): {"attachment_jobs": "S"},
|
||||
("jobs", "get_attachment_job"): {"attachment_jobs": "S"},
|
||||
("jobs", "start_attempt"): {
|
||||
"attachment_jobs": (
|
||||
"S,U(state attempt lease_expires_at next_attempt_at updated_at)"
|
||||
),
|
||||
},
|
||||
("jobs", "return_to_queued"): {
|
||||
"attachment_jobs": f"S,U({' '.join(_JOB_RETRY)})",
|
||||
},
|
||||
("jobs", "finish_job"): {
|
||||
"attachment_jobs": (
|
||||
"S,U(state lease_expires_at next_attempt_at finished_at "
|
||||
"updated_at last_error_code)"
|
||||
),
|
||||
},
|
||||
("jobs", "lock_due_jobs"): {"attachment_jobs": "S,L"},
|
||||
("jobs", "count_published"): {"attachment_jobs": "S"},
|
||||
("jobs", "count_unfinished"): {"attachment_jobs": "S"},
|
||||
("jobs", "queue_snapshot"): {"attachment_jobs": "S"},
|
||||
("jobs", "mark_published"): {
|
||||
"attachment_jobs": "S,U(published_at updated_at)",
|
||||
},
|
||||
("jobs", "recover_expired_leases"): {
|
||||
"attachment_jobs": f"S,L,U({' '.join(_JOB_RETRY)})",
|
||||
},
|
||||
("jobs", "has_published_before"): {"attachment_jobs": "S"},
|
||||
("jobs", "reset_published_before"): {
|
||||
"attachment_jobs": "S,U(published_at updated_at)",
|
||||
},
|
||||
("jobs", "replay_job"): {
|
||||
"attachment_jobs": (
|
||||
"S,U(state attempt_base last_error_code next_attempt_at "
|
||||
"lease_expires_at published_at finished_at updated_at)"
|
||||
),
|
||||
},
|
||||
("jobs", "list_failed"): {"attachment_jobs": "S", "attachments": "S"},
|
||||
("variants", "insert_variant"): {"attachment_variants": "S,I"},
|
||||
("variants", "get_variants"): {"attachment_variants": "S"},
|
||||
("variants", "get_variant"): {"attachment_variants": "S"},
|
||||
("job_replays", "insert_replay"): {"attachment_job_replays": "I"},
|
||||
("job_replays", "get_job_replays"): {"attachment_job_replays": "S"},
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Need:
|
||||
select: bool = False
|
||||
insert: bool = False
|
||||
delete: bool = False
|
||||
lock: bool = False
|
||||
update: set[str] = field(default_factory=set)
|
||||
|
||||
def add(self, spec: str) -> None:
|
||||
for part in re.findall(r"[SIDL]|U\([^)]*\)", spec):
|
||||
if part == "S":
|
||||
self.select = True
|
||||
elif part == "I":
|
||||
self.insert = True
|
||||
elif part == "D":
|
||||
self.delete = True
|
||||
elif part == "L":
|
||||
self.lock = True
|
||||
else:
|
||||
self.update.update(part[2:-1].split())
|
||||
|
||||
def missing_in(self, grant: roles.TableGrant) -> list[str]:
|
||||
missing = [
|
||||
name
|
||||
for name, needed, granted in (
|
||||
("SELECT", self.select, grant.select),
|
||||
("INSERT", self.insert, grant.insert),
|
||||
("DELETE", self.delete, grant.delete),
|
||||
)
|
||||
if needed and not granted
|
||||
]
|
||||
missing.extend(
|
||||
f"UPDATE({column})"
|
||||
for column in sorted(self.update - grant.update)
|
||||
)
|
||||
if self.lock and not grant.update:
|
||||
missing.append("UPDATE of any column (row lock)")
|
||||
return missing
|
||||
|
||||
|
||||
def _service_modules(entry: Path) -> set[str]:
|
||||
"""Модули сервисов, которые импортирует точка входа, с замыканием по
|
||||
импортам между модулями сервисов."""
|
||||
package = ast.parse((SERVICES_DIR / "__init__.py").read_text())
|
||||
exported = {
|
||||
alias.asname or alias.name: node.module
|
||||
for node in package.body
|
||||
if isinstance(node, ast.ImportFrom) and node.module
|
||||
for alias in node.names
|
||||
}
|
||||
pending: set[str] = set()
|
||||
for node in ast.walk(ast.parse(entry.read_text())):
|
||||
if not isinstance(node, ast.ImportFrom) or node.module is None:
|
||||
continue
|
||||
if node.module == SERVICES_PACKAGE:
|
||||
pending.update(exported[alias.name] for alias in node.names)
|
||||
elif node.module.startswith(f"{SERVICES_PACKAGE}."):
|
||||
pending.add(node.module.removeprefix(f"{SERVICES_PACKAGE}."))
|
||||
seen: set[str] = set()
|
||||
while pending:
|
||||
module = pending.pop()
|
||||
if module in seen:
|
||||
continue
|
||||
seen.add(module)
|
||||
tree = ast.parse((SERVICES_DIR / f"{module}.py").read_text())
|
||||
for node in ast.walk(tree):
|
||||
if (
|
||||
isinstance(node, ast.ImportFrom)
|
||||
and node.module
|
||||
and node.module.startswith(f"{SERVICES_PACKAGE}.")
|
||||
):
|
||||
pending.add(node.module.removeprefix(f"{SERVICES_PACKAGE}."))
|
||||
return seen
|
||||
|
||||
|
||||
def _uow_calls(module: str) -> Iterator[tuple[str, str]]:
|
||||
"""`uow.<repo>.<метод>` (в том числе `self.uow…`) в модуле сервиса."""
|
||||
tree = ast.parse((SERVICES_DIR / f"{module}.py").read_text())
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Attribute):
|
||||
continue
|
||||
repo = node.value
|
||||
if not isinstance(repo, ast.Attribute):
|
||||
continue
|
||||
owner = repo.value
|
||||
named_uow = (isinstance(owner, ast.Name) and owner.id == "uow") or (
|
||||
isinstance(owner, ast.Attribute) and owner.attr == "uow"
|
||||
)
|
||||
if named_uow:
|
||||
yield repo.attr, node.attr
|
||||
|
||||
|
||||
def _process_calls(role: str) -> dict[tuple[str, str], str]:
|
||||
"""(repo, метод) → модуль сервиса процесса роли."""
|
||||
return {
|
||||
call: module
|
||||
for module in sorted(_service_modules(PROCESS_ENTRY_POINTS[role]))
|
||||
for call in _uow_calls(module)
|
||||
}
|
||||
|
||||
|
||||
def _process_needs(role: str) -> dict[str, Need]:
|
||||
needs: dict[str, Need] = {}
|
||||
for call in _process_calls(role):
|
||||
for table, spec in METHOD_NEEDS[call].items():
|
||||
needs.setdefault(table, Need()).add(spec)
|
||||
return needs
|
||||
|
||||
|
||||
def test_matrix_covers_every_model_table() -> None:
|
||||
model_tables = set(Base.metadata.tables)
|
||||
assert set(roles.TABLES) == model_tables
|
||||
for role in roles.PROCESS_ROLES:
|
||||
assert set(roles.MATRIX[role]) == model_tables, role
|
||||
|
||||
|
||||
def test_update_columns_exist_in_models() -> None:
|
||||
for role in roles.PROCESS_ROLES:
|
||||
for table, grant in roles.MATRIX[role].items():
|
||||
columns = set(Base.metadata.tables[table].columns.keys())
|
||||
assert grant.update <= columns, (role, table, grant.update)
|
||||
|
||||
|
||||
def test_every_called_repo_method_is_described() -> None:
|
||||
for role in roles.PROCESS_ROLES:
|
||||
for call, module in _process_calls(role).items():
|
||||
assert call in METHOD_NEEDS, (
|
||||
f"process {role}: {module} calls uow.{call[0]}.{call[1]} — "
|
||||
"add its SQL needs to METHOD_NEEDS"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", roles.PROCESS_ROLES)
|
||||
def test_role_has_rights_of_its_repo_calls(role: str) -> None:
|
||||
"""Задача 2.2: у роли есть всё, что нужно методам её процесса."""
|
||||
problems = []
|
||||
for (repo, method), module in sorted(_process_calls(role).items()):
|
||||
for table, spec in METHOD_NEEDS[(repo, method)].items():
|
||||
need = Need()
|
||||
need.add(spec)
|
||||
missing = need.missing_in(roles.MATRIX[role][table])
|
||||
if missing:
|
||||
problems.append(
|
||||
f"process {role}: {module} uow.{repo}.{method} needs "
|
||||
f"{', '.join(missing)} on {table}",
|
||||
)
|
||||
assert not problems, "\n".join(problems)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", roles.PROCESS_ROLES)
|
||||
def test_role_has_no_rights_beyond_its_code(role: str) -> None:
|
||||
"""Least privilege: права роли — не больше потребностей её процесса."""
|
||||
needs = _process_needs(role)
|
||||
extra = []
|
||||
for table, grant in roles.MATRIX[role].items():
|
||||
need = needs.get(table, Need())
|
||||
for name, granted, needed in (
|
||||
("SELECT", grant.select, need.select),
|
||||
("INSERT", grant.insert, need.insert),
|
||||
("DELETE", grant.delete, need.delete),
|
||||
):
|
||||
if granted and not needed:
|
||||
extra.append(f"{name} on {table}")
|
||||
unused = grant.update - need.update
|
||||
# колонка только ради блокировки допустима, если других нет
|
||||
if unused and not (need.lock and not need.update and len(unused) == 1):
|
||||
extra.extend(f"UPDATE({column}) on {table}" for column in unused)
|
||||
assert not extra, f"process {role}: rights beyond code: {extra}"
|
||||
|
||||
|
||||
def test_process_calls_found() -> None:
|
||||
"""Разбор AST видит вызовы каждого процесса (иначе сверка пуста)."""
|
||||
for role in roles.PROCESS_ROLES:
|
||||
assert _process_calls(role), role
|
||||
assert ("variants", "insert_variant") in _process_calls(roles.WORKER_ROLE)
|
||||
assert ("job_replays", "insert_replay") in _process_calls(
|
||||
roles.RELAY_ROLE,
|
||||
)
|
||||
|
||||
|
||||
def test_privilege_statements_quote_identifiers() -> None:
|
||||
statements = roles.privilege_statements({"users", "attachments"})
|
||||
assert statements[0] == (
|
||||
'REVOKE ALL ON ALL TABLES IN SCHEMA "public" FROM '
|
||||
'"api", "worker", "relay", "cleaner"'
|
||||
)
|
||||
assert 'GRANT SELECT, INSERT ON "public"."users" TO "api"' in statements
|
||||
assert (
|
||||
'GRANT UPDATE ("password_hash") ON "public"."users" TO "api"'
|
||||
in statements
|
||||
)
|
||||
# таблиц, которых нет в базе, в GRANT нет
|
||||
assert not any('"sessions"' in statement for statement in statements)
|
||||
# offline (--sql) — все таблицы матрицы
|
||||
assert any(
|
||||
'"attachment_job_replays" TO "relay"' in statement
|
||||
for statement in roles.privilege_statements()
|
||||
)
|
||||
|
||||
|
||||
def test_quote_ident_escapes_quotes() -> None:
|
||||
assert roles.quote_ident("api") == '"api"'
|
||||
assert roles.quote_ident('a"b') == '"a""b"'
|
||||
with pytest.raises(ValueError):
|
||||
roles.quote_ident("")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
["Messenger", "test-db", "db;drop", "", "a b", 'x"y'],
|
||||
)
|
||||
def test_database_name_outside_pattern(name: str) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
roles.check_database_name(name)
|
||||
with pytest.raises(ValueError):
|
||||
roles.database_access_sql(name)
|
||||
|
||||
|
||||
def test_database_access_sql() -> None:
|
||||
assert roles.database_access_sql("test_uow_messenger") == (
|
||||
'REVOKE ALL ON DATABASE "test_uow_messenger" FROM PUBLIC',
|
||||
'GRANT CONNECT ON DATABASE "test_uow_messenger" TO "migrate", '
|
||||
'"api", "worker", "relay", "cleaner"',
|
||||
'REVOKE CREATE ON SCHEMA "public" FROM PUBLIC',
|
||||
)
|
||||
|
||||
|
||||
def test_cluster_statements() -> None:
|
||||
assert roles.create_role_sql("api") == (
|
||||
'CREATE ROLE "api" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE '
|
||||
"NOREPLICATION NOBYPASSRLS NOINHERIT"
|
||||
)
|
||||
assert roles.revoke_membership_sql("worker", "pg_read_server_files") == (
|
||||
'REVOKE "pg_read_server_files" FROM "worker"'
|
||||
)
|
||||
assert roles.object_owner_sql("TABLE", "users") == (
|
||||
'ALTER TABLE "public"."users" OWNER TO "migrate"'
|
||||
)
|
||||
with pytest.raises(ValueError):
|
||||
roles.object_owner_sql("FUNCTION", "f")
|
||||
|
||||
|
||||
def test_scram_verifier_format_and_match() -> None:
|
||||
salt = bytes(range(16))
|
||||
verifier = roles.scram_verifier("known-password", salt=salt)
|
||||
found = re.fullmatch(roles.SCRAM_VERIFIER_PATTERN, verifier)
|
||||
assert found is not None
|
||||
assert found["iterations"] == "4096"
|
||||
assert base64.b64decode(found["salt"]) == salt
|
||||
assert len(base64.b64decode(found["stored"])) == 32
|
||||
assert roles.verifier_matches(verifier, "known-password")
|
||||
assert not roles.verifier_matches(verifier, "other-password")
|
||||
assert not roles.verifier_matches(None, "known-password")
|
||||
assert not roles.verifier_matches("md5abcdef", "known-password")
|
||||
# соль случайная: два верификатора одного пароля разные, оба подходят
|
||||
other = roles.scram_verifier("known-password")
|
||||
assert other != roles.scram_verifier("known-password")
|
||||
assert roles.verifier_matches(other, "known-password")
|
||||
|
||||
|
||||
def test_scram_verifier_known_vector() -> None:
|
||||
"""RFC 7677, пример обмена: пароль `pencil`, соль
|
||||
`W22ZaJ0SNY7soEsUEjb6gQ==`, 4096 итераций. ServerKey верификатора даёт
|
||||
подпись сервера `v=…`, StoredKey проверяет доказательство клиента `p=…`."""
|
||||
salt = base64.b64decode("W22ZaJ0SNY7soEsUEjb6gQ==")
|
||||
verifier = roles.scram_verifier("pencil", salt=salt)
|
||||
stored, server = (
|
||||
base64.b64decode(part) for part in verifier.split("$")[2].split(":")
|
||||
)
|
||||
nonce = "rOprNGfwEbeRWgbNEkqO%hvYDpWUa2RaTCAfuxFIlj)hNlF$k0"
|
||||
auth_message = (
|
||||
f"n=user,r=rOprNGfwEbeRWgbNEkqO,r={nonce},"
|
||||
f"s=W22ZaJ0SNY7soEsUEjb6gQ==,i=4096,c=biws,r={nonce}"
|
||||
).encode()
|
||||
server_signature = hmac.new(server, auth_message, "sha256").digest()
|
||||
assert base64.b64encode(server_signature).decode() == (
|
||||
"6rriTRBi23WpRR/wtup+mMhUZUn/dB5nLTJRsjl95G4="
|
||||
)
|
||||
proof = base64.b64decode("dHzbZapWIk4jUhN+Ute9ytag9zjfMHgsqmmiz7AndVQ=")
|
||||
client_signature = hmac.new(stored, auth_message, "sha256").digest()
|
||||
client_key = bytes(
|
||||
a ^ b for a, b in zip(proof, client_signature, strict=True)
|
||||
)
|
||||
assert hashlib.sha256(client_key).digest() == stored
|
||||
|
||||
|
||||
def test_set_password_sql_accepts_only_verifier() -> None:
|
||||
verifier = roles.scram_verifier("p")
|
||||
assert roles.set_password_sql("api", verifier) == (
|
||||
f"ALTER ROLE \"api\" PASSWORD '{verifier}'"
|
||||
)
|
||||
for bad in ("plain-password", verifier + "'; DROP TABLE users; --"):
|
||||
with pytest.raises(ValueError):
|
||||
roles.set_password_sql("api", bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", ["", "пароль", "tab\there", "a\nb"])
|
||||
def test_role_password_outside_pattern(password: str) -> None:
|
||||
with pytest.raises(ValueError):
|
||||
roles.check_role_password(password)
|
||||
|
||||
|
||||
def test_roles_module_has_no_logger() -> None:
|
||||
source = (BASE_DIR / "src" / "infra" / "db" / "roles.py").read_text()
|
||||
assert "get_logger" not in source
|
||||
assert "src.config" not in source
|
||||
@@ -22,6 +22,7 @@ from src.config.settings import (
|
||||
ApiTls,
|
||||
App,
|
||||
Auth,
|
||||
DbRoles,
|
||||
Settings,
|
||||
Telemetry,
|
||||
Uploads,
|
||||
@@ -254,6 +255,31 @@ def test_client_tls_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
assert _EnvironmentOnly().client_tls.ca_file == "/run/secrets/ca.crt"
|
||||
|
||||
|
||||
def test_db_roles_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Спек `service-configuration`, «Подключение к PostgreSQL»: пароли ролей
|
||||
читает bootstrap из `DB_ROLES__*`, по умолчанию пусто; в шаблоне toml их
|
||||
нет (источник — `.env`)."""
|
||||
loaded = _EnvironmentOnly()
|
||||
assert loaded.db_roles == DbRoles()
|
||||
assert loaded.db_roles.api_password.get_secret_value() == ""
|
||||
monkeypatch.setenv("DB_ROLES__WORKER_PASSWORD", "worker-secret")
|
||||
loaded = _EnvironmentOnly()
|
||||
assert loaded.db_roles.worker_password.get_secret_value() == (
|
||||
"worker-secret"
|
||||
)
|
||||
assert "worker-secret" not in repr(loaded.db_roles)
|
||||
assert "db_roles" not in EXAMPLE_TOML_PATH.read_text()
|
||||
|
||||
|
||||
def test_cache_username_from_environment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Пользователь ACL Valkey: пусто — `default`, у API — `api`."""
|
||||
assert _EnvironmentOnly().cache.username == ""
|
||||
monkeypatch.setenv("CACHE__USERNAME", "api")
|
||||
assert _EnvironmentOnly().cache.username == "api"
|
||||
|
||||
|
||||
def test_s3_endpoint_is_https() -> None:
|
||||
"""Шлюз S3 — только HTTPS (change `storage-tls`): URL с именем хоста."""
|
||||
s3 = _ArgumentsOnly(s3={"host": "s3", "port": 8333}).s3
|
||||
|
||||
Reference in New Issue
Block a user