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>
This commit is contained in:
2026-12-02 05:50:36 +03:00
co-authored by Claude Opus 5.5
parent 55959e3805
commit 5a9721876e
15 changed files with 299 additions and 56 deletions
+16 -1
View File
@@ -7,12 +7,27 @@ from typing import Any
import asyncpg
from conftest import TEST_DB
from conftest import ROLE_PASSWORDS, TEST_DB, settings
from src.infra.tls import build_client_context
PIPELINE_VERSION = 1
VARIANTS = ("thumbnail", "crop", "optimized")
async def connect_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 add_world(connection: asyncpg.Connection) -> tuple[uuid.UUID, ...]:
"""Пользователь, чат и участник: владелец вложений."""
user, chat = uuid.uuid4(), uuid.uuid4()
+94 -1
View File
@@ -10,7 +10,14 @@ from collections.abc import AsyncIterator
import asyncpg
import pytest
from incident_rows import VARIANTS, add_attachment, add_world
from incident_rows import (
INSERT_VARIANT_SQL,
VARIANTS,
add_attachment,
add_world,
connect_as,
variant_key,
)
from conftest import ROOT, admin, truncate_all
@@ -358,6 +365,92 @@ async def test_requeued_row_is_processable(
assert tuple(row) == ("ready", None, "succeeded", 3)
async def _result(
connection: asyncpg.Connection,
attachment: uuid.UUID,
) -> tuple[object, ...]:
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 LEFT JOIN attachment_jobs j ON j.attachment_id = a.id "
"WHERE a.id = $1",
attachment,
)
return tuple(row)
@pytest.mark.parametrize(
("start", "variants", "expected"),
[
(
("failed", "failed", ()),
(),
("failed", "processing_failed", "failed", 0),
),
# строка варианта своим ключом — право worker, результата нет
(
("failed", "failed", ()),
("thumbnail",),
("failed", "processing_failed", "failed", 0),
),
(
("ready", "succeeded", VARIANTS),
(),
("ready", None, "succeeded", 3),
),
],
)
async def test_verified_restored_by_fact(
connection: asyncpg.Connection,
start: tuple[str, str, tuple[str, ...]],
variants: tuple[str, ...],
expected: tuple[object, ...],
) -> None:
"""Сверенное уборщиком: законный `failed` после срока хранения (исходник,
оригинал и варианты убраны) и сверенное готовое. Роль worker возвращает
его в `queued` — сверка называет порчу сверенного, возврат
восстанавливает по факту: три варианта — готовое, иначе снова `failed` с
известным кодом, а не `ready` без содержимого (verify W1)."""
status, state, legal_variants = start
world = await add_world(connection)
row = await add_attachment(
connection,
world,
status=status,
state=state,
staging=False,
variants=legal_variants,
)
worker = await connect_as("worker")
try:
await worker.execute(
"UPDATE attachments SET status = 'queued', error_code = NULL "
"WHERE id = $1",
row,
)
await worker.execute(
"UPDATE attachment_jobs SET state = 'queued' "
"WHERE attachment_id = $1",
row,
)
for name in variants:
await worker.execute(
INSERT_VARIANT_SQL,
row,
name,
variant_key(row, name),
)
finally:
await worker.close()
assert await _found(connection) == {row: {"verified_damaged"}}
await _repair(connection)
assert await _result(connection, row) == expected
assert await _found(connection) == {}
after = await _snapshot(connection)
await _repair(connection)
assert await _snapshot(connection) == after
async def test_job_created_for_accepted_without_job(
connection: asyncpg.Connection,
) -> None:
+18 -23
View File
@@ -14,18 +14,11 @@ from incident_rows import (
VARIANTS,
add_attachment,
add_world,
connect_as,
variant_key,
)
from conftest import (
ROLE_PASSWORDS,
TEST_DB,
admin,
run_alembic,
settings,
truncate_all,
)
from src.infra.tls import build_client_context
from conftest import TEST_DB, admin, run_alembic, truncate_all
pytestmark = pytest.mark.anyio
@@ -42,22 +35,9 @@ async def connection() -> AsyncIterator[asyncpg.Connection]:
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)
opened = await connect_as(role)
try:
try:
await opened.execute(statement, *args)
@@ -294,6 +274,21 @@ async def test_revision_on_filled_database(
"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(