Files
mtusi2026lab7/scripts/stand.py
T
wh1tet3a f2ea9d65a8
Skeleton contracts / contracts (pull_request) Canceled after 0s
feat(security): add operator rotation and recovery commands
2026-11-20 19:02:00 +03:00

180 lines
4.4 KiB
Python

import json
import os
import subprocess
import time
from pathlib import Path
from uuid import uuid4
import httpx
ROOT = Path(__file__).resolve().parents[1]
BASE = os.environ.get("BASE_URL", "https://localhost:8443")
def command(args, *, input=None):
result = subprocess.run(
args, cwd=ROOT, input=input, capture_output=True, text=True
)
if result.returncode:
raise RuntimeError(
"Command failed: "
+ args[0]
+ "; "
+ result.stderr.replace(str(ROOT), "<repository>")
)
return result.stdout.strip()
def compose(*args, input=None):
if args[0] == "exec" and "controller" in args:
from scripts.operator_task import prepare
prepare()
result = command(["docker", "compose", *args], input=input)
# A restarted native container can get a new network namespace. Rejoin
# its TLS gateway explicitly instead of keeping an obsolete loopback hop.
native = {
"postgres",
"cache",
"broker",
"s3",
"lb",
"otel",
"prometheus",
"loki",
"tempo",
"grafana",
}
if args[0] in {"restart", "up"}:
targets = sorted(native.intersection(args[1:]))
if targets:
command(
[
"docker",
"compose",
"up",
"-d",
"--no-deps",
"--force-recreate",
*[role + "-tls" for role in targets],
]
)
if "lb" in targets:
command(
["docker", "compose", "up", "-d", "--no-deps", "identity-lb"]
)
return result
def sql(query, *, database="messenger"):
return compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
database,
"-A",
"-t",
"-v",
"ON_ERROR_STOP=1",
"-c",
query,
)
def cache(command_name, *args):
script = (
'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; '
'exec valkey-cli "$@"'
)
return compose(
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
)
def ready(base=BASE, *, timeout=30):
end = time.monotonic() + timeout
import ssl
context = ssl.create_default_context(cafile=ROOT / "trust/ca.pem")
with httpx.Client(
base_url=base, trust_env=False, timeout=6, verify=context
) as client:
while time.monotonic() < end:
try:
if client.get("/health/ready").status_code == 200:
return
except httpx.HTTPError:
pass
time.sleep(0.2)
raise TimeoutError("API readiness")
def actor(client):
username = "verify_" + uuid4().hex[:20]
password = "Synthetic-" + uuid4().hex + ":🌍"
result = client.post(
"/api/v1/users",
json={
"username": username,
"display_name": "Synthetic",
"password": password,
},
)
assert result.status_code == 201
user = result.json()
session = client.post(
"/api/v1/auth/sessions", auth=httpx.BasicAuth(username, password)
)
assert session.status_code == 201
return user, password, session.json()
def auth(session):
return {"Authorization": "Bearer " + session["token"]}
def extra_api(*, ttl=3600, pool_size=1):
name = "mtusi-lab6-test-" + uuid4().hex[:10]
compose(
"run",
"-d",
"--no-deps",
"--name",
name,
"-e",
"SESSION_TTL_SECONDS=" + str(ttl),
"-e",
"DB_POOL_SIZE=" + str(pool_size),
"-p",
"127.0.0.1::8080",
"api",
)
try:
info = json.loads(command(["docker", "inspect", name]))[0]
base = (
"http://127.0.0.1:"
+ info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
)
ready(base)
return name, base
except Exception:
command(["docker", "rm", "-f", name])
raise
def instances():
data = {}
for role in ["api", "postgres", "cache"]:
cid = compose("ps", "-q", role)
info = json.loads(command(["docker", "inspect", cid]))[0]
data[role] = {
"container": cid[:12],
"pid": info["State"]["Pid"],
"started_at": info["State"]["StartedAt"],
}
return data