feat: core func lab7

This commit is contained in:
Enterxx2
2026-11-24 14:04:04 +03:00
parent 4829fc7b4e
commit 411ca73aa0
83 changed files with 2883 additions and 523 deletions
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Ротация клиентского сертификата LB или пароля ACL Valkey."""
import argparse
import hashlib
import json
import os
import secrets
import ssl
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import urlopen
from bootstrap_security import OPERATOR, ROOT, SECRETS, TLS, fingerprint, issue, write
def compose(*args):
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True)
def wait_replicas(url, status, timeout):
config = dict(
line.split("=", 1) for line in (ROOT / ".env").read_text().splitlines()
if line and not line.startswith("#") and "=" in line
)
replicas = int(os.environ.get("API_REPLICAS") or config.get("API_REPLICAS", "2"))
context = ssl.create_default_context(cafile=str(ROOT / "certs/ca.crt"))
started = time.monotonic()
instances = set()
while time.monotonic() - started < timeout:
code, instance = None, None
try:
with urlopen(url + "/health/ready", context=context, timeout=3) as response:
code, instance = response.status, response.headers.get("X-Instance-Id")
except HTTPError as error:
with error:
code, instance = error.code, error.headers.get("X-Instance-Id")
except (URLError, TimeoutError):
pass
if code == status and instance and instance != "nginx":
instances.add(instance)
if len(instances) == replicas:
return time.monotonic() - started
else:
instances.clear()
time.sleep(0.5)
raise RuntimeError(f"Не все {replicas} API-реплики вернули HTTP {status} за {timeout} с")
def wait_ready(url):
wait_replicas(url, 200, 45)
def rotate_lb(url):
current = TLS / "lb"
pins = TLS / "api-server/lb-pins"
old = OPERATOR / "old-lb"
old.mkdir(exist_ok=True)
files = ("tls.crt", "tls.key")
for name in files:
write(old / name, (current / name).read_text(), 0o600)
previous = fingerprint(old / "tls.crt")
with tempfile.TemporaryDirectory(dir=OPERATOR) as directory:
next_identity = Path(directory) / "lb"
issue(next_identity, "lb", (OPERATOR / "ca.crt", OPERATOR / "ca.key"))
replacement = fingerprint(next_identity / "tls.crt")
write(pins, f"{previous}\n{replacement}\n")
try:
for name in files:
write(current / name, (next_identity / name).read_text())
compose("exec", "-T", "nginx", "nginx", "-t")
compose("exec", "-T", "nginx", "nginx", "-s", "reload")
# При удалении старого отпечатка новые соединения принимают только новый leaf.
write(pins, replacement + "\n")
wait_ready(url)
except (OSError, RuntimeError, subprocess.CalledProcessError):
for name in files:
write(current / name, (old / name).read_text())
write(pins, previous + "\n")
compose("exec", "-T", "nginx", "nginx", "-s", "reload")
raise
print("PASS rotation: новый LB leaf принят, старый отпечаток удалён без пересборки")
def rotate_valkey(url):
credentials = OPERATOR / "valkey.json"
previous = json.loads(credentials.read_text())["password"]
replacement = secrets.token_hex(24)
archive = OPERATOR / "old-valkey"
archive.mkdir(exist_ok=True)
write(archive / "password", previous + "\n", 0o600)
acl = SECRETS / "valkey.acl"
current_acl = acl.read_text()
source = hashlib.sha256(previous.encode()).hexdigest()
target = hashlib.sha256(replacement.encode()).hexdigest()
if source not in current_acl:
raise RuntimeError("Valkey ACL не соответствует данным оператора")
def apply(password, acl_text):
write(credentials, json.dumps({"password": password}) + "\n", 0o600)
write(acl, acl_text)
subprocess.run(
[sys.executable, str(ROOT / "scripts/manage_openbao.py"), "sync-secret", "--role", "api"],
cwd=ROOT, check=True,
)
compose("up", "-d", "--no-deps", "--force-recreate", "--wait", "valkey")
compose("restart", "--no-deps", "api")
try:
apply(replacement, current_acl.replace(source, target))
wait_ready(url)
except (OSError, RuntimeError, subprocess.CalledProcessError):
apply(previous, current_acl)
raise
print("PASS rotation: Valkey ACL и OpenBao обновлены без пересборки; API ready")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("target", choices=("lb", "valkey"))
parser.add_argument("--url", default=os.environ.get("BASE_URL", "https://localhost:8443"))
args = parser.parse_args()
os.umask(0o077)
rotation = {"lb": rotate_lb, "valkey": rotate_valkey}
rotation[args.target](args.url.rstrip("/"))
if __name__ == "__main__":
main()