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
+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