feat(redis): lab7 rotate the API password through OpenBao
This commit is contained in:
@@ -0,0 +1,114 @@
|
|||||||
|
"""Поменять пароль 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()
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Общие операции для ротации credentials в ЛР7."""
|
||||||
|
import fcntl
|
||||||
|
import getpass
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
PRIVATE = ROOT / "certs/private"
|
||||||
|
CA = PRIVATE / "ingress/ca.crt"
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args, **kwargs):
|
||||||
|
return subprocess.run(["docker", "compose", "--project-directory", str(ROOT),
|
||||||
|
"-f", str(ROOT / "compose.yaml"), *args], cwd="/tmp",
|
||||||
|
check=True, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
def write_file(path, data, mode):
|
||||||
|
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as tmp:
|
||||||
|
try:
|
||||||
|
tmp.write(data)
|
||||||
|
tmp.flush()
|
||||||
|
os.fchmod(tmp.fileno(), mode)
|
||||||
|
os.fsync(tmp.fileno())
|
||||||
|
os.replace(tmp.name, path)
|
||||||
|
finally:
|
||||||
|
Path(tmp.name).unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
class Operator:
|
||||||
|
def __init__(self):
|
||||||
|
self.lock = (PRIVATE / ".rotation.lock").open("a")
|
||||||
|
fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
self.token = getpass.getpass("Токен оператора OpenBao: ")
|
||||||
|
self.context = ssl.create_default_context(cafile=str(CA))
|
||||||
|
|
||||||
|
def request(self, path, body=None):
|
||||||
|
data = None if body is None else json.dumps(body).encode()
|
||||||
|
request = urllib.request.Request("https://127.0.0.1:18200/v1/" + path, data=data,
|
||||||
|
headers={"X-Vault-Token": self.token,
|
||||||
|
"Content-Type": "application/json"})
|
||||||
|
with urllib.request.urlopen(request, context=self.context, timeout=10) as response:
|
||||||
|
return json.loads(response.read() or b"{}")
|
||||||
Reference in New Issue
Block a user