# Что доказывает: внешний вход лабы 7 (рубрика «3», contracts/trust-matrix.md,
#   строка «Клиент → ingress/LB» и отрицательная проверка 1): наружу только
#   HTTPS HAProxy на 127.0.0.1:HTTPS_HOST_PORT с сертификатом ingress (SAN
#   localhost, CA стенда), TLS ≥ 1.2, HTTP-порта API нет. Публичные проверки
#   skeleton (make test, make test-security), hooks (test-persistence,
#   test-failover обоих режимов), свои тесты и операторские команды ходят по
#   HTTPS с CA стенда; пустой или чужой CA и неверный hostname — ошибка
#   проверки сертификата, а не «сервер недоступен»; выключателя проверки нет.
# Дата: 2026-11-26 UTC, 20:47–20:56.
# Окружение: машина переноса (не машина замеров): macOS 26.7.1, Docker 29.9.2
#   (ВМ 12 CPU / 11,6 ГиБ), Compose 5.6.1, python3 хоста 3.11.9, OpenSSL 4.1.0.
# Стенд: рабочий vladimirceva-lab7 (make up), LB https://localhost:18443
#   (HTTPS_HOST_PORT=18443 — рядом шёл чужой стенд на 8443; прежний HTTP-порт
#   этой машины — 18180), две реплики.
# Код: src_sha256 532af6518ccba1d21169c07d33fbd6a0c0561ec307472f5cc5f1dde404978e82
#   (перенос pki-ingress-mtls).
# Повторить: make up; make test; make test-security; make student-test;
#   make test-persistence ACTION_SCRIPT=scripts/restart.sh; make failover-each
#   [STOP_MODE=kill]; make attachment-failover; make defense; команды ниже.

$ make -n test
python3 tests/smoke.py --base-url "https://localhost:18443" --ca-file "<репозиторий>/.pki/stand/ca.crt"
$ make test
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
$ make test-security
python3 tests/security.py --base-url "https://localhost:18443" --ca-file "<репозиторий>/.pki/stand/ca.crt"
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
$ make student-test
...
================ 193 passed, 34 deselected, 1 warning in 50.11s ================

## Отрицательные проверки внешнего канала

$ make test CA_FILE=   # системное хранилище: CA стенда в нём нет
FAIL: GET /health/live: connection/TLS failure (URLError)
make: *** [test] Error 1
$ make student-test CA_FILE=   # то же своим набором: причина — проверка сертификата
! _pytest.outcomes.Exit: TLS certificate of https://localhost:18443 failed verification (CA_FILE=system store): unable to get local issuer certificate !
make: *** [student-test] Error 2
$ make student-test BASE_URL=https://127.0.0.1:18443   # CA стенда, но не тот hostname
! _pytest.outcomes.Exit: TLS certificate of https://127.0.0.1:18443 failed verification (CA_FILE=<репозиторий>/.pki/stand/ca.crt): IP address mismatch, certificate is not valid for '127.0.0.1'. !
make: *** [student-test] Error 2
$ python3 tests/smoke.py --base-url https://127.0.0.1:18443 --ca-file .pki/stand/ca.crt
FAIL: GET /health/live: connection/TLS failure (URLError)
$ curl -sS --max-time 5 http://localhost:18443/health/live   # HTTP открытым текстом на порт HTTPS
curl: (52) Empty reply from server
$ curl -sS --max-time 5 http://localhost:18180/health/live   # прежний HTTP-порт стенда
curl: (7) Failed to connect to localhost port 18180 after 0 ms: Couldn't connect to server
$ openssl s_client -connect localhost:18443 -tls1_1 -cipher 'DEFAULT@SECLEVEL=0' -CAfile .pki/stand/ca.crt </dev/null
C021C9F201000000:error:0A00042E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version:ssl/record/rec_layer_s3.c:910:SSL alert number 70
New, (NONE), Cipher is (NONE)
$ openssl s_client -connect localhost:18443 -tls1_2 -servername localhost -CAfile .pki/stand/ca.crt </dev/null | grep -E "Protocol|Verify return code"
    Protocol  : TLSv1.2
    Verify return code: 0 (ok)
$ openssl s_client -connect localhost:18443 -servername localhost -CAfile .pki/stand/ca.crt </dev/null | grep -E "^subject=|^issuer=|Protocol|Verify return code"
subject=CN=ingress
issuer=CN=MTUSI lab7 vladimirceva operator CA
Protocol: TLSv1.3
Verify return code: 0 (ok)
$ docker compose ps --format "{{.Service}}\t{{.Ports}}" | sort   # у api портов на хосте нет, у LB — только HTTPS
api	8080/tcp
api	8080/tcp
cleaner	8080/tcp
grafana	127.0.0.1:13180->3000/tcp
haproxy	127.0.0.1:18443->8443/tcp
loki	3100/tcp
otel-collector	4317-4318/tcp, 55679/tcp
postgres	127.0.0.1:15433->5432/tcp
prometheus	9090/tcp
rabbitmq	127.0.0.1:15673->5672/tcp
relay	8080/tcp
s3	127.0.0.1:18334->8333/tcp
tempo
valkey	127.0.0.1:16380->6379/tcp
worker	8080/tcp
$ grep -rnE "verify=False|CERT_NONE|check_hostname *= *False|--insecure|curl -k| -k " student-tests scripts tools src Makefile bench/*.py   # выключателя проверки нет
(пусто)

## Hooks skeleton по HTTPS

$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:18443" --ca-file "<репозиторий>/.pki/stand/ca.crt"
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
$ make failover-each   # make test-failover ACTION_SCRIPT=scripts/stop-one.sh для каждой реплики, STOP_MODE=stop
=== attempt 1: docker compose ps before
...
{"observed_instances_before": 2, "successful_writes": 127, "failed_attempts": 0, "first_recovery_seconds": 1.447}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
STOP_ONE_LOG: 2026-11-26T20:50:24Z TARGET_INSTANCE_ID=7ab783f2ee64d0c4 container=0b087ad17427e42a1b0c53a66bfd7c8ec970f82ff1010a830f73b33e693ec3c0 mode=stop
=== attempt 2: docker compose ps before
...
{"observed_instances_before": 2, "successful_writes": 122, "failed_attempts": 0, "first_recovery_seconds": 1.963}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
STOP_ONE_LOG: 2026-11-26T20:50:44Z TARGET_INSTANCE_ID=2e665157adf07250 container=81f6dae7450a014a5843956b509136bc7d7399bb5f8943667113343507b68fb5 mode=stop
replicas stopped one by one: ['0b087ad17427', '81f6dae7450a']; all restored:
$ make failover-each STOP_MODE=kill
...
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 0.863}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
STOP_ONE_LOG: 2026-11-26T20:51:09Z TARGET_INSTANCE_ID=c6d8f948c805eced container=81f6dae7450a014a5843956b509136bc7d7399bb5f8943667113343507b68fb5 mode=kill
...
{"observed_instances_before": 2, "successful_writes": 127, "failed_attempts": 0, "first_recovery_seconds": 0.875}
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
STOP_ONE_LOG: 2026-11-26T20:51:30Z TARGET_INSTANCE_ID=f3c776e948225ce3 container=0b087ad17427e42a1b0c53a66bfd7c8ec970f82ff1010a830f73b33e693ec3c0 mode=kill
replicas stopped one by one: ['0b087ad17427', '81f6dae7450a']; all restored:
$ make attachment-failover
...
upload: 202 queued X-Instance-Id=ccce7c525c6d52b6 size=111817 sha256=99ea7533c441f79c… (fixture 99ea7533c441f79c…)
processed: ready variants=3
download by bob after stop: 200 X-Instance-Id=2ef33ca095a14651 after 0.52s, bytes=111817, sha256 == fixture, content-type=image/png
outsider GET /attachments/{id}: 404
outsider GET /attachments/{id}/content: 404
PASS
$ make defense
worker stopped; upload -> 202 queued
message with queued attachment -> 201
content while worker is stopped -> 409
plain text message meanwhile -> 201
...
after worker start: ready error_code=None
...
PASS
$ make s3-check
...
checks: 79, failed: 0, bootstrap exit 0
$ make telemetry-check
...
telemetry-check: PASS (22/22 checks)

# Итог: стенд отдаёт API только по HTTPS на 127.0.0.1:18443 (leaf ingress
# от CA оператора, TLS 1.2 и 1.3, TLS 1.1 — отказ, HTTP — без ответа,
# прежнего HTTP-порта нет), у реплик портов на хосте нет. Публичный smoke,
# test-security, свои тесты (193 passed, из них alias и TLS) и оба hook
# skeleton проходят по HTTPS с CA стенда; без CA стенда и с адресом вне SAN —
# ошибка проверки сертификата с причиной. stop-one.sh находит реплику по
# alias (X-Instance-Id) в режимах stop и kill, восстановление записи ≤ 2 с.
