Files
mtusi2026lab7-safronov/service-tests/db/test_worker_values.py
T
ricoromaandClaude Opus 5.5 5a9721876e fix: address track1-worker-compromise verify findings
- restore a verified row by fact: three variants give ready, otherwise
  failed with a known code instead of ready without content
- check trigger functions are not SECURITY DEFINER and pin search_path
- record the working stand comparison, the permanent drill lock file and
  the remaining SeaweedFS details

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 05:50:36 +03:00

307 lines
9.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Значения, которых роль процесса не может записать (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,
connect_as,
variant_key,
)
from conftest import TEST_DB, admin, run_alembic, truncate_all
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 _execute(role: str, statement: str, *args: object) -> str:
"""Выражение роли в своей транзакции: `ok` или SQLSTATE."""
opened = await connect_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",
]
# функции исполняет роль процесса: права вызывающего и свой search_path
# (verify W4)
functions = await connection.fetch(
"SELECT proname, prosecdef, proconfig FROM pg_proc WHERE proname IN "
"('attachment_accepted_not_pending', "
"'attachment_variant_key_namespace') ORDER BY 1",
)
assert [tuple(item) for item in functions] == [
("attachment_accepted_not_pending", False, ["search_path=pg_catalog"]),
(
"attachment_variant_key_namespace",
False,
["search_path=pg_catalog"],
),
]
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