Files
mtusi2026lab7/scripts/rotation_common.py
T

66 lines
2.2 KiB
Python

"""Общие операции для ротации credentials в ЛР7."""
import fcntl
import getpass
import json
import os
import stat
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:
staged = Path(tmp.name)
try:
with staged.open("wb") as stream:
stream.write(data)
stream.flush()
os.fchmod(stream.fileno(), mode)
os.fsync(stream.fileno())
try:
os.replace(staged, path)
except PermissionError:
previous = stat.S_IMODE(path.stat().st_mode)
if previous & stat.S_IWUSR:
raise
path.chmod(previous | stat.S_IWUSR)
try:
os.replace(staged, path)
except OSError:
path.chmod(previous)
raise
finally:
if staged.exists():
staged.chmod(0o600)
staged.unlink()
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"{}")