fix: address rotation-revocation control verify findings

Keep the hold mark of an identity whose revocation has started whatever
signal ends pki.sh, refuse every rotation command while the files of a
held identity are missing, bound the handshake of the LB metrics port,
name sessions of another password until verify ends, and run Makefile
prerequisites in order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 15:19:42 +03:00
co-authored by Claude Opus 5.5
parent d4a882ddd6
commit 10973231a0
24 changed files with 671 additions and 124 deletions
+55 -25
View File
@@ -172,6 +172,14 @@ REVOKE_BY_ROTATION = {
"CRL would never reach every replica",
}
# каталог стенда создан заново при удержанной identity: после `pki.sh rotate`
# (те же шаги печатает pki.sh, сверяет быстрый тест)
RECREATED_STEPS = (
"make stop",
"make bao_unseal",
"make run_docker",
"make pki_renew",
)
# порядок применения CRL: сначала секунды (OpenBao, брокер, LB), затем
# перезапуски, последней — поочерёдная замена реплик
CRL_ORDER = (
@@ -471,8 +479,13 @@ class Stand:
fcntl.flock(self.lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise NotReady("another rotation command is running") from None
except FileNotFoundError:
raise NotReady(f"no {self.pki_dir}: run make pki_stand") from None
except OSError as error:
raise NotReady(f"{self.pki_dir}: {type(error).__name__}") from None
raise NotReady(
f"cannot lock {self.pki_dir / '.rotation.lock'}: "
f"{error.strerror}",
) from None
def on_signal(self, signum: int, _frame: object) -> None:
name = signal.Signals(signum).name
@@ -762,6 +775,8 @@ class Stand:
for name in ("ca.crt", "crl.pem"):
if not (self.pki_dir / name).is_file():
raise NotReady(f"no {name}: run make pki_stand")
if self.missing:
raise NotReady(self.recreated())
for service in sorted(services - {"openbao"}):
problem = self.service_problem(service)
if problem is None:
@@ -796,25 +811,36 @@ class Stand:
if replicas:
self.require_replicas(revoked=owner == "api")
def hint(self, service: str) -> str:
"""Чем вернуть неготовый сервис: отозванный leaf — только заменой, LB
без реплик — заменой их leaf. Файлов удержанной identity нет — compose
не стартует, и `rotate_leaf` нужного стенда не дождётся: leaf выдаёт
`pki.sh rotate` (стенд ему не нужен), стенд поднимает `run_docker`, а
def recreated(self) -> str:
"""Файлов удержанной identity нет: каталог стенда создан заново, и у
работающих контейнеров прежних файлов нет тоже, а compose без них не
стартует. Leaf выдаёт `pki.sh rotate` (стенд ему не нужен), файлы
контейнеры получают только стартом (`make stop` — и OpenBao запечатан),
прежние leaf заново созданного каталога отзывает `pki_renew`."""
if self.missing:
steps = [
f"infra/pki/pki.sh rotate {identity}"
for identity in sorted(self.missing)
]
steps += ["make run_docker", "make pki_renew"]
return "compose cannot start without its files, run " + "; ".join(
steps,
)
owners = {service} | ({"api"} if service == "haproxy" else set())
names = sorted(self.missing)
steps = [f"infra/pki/pki.sh rotate {name}" for name in names]
return (
f"no files of the revoked {', '.join(names)} in the stand "
f"directory: run {'; '.join([*steps, *RECREATED_STEPS])}"
)
def hint(self, service: str) -> str:
"""Чем вернуть неготовый сервис: отозванный leaf — только заменой. LB
без реплик: отозванную `api-client` — заменой; на отозванном или
прежнем leaf `api` реплики работают, а LB их не принимает, и
`rotate_leaf api` ждёт LB — их перезапускает оператор."""
for identity in sorted(self.revoked):
if identity in LEAVES and LEAVES[identity].owner in owners:
if identity in LEAVES and (
identity in ("haproxy", "api-client")
if service == "haproxy"
else LEAVES[identity].owner == service
):
return f"run make rotate_leaf IDENTITY={identity} first"
if service == "haproxy":
return (
"run make run_docker first; if the LB still has no ready "
"replica: docker compose restart api"
)
return "run make run_docker first"
def require_replicas(self, *, revoked: bool) -> None:
@@ -1819,11 +1845,12 @@ def cmd_secret(stand: Stand, path: str) -> None:
new = {field: new_value(value) for field, value in old.items()}
stand.begin_change(".env")
if secret.kind == "postgres":
# с первой же фазы: `run_docker` сменил бы пароль по новому .env, а
# сессии прежнего оставил
# с первой же фазы и до конца verify: `run_docker` сменил бы пароль по
# новому .env, а сессии прежнего оставил; и закрытая сессия могла
# раньше сменить пароль роли и открыть другую — это видит только verify
stand.exposed = (
f"sessions of role {secret.name} opened with the previous "
"password stay open"
f"sessions of role {secret.name} opened with another password "
"may stay open"
)
replace_env_values(
stand.env_file,
@@ -1855,7 +1882,6 @@ def cmd_secret(stand: Stand, path: str) -> None:
if "api" not in consumers:
stand.enter("previous sessions")
stand.close_sessions(secret.name, before)
stand.exposed = ""
elif secret.kind == "valkey":
stand.enter("storage")
rejected = stand.elapsed()
@@ -1871,7 +1897,6 @@ def cmd_secret(stand: Stand, path: str) -> None:
elif secret.kind == "postgres":
stand.enter("sessions")
stand.close_sessions(secret.name, before)
stand.exposed = ""
stand.enter("verify")
stand.check_values(path, old, new)
if rejected is None:
@@ -1900,8 +1925,13 @@ def cmd_idle(stand: Stand) -> None:
"""Команда ротации не идёт (код 2 — идёт). Блокировку берёт и с концом
процесса отпускает: начатая после проверки команда пойдёт рядом. Каталога
стенда ещё нет (первый запуск) — идти нечему."""
if stand.pki_dir.is_dir():
stand.lock()
try:
os.stat(stand.pki_dir)
except FileNotFoundError:
return
except OSError:
pass # назовёт блокировка
stand.lock()
def build_parser() -> argparse.ArgumentParser: