forked from mtusi2026/mtusi2026lab7
feat: confine a compromised worker and drill its compromise end to end
- narrow the worker S3 user to staging reads and attachments writes - add database rules the worker role cannot bypass: no return to pending, variant keys of its own attachment, known error codes only - let the cleaner remove a ready source only after its own SHA-256 check - add make jobs_audit [REPAIR=1] to name and requeue damaged jobs - add make worker_compromise: isolated before/after stands, one operation table, response windows, job safety, controls and committed hypotheses Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
"""Ложный `failed` и срок хранения исходника (change `track1-worker-compromise`,
|
||||
спек `worker-compromise`, «Ложный failed с датой приёма»).
|
||||
|
||||
Строку портит роль `worker`, проходы делают настоящие `clean_staging` (роль
|
||||
`cleaner`) и `replay_pass` (роль `relay`); S3 — объекты в памяти. Отсчёт срока —
|
||||
от `updated_at`, который worker пишет сам, но не раньше `created_at`. Вложение,
|
||||
принятое меньше срока хранения назад, ложным `failed` не теряется; принятое
|
||||
раньше и не сверенное — теряется на ближайшем проходе: граница показана здесь
|
||||
же."""
|
||||
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import timedelta
|
||||
|
||||
import asyncpg
|
||||
import pytest
|
||||
from incident_rows import add_attachment, add_world
|
||||
|
||||
from conftest import (
|
||||
ROLE_PASSWORDS,
|
||||
TEST_DB,
|
||||
admin,
|
||||
make_engine,
|
||||
make_factory,
|
||||
make_uow,
|
||||
role_settings,
|
||||
settings,
|
||||
truncate_all,
|
||||
)
|
||||
from fakes import FakeDatabase, FakeObjectStorage
|
||||
from src.config.settings import Cleaner
|
||||
from src.core.services.attachment_cleanup import AttachmentCleanupService
|
||||
from src.core.services.attachment_replay import (
|
||||
REFUSAL_SOURCE_GONE,
|
||||
AttachmentReplayService,
|
||||
)
|
||||
from src.infra.db.uow import SqlAlchemyUnitOfWork
|
||||
from src.infra.tls import build_client_context
|
||||
from src.utils.utc import utcnow
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
|
||||
# умолчание кода, а не локальный config.toml
|
||||
RETENTION = timedelta(
|
||||
seconds=Cleaner.model_fields["staging_retention_seconds"].default,
|
||||
)
|
||||
MARGIN = timedelta(minutes=5)
|
||||
PASSES = 3
|
||||
# что worker пишет в `updated_at` вместе с `failed`
|
||||
FORGED_DATES = {
|
||||
"created_at": "created_at",
|
||||
"now": "clock_timestamp()",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def connection() -> AsyncIterator[asyncpg.Connection]:
|
||||
await truncate_all()
|
||||
opened = await admin()
|
||||
yield opened
|
||||
await opened.close()
|
||||
await truncate_all()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage() -> FakeObjectStorage:
|
||||
return FakeObjectStorage(FakeDatabase(), namespace=TEST_DB)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _uow(role: str) -> AsyncIterator[SqlAlchemyUnitOfWork]:
|
||||
engine = make_engine(pool_size=1, **role_settings(role))
|
||||
try:
|
||||
yield make_uow(make_factory(engine))
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
async def _as_worker(statements: tuple[str, ...], row: uuid.UUID) -> str:
|
||||
"""Выражения роли worker одной транзакцией: `ok` или SQLSTATE."""
|
||||
source = settings.database
|
||||
opened = await asyncpg.connect(
|
||||
host=source.host,
|
||||
port=source.port,
|
||||
user="worker",
|
||||
password=ROLE_PASSWORDS["worker"],
|
||||
database=TEST_DB,
|
||||
timeout=source.connect_timeout_seconds,
|
||||
ssl=build_client_context(settings.client_tls.ca_file),
|
||||
)
|
||||
try:
|
||||
async with opened.transaction():
|
||||
for statement in statements:
|
||||
await opened.execute(statement, row)
|
||||
except asyncpg.PostgresError as error:
|
||||
return error.sqlstate
|
||||
finally:
|
||||
await opened.close()
|
||||
return "ok"
|
||||
|
||||
|
||||
def _false_failed(updated_at: str) -> tuple[str, ...]:
|
||||
return (
|
||||
"UPDATE attachments SET status = 'failed', error_code = "
|
||||
f"'processing_failed', updated_at = {updated_at} WHERE id = $1",
|
||||
"UPDATE attachment_jobs SET state = 'failed', finished_at = now() "
|
||||
"WHERE attachment_id = $1",
|
||||
)
|
||||
|
||||
|
||||
async def _accepted(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
*,
|
||||
age: timedelta,
|
||||
) -> tuple[uuid.UUID, str]:
|
||||
"""Принятое и ещё не обработанное вложение с исходником в staging."""
|
||||
world = await add_world(connection)
|
||||
row = await add_attachment(
|
||||
connection,
|
||||
world,
|
||||
status="queued",
|
||||
state="queued",
|
||||
age_seconds=int(age.total_seconds()),
|
||||
)
|
||||
key = f"{TEST_DB}/staging/{row}/original"
|
||||
storage.seed(key)
|
||||
return row, key
|
||||
|
||||
|
||||
async def _clean(storage: FakeObjectStorage) -> int:
|
||||
"""Проходы уборщика его ролью и сроком хранения; сколько `failed` убрано."""
|
||||
removed = 0
|
||||
async with _uow("cleaner") as uow:
|
||||
service = AttachmentCleanupService(uow, storage)
|
||||
for _ in range(PASSES):
|
||||
result = await service.clean_staging(
|
||||
retention_before=utcnow() - RETENTION,
|
||||
batch_size=10,
|
||||
)
|
||||
assert result.interrupted_by is None
|
||||
removed += result.removed_failed
|
||||
return removed
|
||||
|
||||
|
||||
async def _replay(row: uuid.UUID) -> tuple[int, str | None]:
|
||||
async with _uow("relay") as uow:
|
||||
service = AttachmentReplayService(uow)
|
||||
done = await service.replay_pass(
|
||||
attachment_ids=[row],
|
||||
error_code=None,
|
||||
reason=None,
|
||||
limit=10,
|
||||
apply=True,
|
||||
operator="test",
|
||||
)
|
||||
if done.refused == 0:
|
||||
return done.replayed, None
|
||||
refused = await service.replay_one(
|
||||
attachment_id=row,
|
||||
apply=True,
|
||||
operator="test",
|
||||
)
|
||||
return done.replayed, refused.refusal
|
||||
|
||||
|
||||
async def _state(
|
||||
connection: asyncpg.Connection,
|
||||
row: uuid.UUID,
|
||||
) -> tuple[str, str, bool]:
|
||||
found = await connection.fetchrow(
|
||||
"SELECT a.status, j.state, a.staging_key IS NOT NULL FROM "
|
||||
"attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
|
||||
"WHERE a.id = $1",
|
||||
row,
|
||||
)
|
||||
return tuple(found)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("age", [timedelta(hours=1), RETENTION - MARGIN])
|
||||
@pytest.mark.parametrize("date", FORGED_DATES)
|
||||
async def test_younger_than_retention_is_not_lost(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
date: str,
|
||||
age: timedelta,
|
||||
) -> None:
|
||||
"""Принятое меньше срока хранения назад: исходник на месте при самой ранней
|
||||
дате, которую роль может записать, и replay возвращает задание."""
|
||||
row, key = await _accepted(connection, storage, age=age)
|
||||
assert await _as_worker(_false_failed(FORGED_DATES[date]), row) == "ok"
|
||||
assert await _clean(storage) == 0
|
||||
assert key in storage.objects
|
||||
assert await _state(connection, row) == ("failed", "failed", True)
|
||||
assert await _replay(row) == (1, None)
|
||||
assert await _state(connection, row) == ("queued", "queued", True)
|
||||
# возвращённое — текущая работа: уборщик его не видит
|
||||
assert await _clean(storage) == 0
|
||||
assert key in storage.objects
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"date",
|
||||
[
|
||||
"created_at - interval '1 microsecond'",
|
||||
"created_at - interval '2 days'",
|
||||
"'-infinity'",
|
||||
"'2000-01-01'",
|
||||
],
|
||||
)
|
||||
async def test_date_before_acceptance_refused(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
date: str,
|
||||
) -> None:
|
||||
"""Состарить вложение роль не может: `updated_at` раньше `created_at` —
|
||||
23514, строка и исходник прежние."""
|
||||
row, key = await _accepted(connection, storage, age=timedelta(hours=1))
|
||||
assert await _as_worker(_false_failed(date), row) == "23514"
|
||||
only_date = f"UPDATE attachments SET updated_at = {date} WHERE id = $1"
|
||||
assert await _as_worker((only_date,), row) == "23514"
|
||||
assert await _clean(storage) == 0
|
||||
assert key in storage.objects
|
||||
assert await _state(connection, row) == ("queued", "queued", True)
|
||||
|
||||
|
||||
async def test_created_at_is_not_writable(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
) -> None:
|
||||
"""Нижнюю границу даты роль не сдвинет: `created_at` не её колонка."""
|
||||
row, _ = await _accepted(connection, storage, age=timedelta(hours=1))
|
||||
statement = (
|
||||
"UPDATE attachments SET created_at = created_at - interval '2 days' "
|
||||
"WHERE id = $1"
|
||||
)
|
||||
assert await _as_worker((statement,), row) == "42501"
|
||||
|
||||
|
||||
async def test_older_than_retention_is_lost(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
) -> None:
|
||||
"""Граница: принятое раньше срока хранения и не обработанное ложный
|
||||
`failed` с датой приёма теряет на ближайшем проходе — исходник удалён,
|
||||
replay отвечает «исходника нет». Ложный `failed` с сегодняшней датой —
|
||||
нет."""
|
||||
old, old_key = await _accepted(
|
||||
connection,
|
||||
storage,
|
||||
age=RETENTION + MARGIN,
|
||||
)
|
||||
dated, dated_key = await _accepted(
|
||||
connection,
|
||||
storage,
|
||||
age=RETENTION + MARGIN,
|
||||
)
|
||||
assert await _as_worker(_false_failed("created_at"), old) == "ok"
|
||||
assert await _as_worker(_false_failed("clock_timestamp()"), dated) == "ok"
|
||||
assert await _clean(storage) == 1
|
||||
assert old_key not in storage.objects
|
||||
assert await _state(connection, old) == ("failed", "failed", False)
|
||||
assert await _replay(old) == (0, REFUSAL_SOURCE_GONE)
|
||||
assert dated_key in storage.objects
|
||||
assert await _replay(dated) == (1, None)
|
||||
|
||||
|
||||
async def test_unfinished_older_than_retention_is_kept(
|
||||
connection: asyncpg.Connection,
|
||||
storage: FakeObjectStorage,
|
||||
) -> None:
|
||||
"""Теряет именно ложный `failed`, а не возраст: текущую работу уборщик не
|
||||
трогает ни в каком возрасте."""
|
||||
row, key = await _accepted(connection, storage, age=RETENTION * 3)
|
||||
assert await _clean(storage) == 0
|
||||
assert key in storage.objects
|
||||
assert await _state(connection, row) == ("queued", "queued", True)
|
||||
Reference in New Issue
Block a user