This commit is contained in:
k00kzaAntonovaIra
2026-11-25 20:16:24 +03:00
parent 20afc2c790
commit 9dcf5b1118
197 changed files with 21197 additions and 182 deletions
+92
View File
@@ -0,0 +1,92 @@
"""Ротация пароля PostgreSQL и cert identity worker из операторского контура."""
import argparse
import base64
import hashlib
import hmac
import os
from pathlib import Path
import secrets
from tempfile import TemporaryDirectory
from urllib.error import HTTPError
from scripts.bootstrap_bao import ROOT, TLS, Bao, operator_token
from scripts.deployment import ComposeProject
from scripts.init_tls import issue
def cert_role(certificate: Path, role: str, ttl: str = "10m") -> dict:
return {
"certificate": certificate.read_text(),
"token_policies": [role],
"token_no_default_policy": True,
"token_ttl": ttl,
"token_max_ttl": ttl,
}
def change_db_password(project: ComposeProject, password: str) -> None:
salt = secrets.token_bytes(16)
iterations = 4096
salted = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
client_key = hmac.digest(salted, b"Client Key", "sha256")
server_key = hmac.digest(salted, b"Server Key", "sha256")
def encode(value):
return base64.b64encode(value).decode()
verifier = (f"SCRAM-SHA-256${iterations}:{encode(salt)}"
f"${encode(hashlib.sha256(client_key).digest())}:{encode(server_key)}")
project.run("exec", "-T", "postgres", "sh", "-ec",
'exec psql --no-psqlrc -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
input_text=f"ALTER ROLE worker PASSWORD '{verifier}';\n")
def rotate(project: ComposeProject, port: int) -> None:
bao, token = Bao(port), operator_token(port)
role_path = "auth/cert/certs/worker"
secret_path = "messenger/data/worker"
previous = bao.call(secret_path, token=token)["data"]["data"]
current_cert = TLS / "worker-bao.crt"
current_key = TLS / "worker-bao.key"
password_file = ROOT / "secrets/worker_db_password"
password = secrets.token_urlsafe(24)
with TemporaryDirectory(prefix=".worker-rotation-", dir=TLS) as directory:
staging = Path(directory)
for suffix in ("crt", "key"):
(staging / f"ca.{suffix}").symlink_to(TLS / f"ca.{suffix}")
issue(staging, "worker-bao", "DNS:worker-bao", "clientAuth", "ca")
new_cert, new_key = (staging / f"worker-bao.{suffix}" for suffix in ("crt", "key"))
old_certificate, old_key = current_cert.read_bytes(), current_key.read_bytes()
project.run("stop", "worker")
try:
change_db_password(project, password)
bao.call(secret_path, {"data": {"db_password": password}}, token=token)
bao.call(role_path, cert_role(new_cert, "worker"), token=token)
password_stage = staging / "password"
password_stage.write_text(password)
password_stage.chmod(0o444)
os.replace(password_stage, password_file)
os.replace(new_cert, current_cert)
os.replace(new_key, current_key)
project.run("up", "-d", "--no-build", "--no-deps", "--force-recreate", "worker")
except (HTTPError, OSError, RuntimeError):
change_db_password(project, previous["db_password"])
bao.call(secret_path, {"data": previous}, token=token)
for path, data in ((current_cert, old_certificate), (current_key, old_key),
(password_file, previous["db_password"].encode())):
temporary = staging / (path.name + ".rollback")
temporary.write_bytes(data)
temporary.chmod(0o444)
os.replace(temporary, path)
bao.call(role_path, cert_role(current_cert, "worker"), token=token)
project.run("up", "-d", "--no-build", "--no-deps", "--force-recreate", "worker")
raise
print("PASS: пароль PostgreSQL и клиентский сертификат worker заменены без сборки")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--bao-port", type=int, default=18200)
rotate(ComposeProject(), parser.parse_args().bao_port)