feat: rotate and revoke credentials on the running stand

Add operator commands for leaf and secret rotation, identity revocation
and CRL renewal without rebuilding images, and a drill under load.
A rejected PostgreSQL role password is now 503 instead of 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 06:46:55 +03:00
co-authored by Claude Opus 5.5
parent 21b8a08e46
commit c40fbef36a
40 changed files with 5804 additions and 127 deletions
+63 -4
View File
@@ -39,10 +39,14 @@ token и доли читаются в память, токен уходит то
версией с теми же значениями; вывод — путь и версии N -> N+1
без значений; данных пути в KV нет — код 1. Следующий seed
версий не прибавляет (данные равны модели compose)
revoke-tokens — отозвать токены, выданные роли входа из таблицы ROLES, не
дожидаясь срока (change rotation-revocation, design, решение
8): токен не привязан к сертификату. `--keep-serial <hex>` —
кроме выданных leaf с этим серийным номером (ротация). Вывод —
роль и число, без токенов и accessors
Коды: 0 — выполнено; 1 — отказ OpenBao или материалов; 2 — запечатан
(`ready`), неверные аргументы (в том числе путь rewrite не из SEED) или нет
файлов.
Коды: 0 — выполнено; 1 — отказ OpenBao или материалов; 2 — запечатан,
неверные аргументы (в том числе путь rewrite не из SEED) или нет файлов.
"""
# аннотации — строками: синтаксис `X | None` и `dict[…]` системный python3 3.9
@@ -170,6 +174,13 @@ def parse_duration(value: str) -> int:
return seconds
def parse_serial(value: str) -> int:
"""Серийный номер leaf, как его печатает `openssl x509 -serial` (hex)."""
if not re.fullmatch(r"[0-9A-Fa-f]+", value):
raise argparse.ArgumentTypeError("serial must be hex")
return int(value, 16)
def policy_paths(name: str, directory: Path = POLICIES_DIR) -> list[str]:
"""Пути `messenger/data/…` файла политики (без префикса)."""
text = (directory / f"{name}.hcl").read_text(encoding="utf-8")
@@ -843,6 +854,47 @@ class Operator:
log(f"kv {KV_MOUNT}/{path}: version {before} -> {after}, rewritten")
return 0
def revoke_tokens(self) -> int:
"""Отозвать выданные роли входа токены (кроме выданных leaf с
`--keep-serial`). Токены и accessors не печатаются."""
self._require_unsealed()
token = self.root_token()
role, keep = self.args.role, self.args.keep_serial
revoked = kept = 0
for accessor in self._list("auth/token/accessors", token):
# 403 / 404 (и 400 у отзыва) — токен уже истёк или отозван
status, found = self.http.request(
"POST",
"auth/token/lookup-accessor",
{"accessor": accessor},
token=token,
ok=(200, 403, 404),
)
data = (found.get("data") or {}) if status == 200 else {} # noqa: PLR2004
if (
data.get("path") != f"auth/{CERT_MOUNT}/login"
or data.get("display_name") != f"{CERT_MOUNT}-{role}"
):
continue
# серийный номер leaf у токена — десятичная строка
serial = str((data.get("meta") or {}).get("serial_number") or "")
if keep is not None and serial == str(keep):
kept += 1
continue
status, _ = self.http.request(
"POST",
"auth/token/revoke-accessor",
{"accessor": accessor},
token=token,
ok=(200, 204, 400, 403, 404),
)
revoked += status in (200, 204)
log(
f"role {role}: revoked {revoked} tokens"
+ (f", kept {kept}" if keep is not None else ""),
)
return 0
def _same(current: object, desired: object) -> bool:
if isinstance(desired, list):
@@ -954,6 +1006,13 @@ def build_parser() -> argparse.ArgumentParser:
)
rewrite = commands.add_parser("rewrite")
rewrite.add_argument("path", choices=sorted(SEED))
tokens = commands.add_parser("revoke-tokens")
tokens.add_argument("--role", choices=sorted(ROLES), required=True)
tokens.add_argument(
"--keep-serial",
type=parse_serial,
help="hex serial of the leaf whose tokens stay (rotation)",
)
return parser
@@ -963,7 +1022,7 @@ def main(argv: list[str] | None = None) -> int:
args.operator_dir = default_operator_dir(args.project)
try:
operator = Operator(args)
return int(getattr(operator, args.command)())
return int(getattr(operator, args.command.replace("-", "_"))())
except Sealed as error:
log(f"bao: {error}")
return 2