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:
2026-12-02 03:01:20 +03:00
co-authored by Claude Opus 5.5
parent ea3f791364
commit 4f2f940a07
53 changed files with 10062 additions and 101 deletions
+127
View File
@@ -0,0 +1,127 @@
"""Строки конвейера для тестов значений роли worker и сверки заданий (change
`track1-worker-compromise`, design, решения 6 и 8): вложение с заданием и
вариантами — мимо приложения, соединением администратора."""
import uuid
from typing import Any
import asyncpg
from conftest import TEST_DB
PIPELINE_VERSION = 1
VARIANTS = ("thumbnail", "crop", "optimized")
async def add_world(connection: asyncpg.Connection) -> tuple[uuid.UUID, ...]:
"""Пользователь, чат и участник: владелец вложений."""
user, chat = uuid.uuid4(), uuid.uuid4()
await connection.execute(
"INSERT INTO users (id, username, display_name, password_hash, "
"created_at) VALUES ($1, $2, 'u', '$argon2id$v=19$m=65536,t=3,p=4$"
"c29tZXNhbHQ$c29tZWhhc2g', now())",
user,
f"u{user.hex[:12]}",
)
await connection.execute(
"INSERT INTO chats (id, title, created_at) VALUES ($1, 't', now())",
chat,
)
await connection.execute(
"INSERT INTO chat_members (chat_id, user_id, position, created_at) "
"VALUES ($1, $2, 0, now())",
chat,
user,
)
return user, chat
def variant_key(
attachment: uuid.UUID,
name: str,
*,
namespace: str = TEST_DB,
version: int = PIPELINE_VERSION,
) -> str:
return f"{namespace}/attachments/{attachment}/v{version}-{name}"
async def add_variants(
connection: asyncpg.Connection,
attachment: uuid.UUID,
names: tuple[str, ...] = VARIANTS,
) -> None:
for name in names:
await connection.execute(
INSERT_VARIANT_SQL,
attachment,
name,
variant_key(attachment, name),
)
INSERT_VARIANT_SQL = (
"INSERT INTO attachment_variants (attachment_id, pipeline_version, "
"variant, object_key, content_type, size_bytes, width, height, sha256, "
"created_at) VALUES ($1, 1, $2, $3, 'image/jpeg', 1, 1, 1, "
"decode(repeat('ab', 32), 'hex'), now())"
)
async def add_attachment(
connection: asyncpg.Connection,
world: tuple[uuid.UUID, ...],
*,
status: str,
state: str | None = None,
staging: bool = True,
variants: tuple[str, ...] = (),
age_seconds: int = 3600,
**job: Any,
) -> uuid.UUID:
"""Вложение `status` с заданием `state` (`None` — без задания); `job` —
колонки задания выражениями SQL."""
user, chat = world
attachment = uuid.uuid4()
namespace = TEST_DB
await connection.execute(
"INSERT INTO attachments (id, chat_id, owner_id, filename, "
"content_type, size_bytes, sha256, object_key, staging_key, status, "
"error_code, updated_at, created_at) VALUES ($1, $2, $3, 'a.png', "
"'image/png', 1, decode(repeat('ab', 32), 'hex'), $4, $5, $6, $7, "
"now() - make_interval(secs => $8), "
"now() - make_interval(secs => $8))",
attachment,
chat,
user,
f"{namespace}/attachments/{attachment}/original",
f"{namespace}/staging/{attachment}/original" if staging else None,
status,
"processing_failed" if status == "failed" else None,
float(age_seconds),
)
if state is not None:
columns = {
"lease_expires_at": (
"now() + interval '60 s'" if state == "processing" else "NULL"
),
"published_at": "now() - interval '1 s'",
"next_attempt_at": "NULL",
"attempt": "1",
"attempt_base": "0",
"updated_at": "now()",
**job,
}
names = ", ".join(columns)
values = ", ".join(columns.values())
await connection.execute(
"INSERT INTO attachment_jobs (id, attachment_id, "
f"pipeline_version, state, created_at, {names}) VALUES "
"(gen_random_uuid(), $1, 1, $2, "
f"now() - make_interval(secs => $3), {values})",
attachment,
state,
float(age_seconds),
)
await add_variants(connection, attachment, variants)
return attachment
+278
View File
@@ -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)
+464
View File
@@ -0,0 +1,464 @@
"""Сверка и возврат заданий после инцидента (change `track1-worker-compromise`,
design, решение 8; спек `worker-compromise`, «Сохранность заданий»):
`infra/incident/*.sql` на временной базе. По испорченной строке каждого класса
и законные состояния: сверка называет ровно испорченные, возврат исправляет их
и не трогает законные, второй прогон — ноль."""
import subprocess
import uuid
from collections.abc import AsyncIterator
import asyncpg
import pytest
from incident_rows import VARIANTS, add_attachment, add_world
from conftest import ROOT, admin, truncate_all
pytestmark = pytest.mark.anyio
INCIDENT_DIR = ROOT / "infra" / "incident"
CLASSES = (
"stuck_time",
"attempt_number",
"state_mismatch",
"false_success",
"future_updated_at",
"verified_damaged",
)
@pytest.fixture
async def connection() -> AsyncIterator[asyncpg.Connection]:
await truncate_all()
opened = await admin()
yield opened
await opened.close()
await truncate_all()
def _script(*names: str, stale_seconds: int = 300) -> str:
text = "".join(
(INCIDENT_DIR / name).read_text(encoding="utf-8") for name in names
)
# подстановка переменной psql
return text.replace(":stale_seconds", str(stale_seconds))
async def _found(
connection: asyncpg.Connection,
**options: int,
) -> dict[uuid.UUID, set[str]]:
"""Вложение → его классы; транзакция откатывается."""
transaction = connection.transaction()
await transaction.start()
try:
await connection.execute(_script("jobs_classes.sql", **options))
rows = await connection.fetch("SELECT * FROM incident")
finally:
await transaction.rollback()
return {
row["attachment_id"]: found
for row in rows
if (found := {name for name in CLASSES if row[name]})
}
async def _repair(connection: asyncpg.Connection) -> None:
async with connection.transaction():
await connection.execute(
_script("jobs_classes.sql", "jobs_repair.sql"),
)
async def _snapshot(
connection: asyncpg.Connection,
) -> list[tuple[object, ...]]:
rows = [
*await connection.fetch("SELECT * FROM attachments ORDER BY id"),
*await connection.fetch("SELECT * FROM attachment_jobs ORDER BY id"),
*await connection.fetch(
"SELECT * FROM attachment_variants ORDER BY attachment_id, "
"variant",
),
]
return [tuple(row) for row in rows]
async def _legal(
connection: asyncpg.Connection,
world: tuple[uuid.UUID, ...],
) -> None:
"""Законные состояния: каждое, которое пишут процессы."""
for spec in (
{"status": "pending"},
# старая версия: готовое без задания и без исходника
{"status": "ready", "staging": False},
{"status": "queued", "state": "queued", "published_at": "NULL"},
{"status": "queued", "state": "queued"},
# пауза перед повтором и пустой брокер: сроки истекут сами
{
"status": "queued",
"state": "queued",
"published_at": "NULL",
"next_attempt_at": "now() + interval '300 s'",
"attempt": "4",
},
{
"status": "queued",
"state": "queued",
"published_at": "now() - interval '3 days'",
},
{"status": "processing", "state": "processing"},
{
"status": "processing",
"state": "processing",
"lease_expires_at": "now() - interval '1 day'",
},
# исходник ждёт уборщика меньше срока
{
"status": "ready",
"state": "succeeded",
"variants": VARIANTS,
"age_seconds": 100,
},
{
"status": "ready",
"state": "succeeded",
"variants": VARIANTS,
"staging": False,
},
{"status": "failed", "state": "failed"},
{"status": "failed", "state": "failed", "staging": False},
# после replay: номер большой, бюджет свой
{
"status": "queued",
"state": "queued",
"attempt": "104",
"attempt_base": "100",
},
):
await add_attachment(connection, world, **spec)
# испорченная строка → её классы: одна на строку design, решение 8, и
# разновидности
DAMAGED: list[tuple[dict[str, object], set[str]]] = [
(
{
"status": "processing",
"state": "processing",
"lease_expires_at": "'2100-01-01'",
},
{"stuck_time"},
),
(
{
"status": "processing",
"state": "processing",
"lease_expires_at": "NULL",
},
{"stuck_time"},
),
(
{
"status": "queued",
"state": "queued",
"next_attempt_at": "'infinity'",
},
{"stuck_time"},
),
(
{
"status": "queued",
"state": "queued",
"published_at": "'2100-01-01'",
},
{"stuck_time"},
),
(
{"status": "queued", "state": "queued", "attempt": "2147483647"},
{"attempt_number"},
),
(
{
"status": "processing",
"state": "processing",
"attempt": "150",
},
{"attempt_number"},
),
(
{"status": "failed", "state": "failed", "attempt": "2147483647"},
{"attempt_number"},
),
({"status": "queued", "state": "succeeded"}, {"state_mismatch"}),
({"status": "queued", "state": "failed"}, {"state_mismatch"}),
({"status": "ready", "state": "queued"}, {"state_mismatch"}),
({"status": "failed", "state": "processing"}, {"state_mismatch"}),
({"status": "processing"}, {"state_mismatch"}),
({"status": "ready"}, {"state_mismatch"}),
(
{
"status": "ready",
"state": "succeeded",
"age_seconds": 10,
},
{"false_success"},
),
(
{
"status": "ready",
"state": "succeeded",
"variants": ("thumbnail",),
"age_seconds": 10,
},
{"false_success"},
),
(
{
"status": "ready",
"state": "succeeded",
"variants": VARIANTS,
"age_seconds": 3600,
},
{"false_success"},
),
(
{
"status": "queued",
"state": "queued",
"updated_at": "'2100-01-01'",
},
{"future_updated_at"},
),
(
{"status": "queued", "state": "queued", "staging": False},
{"verified_damaged"},
),
(
{
"status": "processing",
"state": "succeeded",
"staging": False,
"variants": VARIANTS,
},
{"verified_damaged"},
),
(
{
"status": "failed",
"state": "failed",
"staging": False,
"variants": VARIANTS,
},
{"verified_damaged"},
),
({"status": "queued", "staging": False}, {"verified_damaged"}),
]
async def test_legal_states_are_not_named(
connection: asyncpg.Connection,
) -> None:
world = await add_world(connection)
await _legal(connection, world)
assert await _found(connection) == {}
before = await _snapshot(connection)
await _repair(connection)
assert await _snapshot(connection) == before
async def test_every_class_named_and_repaired(
connection: asyncpg.Connection,
) -> None:
"""K из K: названо ровно испорченное, после возврата — ничего; законное
не изменено."""
world = await add_world(connection)
await _legal(connection, world)
legal = await _snapshot(connection)
expected: dict[uuid.UUID, set[str]] = {}
for spec, classes in DAMAGED:
row = await add_attachment(connection, world, **spec)
expected[row] = classes
assert set().union(*(item for _, item in DAMAGED)) == set(CLASSES)
# строка вложения в будущем: своя колонка
future = await add_attachment(
connection,
world,
status="ready",
state="succeeded",
variants=VARIANTS,
)
await connection.execute(
"UPDATE attachments SET updated_at = '2100-01-01' WHERE id = $1",
future,
)
expected[future] = {"future_updated_at", "false_success"}
assert await _found(connection) == expected
await _repair(connection)
assert await _found(connection) == {}
after = await _snapshot(connection)
assert set(map(repr, legal)) <= set(map(repr, after))
await _repair(connection)
assert await _snapshot(connection) == after
async def test_requeued_row_is_processable(
connection: asyncpg.Connection,
) -> None:
"""Возвращённое — намерение relay: queued без сроков и отметки, бюджет
новый, номер не уменьшен, строк вариантов нет; сверенное — готовое."""
world = await add_world(connection)
requeued = await add_attachment(
connection,
world,
status="ready",
state="succeeded",
variants=VARIANTS,
attempt="3",
attempt_base="1",
)
restored = await add_attachment(
connection,
world,
status="failed",
state="failed",
staging=False,
variants=VARIANTS,
)
await _repair(connection)
row = await connection.fetchrow(
"SELECT a.status, a.error_code, j.state, j.attempt, j.attempt_base, "
"j.published_at, j.next_attempt_at, j.lease_expires_at, "
"j.finished_at, (SELECT count(*) FROM attachment_variants v WHERE "
"v.attachment_id = a.id) AS variants FROM attachments a JOIN "
"attachment_jobs j ON j.attachment_id = a.id WHERE a.id = $1",
requeued,
)
assert tuple(row) == (
"queued",
None,
"queued",
3,
3,
None,
None,
None,
None,
0,
)
row = await connection.fetchrow(
"SELECT a.status, a.error_code, j.state, (SELECT count(*) FROM "
"attachment_variants v WHERE v.attachment_id = a.id) FROM "
"attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.id = $1",
restored,
)
assert tuple(row) == ("ready", None, "succeeded", 3)
async def test_job_created_for_accepted_without_job(
connection: asyncpg.Connection,
) -> None:
world = await add_world(connection)
row = await add_attachment(connection, world, status="ready")
await _repair(connection)
job = await connection.fetchrow(
"SELECT state, attempt, pipeline_version FROM attachment_jobs "
"WHERE attachment_id = $1",
row,
)
assert tuple(job) == ("queued", 0, 1)
async def test_stale_threshold_is_a_parameter(
connection: asyncpg.Connection,
) -> None:
world = await add_world(connection)
row = await add_attachment(
connection,
world,
status="ready",
state="succeeded",
variants=VARIANTS,
age_seconds=60,
)
assert await _found(connection) == {}
assert await _found(connection, stale_seconds=10) == {
row: {"false_success"},
}
async def test_audit_output(connection: asyncpg.Connection) -> None:
"""Строки, которые разбирает `jobs.sh`: каждый класс — и нулевой."""
world = await add_world(connection)
await add_attachment(connection, world, status="failed", state="failed")
await add_attachment(
connection,
world,
status="queued",
state="queued",
attempt="2147483647",
published_at="'2100-01-01'",
)
statements = [
item.strip()
for item in _script("jobs_audit.sql").split(";\n")
if item.strip()
]
async with connection.transaction():
await connection.execute(_script("jobs_classes.sql"))
lines = [
row[0]
for statement in statements
for row in await connection.fetch(statement)
]
assert lines == [
"class stuck_time 1",
"class attempt_number 1",
"class state_mismatch 0",
"class false_success 0",
"class future_updated_at 0",
"class verified_damaged 0",
"info failed_with_source 1",
"info ready_without_variants 0",
"damaged 1",
]
async def test_audit_changes_nothing(connection: asyncpg.Connection) -> None:
world = await add_world(connection)
for spec, _ in DAMAGED:
await add_attachment(connection, world, **spec)
before = await _snapshot(connection)
async with connection.transaction():
await connection.execute(
_script("jobs_classes.sql", "jobs_audit.sql"),
)
assert await _snapshot(connection) == before
@pytest.mark.parametrize(
("args", "env"),
[
(("fix",), {}),
(("audit",), {"STALE_SECONDS": "5; DROP TABLE x"}),
# пустое — умолчание; стенда нет — тоже 2
(("audit",), {"STALE_SECONDS": ""}),
],
)
def test_script_refuses_bad_arguments(
args: tuple[str, ...],
env: dict[str, str],
) -> None:
"""Код 2 до обращения к стенду (docker в PATH нет)."""
result = subprocess.run(
["/bin/sh", str(INCIDENT_DIR / "jobs.sh"), *args],
env={"PATH": "/bin:/usr/bin", **env},
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 2
assert result.stdout == ""
+311
View File
@@ -0,0 +1,311 @@
"""Значения, которых роль процесса не может записать (change
`track1-worker-compromise`, design, решение 6; спек `storage-access`): возврат
вложения в `pending`, чужой ключ варианта, неизвестный код ошибки. Законные
записи worker, API, relay и уборщика проходят; ревизия ставится и снимается на
базе с наполненными строками."""
import uuid
from collections.abc import AsyncIterator
import asyncpg
import pytest
from incident_rows import (
INSERT_VARIANT_SQL,
VARIANTS,
add_attachment,
add_world,
variant_key,
)
from conftest import (
ROLE_PASSWORDS,
TEST_DB,
admin,
run_alembic,
settings,
truncate_all,
)
from src.infra.tls import build_client_context
pytestmark = pytest.mark.anyio
REVISION = "b9d27c4e1f03"
PREVIOUS = "e4b8c2d17f90"
@pytest.fixture
async def connection() -> AsyncIterator[asyncpg.Connection]:
await truncate_all()
opened = await admin()
yield opened
await opened.close()
await truncate_all()
async def _as(role: str) -> asyncpg.Connection:
source = settings.database
return await asyncpg.connect(
host=source.host,
port=source.port,
user=role,
password=ROLE_PASSWORDS[role],
database=TEST_DB,
timeout=source.connect_timeout_seconds,
ssl=build_client_context(settings.client_tls.ca_file),
)
async def _execute(role: str, statement: str, *args: object) -> str:
"""Выражение роли в своей транзакции: `ok` или SQLSTATE."""
opened = await _as(role)
try:
try:
await opened.execute(statement, *args)
except asyncpg.PostgresError as error:
return error.sqlstate
return "ok"
finally:
await opened.close()
async def _status(
connection: asyncpg.Connection,
attachment: uuid.UUID,
) -> str:
return await connection.fetchval(
"SELECT status FROM attachments WHERE id = $1",
attachment,
)
@pytest.mark.parametrize(
"status",
["queued", "processing", "ready", "failed"],
)
async def test_accepted_does_not_return_to_pending(
connection: asyncpg.Connection,
status: str,
) -> None:
world = await add_world(connection)
row = await add_attachment(connection, world, status=status)
for role in ("worker", "relay", "api"):
extra = "" if role == "api" else ", error_code = NULL"
got = await _execute(
role,
f"UPDATE attachments SET status = 'pending'{extra} WHERE id = $1",
row,
)
assert got == "23514", (role, status)
assert await _status(connection, row) == status
async def test_new_upload_is_pending(connection: asyncpg.Connection) -> None:
"""Законное: вставка `pending`, `updated_at` у `pending` и пометка
уборщика."""
user, chat = await add_world(connection)
row = uuid.uuid4()
got = await _execute(
"api",
"INSERT INTO attachments (id, chat_id, owner_id, filename, "
"content_type, size_bytes, sha256, object_key, staging_key, status, "
"updated_at, created_at) VALUES ($1, $2, $3, 'a.png', 'image/png', "
"1, decode(repeat('ab', 32), 'hex'), $4, $5, 'pending', now(), now())",
row,
chat,
user,
f"{TEST_DB}/attachments/{row}/original",
f"{TEST_DB}/staging/{row}/original",
)
assert got == "ok"
assert (
await _execute(
"cleaner",
"UPDATE attachments SET updated_at = now() WHERE id = $1",
row,
)
== "ok"
)
# строка, прочитанная в `pending`, может быть записана тем же статусом
assert (
await _execute(
"api",
"UPDATE attachments SET status = 'pending' WHERE id = $1",
row,
)
== "ok"
)
assert (
await _execute(
"api",
"UPDATE attachments SET status = 'queued' WHERE id = $1",
row,
)
== "ok"
)
async def test_foreign_variant_key_refused(
connection: asyncpg.Connection,
) -> None:
world = await add_world(connection)
own = await add_attachment(connection, world, status="processing")
other = await add_attachment(connection, world, status="ready")
for key in (
f"{TEST_DB}/attachments/{other}/original",
variant_key(other, "thumbnail"),
f"{TEST_DB}/attachments/{own}/original",
f"{TEST_DB}/staging/{other}/original",
variant_key(own, "thumbnail", namespace="other"),
variant_key(own, "thumbnail", namespace=f"test_{TEST_DB}"),
f"{TEST_DB}/attachments/{own}/../{other}/v1-thumbnail",
f"{TEST_DB}/attachments/{own}/v1-thumbnail/../../{other}/original",
f"x/{variant_key(own, 'thumbnail')}",
f"{variant_key(own, 'thumbnail')}\n",
variant_key(own, "thumbnail", version=0),
variant_key(own, "THUMBNAIL"),
):
got = await _execute(
"worker",
INSERT_VARIANT_SQL,
own,
"thumbnail",
key,
)
assert got == "23514", key
left = await connection.fetchval(
"SELECT count(*) FROM attachment_variants",
)
assert left == 0
async def test_own_variant_key_accepted(
connection: asyncpg.Connection,
) -> None:
world = await add_world(connection)
own = await add_attachment(connection, world, status="processing")
for name in VARIANTS:
got = await _execute(
"worker",
INSERT_VARIANT_SQL,
own,
name,
variant_key(own, name),
)
assert got == "ok", name
@pytest.mark.parametrize("role", ["worker", "relay"])
async def test_unknown_error_code_refused(
connection: asyncpg.Connection,
role: str,
) -> None:
world = await add_world(connection)
row = await add_attachment(connection, world, status="queued")
statement = (
"UPDATE attachments SET status = 'failed', error_code = $2 "
"WHERE id = $1"
)
for code in ("boom", "", "INVALID_IMAGE", "invalid_image "):
assert await _execute(role, statement, row, code) == "23514", code
assert await _status(connection, row) == "queued"
for code in ("invalid_image", "processing_failed", "retry_exhausted"):
assert await _execute(role, statement, row, code) == "ok", code
async def test_legal_transitions_pass(
connection: asyncpg.Connection,
) -> None:
"""Переходы worker и relay между принятыми состояниями, очистка staging
уборщиком."""
world = await add_world(connection)
row = await add_attachment(connection, world, status="queued")
for role, status, code in (
("worker", "processing", None),
("worker", "queued", None),
("worker", "processing", None),
("worker", "failed", "processing_failed"),
("relay", "queued", None),
("worker", "processing", None),
("worker", "ready", None),
):
got = await _execute(
role,
"UPDATE attachments SET status = $2, error_code = $3 "
"WHERE id = $1",
row,
status,
code,
)
assert got == "ok", (role, status)
assert (
await _execute(
"cleaner",
"UPDATE attachments SET staging_key = NULL WHERE id = $1",
row,
)
== "ok"
)
async def test_revision_on_filled_database(
connection: asyncpg.Connection,
) -> None:
"""`downgrade` снимает правила, `upgrade` ставит их на наполненной базе и
проверяет существующие строки (`VALIDATE`); повтор — no-op."""
world = await add_world(connection)
row = await add_attachment(
connection,
world,
status="ready",
state="succeeded",
variants=VARIANTS,
)
await add_attachment(connection, world, status="failed", state="failed")
try:
run_alembic("downgrade", PREVIOUS)
assert (
await _execute(
"worker",
"UPDATE attachments SET status = 'pending' WHERE id = $1",
row,
)
== "ok"
)
await connection.execute(
"UPDATE attachments SET status = 'ready' WHERE id = $1",
row,
)
finally:
run_alembic("upgrade", "head")
run_alembic("upgrade", "head")
rows = await connection.fetch(
"SELECT conname, convalidated FROM pg_constraint WHERE conname IN "
"('ck_attachment_variants_object_key_own', "
"'ck_attachments_error_code') ORDER BY 1",
)
assert [tuple(item) for item in rows] == [
("ck_attachment_variants_object_key_own", True),
("ck_attachments_error_code", True),
]
triggers = await connection.fetch(
"SELECT tgname FROM pg_trigger WHERE NOT tgisinternal ORDER BY 1",
)
assert [item["tgname"] for item in triggers] == [
"attachment_variants_key_namespace",
"attachments_accepted_not_pending",
]
async def test_interrupted_revision_repeats(
connection: asyncpg.Connection,
) -> None:
"""Сбой между правилами и отметкой версии (`VALIDATE` идёт вне общей
транзакции): повтор `upgrade` проходит."""
try:
run_alembic("stamp", PREVIOUS)
finally:
run_alembic("upgrade", "head")
current = await connection.fetchval(
"SELECT version_num FROM alembic_version",
)
assert current == REVISION
+2
View File
@@ -315,6 +315,8 @@ class FakeAttachmentRepository(_FakeRepository, AbstractAttachmentRepository):
staging_key=row.staging_key,
status=row.status,
updated_at=row.updated_at,
size_bytes=row.size_bytes,
sha256=row.sha256,
)
@staticmethod
+11 -1
View File
@@ -557,6 +557,11 @@ async def check_lock_staging_candidate(new_uow: NewUow) -> None:
)
assert found is not None
assert found.staging_key == row.staging_key
# по ним уборщик сверяет результат до удаления исходника
assert (found.size_bytes, found.sha256) == (
row.size_bytes,
row.sha256,
)
assert (
await uow.attachments.lock_staging_candidate(
attachment_id=row.id,
@@ -1458,7 +1463,12 @@ async def check_variants(new_uow: NewUow) -> None:
)
assert not await repo.insert_variant(
attachment_id=row.id,
variant=replace(thumbnail, object_key="other"),
# ключ другой, но своего вложения: чужой отвергает БД (спек
# storage-access, «Значения, которых роль не может записать»)
variant=replace(
thumbnail,
object_key=f"{thumbnail.object_key}other",
),
)
assert await repo.insert_variant(attachment_id=row.id, variant=crop)
await uow.commit()
+136 -2
View File
@@ -8,6 +8,7 @@ from builders import NOW, at, attachment_dto
from fakes import FakeDatabase, FakeObjectStorage, FakeUnitOfWork
from src.core import exceptions
from src.core.repos import attachment_object
from src.core.services import attachment_cleanup
from src.core.services.attachment_cleanup import (
INTERRUPTED_BY_DATABASE,
INTERRUPTED_BY_OBJECT_STORAGE,
@@ -24,6 +25,9 @@ from src.utils.constants import ATTACHMENT_PIPELINE_VERSION
pytestmark = pytest.mark.anyio
# байты, чей SHA-256 в метаданных `attachment_dto` по умолчанию
CONTENT = b"content"
@pytest.fixture
def service(
@@ -278,7 +282,7 @@ async def test_ready_staging_removed_at_next_pass(
status=AttachmentStatus.READY,
updated_seconds=100,
)
storage.seed(row.object_key)
storage.seed(row.object_key, CONTENT)
database.events.clear()
result = await _staging_pass(service)
assert result.removed_ready == 1
@@ -292,11 +296,13 @@ async def test_ready_staging_removed_at_next_pass(
assert block == [
"enter",
"attachments.lock_staging_candidate",
# сверка результата — под той же блокировкой, до удаления исходника
"storage.get",
"storage.delete",
"attachments.clear_staging_key",
"commit",
"exit",
*block[6:],
*block[7:],
]
@@ -372,6 +378,7 @@ async def test_staging_held_and_storage_failure_and_stop(
database: FakeDatabase,
) -> None:
row = await _for_staging(uow, storage, status=AttachmentStatus.READY)
storage.seed(row.object_key, CONTENT)
database.held.add(row.id)
assert (await _staging_pass(service)).skipped == 1
database.held.clear()
@@ -389,6 +396,7 @@ async def test_staging_keyset_more_than_one_batch(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
) -> None:
for index in range(5):
await _for_staging(
@@ -397,5 +405,131 @@ async def test_staging_keyset_more_than_one_batch(
status=AttachmentStatus.READY,
updated_seconds=-1000 + index,
)
for row in database.attachments.values():
storage.seed(row.object_key, CONTENT)
result = await _staging_pass(service, batch_size=2)
assert result.removed_ready == 5
class Journal:
"""Записи сервиса с уровнем: что назвал проход."""
def __init__(self) -> None:
self.records: list[tuple[str, str, dict[str, object]]] = []
def bind(self, **_: object) -> "Journal":
return self
def __getattr__(self, level: str) -> object:
def write(event: str, **fields: object) -> None:
self.records.append((level, event, fields))
return write
def errors(self) -> list[dict[str, object]]:
return [
fields
for level, event, fields in self.records
if (level, event)
== ("error", "Attachment result does not match its source")
]
@pytest.fixture
def journal(monkeypatch: pytest.MonkeyPatch) -> Journal:
found = Journal()
monkeypatch.setattr(attachment_cleanup, "logger", found)
return found
@pytest.mark.parametrize(
("stored", "reason"),
[
(None, "missing"),
(CONTENT + b"!", "size"),
(b"CONTENT", "checksum"),
(b"", "size"),
],
)
async def test_ready_source_kept_without_matching_result(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
journal: Journal,
stored: bytes | None,
reason: str,
) -> None:
"""Слово worker «готово» исходник не удаляет (change
track1-worker-compromise, решение 7): объекта нет, другой размер, другие
байты того же размера. Остальные строки прохода убираются; следующие
проходы — то же самое, пока результат не сойдётся."""
bad = await _for_staging(
uow,
storage,
status=AttachmentStatus.READY,
updated_seconds=-1000,
)
good = await _for_staging(
uow,
storage,
status=AttachmentStatus.READY,
updated_seconds=-900,
)
storage.seed(good.object_key, CONTENT)
if stored is not None:
storage.seed(bad.object_key, stored)
for expected in (1, 0):
result = await _staging_pass(service)
assert result.interrupted_by is None
assert (result.removed_ready, result.skipped) == (expected, 1)
assert bad.staging_key in storage.objects
kept = database.attachments[bad.id]
assert kept.staging_key == bad.staging_key
assert good.staging_key not in storage.objects
assert database.attachments[good.id].staging_key is None
assert (
journal.errors()
== [
{
"attachment_id": bad.id,
"object_key": bad.object_key,
"reason": reason,
},
]
* 2
)
# результат сошёлся — исходник убран
storage.seed(bad.object_key, CONTENT)
assert (await _staging_pass(service)).removed_ready == 1
assert bad.staging_key not in storage.objects
async def test_staging_result_read_failure_interrupts(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
database: FakeDatabase,
journal: Journal,
) -> None:
"""Отказ S3 на чтении оригинала — прерванный проход, а не «не сошлось»."""
row = await _for_staging(uow, storage, status=AttachmentStatus.READY)
storage.seed(row.object_key, CONTENT)
database.fail_on["storage.get"] = exceptions.ObjectStorageUnavailable()
result = await _staging_pass(service)
assert result.interrupted_by == INTERRUPTED_BY_OBJECT_STORAGE
assert row.staging_key in storage.objects
assert database.attachments[row.id].staging_key is not None
assert journal.errors() == []
async def test_failed_staging_is_not_compared(
service: AttachmentCleanupService,
uow: FakeUnitOfWork,
storage: FakeObjectStorage,
) -> None:
"""У `failed` результата нет и сверять нечего: срок хранения прежний."""
row = await _for_staging(uow, storage, status=AttachmentStatus.FAILED)
assert (await _staging_pass(service)).removed_failed == 1
assert row.staging_key not in storage.objects
assert storage.calls["get"] == 0
+52
View File
@@ -15,6 +15,8 @@
import copy
import importlib.util
import io
import json
import os
import signal
import subprocess
@@ -175,6 +177,56 @@ def test_secret_table_matches_seed() -> None:
assert f"\n{variable}=" in template, variable
def test_s3_value_checked_under_staging(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
"""Ключ проверки S3 — под `staging` своей базы: пользователь worker читает
только там (change track1-worker-compromise, решение 5), и принятый ключ
вне его отвечал бы `AccessDenied` вместо «ok»."""
keys: list[str] = []
class Missing(Exception):
def __init__(self, code: str) -> None:
super().__init__(code)
self.response = {"Error": {"Code": code}}
class Client:
def get_object(self, *, Bucket: str, Key: str) -> None: # noqa: N803
keys.append(Key)
raise Missing(
"NoSuchKey"
if Key.startswith("messenger/staging/")
else "AccessDenied",
)
class Session:
def create_client(self, *_args: object, **_kwargs: object) -> Client:
return Client()
stub = ModuleType("botocore.session")
stub.get_session = Session # type: ignore[attr-defined]
monkeypatch.setitem(sys.modules, "botocore.session", stub)
monkeypatch.setattr("botocore.session", stub, raising=False)
value = {"access_key_id": "a", "secret_access_key": "b"}
monkeypatch.setattr(
sys,
"stdin",
io.StringIO(json.dumps({"old": value, "new": value})),
)
for name, text in (
("DATABASE__NAME", "messenger"),
("S3__HOST", "s3"),
("S3__PORT", "8333"),
("S3__BUCKET", "messenger"),
("CLIENT_TLS__CA_FILE", "/run/secrets/ca.crt"),
):
monkeypatch.setenv(name, text)
exec(rotation.CHECK_PY["s3"], {}) # noqa: S102
assert keys == ["messenger/staging/rotation-check"] * 2
assert json.loads(capsys.readouterr().out) == {"old": "ok", "new": "ok"}
def test_secret_readers() -> None:
bao = rotation.load_bao()
assert rotation.readers_of(bao, "postgres/api") == ["api"]
File diff suppressed because it is too large Load Diff