Files
mtusi2026lab7/scripts/rotate-redis.py
T

115 lines
5.2 KiB
Python

"""Поменять пароль API в Redis и OpenBao, продолжая прерванную операцию."""
import hashlib
import json
import os
import re
import secrets
import subprocess
import time
from urllib.parse import urlsplit
from rotation_common import Operator, PRIVATE, compose, write_file
directory = PRIVATE / "redis"
journal = directory / ".rotation.json"
url_file = directory / "api.url"
acl_file = directory / "users.acl"
def redis_ping(url):
password = urlsplit(url).password
command = 'IFS= read -r REDISCLI_AUTH; export REDISCLI_AUTH; exec redis-cli --tls --cacert /run/redis/ca.crt -h redis --user api ping'
try:
result = compose("exec", "-T", "redis", "sh", "-c", command,
input=password + "\n", text=True, capture_output=True)
output = result.stdout + result.stderr
except subprocess.CalledProcessError as error:
output = (error.stdout or "") + (error.stderr or "")
if "WRONGPASS" in output:
return False
if output.strip() == "PONG":
return True
raise SystemExit("Redis не подтвердил ни PONG, ни отказ WRONGPASS.")
def wait_api(cid):
for _ in range(90):
state = subprocess.check_output(["docker", "inspect", "-f",
"{{.State.Health.Status}}", cid], text=True).strip()
if state == "healthy":
return
time.sleep(1)
raise SystemExit("Реплика API не стала healthy. Повторите ротацию после диагностики.")
def apply_acl(old, new, retire):
def hashed(url):
return "#" + hashlib.sha256(urlsplit(url).password.encode()).hexdigest()
lines = acl_file.read_text().splitlines()
indices = [i for i, line in enumerate(lines) if line.startswith("user api ")]
if len(indices) != 1:
raise SystemExit("Ожидалась одна ACL-запись API.")
i = indices[0]
fields = lines[i].split()
if not {hashed(old), hashed(new)}.intersection(fields):
raise SystemExit("Пароли из журнала не совпадают с ACL.")
fields = [f for f in fields if f not in (hashed(old), hashed(new))]
fields[3:3] = [hashed(new)] if retire else [hashed(old), hashed(new)]
lines[i] = " ".join(fields)
write_file(acl_file, ("\n".join(lines) + "\n").encode(), 0o444)
# Отдельный bind-mount файла требует пересоздания после атомарной замены.
compose("up", "-d", "--no-deps", "--no-build", "--force-recreate", "--wait",
"--wait-timeout", "90", "redis")
def main():
operator = Operator()
record = operator.request("lab7/data/api")["data"]
values = record["data"]
if journal.exists():
state = json.loads(journal.read_text())
else:
old = values["cache_url"]
if not re.fullmatch(r"rediss://api:[0-9a-f]{64}@redis:6379/0", old):
raise SystemExit("Неожиданный формат cache_url.")
if url_file.read_text().strip() != old or not redis_ping(old):
raise SystemExit("Исходные credentials Redis и OpenBao не согласованы.")
state = {"old": old, "new": old.replace(urlsplit(old).password, secrets.token_hex(32)),
"phase": "prepare"}
write_file(journal, json.dumps(state).encode(), 0o600)
old, new = state["old"], state["new"]
if values["cache_url"] not in (old, new):
raise SystemExit("cache_url изменился вне этой ротации.")
ids = compose("ps", "-q", "api", capture_output=True, text=True).stdout.split()
if len(ids) != 2:
raise SystemExit("Ожидались две запущенные реплики API.")
if state["phase"] == "prepare":
apply_acl(old, new, False)
if not all(redis_ping(url) for url in (old, new)):
raise SystemExit("Переходный ACL не прошёл проверку.")
if values["cache_url"] != new:
operator.request("lab7/data/api", {"options": {"cas": record["metadata"]["version"]},
"data": dict(values, cache_url=new)})
write_file(url_file, (new + "\n").encode(), 0o444)
for cid in ids:
subprocess.run(["docker", "restart", cid], check=True)
wait_api(cid)
# Успешная готовность дополняется сверкой полученной версии секрета.
probe = subprocess.run(["docker", "exec", "-i", cid, "sh", "-c",
'IFS= read -r expected; test "$(cat /run/bao/cache_url)" = "$expected"'],
input=new + "\n", text=True)
probe.check_returncode()
state["phase"] = "retire"
write_file(journal, json.dumps(state).encode(), 0o600)
apply_acl(old, new, True)
if not redis_ping(new) or redis_ping(old):
raise SystemExit("Не подтверждён отзыв старого пароля Redis.")
journal.unlink()
print("Пароль Redis заменён. Обе реплики получили новый секрет.")
if __name__ == "__main__":
os.umask(0o077)
main()