Files
mtusi2026lab7/scripts/secure_runtime.py

108 lines
3.5 KiB
Python

import json
import os
import signal
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from threading import Event
STOP = Event()
KEYS = {
"DATABASE_URL",
"CACHE_URL",
"CURSOR_SECRET",
"S3_ACCESS_KEY_ID",
"S3_SECRET_ACCESS_KEY",
"BROKER_URL",
}
def stopping(_signum, _frame):
STOP.set()
def request(path, payload=None, token=None):
context = ssl.create_default_context(cafile="/run/pki/ca.crt")
context.load_cert_chain("/run/pki/tls.crt", "/run/pki/tls.key")
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(os.environ["BAO_ADDR"] + "/v1/" + path, data=data, headers=headers)
with urllib.request.urlopen(req, context=context, timeout=3) as response:
return json.load(response)
def configuration():
role = os.environ["SERVICE_ROLE"]
auth = request("auth/cert/login", {"name": role})["auth"]
data = request("secret/data/" + role, token=auth["client_token"])["data"]["data"]
if not data or set(data) - KEYS or any(not isinstance(v, str) for v in data.values()):
raise ValueError("Invalid scoped configuration")
return data, time.monotonic() + min(auth["lease_duration"], 300)
def terminate(process):
if process and process.poll() is None:
os.killpg(process.pid, signal.SIGTERM)
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL)
process.wait()
def main():
signal.signal(signal.SIGTERM, stopping)
signal.signal(signal.SIGINT, stopping)
proxy = None
child = None
deadline = 0
config = None
next_refresh = 0
bootstrap_deadline = time.monotonic() + 60
try:
cfg = "/etc/security/" + os.environ["SERVICE_ROLE"] + ".cfg"
if Path(cfg).exists():
proxy = subprocess.Popen(["haproxy", "-W", "-db", "-f", cfg], start_new_session=True)
while not STOP.is_set():
now = time.monotonic()
if proxy and proxy.poll() is not None:
return 1
if now >= next_refresh:
try:
updated, deadline = configuration()
if updated != config or child is None:
terminate(child)
env = {
k: v
for k, v in os.environ.items()
if k not in {name + "_FILE" for name in KEYS}
}
child = subprocess.Popen(
sys.argv[1:], env={**env, **updated}, start_new_session=True
)
config = updated
print("security.configuration.accepted", flush=True)
except (OSError, ValueError, KeyError):
print("security.configuration.unavailable", flush=True)
next_refresh = now + 10
if child and child.poll() is not None:
return child.returncode
if (child and now >= deadline) or (child is None and now >= bootstrap_deadline):
print("security.authorization.expired", flush=True)
return 1
time.sleep(0.2)
finally:
terminate(child)
terminate(proxy)
return 0
if __name__ == "__main__":
sys.exit(main())