Files
mtusi2026lab7-safronov/evidence/security/rotation-revocation.md
T
ricoromaandClaude Opus 5.5 6b637109de fix: address rotation-revocation verify findings
Close handshakes and logins that started before a revocation or a
password change, converge after a failure in any phase, survive a closed
terminal, lock parallel commands and make the drill detect a dead load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:11:17 +03:00

639 lines
60 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Ротация, отзыв и продление (change `rotation-revocation`)
- Код: commit `c40fbef` (снято на рабочем дереве поверх `21b8a08` — propose, код стенда `4fde9cb` — с правками apply до
коммита, 2026-12-01; рабочее дерево и commit совпадают). Разделы 1–2 («до», пробы) сняты **до** правок кода стенда.
- Docker Desktop 29.9.3 (linux/arm64), Compose 5.7.1, ВМ 12 CPU / 11 902 МиБ, OpenSSL 3 хоста; образы стенда по digest
`docker-compose.yml` (HAProxy 3.4.7, RabbitMQ 4.3.7, OpenBao 2.7.3, PostgreSQL 18.6, Valkey 9.1.4, SeaweedFS 4.48).
- Спеки `credential-lifecycle` и дельты `pki`, `secret-store`, `transport-security`, `load-balancing`,
`object-storage`, `data-storage`; design, решения 2–15 и «Уточнения apply».
- **Роль оператора** (unseal, ротация, отзыв, продление) исполнял агент через `make bao_*`, `make pki_*` и команды
change; файлы материалов не читались. Ключей, PEM, токенов, долей и значений `.env` в выводах нет; домашний
каталог заменён на `~`.
## 1. «До»
Нагрузка — `DriverLoad` через LB (6 потоков записи, чтение, 25 запросов/с, прогрев 10 с), окно — от начала команды до
8 с после готовности реплик; одноразовый скрипт поверх функций драйвера (scratchpad). Значение в `.env` меняла функция
правки строки `rotation.py`, не печатая его.
| Действие | Команды | Прогон | Запросов | Неуспешных | Разброс неуспешных | Промежуток без успеха |
| --- | --- | --- | --- | --- | --- | --- |
| (а) пароль `postgres/api` | новая строка `.env`, `make run_docker` (9,8 и 9,9 с) | 1 | 495 | 50 (5xx) | 2,3 с | 2,88 с |
| | | 2 | 529 | 86 (5xx) | 3,3 с | 3,82 с |
| (б) leaf `haproxy` | `pki_revoke`, рестарт `api`, `pki_stand`, рестарт `api haproxy` (4,0 и 4,1 с) | 1 | 362 | 138 (132 × 5xx, 6 × обрыв) | 5,6 с | 6,11 с |
| | | 2 | 363 | 138 (132 × 5xx, 6 × обрыв) | 5,6 с | 6,17 с |
| (в) новое соединение с прежним паролем | `ALTER ROLE api`, сессии закрыты | 1 | 6 | 5 × **500 `internal_error`**, 1 × 503 (LB: готовность 503) | — | — |
В прогреве 200 из 200 успешны. После (в) — `postgres-bootstrap`, 200; `make test` — PASS, стенд возвращён.
## 2. Пробы P1–P6 на временных контейнерах
Одним сценарием (`probes.sh` в scratchpad): своя PKI во временном каталоге, контейнеры и сеть `mtusi-probe-rot-*`.
Осталось контейнеров и сетей пробы — 0, каталог удалён.
| № | Что | Получено |
| --- | --- | --- |
| P1 | `rotate` файлов `mv`: `/run/secrets/haproxy.pem` в работающем контейнере | `No such file or directory` |
| P1 | `set` / `commit ssl cert` пары `haproxy` под нагрузкой | «Success!», 51 запрос — все 200, новый номер со следующего соединения |
| P1 | `set` / `commit ssl crl-file` с прежним номером | «Success!», 49 — все 200 |
| P1 | CRL с отозванным серверным leaf `api` | backend `DOWN` через 1,2 с, живое keep-alive клиента — 503 |
| P1 | `SIGUSR2` после `mv` | новый worker не стартует («unable to load /run/secrets/crl.pem»), прежний обслуживает |
| P1 | `docker restart` LB | 4 обрыва и 2 × 503 за 0,3 с |
| P2 | CRL на работающем брокере, новое соединение отозванного `relay` | `CERTIFICATE_REVOKED`; `worker` — ok |
| P2 | живое соединение отозванного | открыто до `close_all_user_connections` |
| P2 | новая пара | до `ssl:clear_pem_cache()` отдаётся прежняя, после — новая |
| P2 | просроченный CRL → свежий | отказ (`BAD_CERTIFICATE`) → ok |
| P2 | истёкший leaf | новое — `CERTIFICATE_EXPIRED`, живое открыто; билетов TLS — 0 |
| P3 | возобновление TLS OpenBao | билет есть (7 суток), возобновлено |
| P3 | CRL загружен: вход новым, живым, возобновлённым соединением отозванного | 400, 400, 400 |
| P3 | токен отозванного: своим соединением / поверх сертификата `worker` | 200 / 200 |
| P3 | `revoke-accessor` | 403 сразу, токен `worker` — 200 |
| P3 | **CRL с прошедшим сроком**: вход действующим / отозванным | **200** / 400 |
| P3 | истёкший leaf: новый вход / вход, продление, чтение по живому соединению | отказ рукопожатия / 500, 500, 200 |
| P3 | leaf сервера: запись на месте и `SIGHUP` | новый номер, не запечатан (первый прогон не дождался 2 с — повтор с опросом) |
| P4 | `ALTER ROLE`: прежний / новый / живая сессия / `pg_terminate_backend` | отказ / ok / живёт / закрыта; билетов 0 |
| P4 | Valkey: два пароля / снятие прежнего / живое соединение | оба PONG / `WRONGPASS` / PONG до `CLIENT KILL` |
| P5 | шлюз: истёкший leaf, просроченный CRL; keep-alive; CRL заменён и рестарт | отказ, отказ (`X509_V_ERR_CRL_HAS_EXPIRED`); 404 (обслуживается); 404 (принято) |
| P6 | SeaweedFS: прежний и новый ключ вместе; удалённый | оба читают и пишут; `InvalidAccessKeyId` через 0,05 с |
## 3. Тесты и красные прогоны до кода
| Тест | До кода | После |
| --- | --- | --- |
| `service-tests/unit/test_pki_rotation.py` (11) | 7 красных: `rotate`, `--superseded`, `--not-after`, подсказка — usage, код 2 | 11 зелёных |
| `test_bao_operator.py`, отзыв токенов (6) | 3 красных: «invalid choice: 'revoke-tokens'» | зелёные |
| `test_db_errors.py` (9) | красный `28P01` («assert False») | зелёные |
| `test_api_tls.py::test_expired_client_leaf` | контроль внутри теста: тот же leaf до конца срока — 200, после — отказ, контекст: «certificate has expired» | зелёный |
| `test_failures.py::test_role_password_rejected` (стенд отказов) | «expected 503; got 500 internal_error» на прежнем `errors.py` | PASSED |
| `test_rotation.py` (57) | написан после кода; `test_one_off_containers_are_not_the_service` — красный до правки | зелёные |
~~Контроль `test_rotation.py` — 16 мутаций `rotation.py` в копии репозитория, все красные с именем теста~~ (неполно: из
30 мутаций проверяющего выжили 25 — методы `Stand` подменял `FakeStand`; перечень и итог — раздел 14, W7): CRL не
применён, прежний отозван при владельце на прежнем, отказ LB без `abort`, ротация закрывает все соединения, отзыв до
перехода, сигнал прерывает, права `.env` теряются, `seed` после хранилища, сессии не закрыты, S3 без перекрытия, значения
не проверены, `haproxy` отзывается, `renew` останавливает клиентов OpenBao, токены нового leaf отозваны, предусловие
после изменения, реплики первыми.
## 4. Брокер на работающем узле
Временный брокер, `start.sh` рабочего дерева, контейнер без capabilities, корень только на чтение.
```
relay before: connect: ok worker before: connect: ok
CRL of another CA: (1, 'rabbitmq start: stdin is not a CRL signed by the CA of the node: previous CRL kept')
expired CRL: (1, 'rabbitmq start: CRL cannot be used (verify error 12): expired or not valid yet; previous CRL kept')
not a CRL: (1, 'rabbitmq start: stdin is not a CRL signed by the CA of the node: previous CRL kept')
relay after bad CRLs: connect: ok
pair: foreign key: (1, '… the key does not match the certificate: previous pair kept')
pair: another CA / client leaf: (1, '… does not verify against the CA and CRL of the node (…): previous pair kept')
pair: no key: (1, '… stdin has no private key: previous pair kept')
served the previous pair: True
install CRL: (0, 'rabbitmq: CRL installed, nextUpdate=Dec 31 02:19:04 2026 GMT')
relay new connection: … SSLV3_ALERT_CERTIFICATE_REVOKED worker new connection: connect: ok
relay live connection: connect: ok -> after close: connect: ok | closed after 12.3s (is_closed)
worker live connection after close: connect: ok
install pair: (0, 'rabbitmq: pair installed, serial=015A06B5D916E6CC12B3E9A345E2ECDC'); clear_pem_cache: ok
served new serial: True; worker new connection: connect: ok; worker live connection: connect: ok
install CRL with the previous / current broker leaf revoked: (0, …) / (0, …)
node restarted: False; tmpfs leftovers: crl definitions.json tls; PRIVATE KEY in logs: 0
after restart: served the stand leaf: True; revoked relay: … CERTIFICATE_REVOKED; worker: connect: ok
```
## 5. Leaf и продление на рабочем стенде
Нагрузка `RotationLoad` (запись с ключом и повтором до 201, чтение, загрузки, скачивания), после каждой команды —
`make test` (PASS во всех строках).
| Команда | Секунд | Запросов | Неуспешных первых попыток | Наибольший промежуток |
| --- | --- | --- | --- | --- |
| `rotate_leaf ingress` | 2,6 | 146 | 0 | 0,25 с |
| `rotate_leaf haproxy` | 15,6 | 483 | 0 | 0,27 с |
| `rotate_leaf api` | 14,0 | 445 | 0 | 0,27 с |
| `rotate_leaf api-client` | 20,2 | 604 | 0 | 0,26 с |
| `rotate_leaf relay` | 13,2 | 420 | 0 | 0,22 с |
| `rotate_leaf cleaner` | 7,0 | 265 | 0 | 0,25 с |
| `rotate_leaf rabbitmq` | 8,9 | 312 | 0 | 0,25 с |
| `rotate_leaf otel-collector` | 29,5 | 850 | 0 | 0,28 с |
| `rotate_leaf grafana-client` | 22,0 | 650 | 0 | 0,26 с |
| `rotate_leaf valkey` (рестарт хранилища 2,0 с) | 3,9 | 179 | 0 | 0,21 с |
| `revoke_identity cleaner` (токенов отозвано 1) | 2,1 | 137 | 0 | 0,25 с |
| `rotate_leaf cleaner` (возврат) | 6,8 | 259 | 0 | 0,26 с |
| `pki_renew` без перевыпуска | 49,6 | 1376 | 0 | 0,24 с |
| `rotate_leaf openbao` — только выпуск | 3,4 | 169 | 0 | 0,27 с |
| рестарт OpenBao, `rotate_leaf relay` (код 2, запечатан), `make bao_unseal` | 6,6 | 247 | 0 | 0,26 с |
| `pki_renew` (отозвал прежний leaf `openbao`) | 48,3 | 1334 | 0 | 0,26 с |
| `pki_renew` с перевыпуском `api`, `ingress`, `relay` (leaf на 20 дней) | 63,9 | 1752 | 0 | 0,27 с |
| `rolling_update BUILD=0 MIGRATE=0` | 10,1 | 344 | 0 | 0,27 с |
- `rotate_leaf openbao`: «openbao still works with the previous leaf, which is not revoked: a restart would seal it.
Operator steps: docker compose restart openbao; make bao_unseal; make pki_renew»; контейнер прежний и `healthy`,
`pki_status` — «older leaf openbao: 1 still valid…»; после шагов — строки нет.
- `pki_renew`: каждый проверяющий назван с секундой (OpenBao 7,8, брокер 8,0, LB 8,2, шлюзы 13,6–28,3, relay 33,1,
worker 34,7, уборщик 38,8, реплики 49,6 с); leaf с остатком больше 30 дней прежние.
- `rolling_update BUILD=0 MIGRATE=0`: «build skipped», «migrate skipped», обе реплики новые, образ прежний, контейнер
`migrate` не запускался. Процесс LB (`StartedAt` 03:14:43) тот же до и после замены пары и CRL `haproxy`.
- Сверка всей нагрузки этих прогонов: 2365, 2484, 2132, 2124, 2190 и 1380 подтверждённых сообщений — каждое один раз;
50, 53, 46, 45, 47 и 30 вложений — `ready`, тот же SHA-256.
- Первый `pki_status` нового скрипта: «older leaf ingress: 1 still valid and not revoked besides the stand leaf» —
забытый прежний leaf (перевыпуск до change), отозван первой ротацией.
- CRL для LB: `set ssl crl-file` принят до 400 отозванных (26 898 байт); в CRL стенда 112.
## 6. Предусловия, отказы, сигналы
Сверка «ничего не изменено» — размер, время и inode базы CA, `crlnumber` и каждого файла `.pki/stand`, ID и `StartedAt`
контейнеров, SHA-256 `.env`.
```
unknown identity / unknown path: code 2, unchanged True | … invalid choice: 'mallory' (choose from …)
revoke haproxy | api | openbao | ingress | postgres | valkey | s3 | loki | tempo | prometheus | grafana | bao-operator:
code 2, unchanged True | … Run make rotate_leaf IDENTITY=<имя>; nothing changed (12 строк)
stopped replica: leaf haproxy | renew | secret s3/api: code 2, unchanged True | rotation: api is exited: run make run_docker first; nothing changed
ROLLOUT_CHECK=1 with a stopped replica: code 2 unchanged True | error: stopped api replicas exist: run make replicas first
ROLLOUT_CHECK=1 on the ready stand: code 0 | preconditions hold: 2 replicas UP, nothing changed
stopped relay: leaf relay: code 2, unchanged True | rotation: relay is exited: …
sealed OpenBao: secret postgres/api | leaf relay | revoke relay | renew: code 2, unchanged True | OpenBao is sealed: run make bao_unseal; nothing changed
LB while sealed: 200; bao.py revoke-tokens --role relay -> 2 | bao: OpenBao is sealed: run make bao_unseal
variable hidden by the environment: code 2, unchanged True | POSTGRES_API_PASSWORD is set in the environment and hides .env: unset it
LB, pair with a foreign key: LB refused /run/secrets/haproxy.pem: Can't commit …; the previous one is in use
LB, CRL garbage: LB refused /run/secrets/crl.pem: Can't update …; the previous one is in use
LB serial unchanged: True process the same: True ready: 200
bundle with a foreign key before sending: ingress.pem: the key does not match the certificate
SIGINT before any change: code 130 unchanged True | rotation: SIGINT before any change, stopped
SIGINT in the middle of rotate_leaf relay: code 0 — «SIGINT received: the command will be finished first», доведена
SIGINT after the new value is written (postgres/cleaner): code 0 — доведена: версия 3, прежнее отвергнуто
converged: make run_docker -> 0, «seed: 0 of 9 paths written; services to restart: none»; make test — PASS
```
~~Последняя строка — «`make run_docker` сводит»~~: она снята после доведённых команд. После сбоя посередине прежний
`run_docker` не сводил ни секрет, ни отзыв, ни leaf (раздел 14, C4).
~~Образ тега другой, чем у реплик (проба: тег с лишним файлом кода) — код 2 «runs another build»~~ (только путь, размер и
время файлов `/app` и `/usr/local`: другие ENV, CMD и файл того же размера и времени проходили — раздел 14, W5); тот же
код, собранный другим проектом compose (метки) — код 0. Учения на таком теге — код 2 «was rebuilt after the replicas started: run make
run_docker first»; на остановленном стенде — код 2 «no stand on port 8443».
## 7. Секреты
Все девять путей, под той же нагрузкой, после каждого `make test` — PASS; неуспешных первых попыток 0 в каждой строке.
| Путь | Секунд | Запросов | Промежуток | Отказ прежнего | Окно «прежнее отвергнуто — процессы заменены» |
| --- | --- | --- | --- | --- | --- |
| `s3/api` | 24,2 | 713 | 0,21 с | `InvalidAccessKeyId` | 0 (оба ключа действовали) |
| `s3/worker` | 13,4 | 425 | 0,15 с | `InvalidAccessKeyId` | 0 |
| `s3/cleaner` | 17,4 | 531 | 0,22 с | `InvalidAccessKeyId` | 0 |
| `postgres/api` | 18,6 | 562 | 0,19 с | `28P01` | 11,3 с (в учениях — оценка сверху 13,7 с) |
| `postgres/worker` | 7,9 | 284 | 0,18 с | `28P01` | ≤ 4,8 с |
| `postgres/relay` | 11,4 | 373 | 0,16 с | `28P01` | ≤ 7,5 с |
| `postgres/cleaner` | 12,3 | 400 | 0,26 с | `28P01` | ≤ 8,3 с; перезапущен только уборщик |
| `postgres/migrate` | 6,4 | 247 | 0,27 с | `28P01` | процессов нет |
| `valkey/api` | 17,6 | 539 | 0,27 с | `WRONGPASS` | ≤ 13,5 с (кэш обходится) |
Сверка: 1932 + 2636 сообщений и 41 + 56 вложений — без потерь. Сессия, открытая прежним паролем (контейнер роли
`cleaner`): «postgres: sessions of role cleaner older than the change closed: 1, left: 0», держатель — «CLOSED BY
SERVER». Первый прогон этой пробы ждал до срока: `docker compose ps` назвал контейнер `docker compose run` среди
контейнеров сервиса — исправлено (метка `oneoff`), быстрый тест красный до правки.
Два ключа S3 (спек `object-storage`): в режиме ротации прежний и новый ключ `api` — `put ok, get ok, list AccessDenied,
delete ok`, ключи `worker` и `cleaner` — ok; после обычного запуска прежний — `InvalidAccessKeyId` на всё, новый — те же
права, `worker` и `cleaner` — ok. `make s3_check` — PASS, 94 проверки.
## 8. Учения: `make rotation_check` (полный вывод)
2026-12-01T03:31:10Z, код 0. Строки `phase:` опущены; `Control` и Ctrl+C — раздел 9.
```
load started, warm-up 15 s
warm-up: failed first attempts | expected 0 | got 0
== 1. leaf rotation: ingress, haproxy
$ rotation.py leaf ingress
[ 1.9 s] rotated ingress: serial 01A9A23205315927156C54D25B0DFC38 -> 01A9A23205315927156C54D25B0DFC3D; the previous leaf is not revoked yet
[ 2.3 s] haproxy: pair ingress 01A9A23205315927156C54D25B0DFC3D
[ 2.5 s] revoked ingress: serial 01A9A23205315927156C54D25B0DFC38
[ 2.5 s] ingress: serial 01A9A23205315927156C54D25B0DFC3D in use
[ 2.5 s] done
rotate_leaf ingress: exit code | expected 0 | got 0
rotate_leaf ingress: command 2.5 s, requests 147, failed first attempts 0, longest gap 0.27 s
ingress: new serial outside, same CA and name | expected changed and equal to the stand leaf | got 1A9A23205315927156C54D25B0DFC38 -> 1A9A23205315927156C54D25B0DFC3D
ingress: failed requests | expected 0 | got 0
haproxy pair before, every replica | expected 200 | got 200
$ rotation.py leaf haproxy
[ 2.9 s] rotated haproxy: serial 01A9A23205315927156C54D25B0DFC2C -> 01A9A23205315927156C54D25B0DFC3E; the previous leaf is not revoked yet
[ 3.2 s] haproxy: pair haproxy 01A9A23205315927156C54D25B0DFC3E
[ 3.4 s] revoked haproxy: serial 01A9A23205315927156C54D25B0DFC2C
[ 13.8 s] api: done: 2 replicas 549dd61130d8 79738cecc11a UP in 10s
[ 13.9 s] api: new CRL applied
[ 13.9 s] haproxy: serial 01A9A23205315927156C54D25B0DFC3E in use
[ 13.9 s] done
rotate_leaf haproxy: exit code | expected 0 | got 0
rotate_leaf haproxy: command 13.9 s, requests 442, failed first attempts 0, longest gap 0.26 s
haproxy: failed requests | expected 0 | got 0
haproxy previous pair, every replica | expected refused: tls | got refused: tls
haproxy new pair, every replica | expected 200 | got 200
haproxy: serial | expected changed | got 1A9A23205315927156C54D25B0DFC2C -> 1A9A23205315927156C54D25B0DFC3E
== 2. secret rotation: s3/api, postgres/api
s3/api: current value is accepted before | expected ok | got ok
$ rotation.py secret s3/api
[ 2.9 s] new value written to .env: S3_API_ACCESS_KEY, S3_API_SECRET_KEY
[ 6.9 s] s3-bootstrap: both keys are valid
[ 7.1 s] openbao: messenger/s3/api version 8
[ 16.3 s] api: done: 2 replicas 5373e5cd19f6 ae2087eb04c6 UP in 8s
[ 16.4 s] api: loaded s3/api version 8
[ 20.5 s] s3-bootstrap: done
[ 21.5 s] s3/api: previous value refused (InvalidAccessKeyId), new accepted
[ 21.5 s] s3/api: version 8, services api; window between the refusal of the previous value and the last replaced process: 0 s (both keys were valid until the processes moved); total 21.5 s
[ 21.5 s] done
rotate_secret s3/api: exit code | expected 0 | got 0
rotate_secret s3/api: command 21.6 s, requests 645, failed first attempts 0, longest gap 0.27 s
s3/api: only its version changed | expected s3/api | got s3/api
s3/api: version 7 -> 8
s3/api: previous value refused, new accepted | expected yes | got yes
s3/api: failed requests | expected 0 | got 0
s3/api: keys of the user | expected 1 | got 1
postgres/api: current value is accepted before | expected ok | got ok
$ rotation.py secret postgres/api
[ 2.9 s] new value written to .env: POSTGRES_API_PASSWORD
[ 3.1 s] openbao: messenger/postgres/api version 10
[ 6.0 s] postgres-bootstrap: done
[ 16.7 s] api: done: 2 replicas 10fbfa4eea9b 1a77dc1c0f47 UP in 10s
[ 16.8 s] api: loaded postgres/api version 10
[ 17.1 s] postgres: sessions of role api older than the change closed: 0, left: 0
[ 17.9 s] postgres/api: previous value refused (28P01), new accepted
[ 17.9 s] postgres/api: version 10, services api; window between the refusal of the previous value and the last replaced process: at most 13.7 s; total 17.9 s
[ 17.9 s] done
rotate_secret postgres/api: exit code | expected 0 | got 0
rotate_secret postgres/api: command 17.9 s, requests 550, failed first attempts 0, longest gap 0.26 s
postgres/api: only its version changed | expected postgres/api | got postgres/api
postgres/api: version 9 -> 10
postgres/api: previous value refused, new accepted | expected yes | got yes
postgres/api: sessions older than the change are closed | expected yes | got yes
postgres/api: longest gap without a successful response | expected <= 2 s | got 0.26 s
postgres/api: failures other than 503 | expected none | got none
== 3. sealed OpenBao
bao seal | expected 0 | got 0
$ rotation.py secret postgres/api
rotation: OpenBao is sealed: run make bao_unseal; nothing changed
sealed: rotate_secret postgres/api exit code | expected 2 | got 2
sealed: the hint | expected yes | got yes
sealed: .env unchanged | expected yes | got yes
sealed: failed requests through the LB | expected 0 | got 0
bao unseal | expected 0 | got 0
sealed: KV versions unchanged | expected yes | got yes
== 4. revoke relay
TLS session ticket from openbao | expected yes | got yes
TLS session ticket from rabbitmq | expected no | got no
TLS session ticket from otel-collector | expected no | got no
TLS session ticket from api | expected no | got no
TLS session ticket from api | expected no | got no
before: new connections of relay | expected {'amqp': 'ok', 'otlp': 'ok', 'login': '200'} | got {'amqp': 'ok', 'otlp': 'ok', 'login': '200'}
before: held by the stolen leaf | expected {'amqp': 'open', 'otlp': 'open', 'login': '200', 'token': '200', 'ticket': 'yes'} | got {'amqp': 'open', 'otlp': 'open', 'login': '200', 'token': '200', 'ticket': 'yes'}
before: resumed login | expected resumed 200 | got resumed 200
$ rotation.py revoke relay
[ 2.0 s] revoked relay: serial 01A9A23205315927156C54D25B0DFC3A
[ 2.0 s] revoked relay: serial 01A9A23205315927156C54D25B0DFC3C
[ 2.0 s] openbao: new CRL applied
[ 2.2 s] openbao: role relay: revoked 4 tokens
[ 2.3 s] rabbitmq: new CRL applied
[ 2.8 s] rabbitmq: connections of relay closed
[ 8.4 s] otel-gateway: restarted in 5.5 s
[ 8.4 s] otel-gateway: new CRL applied
[ 8.4 s] relay is revoked; seconds from the start to the new CRL: openbao 2.0 s, rabbitmq 2.3 s, otel-gateway 8.4 s
[ 8.4 s] secrets issued to it are still valid (make rotate_secret SECRET=…); to return the service: make rotate_leaf IDENTITY=relay
[ 8.4 s] done
revoke_identity relay: exit code | expected 0 | got 0
revoke_identity names the window of every checker | expected openbao rabbitmq otel-gateway | got openbao rabbitmq otel-gateway
revoked: new AMQP connection (broker) | expected refused: certificate revoked | got refused: certificate revoked
revoked: new OTLP (otel-gateway) | expected refused: certificate revoked | got refused: certificate revoked
revoked: new login (OpenBao) | expected 400 | got 400
revoked: live amqp connection (broker) | expected closed | got closed 2.9 s
revoked: live otlp connection (otel-gateway) | expected closed | got closed 3.3 s
revoked: token read | expected 403 | got 403
revoked: token over the certificate of worker | expected 403 | got 403
revoked: login by the resumed TLS session (OpenBao) | expected resumed 400 | got resumed 400
others: worker new connections | expected {'amqp': 'ok', 'otlp': 'ok', 'login': '200'} | got {'amqp': 'ok', 'otlp': 'ok', 'login': '200'}
others: api-client new connections | expected {'otlp': 'ok', 'login': '200'} | got {'otlp': 'ok', 'login': '200'}
revoked: upload is accepted and waits | expected 202 queued | got 202 queued
revoked: failed requests through the LB | expected 0 | got 0
$ rotation.py leaf relay
[ 2.2 s] rotated relay: serial 01A9A23205315927156C54D25B0DFC3C -> 01A9A23205315927156C54D25B0DFC3F; the previous leaf is not revoked yet
[ 7.2 s] relay: restarted in 5.1 s
[ 7.4 s] relay: only the stand leaf is valid; nothing to revoke
[ 7.5 s] openbao: new CRL applied
[ 7.6 s] openbao: role relay: revoked 0 tokens, kept 1
[ 7.7 s] rabbitmq: new CRL applied
[ 8.3 s] rabbitmq: old connections of relay closed: 0
[ 10.8 s] otel-gateway: restarted in 2.5 s
[ 10.8 s] otel-gateway: new CRL applied
[ 10.8 s] relay: serial 01A9A23205315927156C54D25B0DFC3F in use
[ 10.8 s] done
rotate_leaf relay: exit code | expected 0 | got 0
returned: the waiting upload is ready | expected ready | got ready
returned: the stolen leaf is still refused | expected {'amqp': 'refused: certificate revoked', 'otlp': 'refused: certificate revoked', 'login': '400'} | got {'amqp': 'refused: certificate revoked', 'otlp': 'refused: certificate revoked', 'login': '400'}
returned: the new leaf of relay | expected {'amqp': 'ok', 'otlp': 'ok', 'login': '200'} | got {'amqp': 'ok', 'otlp': 'ok', 'login': '200'}
revocation window (command) 8.4 s; relay was without a leaf 29.8 s
== 5. expired leaf
issued relay (client, SAN relay): serial 01A9A23205315927156C54D25B0DFC40, not after 2026-12-01 03:33:47Z
issue relay --not-after | expected 0 | got 0
issued haproxy (client, SAN haproxy): serial 01A9A23205315927156C54D25B0DFC41, not after 2026-12-01 03:33:47Z
issue haproxy --not-after | expected 0 | got 0
before the end: relay, new connections | expected {'amqp': 'ok', 'otlp': 'ok', 'login': '200'} | got {'amqp': 'ok', 'otlp': 'ok', 'login': '200'}
before the end: every replica | expected 200 | got 200
before the end: held AMQP connection and token | expected open 200 | got open 200
expired: broker, otel-gateway, OpenBao refuse | expected {'amqp': 'refused: certificate expired', 'otlp': 'refused: certificate expired', 'login': 'refused: certificate expired'} | got {'amqp': 'refused: certificate expired', 'otlp': 'refused: certificate expired', 'login': 'refused: certificate expired'}
expired: every replica refuses | expected refused: tls | got refused: tls
expired: AMQP connection opened earlier lives (limitation) | expected open | got open
expired: token obtained earlier reads (limitation) | expected 200 | got 200
$ rotation.py leaf relay
[ 2.2 s] rotated relay: serial 01A9A23205315927156C54D25B0DFC3F -> 01A9A23205315927156C54D25B0DFC42; the previous leaf is not revoked yet
[ 6.8 s] relay: restarted in 4.6 s
[ 6.9 s] revoked relay: serial 01A9A23205315927156C54D25B0DFC3F
[ 7.1 s] openbao: new CRL applied
[ 7.2 s] openbao: role relay: revoked 4 tokens, kept 1
[ 7.3 s] rabbitmq: new CRL applied
[ 8.5 s] rabbitmq: old connections of relay closed: 1
[ 14.0 s] otel-gateway: restarted in 5.5 s
[ 14.0 s] otel-gateway: new CRL applied
[ 14.0 s] relay: serial 01A9A23205315927156C54D25B0DFC42 in use
[ 14.0 s] done
rotate_leaf relay: exit code | expected 0 | got 0
the command closes the connection of the expired leaf | expected closed | got closed 33.3
the command revokes its token | expected 403 | got 403
== 6. results
confirmed messages present exactly once | expected lost 0, duplicated 0, unconfirmed 0 | got 4108 confirmed
accepted attachments ready with the same SHA-256 | expected lost 0 | got 87 accepted
downloads with other bytes | expected 0 | got 0
load of the whole drill: 175 s, 4541 requests, failed first attempts 0
images of every container are the same as before | expected yes | got yes
make test | expected 0 PASS | got 0 PASS
older leaf broker-probe: 2 still valid and not revoked besides the stand leaf
older leaf mtls-probe: 1 still valid and not revoked besides the stand leaf
older leaf s3-grpc-probe: 1 still valid and not revoked besides the stand leaf
older leaf telemetry-probe: 3 still valid and not revoked besides the stand leaf
CRL: next update 2026-12-31 03:33:57Z (30 days, ok), revoked 112, ~/MTUCI/high_load/mtusi2026lab7-safronov/.pki/stand/crl.pem
pki_status: identities of the list with older valid leafs | expected none | got none
PASS: 74 checks
cleanup: probe containers left 0, leaf copies removed, openbao healthy, relay running: yes
```
~~Строка «postgres/api: sessions older than the change are closed»~~ в этом выводе ничего не доказывала: удерживаемой
сессии не было («closed: 0»), а «неуспешных 0» печаталось бы и при мёртвых потоках нагрузки (раздел 14, W6).
Прошлые полные прогоны того же дня: 72 и 74 проверки — PASS (0 неуспешных из 4603 и 4600 запросов); три красных, причины
разобраны: клиент учений терял причину отказа реплики (`BrokenPipe` раньше чтения) и падал в `state` на истёкшем leaf —
дефекты клиента; последняя строка `pki_status` считала разовые leaf соседних проверок и тег, пересобранный стендом
отказов, — правки «Уточнений apply», пп. 1 и 15.
### Сводка «до / после»
| Действие | До (раздел 1): неуспешных, промежуток | После: неуспешных, промежуток |
| --- | --- | --- |
| пароль `postgres/api` | 50 из 495 и 86 из 529; 2,88 и 3,82 с | 0 из 550; 0,26 с; окно ≤ 13,7 с |
| leaf `haproxy` | 138 из 362 и 138 из 363; 6,11 и 6,17 с | 0 из 442; 0,26 с |
| leaf `ingress` | рестарт LB (в строке выше) | 0 из 147; 0,27 с |
| ключ `s3/api` | реплики разом, перекрытия нет | 0 из 645; 0,27 с |
| отзыв `relay` | живое соединение и токен работают дальше | OpenBao 2,0 с, брокер 2,3 с, шлюз 8,4 с; ~~живые AMQP и OTLP закрыты~~ открытые AMQP и OTLP закрыты через 2,9 и 3,3 с; начатые, но не завершённые входы AMQP отзыв переживали (раздел 14, C1) |
| прежний пароль роли, новое соединение | 500 | 503, повтор с тем же ключом проходит |
## 9. Контроль и прерывание
`make rotation_check CONTROL=skip-crl` (отзыв только файлами, `pki.sh revoke relay`) — код драйвера 1 (make 2):
```
FAIL revoked: new AMQP connection (broker): expected refused: certificate revoked, got ok
FAIL revoked: new OTLP (otel-gateway): expected refused: certificate revoked, got ok
FAIL revoked: new login (OpenBao): expected 400, got 200
FAIL revoked: live amqp connection (broker): expected closed, got open
FAIL revoked: live otlp connection (otel-gateway): expected closed, got open
FAIL revoked: token read: expected 403, got 200
FAIL revoked: token over the certificate of worker: expected 403, got 200
FAIL revoked: login by the resumed TLS session (OpenBao): expected resumed 400, got resumed 200
FAIL: 8 of 18 checks
restore: rotate_leaf relay: 0
cleanup: probe containers left 0, leaf copies removed, openbao healthy, relay running: yes
```
Ctrl+C через 2,3 с после начала `revoke_identity relay`: «interrupted: waiting for the operator command» — команда
доведена (`done`), `rotate_leaf relay` — 0, «probe containers left 0, leaf copies removed, openbao healthy, relay running:
yes», код драйвера 130; контейнеров по метке и каталогов `mtusi-rotation-*` нет, `make bao_status` — `sealed=False`, leaf
`relay` действует, прежних действующих нет, `make test` — PASS.
## 10. Регрессия на рабочем стенде
| Команда | Код | Итог |
| --- | --- | --- |
| `make test`, `make test-security` | 0, 0 | PASS |
| `make student_test` | 2 | 233 passed, 2 failed — известные: `test_exclusion_evidence_exists` (последний шаг лабы), `test_every_scenario_is_covered` (маркер «Пароль роли отвергнут» до archive) |
| `make test-persistence` | 0 | PASS |
| `make test-failover` (`stop`, `kill`) | 0, 0 | PASS |
| `make mtls_check`, `storage_tls_check`, `storage_roles_check`, `broker_mtls_check`, `telemetry_tls_check`, `bao_check` | 0 × 6 | PASS |
| `make s3_check` | 0 | PASS: 94 |
| `make hardening_check` сразу и после ≥ 11 мин (Loki 14 мин) | 0, 0 | PASS: 674 |
| `driver.py openbao-outage` | 0 | PASS, роли и процессы возвращены |
| `make rolling_update` (со сборкой) | 0 | 14 с |
| `driver.py telemetry-check` | 1 | единственная строка `service.version` 1.7.0 / 1.6.0 — известная (`KNOWN_ISSUES.md`) |
| `make test_isolated` | 2 | smoke 0, `student_test` — те же 2 известных |
| `make failure_checks FAULT_ARGS='-k "role_password or openbao or secret_new_version"'` | 0 | 7 passed, сводка секретов 0 |
## 11. Поиск утечек
За учения раздела 8: 21 значение секретов `.env` (до и после), 75 строк ключей `.pki/stand`, токены `s.…`, строки «PRIVATE
KEY» — вывод команд 0; argv процессов хоста 0 (976 снимков `ps`, 639 разных строк); журналы 23 контейнеров (3,8 МиБ) — 1;
`docker inspect` 23 контейнеров (PEM, токены, строки ключей) 0; 949 файлов рабочего дерева 0. Единственное совпадение —
журнал SeaweedFS: `InvalidAccessKeyId: attempted key '<20 hex>' not found` — **идентификатор** удалённого прежнего ключа из
проверки отказа, не секрет; по текущим значениям `.env` совпадений в журналах 0.
## 12. Сценарии дельт: 69, без доказательства — 0
~~69~~ — число на `c40fbef`; сценарии правок verify и их доказательства — раздел 14.
| Спек | Сценарий | Доказательство |
| --- | --- | --- |
| credential-lifecycle | Ротация клиентского leaf балансировщика под нагрузкой; Ротация внешнего сертификата; Образы прежние | раздел 8, шаги 1 и 6; раздел 5 |
| | Ротация leaf фонового процесса | разделы 5 и 8 (`rotate_leaf relay`, прежний отвергнут брокером, шлюзом, OpenBao; загрузка `ready`) |
| | Leaf OpenBao | раздел 5; `test_leaf_of_openbao` |
| | Identity, которую отзывают только заменой | раздел 6; `test_revoke_only_by_rotation`, `test_revoke_refused` |
| | Новое подключение отозванной identity; Живые соединения и токен; Работа не теряется; Окно отзыва названо | раздел 8, шаги 4 и 6 |
| | Возобновление сессии TLS; Нет билетов у проверяющих | раздел 8, шаг 4 |
| | Ротация ключа S3; пароля роли; секрета фонового процесса | разделы 7 и 8 |
| | Запечатанный OpenBao; Неизвестный путь | раздел 8, шаг 3; раздел 6; `test_unknown_name` |
| | Продление под нагрузкой; Забытый прежний leaf виден | раздел 5; `test_rotate_keeps_previous_leaf` |
| | Истёкший leaf; Соединение, открытое до истечения | раздел 8, шаг 5; `test_expired_client_leaf` |
| | Просроченный CRL | раздел 2, P2 и P5 |
| | Учения на рабочем стенде; Расхождение называется; Прерывание учений | разделы 8 и 9 |
| | Стенд не готов; Прерывание ротации секрета; Вывод без секретов | разделы 6 и 11; `test_signal_after_change_is_deferred` |
| | Жизненный цикл в матрице | `contracts/trust-matrix.md`, «Lifecycle»; `security/THREAT_MODEL.md`; `REPORT.md`; `grep` отсылок как к будущему — 0 |
| pki (новое) | Новый leaf рядом; Отзыв только прежних; Отзывать нечего; Leaf с концом срока; Подсказка применения отзыва | `test_pki_rotation.py`; разделы 5 и 8 |
| | CRL с прошедшим сроком у OpenBao | раздел 2, P3 |
| pki (прежнее) | Отозванный leaf в CRL; Отзыв неизвестной identity | `test_pki_rotation.py`; `pki.md` |
| | Отозванный клиент брокера / Collector / хранилищ / OpenBao; CRL не нужен клиентам хранилищ | `broker-mtls.md` 7, `telemetry-mtls.md` 7, `telemetry-backends-tls.md` 7, `openbao-secrets.md` 8, `pki.md`; проверки раздела 10 |
| secret-store | Токены отозванной identity; Токен нового leaf остаётся | раздел 8, шаги 4–5 («revoked 4, kept 1»); `test_bao_operator.py` |
| | Запечатанный OpenBao при отзыве токенов | раздел 6; `test_revoke_tokens_sealed` |
| transport-security (новое) | Отозванный клиент без перезапуска брокера; Закрытие живых соединений; Новая пара; Негодный материал | раздел 4; раздел 8, шаг 4 |
| transport-security (прежнее) | порты пространств шлюзов; Collector / хранилище остановлены; рестарт шлюза; сломанный TLS шлюза (8) | `telemetry_tls_check`, `telemetry-check` (раздел 10), `telemetry-mtls.md`, `telemetry-backends-tls.md`; рестарт шлюза с Collector и хранилищем — раздел 5 |
| load-balancing | Замена на том же образе; Только предусловия | разделы 5 и 6 |
| | Новая пара и CRL на работающем LB; Отозванная реплика; Негодный материал | разделы 5 и 8; раздел 2, P1 (`DOWN` 1,2 с); раздел 6 |
| object-storage | Оба ключа действуют; Прежний ключ убран; Ключи других пользователей | раздел 7 |
| data-storage | Пароль роли отвергнут | `test_role_password_rejected` (раздел 3 и 10) |
| | БД остановлена; БД вернулась; Предел соединений | `make failure_checks FAULT_ARGS='-k "database_stopped or connection_limit or role_password"'` — 4 passed, код 0 |
## 13. Проверки проекта и состояние
`make lint` — 0; `make check` — 0; `make validate PYTHON=.venv/bin/python` — 0; `make service_test` — 884 passed; `make
service_test_db` — 124 passed; `make alerts_test` — 0; `graphify update .` — 0; `openspec validate rotation-revocation
--strict` — valid; `wc -c AGENTS.md` ≤ 32768. `.env` и KV стенда согласованы («seed: 0 of 9 paths written»), прежних
действующих leaf у identity списка нет. После прогонов стенд остановлен (`make stop`), контейнеров и сетей `mtusi-probe-rot*`
и каталогов с копиями leaf нет, материалы оператора на месте (имена и права).
## 14. Правки verify, рабочее дерево поверх `f702a70`
2026-12-01, рабочий стенд (2 реплики), код — рабочее дерево; «до» — `f702a70`, снято **до** правок теми же клиентами.
Решения — design, «Уточнения verify». Пробы — префикс `mtusi-probe-rot`, порча базы и параллельный выпуск — на временной
PKI. Значений, ключей, PEM и токенов в выводах нет.
### Находки: как падало и чем доказано
| № | До | После |
| --- | --- | --- |
| C1 | клиент начинает входы AMQP `relay` каждые 0,4 с (TLS без заголовка; `connection.start`) и завершает их после `done` отзыва: 63 начато, **26 открылись** отозванным leaf (`running` у брокера); ротация: `list_connections` ждал входящие 15 с | отзыв `relay`: 101 начато, открылись 0; ротация `worker`: 109 начато, 0, у брокера — только соединения новым leaf. Клиент учений завершает половину **во время** команды: отзыв — 22 открылись и закрыты, после команды 0 из 93; ротация — 30 и 0 из 110 |
| C2 | `rotate_secret postgres/cleaner`, «left: 0», а из 15 начатых входов **4 завершились прежним паролем** (по 2 до и после server-first) и живут дальше | 15 начатых: 6 закрыты, 9 — 28P01, открылись 0 («closed: 7, left: 0») |
| C3 | `cleaner`: `revoke_identity` 0 → `rotate_secret` — код 1 через 126 с, повтор и `rotate_leaf` — код 2 «run make run_docker first», `pki_stand` — «reissue cleaner: revoked» | таблица ниже |
| C4 | leaf: после `run_docker` (0) — «older leaf relay: 1»; отзыв: шлюз «Up 7 minutes» со старым CRL, leaf `worker` перевыпущен; секрет: `run_docker` — «0 of 9 written … none», после обрыва сессий 503, `rotate_secret` / `renew` — код 2, `rolling_update` — «not UP», `run_docker` 0 и снова 503 | таблица отказов ниже |
| C5 | `make rotate_secret … \| head -2`: `BrokenPipeError`, код 120, KV 4 / процесс 3; закрытый pty посреди `rotate_leaf cleaner`: «older leaf cleaner: 1» | труба: KV 5 / процесс 5, `outdated` пуст; pty: доведена за 5,1 с, прежних 0 |
| W1 | `pki_revoke worker`, `pki_renew` — 0: AMQP `open`, токен 200 | AMQP `closed`, токен 403 и поверх leaf `worker`, вход возобновлённой сессией 400 |
| W2 | keep-alive `otel-collector-client` на `:8404` (запрос раз в 1,5 с) через отзыв: 31 ответ, обслуживается и через 30 с | «server closes after every response», отказ рукопожатия на следующем запросе (`certificate revoked`) |
| W3 | 12 параллельных `pki.sh issue` на временной PKI: 4 сбоя (у проверяющего — 11 и база испорчена) | 12 из 12, номера разные, следующий `rotate` — 0; вторая команда `rotation.py` — код 2 «another rotation command is running» |
| W4 | `postgres/worker` остановлен до `seed`, `rotate_secret s3/cleaner` — 0, worker перезапущен на пароле, которого в PostgreSQL нет | код 2 «messenger/postgres/worker in OpenBao differs from .env (an interrupted rotation)»; «KV записан, PostgreSQL — нет» — тоже код 2; `run_docker` сводит («restart services with old secret versions: worker») |
| W5 | сверка путей, размеров и времени `/app`, `/usr/local` | код отказа: новый и изменённый ENV, CMD, ENTRYPOINT, USER, HEALTHCHECK, `/etc/probe`, права, файл того же размера и времени (`COPY`); метка другого проекта — 0. На стенде: тег пересобран `mtusi-lab7-failures` (манифест другой) — предусловия 0, `rotate_leaf haproxy` 0, `rolling_update BUILD=0` 0. `RUN sed` + `touch -d` в той же пробе дал «тот же» верно: BuildKit такой слой не записал |
| W6 | «PASS: 74» при мёртвых потоках | контроль ниже |
| W7 | 25 из 30 мутаций выжили | 155 из 155 красные, ниже |
| W8 | SIGKILL `rotation.py`, когда новая реплика создана / готова / прежняя в `drain`: 3 реплики, в третьем случае слот `api-3` в ручном состоянии, предусловия — код 2 | все три точки: 2 реплики, ручных слотов нет, предусловия — 0 |
| W9 | gRPC `:18333` с leaf `worker` / `relay`: HTTP/2 200 (`unknown service`) | `worker`, `relay`, `api-client`, `cleaner` — `BAD_CERTIFICATE`; `make s3_check` — 94 |
| S1 | — | `test_env_symlink_and_indent` |
| S2 | «Started API», записей о причине 0 | «Database refused login» `sqlstate` 28P01 — одна на процесс за 20 с проб, после bootstrap «Database accepts login again», реплики `healthy` без перезапуска; значения в журнале нет |
| S3 | — | проба OpenSSL 4.1: истёкший отозванный после `ca -updatedb` и `-gencrl` в CRL остался; LB (`set`, `abort`): 1950 номеров — принято, 1970 — «The payload is too big»; в CRL стенда 292 (19,7 КБ): предел назван |
| S4 | каталог с 4 ключами остался после SIGKILL | следующий прогон: «removed leaf copies of a killed run: mtusi-rotation-…», каталогов 0 |
| S5, S6, S7 | — | `test_any_error_has_code_and_phase`, `test_status_marks_revoked`; строки ≤ 79 |
Новые быстрые тесты на коде `f702a70`: `test_pki_rotation.py` — 9 красных, `test_rotation.py` и `test_rotation_stand.py` — 69.
**Найдено прогонами сверх списка**: `bao.py revoke-tokens` падал на accessor, истёкшем между списком и поиском (OpenBao 2.7
отвечает 400 «invalid accessor», принимались 403 / 404) — код 1 в фазе CRL; исправлено, мутация красная.
### Порядок реагирования целиком (C3)
Сессия и начатый вход PostgreSQL прежним паролем удерживаются с начала.
| Шаг | `cleaner` | `relay` |
| --- | --- | --- |
| `make revoke_identity` | 0, 2,0 с; вывод называет `rotate_secret postgres/cleaner`, `s3/cleaner` | 0, 20,6 с (сроки брокера) |
| `make pki_stand` | «held cleaner: revoked…», leaf прежний | «held relay…» |
| `make rotate_secret` | `postgres/cleaner` 0, 8,2 с; `s3/cleaner` 0, 12,9 с; «cleaner: identity cleaner is revoked, not restarted» | `postgres/relay` 0, 8,7 с |
| удерживаемые сессии | 3 из 3 закрыты сразу («closed: 4, left: 0») | 3 из 3 |
| `make run_docker` | 0, «held», leaf не выдан, уборщик `Restarting (2)` после пересоздания | 0, «held» |
| `make pki_status` | «REVOKED, held until make rotate_leaf IDENTITY=cleaner» | то же |
| `make rotate_leaf` | 0, 6,9 с, из `Restarting` в работу | 0, 26,3 с |
| `make test` | PASS | PASS |
### Отказ в каждой фазе: команда × фаза → чем сходится (C4)
Вызов процесса подменяется отказом **до** исполнения или **после** него; команда — код 1 с фазой; затем названная команда.
Сверка каждой строки: сервисы готовы, `.env` = KV = процессы, прежних действующих и отозванных leaf нет, владельцы на своих
leaf, прежнее значение отвергнуто хранилищем, новое принято, `make test` — PASS. 102 прогона, расхождений 0 (после отзыва —
ещё `rotate_leaf`).
| Команда | Фаза | Где отказ | Сходится | Прогонов |
| --- | --- | --- | --- | --- |
| `leaf relay` | issue | `pki.sh rotate` до, после | повтор | 2 |
| | owner | рестарт `relay` до, после | повтор | 2 |
| | revoke previous | `pki.sh revoke` до, после | повтор | 2 |
| | CRL | `configure`, `revoke-tokens`, `--install-crl`, закрытие соединений, рестарт шлюза до и после | повтор | 6 |
| | late connections | повторное закрытие | повтор | 1 |
| `leaf haproxy` | owner, revoke previous, CRL | runtime API; `pki.sh revoke`; замена реплик до, после | повтор | 4 |
| `leaf api-client` | owner, revoke previous | замена реплик; `pki.sh revoke` после | повтор | 2 |
| `leaf rabbitmq` | owner, CRL | `--install-leaf` до, после; сброс кэша; рестарт `worker` | повтор | 4 |
| `revoke relay` | revoke, CRL, late connections | `pki.sh revoke` до, после; шесть вызовов CRL; повторное закрытие | повтор | 9 |
| `renew` | issue, owners, revoke previous | `pki.sh stand`, рестарт владельца, `pki.sh revoke` — до и после | повтор | 6 |
| | CRL, late connections | OpenBao, токены, брокер, LB, шлюз, worker, замена реплик; повторное закрытие | повтор | 8 |
| `secret postgres/api` | seed, storage, processes, sessions, verify | `seed`, bootstrap, замена реплик — до и после; psql; проверка значений | повтор; `run_docker` | 9 + 9 |
| `secret postgres/relay` | .env, seed, storage, previous sessions, processes, sessions | запись `.env`, `seed`, bootstrap, psql, рестарт | повтор; `run_docker` | 6 + 6 |
| `secret s3/cleaner` | .env, storage, seed, processes, remove previous, verify | запись `.env`, bootstrap до и после, `seed`, рестарт, bootstrap, проверка | повтор; `run_docker` | 7 + 7 |
| `secret valkey/api` | .env, seed, storage, processes, verify | запись `.env`, `seed`, пересоздание до и после, замена реплик, проверка | повтор; `run_docker` | 6 + 6 |
`run_docker` сессий прежнего пароля не закрывает — вывод это говорит: «Repeat `make rotate_secret …` to converge: `make
run_docker` only restores the service, sessions of role … opened with the previous password stay open». Две строки первого
прохода были красными не от отказа: номер вызова, до которого `renew` не дошёл (проба), и 400 у `revoke-tokens` (дефект
выше); обе повторены.
### Учения и красный контроль (W6)
`make rotation_check` — код 0, 262 с, **86 проверок**; 6592 запроса, неуспешных первых попыток 0; 5961 сообщение — каждое
один раз, 127 вложений `ready`, тот же SHA-256; образы прежние.
```
rotate_leaf ingress: command 2.6 s, requests 147, failed first attempts 0, longest gap 0.27 s
rotate_leaf haproxy: command 15.1 s, requests 471, failed first attempts 0, longest gap 0.28 s
rotate_secret s3/api: command 24.2 s, requests 713, failed first attempts 0, longest gap 0.25 s
rotate_secret postgres/api: command 20.4 s, requests 610, failed first attempts 0, longest gap 0.26 s
postgres/api: sessions older than the change are closed | expected the held ones, left 0 | got closed: 2, left: 0
postgres/api: the held session and the begun login | expected closed or refused | got {'held': 'refused 57P01', 'begun': 'closed'}
revoked: AMQP logins begun before the CRL | … | got {'begun': '93', 'opened during': '22', 'opened after': '0', 'alive': '0'}
rotated: AMQP logins begun before the CRL | … | got {'begun': '110', 'opened during': '30', 'opened after': '0', 'alive': '0'}
PASS: 86 checks
```
Мутация в памяти — после прогрева умирают потоки вложений, скачиваний, чтения и 5 писателей, `close_sessions` и повторное
закрытие у брокера ничего не делают: код 1, **9 из 86** — пять строк «load threads without requests» с именами потоков
(`write-1 dead … read dead, attachment dead, download dead`), «closed: 0», `{'held': 'open', 'begun': 'open'}`, «alive 6» и
«alive 10». `CONTROL=skip-crl` — 9 из 21 (в том числе 34 начатых входа завершились). SIGKILL учений и следующий прогон — S4.
### Мутации (W7)
155 мутаций в копии репозитория (`rotation.py` 126, `pki.sh` 9, `same_image.py` 11, соседи 9), контроль без мутации — пять
файлов зелёные. Первый прогон — 2 выживших (`replicas_up`: чужой backend; `run`: stdin наследуется), тесты дополнены;
итог — **155 красных, выживших 0**. По местам: `require` 15 (в том числе запечатан, не инициализирован, rollout, остановленный
заменяемый, владелец отозванного), `wait_ready` 7, `rollout` 7 (`ROLLOUT_BUILD`, `ROLLOUT_MIGRATE`, `ROLLOUT_CHECK`, вывод в
трубу, блокировка), `owner_current` 6, `verify_material` 6, `apply_secret` 5, `close_sessions` 5, `check_values` 4, брокер 12
(сброс кэша, закрытие, срок и отсчёт повторов), `lagging` и согласованность 10, `emit`, `execute`, `lock`, `.env` 11, SIGHUP
и SIGTERM 2, `renew` / `leaf` / `revoke` / `secret` 12, `pki.sh` 9, `same_image.py` и вызов из `rolling-update.sh` 12,
готовность 4, OpenBao 2, S3 2, остальное — `run`, `compose_ok`, `kv_state`, `seed`, `restart`, `apply_crl`, `apply_owner`.
### Регрессия (рабочее дерево)
| Команда | Код | Итог |
| --- | --- | --- |
| `make lint`, `make check`, `openspec validate rotation-revocation --strict` | 0 | — |
| `make service_test` / `make service_test_db` | 0 / 0 | 1049 passed / 124 passed |
| `make test`, `test-security`, `test-persistence`, `test-failover` (stop, kill) | 0 × 5 | PASS |
| `make student_test` | 2 | 233 passed, 2 failed — известные: `test_exclusion_evidence_exists`, `test_every_scenario_is_covered` |
| `make mtls_check`, `storage_tls_check`, `storage_roles_check`, `broker_mtls_check`, `telemetry_tls_check`, `bao_check` | 0 × 6 | PASS |
| `make s3_check`; `hardening_check` (в начале и через 13 мин) | 0; 0, 0 | 94; 674, 674 |
| `driver.py openbao-outage` | 0 | роли и процессы возвращены |
| `make rolling_update`; `BUILD=0 MIGRATE=0` | 0; 0 | 16 с; 10 с |
| `make rotation_check`; `CONTROL=skip-crl` | 0; 2 (драйвер 1) | 86 PASS; 9 из 21 FAIL |
| `make failure_checks FAULT_ARGS='-k "role_password or openbao or secret_new_version"'` | 0 | 7 passed |
| `make test_isolated` | 2 | smoke 0, `student_test` — те же 2 известных |
Утечки: 69 файлов вывода проб и прогонов, журналы 23 контейнеров, 954 файла рабочего дерева — секретных значений `.env`
(18), 66 строк ключей, PEM и токенов 0. После прогонов: `rotation.py outdated` пуст, «unchanged» 9 из 9, `REVOKED` 0, прежних
действующих leaf у identity списка нет; контейнеров, сетей, образов и каталогов проб нет, стенд остановлен (`make stop`).
### Сценарии правок: доказательство
| Сценарий | Доказательство |
| --- | --- |
| Соединение, начатое до отзыва | C1; учения, «AMQP logins begun before the CRL»; `test_broker_late`, `test_broker_close` |
| Отозванная identity не получает leaf сама; Удержание отозванной identity | C3; `test_hold_until_rotate` |
| Вход, начатый до смены пароля | C2; учения, «the held session and the begun login»; `test_close_sessions` |
| Ротация секрета отозванной identity | C3; `test_secret_of_revoked_identity`, `test_leaf_of_revoked_identity` |
| Прерванная ротация другого пути | W4; `test_secret_refuses_half_rotated_path` |
| Продление после отзыва в файлах | W1; `test_renew_closes_what_a_revoked_leaf_opened` |
| Мёртвая нагрузка и незакрытая сессия названы | W6, красный контроль |
| Сбой в каждой фазе | таблица C4; `test_failure_of_pki_commands_is_repeated`, `test_secret_failure_names_phase` |
| Терминал закрыт | C5; `test_closed_output_does_not_stop`, `test_main_defers_every_signal` |
| Параллельные команды; Занятая база CA | W3; `test_one_command_at_a_time`, `test_busy_ca`, `test_parallel_issue` |
| Команда убита во время замены реплик | W8; `test_run_output_file_and_lock` |
| Другой код в теге; Пересборка другим проектом | W5; `test_same_image.py` |
| Отозванный клиент метрик на открытом соединении | W2 |
| gRPC шлюза S3 и identity стенда | W9; `test_s3_grpc_allowlist`, `make s3_check` |
| Неготовность из-за входа роли названа | S2; `test_readiness_names_refused_login` |