forked from mtusi2026/mtusi2026lab7
feat: implement pki-ingress-mtls
Local CA script, HTTPS ingress on :8443, mandatory mTLS LB -> API with an identity allowlist, separate health listener, random X-Instance-Id alias; tests, hooks and driver over HTTPS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -136,8 +136,9 @@ FastAPI, один процесс на реплику; реплик ≥2 за HAP
|
||||
версия, что `service.version`.
|
||||
- `X-Instance-Id` (лаба 3) ставит тот же middleware, что и
|
||||
`X-Request-Id`, на каждый ответ, включая health, 404 и 405. Значение
|
||||
— `settings.app.instance_id` (по умолчанию hostname процесса, в
|
||||
compose — короткий ID контейнера), вычисляется один раз при старте.
|
||||
— `settings.app.instance_id` (с лабы 7 по умолчанию — случайный alias
|
||||
процесса из 16 hex-символов, а не hostname: `settings.md`, `tls.md`),
|
||||
вычисляется один раз при старте.
|
||||
Ответ 500 собирает `ServerErrorMiddleware` снаружи пользовательских
|
||||
middleware, поэтому обработчик `Exception` в `errors.py` ставит и этот
|
||||
заголовок сам, как `X-Request-Id`.
|
||||
|
||||
@@ -136,8 +136,9 @@ unavailable» (модуль `telemetry`, `cgroup_root`) — один раз пр
|
||||
Поля — как у записей structlog: `event` «Stopped API before startup»
|
||||
(у уборщика — «Stopped cleaner before startup») и `instance_id` первыми, `module` `startup`, `signal` (`SIGTERM` /
|
||||
`SIGINT`), `level` `info`, `timestamp` ISO 8601 UTC с микросекундами и
|
||||
`Z`. `instance_id` — `APP__INSTANCE_ID` или hostname, то же значение по
|
||||
умолчанию, что `[app] instance_id`. Уровень `info`: остановку запросил
|
||||
`Z`. `instance_id` — `APP__INSTANCE_ID` или (с лабы 7) случайный alias, который
|
||||
`install()` сам кладёт в `APP__INSTANCE_ID` окружения процесса, — то же значение,
|
||||
что `[app] instance_id`; hostname в записи нет (до лабы 7 был). Уровень `info`: остановку запросил
|
||||
оператор, и она выполнена верно (design change `fix-known-issues`,
|
||||
решение 5).
|
||||
|
||||
@@ -226,8 +227,8 @@ pass». Модуль `attachment_cleanup_service`: «Finished staging cleanup pa
|
||||
## Журнал уборщика (с лабы 4)
|
||||
|
||||
Спек `service-logging`, «Журнал уборщика»; design change
|
||||
`upload-consistency`. Тот же `get_logger()`, `instance_id` — hostname
|
||||
контейнера уборщика.
|
||||
`upload-consistency`. Тот же `get_logger()`, `instance_id` — alias процесса
|
||||
уборщика (до лабы 7 — hostname контейнера).
|
||||
|
||||
- `cleaner` (`src/cleaner/main.py`): `info` «Started cleaner»
|
||||
(`interval_seconds`, `pending_grace_seconds`, `batch_size`,
|
||||
|
||||
@@ -386,8 +386,10 @@ Skeleton lab4 добавил имена `S3_*` (буквально не заво
|
||||
Соответствие имён — в `REPORT.md`.
|
||||
|
||||
`X-Instance-Id` берётся из `[app] instance_id`: по умолчанию пусто, и
|
||||
тогда валидатор поля подставляет hostname процесса (один раз, при
|
||||
загрузке `settings`); значение проверяется по `INSTANCE_ID_PATTERN`.
|
||||
тогда процесс получает случайный alias (с лабы 7 — из `early_stop.install()`
|
||||
через окружение, без него — валидатор поля, один раз при загрузке
|
||||
`settings`; до лабы 7 — hostname процесса); значение проверяется по
|
||||
`INSTANCE_ID_PATTERN`.
|
||||
Его не задают ни в `config.toml` (он смонтирован во все реплики; в
|
||||
`config_example.toml` вместо поля — комментарий), ни в `.env`, ни в
|
||||
compose (`environment` и `hostname:` сервиса `api`): у реплик одного
|
||||
|
||||
@@ -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) — на хосте или в 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`, 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 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 мессенджера (пользователи, чаты, сообщения) — сервер на
|
||||
@@ -472,7 +472,7 @@ Gotchas:
|
||||
Брокер остановлен ~5–10 с, задания ждут в PostgreSQL, relay пишет «Broker is unavailable» и
|
||||
публикует их после возврата.
|
||||
- **Без `--port` у `defense-scenario`, `defense-faults`, `worker-process`, `relay-process` — код 2**
|
||||
(«no stand on port 18080»): стенд на 8080, а порт драйвера по умолчанию 18080.
|
||||
(«no stand on port 18080»): стенд на 8443 (до лабы 7 — на 8080), а порт драйвера по умолчанию 18080.
|
||||
- **Подмена окружением.** Одноразовый контейнер `worker-process` — такой же потребитель рабочей
|
||||
очереди, у `relay-process` — такой же издатель; живёт секунды и убирается `docker rm -f`: задание
|
||||
worker вернётся по аренде, дубль relay — no-op.
|
||||
@@ -678,6 +678,15 @@ python3 .claude/skills/run-mtusi-messenger/driver.py --port 8443 mtls-check #
|
||||
docker-compose.yml -f <override> up -d --no-deps --wait api`): код 1, случай «forbidden
|
||||
identity» — HTTP 200, записи нет; вернуть — `make run_docker`. Вывод —
|
||||
`evidence/security/mtls-lb-api.md`.
|
||||
- **Команды со своим HAProxy или процессом API** (задача 7.3 change, прогон 2026-11-16) — все
|
||||
работают с лабы 7, неподдерживаемых нет: `lb-upload-timeouts` (файлы PKI стенда в LB и
|
||||
заглушку, заглушка — TLS 1.3 с проверкой клиента), `freeze-lb` (временный проект берёт
|
||||
`secrets` из `.pki/stand/`, клиенты — HTTPS с CA стенда), `freeze-sessions` (вызовы ASGI в
|
||||
процессе одноразового контейнера, TLS не нужен), одноразовый контейнер `telemetry-check` с
|
||||
`OTEL_*`, `stand-from-scratch` и `--fresh-pki` — код 0 (у `telemetry-check` до правки
|
||||
`KNOWN_ISSUES.md` «`service.version` телеметрии — 1.6.0» — одна строка FAIL, не связанная с
|
||||
TLS). Не работают до change `https-tooling` только `make test_isolated`, `make
|
||||
failure_checks`, CI и профили `bench/` (раздел в начале).
|
||||
|
||||
## Direct invocation (без HTTP)
|
||||
|
||||
@@ -728,7 +737,7 @@ HTTP-коды: `authenticate(token="x")` бросает `Unauthenticated`, не
|
||||
## Run (human path)
|
||||
|
||||
```bash
|
||||
make run_dev # Postgres + миграции, Valkey, S3 + bootstrap, затем 127.0.0.1:8080, reload по src/; Ctrl-C
|
||||
make run_dev # pki_stand, Postgres + миграции, Valkey, S3 + bootstrap, затем https://localhost:8080 (ingress, без проверки клиента), reload по src/; Ctrl-C
|
||||
```
|
||||
|
||||
Блокирует терминал — агенту не подходит, используй `driver.py start`.
|
||||
|
||||
@@ -576,7 +576,13 @@ def cmd_start(port: int) -> int:
|
||||
# Valkey работает, но мимо кэша; без S3 — 503 на путях вложений; без
|
||||
# брокера загрузка — 202, задание ждёт в PostgreSQL
|
||||
# pki_stand — файлы PKI стенда (identity ingress для HTTPS консоли)
|
||||
targets = ["pki_stand", "upgrade", "start_cache", "start_s3", "start_broker"]
|
||||
targets = [
|
||||
"pki_stand",
|
||||
"upgrade",
|
||||
"start_cache",
|
||||
"start_s3",
|
||||
"start_broker",
|
||||
]
|
||||
upgrade = subprocess.run(
|
||||
["make", *targets],
|
||||
cwd=ROOT,
|
||||
@@ -12827,11 +12833,16 @@ def cmd_stand_from_scratch(
|
||||
)
|
||||
|
||||
def stand_pki_digest() -> str:
|
||||
# отпечатки файлов PKI рабочего стенда: прогон их не трогает
|
||||
# отпечатки файлов PKI рабочего стенда: прогон их не трогает. CRL
|
||||
# не в счёт: make run_docker без --fresh-pki зовёт pki_stand того же
|
||||
# каталога, а он по design (решение 1) выпускает CRL заново всегда;
|
||||
# ca.crt, сертификаты и ключи leaf остаются прежними
|
||||
stand = pki_stand_dir()
|
||||
return hashlib.sha256(
|
||||
b"".join(
|
||||
p.read_bytes() for p in sorted(stand.glob("*")) if p.is_file()
|
||||
p.read_bytes()
|
||||
for p in sorted(stand.glob("*"))
|
||||
if p.is_file() and p.name != "crl.pem"
|
||||
),
|
||||
).hexdigest()
|
||||
|
||||
@@ -12852,7 +12863,9 @@ def cmd_stand_from_scratch(
|
||||
"PKI_STAND_DIR": str(pki_dir / "stand"),
|
||||
}
|
||||
try:
|
||||
rows.extend(scratch_run(project, run, run_env, scratch, pki_dir))
|
||||
rows.extend(
|
||||
scratch_run(project, run, run_env, scratch, pki_dir),
|
||||
)
|
||||
finally:
|
||||
remove()
|
||||
if pki_dir is not None:
|
||||
@@ -12887,7 +12900,7 @@ def cmd_stand_from_scratch(
|
||||
)
|
||||
rows.append(
|
||||
(
|
||||
f"working stand {working}: PKI files unchanged",
|
||||
f"working stand {working}: PKI files unchanged (but CRL)",
|
||||
"yes",
|
||||
yes(stand_pki_digest() == pki_before),
|
||||
),
|
||||
@@ -15461,7 +15474,9 @@ def mc_networks(container: str) -> dict[str, str]:
|
||||
nets = json.loads(raw or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return {name: str(item.get("IPAddress", "")) for name, item in nets.items()}
|
||||
return {
|
||||
name: str(item.get("IPAddress", "")) for name, item in nets.items()
|
||||
}
|
||||
|
||||
|
||||
def mc_pki(args: list[str], env: dict[str, str]) -> None:
|
||||
@@ -15527,15 +15542,18 @@ def mc_probe(
|
||||
|
||||
def mc_describe(result: dict[str, object]) -> str:
|
||||
if result.get("outcome") == "http":
|
||||
return f"HTTP {result.get('status')} {result.get('version', '')}".strip()
|
||||
return (
|
||||
f"HTTP {result.get('status')} {result.get('version', '')}".strip()
|
||||
)
|
||||
return f"no HTTP ({result.get('outcome')}: {result.get('detail', '')})"
|
||||
|
||||
|
||||
def mc_wait_healthy(container: str) -> bool:
|
||||
return bool(
|
||||
poll(
|
||||
lambda: mc_inspect(container, "{{.State.Health.Status}}")
|
||||
== "healthy",
|
||||
lambda: (
|
||||
mc_inspect(container, "{{.State.Health.Status}}") == "healthy"
|
||||
),
|
||||
timeout=MC_READY_S,
|
||||
interval=1,
|
||||
),
|
||||
@@ -15553,7 +15571,9 @@ def cmd_mtls_check(port: int) -> int:
|
||||
replicas = service_ids("api")
|
||||
lbs = service_ids("haproxy")
|
||||
if not replicas or not lbs:
|
||||
print("mtls-check: no running api replicas or haproxy: start the stand")
|
||||
print(
|
||||
"mtls-check: no running api replicas or haproxy: start the stand",
|
||||
)
|
||||
return 2
|
||||
image = mc_inspect(replicas[0], "{{.Config.Image}}")
|
||||
shared = set(mc_networks(lbs[0])) & set(mc_networks(replicas[0]))
|
||||
@@ -15749,10 +15769,22 @@ def mtls_check(
|
||||
yes(bool(rejected)),
|
||||
),
|
||||
)
|
||||
rows.extend(mc_foreign(port, image, network, api_port, project, tag, label,
|
||||
material, {a for _, a in targets.values()}))
|
||||
rows.extend(mc_control(image, network, api_port, project, tag, label,
|
||||
material))
|
||||
rows.extend(
|
||||
mc_foreign(
|
||||
port,
|
||||
image,
|
||||
network,
|
||||
api_port,
|
||||
project,
|
||||
tag,
|
||||
label,
|
||||
material,
|
||||
{a for _, a in targets.values()},
|
||||
),
|
||||
)
|
||||
rows.extend(
|
||||
mc_control(image, network, api_port, project, tag, label, material),
|
||||
)
|
||||
return report_reconcile(
|
||||
rows,
|
||||
passed="replicas accept only the haproxy identity of the stand CA; a "
|
||||
@@ -15899,8 +15931,13 @@ def mc_control(
|
||||
timeout=120,
|
||||
)
|
||||
healthy = code == 0 and mc_wait_healthy(name)
|
||||
rows = [("control replica (allowlist with the probe) healthy", "yes",
|
||||
yes(healthy))]
|
||||
rows = [
|
||||
(
|
||||
"control replica (allowlist with the probe) healthy",
|
||||
"yes",
|
||||
yes(healthy),
|
||||
),
|
||||
]
|
||||
if not healthy:
|
||||
print(out[-300:])
|
||||
return rows
|
||||
|
||||
Reference in New Issue
Block a user