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:
@@ -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
|
||||
Reference in New Issue
Block a user