forked from mtusi2026/mtusi2026lab7
162 lines
6.0 KiB
Python
162 lines
6.0 KiB
Python
"""Run one workload only while its OpenBao token and database lease are valid."""
|
|
import hashlib
|
|
import logging
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from urllib.parse import quote
|
|
|
|
import psycopg
|
|
|
|
from bao_client import Bao, BaoError
|
|
from security_runtime import CA, CERT, KEY, client_context
|
|
|
|
LOG = logging.getLogger("secrets")
|
|
ROLE = os.environ.get("WORKLOAD_ID", "")
|
|
BAO_ADDR = "https://openbao:8200"
|
|
DRAIN = Path("/run/local/drain")
|
|
READY = Path("/run/local/ready")
|
|
RENEW_BEFORE_SECONDS = 16
|
|
|
|
|
|
def identity():
|
|
fingerprint = hashlib.sha256()
|
|
for path in (CA, CERT, KEY):
|
|
with open(path, "rb") as source:
|
|
fingerprint.update(source.read())
|
|
return fingerprint.digest()
|
|
|
|
|
|
def db_url(credentials):
|
|
username = quote(credentials["username"], safe="")
|
|
password = quote(credentials["password"], safe="")
|
|
return (f"postgresql://{username}:{password}@postgres:5432/messenger"
|
|
f"?sslmode=verify-full&sslrootcert={CA}&connect_timeout=3")
|
|
|
|
|
|
class Workload:
|
|
def __init__(self, command):
|
|
self.command = command
|
|
self.process = None
|
|
self.token = None
|
|
self.lease = None
|
|
self.token_until = self.lease_until = 0.0
|
|
self.fingerprint = None
|
|
self.config = None
|
|
self.dsn = None
|
|
self.stop_requested = False
|
|
|
|
def clear(self):
|
|
if self.process is not None:
|
|
self.process.terminate()
|
|
try:
|
|
self.process.wait(timeout=4)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
self.process.wait()
|
|
self.process = self.token = self.lease = None
|
|
self.token_until = self.lease_until = 0.0
|
|
self.fingerprint = self.config = self.dsn = None
|
|
|
|
def request(self, path, body=None):
|
|
return Bao(BAO_ADDR, client_context()).request(path, body, self.token)
|
|
|
|
def start(self):
|
|
self.fingerprint = identity()
|
|
started = time.monotonic()
|
|
auth = self.request("auth/cert/login", {"name": ROLE})["auth"]
|
|
self.token = auth["client_token"]
|
|
self.token_until = started + auth["lease_duration"]
|
|
issued = time.monotonic()
|
|
db = self.request(f"database/creds/{ROLE}")
|
|
self.lease = db["lease_id"]
|
|
self.lease_until = issued + db["lease_duration"]
|
|
self.config = self.request(f"runtime/data/{ROLE}")["data"]["data"]
|
|
env = os.environ.copy()
|
|
self.dsn = db_url(db["data"])
|
|
env.update(self.config, DATABASE_URL=self.dsn)
|
|
DRAIN.unlink(missing_ok=True)
|
|
READY.unlink(missing_ok=True)
|
|
self.process = subprocess.Popen(self.command, env=env)
|
|
LOG.info("started %s using a scoped token and a database lease", ROLE)
|
|
|
|
def rotate(self):
|
|
if ROLE != "api":
|
|
self.clear()
|
|
return
|
|
# The database serializes planned swaps across API replicas. Keep existing
|
|
# credentials active while another replica gets a new lease and becomes ready.
|
|
with psycopg.connect(self.dsn, autocommit=True) as conn:
|
|
locked = conn.execute("SELECT pg_try_advisory_lock(7107001)").fetchone()[0]
|
|
if not locked:
|
|
return
|
|
DRAIN.touch()
|
|
time.sleep(2.3)
|
|
self.clear()
|
|
self.start()
|
|
# Hold the lock until a real mTLS readiness check succeeds on the new child.
|
|
deadline = time.monotonic() + 5
|
|
while self.process.poll() is None and not READY.exists() and time.monotonic() < deadline:
|
|
time.sleep(0.1)
|
|
|
|
def refresh(self):
|
|
now = time.monotonic()
|
|
if self.process.poll() is not None or identity() != self.fingerprint:
|
|
LOG.info("reloading %s after process exit or identity change", ROLE)
|
|
self.clear()
|
|
return
|
|
if now >= min(self.token_until, self.lease_until):
|
|
LOG.warning("local credential deadline elapsed for %s", ROLE)
|
|
self.clear()
|
|
return
|
|
if now >= self.token_until - RENEW_BEFORE_SECONDS:
|
|
auth = self.request("auth/token/renew-self", {})["auth"]
|
|
renewed_until = now + auth["lease_duration"]
|
|
if renewed_until <= self.token_until + 2:
|
|
self.rotate()
|
|
return
|
|
self.token_until = renewed_until
|
|
if now >= self.lease_until - RENEW_BEFORE_SECONDS:
|
|
renewed = self.request(f"sys/leases/renew/{self.lease}", {})
|
|
renewed_until = now + renewed["lease_duration"]
|
|
if renewed_until <= self.lease_until + 2:
|
|
self.rotate()
|
|
return
|
|
self.lease_until = renewed_until
|
|
config = self.request(f"runtime/data/{ROLE}")["data"]["data"]
|
|
if config != self.config:
|
|
LOG.info("reloading %s after secret rotation", ROLE)
|
|
self.rotate()
|
|
|
|
def run(self):
|
|
try:
|
|
while not self.stop_requested:
|
|
try:
|
|
if self.process is None:
|
|
self.clear()
|
|
self.start()
|
|
else:
|
|
self.refresh()
|
|
except BaoError as exc:
|
|
LOG.warning("%s for %s", exc, ROLE)
|
|
if exc.status in (400, 403, 404) and self.process:
|
|
self.clear()
|
|
except (OSError, ValueError, KeyError, psycopg.Error) as exc:
|
|
LOG.warning("credential check unavailable for %s (%s)", ROLE, type(exc).__name__)
|
|
if self.process and time.monotonic() >= min(self.token_until, self.lease_until):
|
|
self.clear()
|
|
time.sleep(2)
|
|
finally:
|
|
self.clear()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
workload = Workload(sys.argv[1:])
|
|
for signal_number in (signal.SIGTERM, signal.SIGINT):
|
|
signal.signal(signal_number, lambda *_: setattr(workload, "stop_requested", True))
|
|
workload.run()
|