forked from mtusi2026/mtusi2026lab7
173 lines
4.5 KiB
Python
173 lines
4.5 KiB
Python
"""Operator utilities. Never print credentials, tokens, environment or PEM keys."""
|
|
|
|
import json
|
|
import ssl
|
|
import subprocess
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
LOCAL = ROOT / ".local"
|
|
OPERATOR = LOCAL / "operator"
|
|
ROLES = [
|
|
"operator",
|
|
"lb",
|
|
"api",
|
|
"worker",
|
|
"dispatcher",
|
|
"reconciler",
|
|
"postgres",
|
|
"redis",
|
|
"broker",
|
|
"minio",
|
|
"openbao",
|
|
"otel-collector",
|
|
"prometheus",
|
|
"loki",
|
|
"tempo",
|
|
"grafana",
|
|
"intruder",
|
|
"expired",
|
|
]
|
|
|
|
|
|
def compose(*args, capture=False):
|
|
result = subprocess.run(
|
|
["docker", "compose", *args],
|
|
cwd=ROOT,
|
|
text=True,
|
|
stdout=subprocess.PIPE if capture else None,
|
|
check=True,
|
|
)
|
|
return result.stdout.strip() if capture else ""
|
|
|
|
|
|
def openssl(*args):
|
|
subprocess.run(
|
|
["openssl", *map(str, args)],
|
|
cwd=ROOT,
|
|
check=True,
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
|
|
|
|
def put(path, text, mode=0o644):
|
|
path = Path(path)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(text)
|
|
path.chmod(mode)
|
|
|
|
|
|
def tls(role="operator", *, identity=None, trust=True):
|
|
ctx = (
|
|
ssl.create_default_context(cafile=str(LOCAL / "trust/ca.crt"))
|
|
if trust
|
|
else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
)
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
|
|
if role:
|
|
folder = Path(identity) if identity else LOCAL / "identities" / role
|
|
ctx.load_cert_chain(folder / "service.crt", folder / "service.key")
|
|
return ctx
|
|
|
|
|
|
def request(
|
|
path, body=None, *, token=None, role="operator", base="https://localhost:18200", method=None
|
|
):
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
req = urllib.request.Request(
|
|
base + "/v1/" + path,
|
|
headers=headers,
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
method=method,
|
|
)
|
|
with urllib.request.urlopen(req, context=tls(role), timeout=5) as response:
|
|
data = response.read()
|
|
return json.loads(data) if data else {}
|
|
|
|
|
|
def root_token():
|
|
return json.loads((OPERATOR / "bao-init.json").read_text())["root_token"]
|
|
|
|
|
|
def issue(role, *, expired=False):
|
|
folder = LOCAL / "identities" / role
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
openssl(
|
|
"genpkey",
|
|
"-algorithm",
|
|
"EC",
|
|
"-pkeyopt",
|
|
"ec_paramgen_curve:P-256",
|
|
"-out",
|
|
folder / "service.key",
|
|
)
|
|
openssl(
|
|
"req",
|
|
"-new",
|
|
"-key",
|
|
folder / "service.key",
|
|
"-subj",
|
|
f"/CN={role}",
|
|
"-out",
|
|
folder / "service.csr",
|
|
)
|
|
names = [role]
|
|
if role in ["lb", "openbao", "grafana", "prometheus", "loki", "tempo"]:
|
|
names.append("localhost")
|
|
extras = (
|
|
"subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName="
|
|
+ ",".join("DNS:" + name for name in names)
|
|
+ "\n"
|
|
)
|
|
if "localhost" in names:
|
|
extras = extras.rstrip() + ",IP:127.0.0.1\n"
|
|
put(folder / "extensions.cnf", extras)
|
|
dates = (
|
|
["-startdate", "20200101000000Z", "-enddate", "20200102000000Z"]
|
|
if expired
|
|
else ["-days", "2"]
|
|
)
|
|
openssl(
|
|
"ca",
|
|
"-batch",
|
|
"-config",
|
|
OPERATOR / "ca.cnf",
|
|
"-extfile",
|
|
folder / "extensions.cnf",
|
|
"-in",
|
|
folder / "service.csr",
|
|
"-out",
|
|
folder / "service.crt",
|
|
"-notext",
|
|
*dates,
|
|
)
|
|
put(
|
|
folder / "service.pem",
|
|
(folder / "service.crt").read_text() + (folder / "service.key").read_text(),
|
|
)
|
|
# .local itself is 0700; container gets only its own read-only identity directory.
|
|
(folder / "service.key").chmod(0o644)
|
|
if role == "minio":
|
|
put(folder / "public.crt", (folder / "service.crt").read_text())
|
|
put(folder / "private.key", (folder / "service.key").read_text())
|
|
return folder
|
|
|
|
|
|
def refresh_crl():
|
|
openssl("ca", "-gencrl", "-config", OPERATOR / "ca.cnf", "-out", LOCAL / "trust/ca.crl")
|
|
|
|
|
|
def wait_bao():
|
|
for _ in range(60):
|
|
try:
|
|
return request("sys/seal-status")
|
|
except (OSError, urllib.error.URLError):
|
|
time.sleep(1)
|
|
raise RuntimeError("OpenBao did not start")
|