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
+18 -1
View File
@@ -1,6 +1,6 @@
---
name: run-mtusi-messenger
description: Запустить, остановить, прогнать и подёргать API мессенджера MTUSI (FastAPI, PostgreSQL, Valkey; лаба 3 — HAProxy перед репликами API; лаба 4 — S3 на SeaweedFS; лаба 5 — RabbitMQ, relay и worker; лаба 6 — OTel Collector, Prometheus, Loki, Tempo и Grafana; лаба 7 — HTTPS на :8443, mTLS LB → API, локальный CA) — на хосте или в Docker. Use when asked to run / start / stop the server or the stand, check telemetry (find a request in Loki and Tempo, Grafana provisioning, Collector outage, stand from scratch), run the smoke test, `make test`, `make student_test`, `make test_isolated`, `make test-persistence` or `make test-failover`, `make s3_check`, `make mtls_check` (mTLS LB → API negative checks), `make storage_tls_check` (TLS to PostgreSQL, Valkey and S3 negative checks), `make broker_mtls_check` (mTLS to RabbitMQ, relay and worker rights negative checks), `make telemetry_tls_check` (mTLS to the OTel Collector gateway negative checks), `make hardening_check` (container capabilities, users, read-only roots, pids limits, ports), `make scan` (image and uv.lock vulnerability scan with triage), `make rotation_check` / `rotate_leaf` / `revoke_identity` / `rotate_secret` / `pki_renew` (rotation and revocation on the running stand), `make pki_stand` / `pki_status` (stand certificates), check that the S3 bucket is private, run the defense scenario or its failure windows, check the broker, the worker or the relay process, show the pipeline state, stop or restore an API replica, show X-Instance-Id distribution, check that an API change works on a live server, send a request to an endpoint, reproduce a bug over HTTP, check the containers, or call services directly without HTTP.
description: Запустить, остановить, прогнать и подёргать API мессенджера MTUSI (FastAPI, PostgreSQL, Valkey; лаба 3 — HAProxy перед репликами API; лаба 4 — S3 на SeaweedFS; лаба 5 — RabbitMQ, relay и worker; лаба 6 — OTel Collector, Prometheus, Loki, Tempo и Grafana; лаба 7 — HTTPS на :8443, mTLS LB → API, локальный CA) — на хосте или в Docker. Use when asked to run / start / stop the server or the stand, check telemetry (find a request in Loki and Tempo, Grafana provisioning, Collector outage, stand from scratch), run the smoke test, `make test`, `make student_test`, `make test_isolated`, `make test-persistence` or `make test-failover`, `make s3_check`, `make mtls_check` (mTLS LB → API negative checks), `make storage_tls_check` (TLS to PostgreSQL, Valkey and S3 negative checks), `make broker_mtls_check` (mTLS to RabbitMQ, relay and worker rights negative checks), `make telemetry_tls_check` (mTLS to the OTel Collector gateway negative checks), `make hardening_check` (container capabilities, users, read-only roots, pids limits, ports), `make scan` (image and uv.lock vulnerability scan with triage), `make rotation_check` / `rotate_leaf` / `revoke_identity` / `rotate_secret` / `pki_renew` (rotation and revocation on the running stand), `make worker_compromise` (track 1 drill on an isolated stand), `make jobs_audit` (damaged jobs after an incident), `make pki_stand` / `pki_status` (stand certificates), check that the S3 bucket is private, run the defense scenario or its failure windows, check the broker, the worker or the relay process, show the pipeline state, stop or restore an API replica, show X-Instance-Id distribution, check that an API change works on a live server, send a request to an endpoint, reproduce a bug over HTTP, check the containers, or call services directly without HTTP.
---
REST API мессенджера (пользователи, чаты, сообщения) — сервер на
@@ -1081,6 +1081,23 @@ make pki_status # сроки и identity с действ
rolling_update`. Тот же код, собранный другим проектом compose, проходит (сравнение ~11 с).
- Компрометация процесса — `make revoke_identity` → `make rotate_secret` путей, которые назвал вывод → `make
rotate_leaf`: процесс с отозванной identity команды не перезапускают, `pki_stand` и `run_docker` leaf ему не выдают.
У `worker` — затем сверка заданий: `make jobs_audit`, `make jobs_audit REPAIR=1` (уборщик работает), `make replay
ERROR_CODE=… APPLY=1` ложных `failed`, `make reconcile DEEP=1`.
- **`make worker_compromise`** (change `track1-worker-compromise`) — учения «Компрометация worker» на изолированном
стенде, ~10 мин, рабочий стенд остановлен (`make stop`, иначе код 2):
```bash
make worker_compromise OUT=/tmp/track1.md # измеренный прогон: дерево и hypotheses.json закоммичены
make worker_compromise DIRTY=1 ROUNDS=1 # разработочный, «не доказательство»
make worker_compromise CONTROL=wide-rights # контроль: права шире своих — код 1, строки OPENED, ~2 мин
make worker_compromise CONTROL=no-revoke # контроль: отзыва нет — код 1 с именами материалов, ~4 мин
make worker_compromise CONTROL=no-republish # контроль: relay остановлен — код 1, LOST JOBS, ~5 мин
python3 infra/track1/track1.py --dirty --only-stand # только подъём обоих стендов и уборка, ~1,5 мин
```
`UNEXPECTED <стенд> <строка>` — исход таблицы не равен ожидаемому: сначала причина (право, дефект, пробник), ожидание
меняется только вместе с источником прав. Ctrl+C — стенд, сети, образы и каталог убраны, код 130; остаток SIGKILL
убирает следующий прогон. Окна и пороги под чужой нагрузкой хоста — не доказательство.
- Сбой команды: leaf, отзыв, продление — повтор; секрет `s3/*` и `valkey/api` — повтор или `make run_docker`
(перезапускает отставших от KV, `rotation.py outdated`), `postgres/*` — только повтор: сессий `run_docker` не закрывает,
а до конца `verify` они могут быть открыты; «an interrupted rotation» у другого пути — команда, которую назвал отказ (`postgres/*` —
+31 -3
View File
@@ -2351,6 +2351,25 @@ S3_REQUIRED_ROWS = (
"cleaner key list attachments prefix",
"cleaner key list staging prefix",
"cleaner key list database prefix",
# префиксы ключа worker (change track1-worker-compromise, решение 5)
"worker key get other database",
"worker key put other database",
"worker key get bucket root",
"worker key put bucket root",
"worker key copy from attachments",
"worker key copy from other database",
"worker key copy from attachments by dotted path",
"worker key batch delete",
"staging content after worker requests",
)
# те же строки у базы стенда и её тестовой пары
S3_REQUIRED_DATABASE_ROWS = (
"worker key get {}/staging",
"worker key put {}/attachments",
"worker key get {}/attachments",
"worker key put {}/staging",
"worker key delete {}/attachments",
"worker key delete {}/staging",
)
# слушающие сокеты контейнера S3 (busybox netstat образа): вне loopback
# должны быть только API S3 и gRPC шлюза, остальные — только на loopback.
@@ -2609,6 +2628,7 @@ def s3_stand() -> dict[str, str]:
"port": str(published["target"]),
"out_port": str(published["published"]),
"bucket": str(services["s3-bootstrap"]["environment"]["S3_BUCKET"]),
"database": str(api_env["DATABASE__NAME"]),
}
@@ -2707,7 +2727,15 @@ def cmd_s3_check() -> int:
problems.append(f"s3-bootstrap check exited with {rc}")
# bootstrap печатает строки сам; прежний bootstrap.sh их не напечатает
seen_rows = {row[1] for row in rows}
for name in S3_REQUIRED_ROWS:
database = stand["database"]
for name in (
*S3_REQUIRED_ROWS,
*(
row.format(name)
for row in S3_REQUIRED_DATABASE_ROWS
for name in (database, f"test_{database}")
),
):
if name not in seen_rows:
problems.append(f"no row from s3-bootstrap check: {name}")
# с хоста — HTTPS на localhost (SAN identity s3) с CA стенда
@@ -3688,7 +3716,7 @@ SELECT pg_temp.driver_try('second variant of the name', $q$
object_key, content_type, size_bytes, width, height, sha256,
created_at)
SELECT attachment_id, pipeline_version, variant,
object_key || '-probe', content_type, size_bytes, width, height,
object_key || 'probe', content_type, size_bytes, width, height,
sha256, now()
FROM attachment_variants WHERE attachment_id = '{attachment_id}'
$q$) \\g /dev/null
@@ -3698,7 +3726,7 @@ SELECT pg_temp.driver_try('error_code on not failed', $q$
updated_at, created_at)
SELECT gen_random_uuid(), chat_id, owner_id, filename, content_type,
size_bytes, sha256, object_key || '-probe', staging_key, status,
'probe', now(), now()
'invalid_image', now(), now()
FROM attachments WHERE id = '{attachment_id}'
$q$) \\g /dev/null
SELECT pg_temp.driver_try('replay audit of an unknown job', $q$