forked from mtusi2026/mtusi2026lab7
fix: address storage-roles verify findings
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,7 +5,10 @@
|
||||
лишнее право, выданное вручную, снимает повторный `upgrade`; `downgrade -1` и
|
||||
снова `upgrade` сводят права; `alembic check` их не трогает; `--sql` печатает
|
||||
`GRANT`. Отказы ролей — в откатываемых транзакциях: таблицы и строки не
|
||||
меняются. Посторонняя роль кластера к базе не подключается.
|
||||
меняются. Посторонняя роль кластера к базе не подключается. Правки verify:
|
||||
права `PUBLIC` снимает `upgrade` (W1), членство и права на базу — bootstrap
|
||||
(W1), откат на несколько ревизий и промежуточная ревизия сводятся (W2), роли
|
||||
процессов не входят в служебные базы `postgres` и `template1` (S6).
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
@@ -20,6 +23,7 @@ from conftest import (
|
||||
ROLE_PASSWORDS,
|
||||
ROOT,
|
||||
TEST_DB,
|
||||
_bootstrap_roles,
|
||||
admin,
|
||||
migrate_env,
|
||||
settings,
|
||||
@@ -63,14 +67,14 @@ def _alembic(*args: str) -> subprocess.CompletedProcess[str]:
|
||||
)
|
||||
|
||||
|
||||
async def _connect(role: str) -> asyncpg.Connection:
|
||||
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=TEST_DB,
|
||||
database=database,
|
||||
timeout=source.connect_timeout_seconds,
|
||||
ssl=build_client_context(settings.client_tls.ca_file),
|
||||
)
|
||||
@@ -235,6 +239,99 @@ async def test_extra_grant_removed_by_upgrade(converged: None) -> None:
|
||||
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()
|
||||
@@ -244,6 +341,44 @@ async def test_downgrade_and_upgrade_converge(converged: None) -> None:
|
||||
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").stdout
|
||||
assert 'REVOKE ALL ON ALL TABLES IN SCHEMA "public" FROM' in output
|
||||
|
||||
Reference in New Issue
Block a user