feat: complete lab 7 for grade 4

This commit is contained in:
sashadugina06
2026-12-04 13:55:32 +03:00
parent 20afc2c790
commit 11390b65fd
91 changed files with 10163 additions and 50 deletions
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Rotate API PostgreSQL access without invalidating the published KV generation."""
import argparse
import fcntl
import os
import secrets
import shlex
import subprocess
import time
from pathlib import Path
from bao import conninfo, operator, request
from pki import STATE
ROOT = Path(__file__).resolve().parents[1]
PATH = "kv/data/messenger/api"
ALTERNATE = {"api_blue": "api_green", "api_green": "api_blue"}
def compose(*arguments, data=None):
return subprocess.run([str(ROOT / "scripts/compose.sh"), *arguments], input=data,
capture_output=True, text=True, timeout=15, check=True).stdout.strip()
def sql(statement):
return compose("exec", "-T", "--user", "postgres", "postgres", "psql", "-XqAt",
"-v", "ON_ERROR_STOP=1", "-d", "messenger", data=statement)
def db_probe(info):
code = (
"import sys,psycopg; "
"c=psycopg.connect(sys.stdin.read(),connect_timeout=3); "
"print(c.execute('select session_user from pg_stat_ssl where pid=pg_backend_pid() and ssl').fetchone()[0]); "
"c.close()"
)
return compose("exec", "-T", "api-a", "python", "-c", code, data=info)
def read_generation(token):
document = request(PATH, token=token)["data"]
info = document["data"]["database_url"]
fields = dict(field.split("=", 1) for field in shlex.split(info))
role = fields.get("user")
if role not in ALTERNATE or fields.get("sslmode") != "verify-full":
raise RuntimeError("The published API credential does not match the supported roles and TLS mode")
return document, info, role
def await_active(role):
deadline = time.monotonic() + 50
while time.monotonic() < deadline:
for instance in ("api-a", "api-b"):
compose("exec", "-T", instance, "python", "/app/uds_probe.py")
count = sql(f"SELECT count(DISTINCT client_addr) FROM pg_stat_activity WHERE usename='{role}' AND backend_type='client backend';")
if count == "2":
return
time.sleep(1)
raise RuntimeError("Both replicas have not acquired the published role; the previous credential remains enabled")
def retire(token, current, info, active, old_info=None):
previous = ALTERNATE[active]
await_active(active)
deadline = time.monotonic() + 25
while sql(f"SELECT count(*) FROM pg_stat_activity WHERE usename='{previous}';") != "0":
if time.monotonic() >= deadline:
raise RuntimeError("Previous sessions did not drain; both credentials remain usable")
time.sleep(1)
# CAS protects the publication itself. A final version check also prevents
# retiring an identity after an unrelated change during convergence.
latest, _, _ = read_generation(token)
if latest["metadata"]["version"] != current["metadata"]["version"] or db_probe(info) != active:
raise RuntimeError("KV generation changed or TLS verification failed before retirement")
sql(f"ALTER ROLE {previous} PASSWORD NULL;")
if sql(f"SELECT (rolpassword IS NULL)::int FROM pg_authid WHERE rolname='{previous}';") != "1":
raise RuntimeError("Could not verify retirement of the previous password")
if old_info is not None:
try:
db_probe(old_info)
except subprocess.CalledProcessError as exc:
if "password authentication failed" not in exc.stderr:
raise RuntimeError("The previous password denial was not verified") from None
else:
raise RuntimeError("The previous password still authenticates")
if db_probe(info) != active:
raise RuntimeError("Published PostgreSQL credential could not be verified after retirement")
def rotate(token, resume=False):
current, old_info, active = read_generation(token)
if db_probe(old_info) != active:
raise RuntimeError("The published PostgreSQL credential did not pass the TLS probe")
if resume:
retire(token, current, old_info, active)
return
alternate = ALTERNATE[active]
password = secrets.token_hex(24)
sql("SET log_statement=none; SET log_min_error_statement=panic; "
f"ALTER ROLE {alternate} LOGIN PASSWORD '{password}';")
new_info = conninfo(alternate, password)
if db_probe(new_info) != alternate:
raise RuntimeError("The replacement PostgreSQL credential did not pass the TLS probe")
try:
request(PATH, {"data": dict(current["data"], database_url=new_info),
"options": {"cas": current["metadata"]["version"]}}, token)
except (OSError, RuntimeError, ValueError):
# A timeout can follow a committed KV write. Neither role is retired
# on uncertainty and blindly issuing another rotation is unsafe.
raise RuntimeError("KV CAS outcome uncertain; both credentials remain usable. Inspect KV and use --retire-previous.") from None
published, info, role = read_generation(token)
if info != new_info or role != alternate:
raise RuntimeError("OpenBao did not return the expected replacement generation")
retire(token, published, info, role, old_info)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--retire-previous", action="store_true",
help="verify the currently published generation and retire only the other role")
args = parser.parse_args()
lock = STATE / "operator/rotate-db.lock"
with os.fdopen(os.open(lock, os.O_CREAT | os.O_WRONLY | os.O_NOFOLLOW, 0o600), "w") as file:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
rotate(operator()["root_token"], args.retire_previous)
print("PASS: both API replicas use the published TLS credential; the other password is retired")
if __name__ == "__main__":
try:
main()
except RuntimeError as exc:
raise SystemExit(str(exc)) from None
except (OSError, subprocess.SubprocessError, ValueError, KeyError):
raise SystemExit("Rotation stopped. Inspect the active KV generation before resuming; no credentials printed.") from None