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:
@@ -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
|
||||
|
||||
@@ -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
Reference in New Issue
Block a user