Files
mtusi2026lab7-safronov/evidence/security/api-tls.md
T
ricoromaandClaude Opus 5.5 50cb54f0a1 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>
2026-11-16 11:38:32 +03:00

8.6 KiB
Raw Blame History

TLS процесса API (change pki-ingress-mtls)

Дата: 2026-11-16. Код: 5c514b0 и рабочее дерево apply (до коммита). Спеки transport-security («TLS API обязателен на стенде», «Консоль по HTTPS», «Health без обхода бизнес-API»), container-image («Healthcheck без сертификата клиента»). Путь репозитория — <repo>.

Консоль по HTTPS (задача 4.3)

make run_dev: pki_stand, миграции, Valkey, S3, брокер, затем процесс с API_TLS__CERT_FILE / API_TLS__KEY_FILE identity ingress (SAN localhost) и API_TLS__CLIENT_AUTH=false. Запись о старте называет режим TLS без путей, слушателя health в консоли нет:

$ make run_dev
…
{"event": "Uvicorn running on https://127.0.0.1:8080 (Press CTRL+C to quit)", …}
{"event": "Started API", …, "tls_client_auth": false, "tls_allowed_clients": 0, "health_port": null, …}

Публичный smoke по HTTPS с CA стенда по умолчанию (CA_FILE Makefile), HTTP открытым текстом на том же порту HTTP-ответа не получает:

$ make test BASE_URL=https://localhost:8080
python3 tests/smoke.py --base-url "https://localhost:8080" --ca-file "<repo>/.pki/stand/ca.crt"
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
exit=0

$ curl -sS --max-time 5 http://localhost:8080/health/live
curl: (52) Empty reply from server
exit=52

$ curl -sS --cacert .pki/stand/ca.crt -o /dev/null -w "%{http_code} %{ssl_verify_result}\n" https://localhost:8080/health/live
200 0

CA_FILE по умолчанию и из командной строки:

$ make -n test | head -1
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "<repo>/.pki/stand/ca.crt"
$ make -n test CA_FILE=/x | head -1
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/x"

На стенде (задача 8.2)

Дата: 2026-11-16. Код: fef97b3 и рабочее дерево apply (правки драйвера и документов; код приложения и стенда прежний). Рабочий стенд mtusi-lab7 после make run_docker, реплика mtusi-lab7-api-3 (alias 8caa3e42c5e48309, адрес в сети стенда 192.168.176.10). Сбор — скрипт в scratchpad сессии (docker exec с python образа, docker compose run).

Health без обхода бизнес-API

Внутри реплики к слушателю health 127.0.0.1:8081 — четыре запроса по одному соединению на каждый; синтетический username пробы ищется в таблице users до и после, затем журнал реплики с момента пробы:

users 'hprobe1794817773' before: 0
GET /health/live       -> HTTP/1.1 200 OK | Content-Type: application/json; Connection: close | {"status":"ok"}
GET /health/ready      -> HTTP/1.1 200 OK | Content-Type: application/json; Connection: close | {"status":"ok"}
GET /api/v1/users/me   -> HTTP/1.1 404 Not Found | Content-Type: application/json; Connection: close | {"error": {"code": "not_found", "message": "Not found", "request_id": "298e529ab…
POST /api/v1/users     -> HTTP/1.1 404 Not Found | Content-Type: application/json; Connection: close | {"error": {"code": "not_found", "message": "Not found", "request_id": "3e812c75f…
users 'hprobe1794817773' after: 0
records of the replica since the probe mentioning /api/v1/users or hprobe1794817773: 0

Бизнес-пути — 404 в формате контракта, пользователь не создан, записей доступа API о них нет (у слушателя нет middleware и журнала доступа).

Из другого контейнера сети стенда (worker, тот же образ) к порту health реплики по её адресу и, для сравнения, к порту API:

worker -> 192.168.176.10:8081: ConnectionRefusedError: [Errno 111] Connection refused
worker -> 192.168.176.10:8080: connected

Слушающие TCP-сокеты контейнера реплики (/proc/net/tcp и /proc/net/tcp6, состояние 0A):

/proc/net/tcp   LISTEN 127.0.0.11:35737
/proc/net/tcp   LISTEN 0.0.0.0:8080
/proc/net/tcp   LISTEN 127.0.0.1:8081

Кроме встроенного DNS Docker (127.0.0.11) — только порт API с mTLS и порт health на loopback; порт 8080 по mTLS — evidence/security/mtls-lb-api.md (без сертификата и HTTP без TLS — без HTTP-ответа).

Healthcheck без сертификата клиента

$ docker inspect -f '{{json .Config.Healthcheck.Test}}' mtusi-lab7-api-3
["CMD","python","-c","import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/health/ready' % os.environ.get('APP__HEALTH_PORT', '8081'), timeout=2)"]
/mtusi-lab7-api-3 healthy
/mtusi-lab7-api-4 healthy

В команде нет ни сертификата, ни ключа клиента, ни отключения проверки: она идёт по HTTP на loopback-слушатель, а порт API с mTLS не трогает. Обе реплики healthy.

TLS API обязателен на стенде

Одноразовые контейнеры api (docker compose run --rm --no-deps -T -e … api, те же secrets и окружение, что у реплик, одна переменная подменена). Строки: код выхода, запись «Invalid API TLS settings», число строк вывода с /run/secrets и с «Uvicorn running»:

no server key: exit=2            (-e API_TLS__KEY_FILE=/run/secrets/absent.key)
  {"event": "Invalid API TLS settings", "instance_id": "cd2fa796e115f8d1", "module": "startup", "fields": ["api_tls.key_file"], "run_mode": "<RunModeEnum.DOCKER: 'docker'>", "level": "error", "timestamp": "2026-11-16T08:29:36.844963Z", "filename": "main.py", "lineno": 139, "func_name": "main"}
  lines mentioning /run/secrets: 0  'Uvicorn running': 0
no client CA: exit=2             (-e API_TLS__CLIENT_CA_FILE=/run/secrets/absent-ca.crt)
  {"event": "Invalid API TLS settings", "instance_id": "c4d090b17984a4c4", "module": "startup", "fields": ["api_tls.client_ca_file"], "run_mode": "<RunModeEnum.DOCKER: 'docker'>", "level": "error", …}
  lines mentioning /run/secrets: 0  'Uvicorn running': 0
no CRL: exit=2                   (-e API_TLS__CRL_FILE=/run/secrets/absent-crl.pem)
  {"event": "Invalid API TLS settings", "instance_id": "56575b7ee17bb6d6", "module": "startup", "fields": ["api_tls.crl_file"], "run_mode": "<RunModeEnum.DOCKER: 'docker'>", "level": "error", …}
  lines mentioning /run/secrets: 0  'Uvicorn running': 0
client auth off: exit=2          (-e API_TLS__CLIENT_AUTH=false)
  {"event": "Invalid API TLS settings", "instance_id": "6f52bafc328b22b5", "module": "startup", "fields": ["api_tls.client_auth"], "run_mode": "<RunModeEnum.DOCKER: 'docker'>", "level": "error", …}
  lines mentioning /run/secrets: 0  'Uvicorn running': 0
empty allowlist: exit=2          (-e 'API_TLS__ALLOWED_CLIENTS=[]')
  {"event": "Invalid API TLS settings", "instance_id": "7129242ee1229f59", "module": "startup", "fields": ["api_tls.allowed_clients"], "run_mode": "<RunModeEnum.DOCKER: 'docker'>", "level": "error", …}
  lines mentioning /run/secrets: 0  'Uvicorn running': 0

Каждый случай — код 2 до uvicorn.run (сервер не стартовал, соединений не принимал), запись называет поле без пути и содержимого файла.

Фоновые процессы на том же образе без настроек TLS API:

worker: running restarts=0, API_TLS__* in env: 0, /run/secrets mounts: 0, 'Started worker' records: 2
relay: running restarts=0, API_TLS__* in env: 0, /run/secrets mounts: 0, 'Started relay' records: 2
cleaner: running restarts=0, API_TLS__* in env: 0, /run/secrets mounts: 0, 'Started cleaner' records: 2

Две записи о старте — контейнеры созданы в 03:40 (прежний make run_docker apply) и снова запущены в 08:11 этим make run_docker (журнал Docker переживает stop и start). Они работают без [api_tls] и без файлов PKI; загрузка до ready через worker и relay — make test (PASS на этом же стенде).