Lab 7
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-27 20:47:58 +03:00
parent 20afc2c790
commit d995f98446
97 changed files with 8638 additions and 56 deletions
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
set -eu
# Operator-run: create the two mTLS service identities in RabbitMQ and give them
# least-privilege ACLs. RabbitMQ maps the client-certificate CN to a username
# (EXTERNAL auth), so the users must exist beforehand.
#
# api-broker configure + write the pipeline queue (it only publishes)
# worker-broker configure + read the pipeline queue (it only consumes)
#
# Neither identity can touch any other queue or exchange. Re-running is safe.
cd "$(dirname "$0")/.."
compose() { docker compose --env-file .env "$@"; }
rmq() { compose exec -T broker rabbitmqctl "$@"; }
Q='attachment\.process\.v1'
rand() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
rmq add_user api-broker "$(rand)" >/dev/null 2>&1 || true
rmq add_user worker-broker "$(rand)" >/dev/null 2>&1 || true
# EXTERNAL auth sends no password; disable password login so the TLS identity is
# the only way to use these accounts.
rmq clear_password api-broker >/dev/null 2>&1 || true
rmq clear_password worker-broker >/dev/null 2>&1 || true
# Publishing to the default exchange (amq.default) with the queue name as the
# routing key requires write on BOTH the exchange and the routing key, so the
# API is granted exactly those two names. The worker may only read its queue.
# configure write read
rmq set_permissions -p / api-broker "^${Q}$" "^(amq\.default|${Q})$" "^$"
rmq set_permissions -p / worker-broker "^${Q}$" "^$" "^${Q}$"
echo "broker identities ready: api-broker (configure+write), worker-broker (configure+read), queue $Q"
+225
View File
@@ -0,0 +1,225 @@
#!/usr/bin/env python3
"""Track 5.1 - the cost of observability.
Compares identical load with telemetry:
* OFF (no SDK providers);
* ON, sampler = always_on (keep 100% of traces);
* ON, sampler = ratio 0.1 (head sampling keeps ~10%);
* ON, Collector tail_sampling (keep all errors + slow, 10% baseline).
For each configuration it recreates the API + worker (and the Collector when the
sampling strategy changes), runs the same closed-loop load, and reports client
p50/p95 latency, successful RPS, API+worker CPU/RAM, and Collector span ingest /
loss from the Collector's own metrics.
Run from the repository root (docker CLI + running lab6 stand).
"""
from __future__ import annotations
import argparse
import base64
import concurrent.futures
import json
import os
import statistics
import subprocess
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
PROM = os.environ.get("PROM_URL", "http://localhost:9090").rstrip("/")
CONFIGS = [
{"name": "off", "env": {"TELEMETRY_ENABLED": "0"}, "collector": None},
{"name": "on_always_on", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "always_on"}, "collector": None},
{"name": "on_ratio_0.1", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio", "OTEL_TRACES_SAMPLER_ARG": "0.1"}, "collector": None},
{"name": "on_tail_balanced", "env": {"TELEMETRY_ENABLED": "1", "OTEL_TRACES_SAMPLER": "parentbased_always_on"}, "collector": "/etc/otelcol/otel-collector-tailsampling.yaml"},
]
RESULTS = []
def call(method, path, token=None, body=None):
headers = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if token:
headers["Authorization"] = "Bearer " + token
req = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
start = time.perf_counter()
try:
with urllib.request.urlopen(req, timeout=20) as resp:
resp.read()
return resp.status, time.perf_counter() - start
except urllib.error.HTTPError as error:
return error.code, time.perf_counter() - start
def login():
username = "cost_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
call("POST", "/api/v1/users", body={"username": username, "display_name": "Cost", "password": password})
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
req = urllib.request.Request(BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST")
with urllib.request.urlopen(req, timeout=20) as resp:
return json.loads(resp.read())["token"]
def wait_ready(timeout=120):
deadline = time.time() + timeout
while time.time() < deadline:
try:
if call("GET", "/health/ready")[0] == 200:
return
except Exception: # noqa: BLE001
pass
time.sleep(2)
raise SystemExit("stand not ready")
def recreate(env_overrides, collector):
env = dict(os.environ)
env.update(env_overrides)
if collector:
env["COLLECTOR_CONFIG"] = collector
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "api", "worker"],
env=env, check=True, capture_output=True, text=True)
if collector:
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "otel-collector"],
env=env, check=True, capture_output=True, text=True)
time.sleep(6)
def container_stats():
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}"],
capture_output=True, text=True).stdout
cpu = 0.0
mem = 0.0
for line in out.splitlines():
name, _, rest = line.partition("|")
if "api" not in name and "worker" not in name:
continue
cpu_part, _, mem_part = rest.partition("|")
try:
cpu += float(cpu_part.strip().rstrip("%"))
except ValueError:
pass
value = mem_part.split("/")[0].strip()
number = "".join(ch for ch in value if ch.isdigit() or ch == ".")
if value.endswith("GiB"):
mem += float(number) * 1024
elif value.endswith("MiB"):
mem += float(number)
return cpu, mem
def prom_sum(expr):
try:
with urllib.request.urlopen(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}), timeout=10) as resp:
data = json.loads(resp.read())
result = data["data"]["result"]
return float(result[0]["value"][1]) if result else 0.0
except Exception: # noqa: BLE001
return 0.0
def run_case(config, duration, threads):
print(f"\n== config {config['name']} ==", flush=True)
recreate(config["env"], config["collector"])
wait_ready()
token = login()
accepted_before = prom_sum("sum(otelcol_receiver_accepted_spans)")
sent_before = prom_sum("sum(otelcol_exporter_sent_spans)")
latencies = []
errors = 0
lock = threading.Lock()
stop = threading.Event()
peak = {"cpu": 0.0, "mem": 0.0}
def sampler():
while not stop.is_set():
cpu, mem = container_stats()
peak["cpu"] = max(peak["cpu"], cpu)
peak["mem"] = max(peak["mem"], mem)
time.sleep(0.5)
def worker():
nonlocal errors
deadline = time.time() + duration
while time.time() < deadline:
status, latency = call("GET", "/api/v1/users/me", token=token)
with lock:
if status == 200:
latencies.append(latency)
else:
errors += 1
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
start = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as pool:
list(pool.map(lambda _: worker(), range(threads)))
elapsed = time.time() - start
stop.set()
thread.join(timeout=2)
accepted_after = prom_sum("sum(otelcol_receiver_accepted_spans)")
sent_after = prom_sum("sum(otelcol_exporter_sent_spans)")
failed = prom_sum("sum(otelcol_exporter_send_failed_spans)")
result = {
"config": config["name"],
"requests": len(latencies) + errors,
"errors": errors,
"rps": round((len(latencies) + errors) / max(0.001, elapsed), 1),
"p50_ms": round(statistics.median(latencies) * 1000, 2) if latencies else None,
"p95_ms": round(sorted(latencies)[min(len(latencies) - 1, int(0.95 * (len(latencies) - 1)))] * 1000, 2) if latencies else None,
"api_worker_cpu_peak_pct": round(peak["cpu"], 1),
"api_worker_mem_peak_mb": round(peak["mem"], 1),
"spans_accepted_delta": int(accepted_after - accepted_before),
"spans_sent_delta": int(sent_after - sent_before),
"spans_failed_total": int(failed),
}
RESULTS.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--duration", type=int, default=15)
parser.add_argument("--threads", type=int, default=8)
parser.add_argument("--output", default="evidence/lab6-cost.json")
args = parser.parse_args()
for config in CONFIGS:
run_case(config, args.duration, args.threads)
# Restore the default balanced setup.
recreate({}, "/etc/otelcol/otel-collector.yaml")
os.makedirs(os.path.dirname(args.output), exist_ok=True)
with open(args.output, "w", encoding="utf-8") as handle:
json.dump({"duration": args.duration, "threads": args.threads, "results": RESULTS},
handle, ensure_ascii=False, indent=2)
print("\nconfig rps p50_ms p95_ms cpu%_peak memMB_peak spans_accepted spans_sent")
for r in RESULTS:
print(f"{r['config']:<16} {r['rps']:>5} {str(r['p50_ms']):>6} {str(r['p95_ms']):>6} "
f"{r['api_worker_cpu_peak_pct']:>8} {r['api_worker_mem_peak_mb']:>9} "
f"{r['spans_accepted_delta']:>14} {r['spans_sent_delta']:>10}")
print(json.dumps({"output": args.output}))
if __name__ == "__main__":
main()
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env python3
"""Grade-4 failure scenarios for the lab5 attachment pipeline.
Each scenario is explicit and reproducible:
1. worker-stopped accept: 202 while no worker, resume -> ready;
2. outbox gap: broker down at COMMIT -> job stays unpublished -> API restart
-> broker returns -> ready (no new task needed);
3. retry/replay: repeated transient failures -> failed(retry_exhausted) ->
operator replay after recovery -> ready;
4. redelivery of a ready job is a no-op (variants not duplicated);
5. lease recovery: a stuck 'processing' job is requeued by the watchdog.
Run from the repository root (docker CLI + running lab5 stand).
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import os
import struct
import subprocess
import time
import urllib.error
import urllib.request
import uuid
import zlib
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
def _png_chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def make_png(width=320, height=200):
raw = bytearray()
pixels = os.urandom(width * height * 3)
for row in range(height):
raw.append(0)
raw += pixels[row * width * 3 : (row + 1) * width * 3]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _png_chunk(b"IHDR", ihdr) + _png_chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _png_chunk(b"IEND", b"")
def http(method, path, token=None, body=None, raw=None, content_type=None):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=20) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except (urllib.error.URLError, TimeoutError, OSError):
return 0, b""
def compose(*args, check=True):
return subprocess.run(["docker", "compose", *args], check=check, capture_output=True, text=True)
def psql(sql):
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAc", sql],
capture_output=True, text=True,
)
return result.stdout.strip()
def service_running(name: str) -> bool:
result = subprocess.run(
["docker", "compose", "ps", "--status", "running", "--format", "{{.Service}}"],
capture_output=True, text=True,
)
return name in result.stdout.split()
def storage_reachable() -> bool:
# Raw TCP probe (bypasses the app's circuit breaker, which cannot be used to
# decide whether the store is really down).
result = subprocess.run(
["docker", "compose", "exec", "-T", "api", "python", "-c",
"import socket,sys; socket.create_connection(('s3',8333),1); sys.exit(0)"],
capture_output=True, text=True, timeout=30,
)
return result.returncode == 0
def wait_storage_down(timeout: float = 60.0) -> None:
deadline = time.time() + timeout
while time.time() < deadline:
if not storage_reachable():
return
time.sleep(1)
raise SystemExit("S3 still reachable; cannot run the failure scenario")
def wait_ready(timeout=90.0):
deadline = time.time() + timeout
while time.time() < deadline:
if http("GET", "/health/ready")[0] == 200:
return
time.sleep(1)
raise SystemExit("stand did not become ready")
def new_actor():
username = "fail_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
http("POST", "/api/v1/users", body={"username": username, "display_name": "Fail", "password": password})
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=20) as response:
token = json.loads(response.read())["token"]
user_id = json.loads(http("GET", "/api/v1/users/me", token=token)[1])["id"]
chat = json.loads(http("POST", "/api/v1/chats", token=token, body={"title": "fail", "member_ids": [user_id]})[1])
return token, chat["id"]
def upload(token, chat_id, data=None):
data = data if data is not None else make_png()
status, body = http("POST", f"/api/v1/chats/{chat_id}/attachments?filename=x.png", token=token, raw=data, content_type="image/png")
assert status == 202, (status, body)
return json.loads(body)["id"]
def status_of(token, attachment_id):
return json.loads(http("GET", f"/api/v1/attachments/{attachment_id}", token=token)[1])
def wait_status(token, attachment_id, wanted, timeout=120.0):
deadline = time.time() + timeout
last = None
while time.time() < deadline:
last = status_of(token, attachment_id)
if last["status"] == wanted:
return last
time.sleep(0.5)
raise SystemExit(f"attachment {attachment_id} did not reach {wanted}: {last}")
def scenario_worker_stopped(log):
log("\n== scenario 1: accept while worker stopped, resume -> ready ==")
compose("stop", "worker")
try:
token, chat_id = new_actor()
att_id = upload(token, chat_id)
time.sleep(2)
state = status_of(token, att_id)
log(f"with worker stopped: status={state['status']} (expected queued)")
assert state["status"] == "queued", state
compose("restart", "api")
wait_ready()
log("API restarted; work still queued (durable)")
assert status_of(token, att_id)["status"] == "queued"
finally:
compose("start", "worker")
ready = wait_status(token, att_id, "ready")
names = sorted(v["name"] for v in ready["variants"])
log(f"worker resumed: status=ready variants={names}")
assert {"thumbnail", "crop", "optimized"} <= set(names)
def scenario_outbox_gap(log):
log("\n== scenario 2: COMMIT/publish gap (broker down), API restart, then broker ==")
compose("stop", "broker")
try:
token, chat_id = new_actor()
att_id = upload(token, chat_id)
time.sleep(2)
job = psql(f"select published_at from attachment_jobs where attachment_id='{att_id}'")
log(f"broker down: status={status_of(token, att_id)['status']} published_at={job!r} (expected empty)")
assert status_of(token, att_id)["status"] in {"queued", "processing"}
compose("restart", "api")
wait_ready()
log("API restarted with broker still down; intent preserved in PostgreSQL")
finally:
compose("start", "broker")
ready = wait_status(token, att_id, "ready", timeout=180)
log(f"broker back: status={ready['status']} (outbox republished without new task)")
def scenario_retry_replay(log):
log("\n== scenario 3: transient failures -> failed(retry_exhausted) -> replay ==")
compose("stop", "worker")
while service_running("worker"):
time.sleep(0.5)
token, chat_id = new_actor()
att_id = upload(token, chat_id)
original_key = psql(f"select staging_key from attachments where id='{att_id}'")
# Fault injection: the durable original is (temporarily) unavailable, so the
# worker's fetch fails and is retried with backoff until attempts are spent.
psql(f"update attachments set staging_key='staging/missing-{att_id}' where id='{att_id}'")
log("injected: staging object points to a missing key (transient fetch failure)")
compose("start", "worker")
failed = wait_status(token, att_id, "failed", timeout=180)
log(f"status=failed error_code={failed['error_code']} (expected retry_exhausted)")
assert failed["error_code"] == "retry_exhausted", failed
# Operator repairs the cause and replays the failed job explicitly.
psql(f"update attachments set staging_key='{original_key}' where id='{att_id}'")
job_id = att_id_job(att_id)
replayed = subprocess.run(
["docker", "compose", "exec", "-T", "api", "python", "-m", "src.replay", job_id],
capture_output=True, text=True,
).stdout.strip()
log(f"explicit replay after recovery: {replayed}")
ready = wait_status(token, att_id, "ready", timeout=120)
log(f"after replay: status=ready variants={sorted(v['name'] for v in ready['variants'])}")
def att_id_job(attachment_id):
return psql(f"select job_id from attachment_jobs where attachment_id='{attachment_id}'")
def scenario_redelivery(log):
log("\n== scenario 4: redelivery of a ready job is a no-op ==")
token, chat_id = new_actor()
att_id = upload(token, chat_id)
ready = wait_status(token, att_id, "ready")
before = sorted((v["name"], v["sha256"]) for v in ready["variants"])
# Republish the finished job (duplicate delivery).
psql(f"update attachment_jobs set status='pending', published_at=null, available_at=now() where attachment_id='{att_id}'")
log("re-queued the same job (duplicate delivery)")
time.sleep(6)
after = status_of(token, att_id)
after_variants = sorted((v["name"], v["sha256"]) for v in after["variants"])
log(f"status={after['status']} variants={[n for n,_ in after_variants]} (must be unchanged)")
assert after["status"] == "ready"
assert after_variants == before, "duplicate delivery changed variants"
def scenario_lease_recovery(log):
log("\n== scenario 5: stuck processing -> lease recovery ==")
compose("stop", "worker")
token, chat_id = new_actor()
att_id = upload(token, chat_id)
job_id = att_id_job(att_id)
# Simulate a worker that died mid-processing with an already-expired lease.
psql(f"update attachments set status='processing' where id='{att_id}'")
psql(f"update attachment_jobs set status='processing', lease_until=now() - interval '5 seconds' where job_id='{job_id}'")
log("marked attachment+job processing with an expired lease")
compose("start", "worker")
ready = wait_status(token, att_id, "ready", timeout=120)
log(f"watchdog requeued and finished the job: status={ready['status']}")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--only", choices=["1", "2", "3", "4", "5"], help="run one scenario")
args = parser.parse_args()
wait_ready()
def log(message):
print(message, flush=True)
scenarios = {
"1": scenario_worker_stopped,
"2": scenario_outbox_gap,
"3": scenario_retry_replay,
"4": scenario_redelivery,
"5": scenario_lease_recovery,
}
if args.only:
scenarios[args.only](log)
else:
for name in ("1", "2", "3", "4", "5"):
scenarios[name](log)
print("\nPASS: lab5 grade-4 failure scenarios" + (f" (scenario {args.only})" if args.only else ""))
if __name__ == "__main__":
main()
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Internal mTLS audit: LB -> API identity checks (lab7, grade 3/4).
The API replica has no published port: it is reachable only from the compose
network on 8443, where a per-replica nginx terminates mTLS. This script runs a
probe inside the network (using the api service image) and asserts the four
required outcomes from the trust matrix:
no client certificate -> rejected
certificate from a rogue CA -> rejected
project CA, forbidden CN -> rejected (HTTP 403)
project CA, identity CN=lb -> accepted (HTTP 200)
The probe never disables certificate verification.
Run: python scripts/check-internal-mtls.py
"""
from __future__ import annotations
import os
import subprocess
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(ROOT)
PROBE = r'''
import http.client, ssl
def probe(name, certfile, keyfile, expect):
ctx = ssl.create_default_context(cafile="/pki/ca.crt")
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
if certfile:
ctx.load_cert_chain(certfile, keyfile)
try:
conn = http.client.HTTPSConnection("api", 8443, context=ctx, timeout=5)
conn.request("GET", "/health/live")
resp = conn.getresponse(); resp.read()
print("%s: HTTP %d expect=%s" % (name, resp.status, expect))
except ssl.SSLError as exc:
print("%s: TLS-REJECT %s expect=%s" % (name, type(exc).__name__, expect))
except Exception as exc:
print("%s: ERROR %s expect=%s" % (name, type(exc).__name__, expect))
probe("no_client", None, None, "reject")
probe("rogue_ca", "/pki/rogue-client.crt", "/pki/rogue-client.key", "reject")
probe("forbidden_cn", "/pki/evil-client.crt", "/pki/evil-client.key", "reject")
probe("lb_identity", "/pki/lb-client.crt", "/pki/lb-client.key", "accept")
'''
# nginx reports a missing or unverifiable client certificate as HTTP 400 and a
# valid certificate with a forbidden identity as HTTP 403; both are rejections.
EXPECT = {
"no_client": lambda out: "HTTP 400" in out or "TLS-REJECT" in out,
"rogue_ca": lambda out: "HTTP 400" in out or "TLS-REJECT" in out,
"forbidden_cn": lambda out: "HTTP 403" in out,
"lb_identity": lambda out: "HTTP 200" in out,
}
def main() -> int:
cmd = [
"docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "-T",
"-v", os.path.join(ROOT, "secrets", "pki") + ":/pki:ro",
"api", "python", "-c", PROBE,
]
proc = subprocess.run(cmd, capture_output=True, text=True)
output = (proc.stdout + proc.stderr).strip()
print(output)
failures = 0
for line in output.splitlines():
for name, check in EXPECT.items():
if line.startswith(name + ":"):
if not check(line):
print(" MISMATCH:", line)
failures += 1
found = sum(1 for line in output.splitlines() if line.split(":")[0] in EXPECT)
if found != 4:
print(" expected 4 probe results, saw", found)
failures += 1
print("PASS: internal mTLS identity checks" if failures == 0 else "FAIL: %d mismatch(es)" % failures)
return 1 if failures else 0
if __name__ == "__main__":
raise SystemExit(main())
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Login rate limit check (lab7): 429 + Retry-After after the shared budget.
Hits /api/v1/auth/sessions with wrong credentials for one synthetic username
until the per-(ip,user) budget is exhausted. The limiter runs before the
expensive Argon2 verification, so this also bounds password-spray CPU cost.
Run: python scripts/check-login-limit.py
"""
from __future__ import annotations
import base64
import json
import os
import ssl
import sys
import urllib.error
import urllib.request
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE = os.environ.get("BASE_URL", "https://localhost:8443")
CA = os.environ.get("CA_FILE", os.path.join(ROOT, "secrets", "pki", "ca.crt"))
LIMIT = int(os.environ.get("LOGIN_RATE_LIMIT", "10"))
def main() -> int:
context = ssl.create_default_context(cafile=CA)
username = "ratelimit_probe_%d" % os.getpid()
credentials = base64.b64encode((username + ":wrong-password").encode()).decode()
print("probing %s (limit=%d)" % (BASE, LIMIT))
limited = False
retry_after = None
for attempt in range(1, LIMIT + 4):
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions", method="POST",
headers={"Authorization": "Basic " + credentials,
"Content-Type": "application/json"},
)
try:
urllib.request.urlopen(request, timeout=5, context=context).read()
status = 200
except urllib.error.HTTPError as error:
status = error.code
if status == 429:
limited = True
retry_after = error.headers.get("Retry-After")
print(" attempt %2d -> %d%s" % (attempt, status,
" Retry-After=" + str(retry_after) if status == 429 else ""))
if limited:
break
ok = limited and retry_after is not None and int(retry_after) > 0
print("PASS: login limited with 429 and Retry-After" if ok
else "FAIL: no 429/Retry-After observed")
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())
+243
View File
@@ -0,0 +1,243 @@
#!/usr/bin/env python3
"""Track 5.1 - the attachment queue under overload.
Hypothesis: raising worker concurrency increases throughput and shortens
time-to-ready up to a point, after which CPU contention (Pillow resizing) and
memory set the ceiling; the durable queue lets the API keep accepting (202) and
bounds in-flight work, then drains and recovers afterwards.
Method (reproducible):
* for each (concurrency, image size) pair, recreate the worker with a fixed
WORKER_CONCURRENCY, submit a burst of uploads, and poll every attachment
until ready;
* record accepted/errors, throughput, p50/p95 time-to-ready, queue depth over
time (backpressure) and peak worker RSS (docker stats);
* after the largest burst, wait for the queue to drain and confirm a fresh
upload still becomes ready quickly (recovery).
Output: a JSON document plus a readable table. Run from the repository root.
"""
from __future__ import annotations
import argparse
import base64
import concurrent.futures
import json
import os
import statistics
import struct
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
import zlib
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
RESULTS = []
def _chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def make_png(width, height):
raw = bytearray()
pixels = os.urandom(width * height * 3)
stride = width * 3
for row in range(height):
raw.append(0)
raw += pixels[row * stride : (row + 1) * stride]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _chunk(b"IEND", b"")
def http(method, path, token=None, body=None, raw=None, content_type=None):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=30) as response:
return response.status, response.read()
except urllib.error.HTTPError as error:
return error.code, error.read()
except (urllib.error.URLError, TimeoutError, OSError):
return 0, b""
def login():
username = "q_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
http("POST", "/api/v1/users", body={"username": username, "display_name": "Q", "password": password})
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
request = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=20) as response:
token = json.loads(response.read())["token"]
user_id = json.loads(http("GET", "/api/v1/users/me", token=token)[1])["id"]
chat = json.loads(http("POST", "/api/v1/chats", token=token, body={"title": "q", "member_ids": [user_id]})[1])
return token, chat["id"]
def worker_mem_mb():
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.MemUsage}}"],
capture_output=True, text=True).stdout
for line in out.splitlines():
name, _, usage = line.partition("|")
if "worker" not in name:
continue
value = usage.split("/")[0].strip()
number = "".join(ch for ch in value if ch.isdigit() or ch == ".")
if value.endswith("GiB"):
return float(number) * 1024
if value.endswith("MiB"):
return float(number)
return 0.0
def set_worker_concurrency(value):
env = dict(os.environ, WORKER_CONCURRENCY=str(value))
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "worker"],
env=env, check=True, capture_output=True, text=True)
time.sleep(3)
def percentile(values, pct):
if not values:
return 0.0
ordered = sorted(values)
index = min(len(ordered) - 1, int(round((pct / 100.0) * (len(ordered) - 1))))
return ordered[index]
def run_case(concurrency, size_name, width, height, count, submit_workers=8):
set_worker_concurrency(concurrency)
token, chat_id = login()
payload = make_png(width, height)
pending = {}
codes = {}
lock = threading.Lock()
def submit(_):
status, body = http("POST", f"/api/v1/chats/{chat_id}/attachments?filename=q.png", token=token,
raw=payload, content_type="image/png")
with lock:
codes[status] = codes.get(status, 0) + 1
if status != 202:
return
attachment_id = json.loads(body)["id"]
with lock:
pending[attachment_id] = time.time()
queue_samples = []
stop = threading.Event()
peak = {"value": worker_mem_mb()}
def sampler():
while not stop.is_set():
with lock:
depth = len(pending)
queue_samples.append(depth)
peak["value"] = max(peak["value"], worker_mem_mb())
time.sleep(0.2)
thread = threading.Thread(target=sampler, daemon=True)
thread.start()
submit_start = time.time()
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, min(submit_workers, count))) as pool:
list(pool.map(submit, range(count)))
submit_done = time.time()
latencies = []
deadline = time.time() + 300
while pending and time.time() < deadline:
with lock:
ids = list(pending.keys())
for attachment_id in ids:
status, body = http("GET", f"/api/v1/attachments/{attachment_id}", token=token)
if status != 200:
continue
state = json.loads(body)["status"]
if state in {"ready", "failed"}:
with lock:
started = pending.pop(attachment_id, None)
if started is not None:
latencies.append((time.time() - started, state))
time.sleep(0.2)
stop.set()
thread.join(timeout=2)
ready = [lat for lat, state in latencies if state == "ready"]
failed = [lat for lat, state in latencies if state == "failed"]
result = {
"concurrency": concurrency,
"size": size_name,
"bytes": len(payload),
"submitted": count,
"accepted": codes.get(202, 0),
"errors": sum(v for k, v in codes.items() if k != 202),
"codes": codes,
"ready": len(ready),
"failed": len(failed),
"submit_seconds": round(submit_done - submit_start, 2),
"drain_seconds": round(time.time() - submit_done, 2),
"throughput_per_s": round(len(ready) / max(0.001, time.time() - submit_start), 2),
"p50_ready_s": round(statistics.median(ready), 2) if ready else None,
"p95_ready_s": round(percentile(ready, 95), 2) if ready else None,
"max_queue_depth": max(queue_samples) if queue_samples else 0,
"worker_peak_mem_mb": round(peak["value"], 1),
}
RESULTS.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--count", type=int, default=12)
parser.add_argument("--output", default="evidence/lab5-overload.json")
args = parser.parse_args()
os.makedirs(os.path.dirname(args.output), exist_ok=True)
plan = [
(1, "small", 640, 480, 8),
(2, "small", 640, 480, 8),
(4, "small", 640, 480, 8),
(1, "large", 2200, 1500, 4),
(2, "large", 2200, 1500, 4),
(4, "large", 2200, 1500, 4),
]
for concurrency, size_name, width, height, workers in plan:
run_case(concurrency, size_name, width, height, args.count, submit_workers=workers)
# Recovery: after the heaviest cases the queue must drain and a fresh upload
# must still be served promptly.
set_worker_concurrency(2)
token, chat_id = login()
fresh = run_case(2, "recovery", 800, 600, 1)
drained = fresh["ready"] == 1 and fresh["p95_ready_s"] is not None and fresh["p95_ready_s"] < 30
with open(args.output, "w", encoding="utf-8") as handle:
json.dump({"results": RESULTS, "recovered": drained}, handle, ensure_ascii=False, indent=2)
print("\nconcurrency size bytes accepted ready p50_s p95_s maxq peakRSS_MB")
for r in RESULTS:
print(f"{r['concurrency']:>11} {r['size']:<7} {r['bytes']:>7} {r['accepted']:>8} {r['ready']:>5} "
f"{str(r['p50_ready_s']):>5} {str(r['p95_ready_s']):>5} {r['max_queue_depth']:>5} {r['worker_peak_mem_mb']:>10}")
print(f"\nrecovery after overload: {'OK' if drained else 'FAILED'}")
print(json.dumps({"output": args.output, "recovered": drained}))
if __name__ == "__main__":
main()
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Regression check: logout must not be bypassed while Valkey is unavailable.
Scenario (the one that used to fail):
1. login and warm any session cache;
2. pause Valkey;
3. logout -> 204 (session row removed from PostgreSQL);
4. resume Valkey;
5. after the cache circuit breaker window, the old token must still be 401 on
every replica, and it must not be able to send a message.
Requires the docker CLI and a running lab3 stack.
"""
import argparse
import os
import subprocess
import sys
import time
import uuid
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests"))
from client import Client # noqa: E402
def _docker(*args: str) -> None:
subprocess.run(["docker", *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
parser.add_argument("--valkey-container", default=os.environ.get("VALKEY_CONTAINER", "messenger-lab3-valkey-1"))
parser.add_argument("--wait", type=float, default=6.0, help="seconds to wait after resuming Valkey")
args = parser.parse_args()
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
# Warm the cache on both replicas.
for _ in range(6):
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
c.message(alice, chat, "warm-up before revocation")
print("Pausing Valkey (%s) ..." % args.valkey_container)
_docker("pause", args.valkey_container)
try:
logout = c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
assert logout["status"] == 204, logout["status"]
print("Logout returned 204 while the cache was unavailable.")
finally:
_docker("unpause", args.valkey_container)
print("Valkey resumed; waiting %.1fs for the cache circuit breaker ..." % args.wait)
time.sleep(args.wait)
seen = set()
for _ in range(12):
response = c.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error")
seen.add(response["headers"].get("X-Instance-Id"))
assert len(seen) >= 1, "no replica observed"
blocked = c.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
401,
actor=alice,
body={"text": "must not be written"},
headers={"Idempotency-Key": uuid.uuid4().hex},
schema="Error",
)
assert blocked["status"] == 401, blocked["status"]
print(
"PASS: revoked session stays 401 through %d replica(s) and cannot post after a "
"failed cache invalidation." % len(seen)
)
if __name__ == "__main__":
main()
+276
View File
@@ -0,0 +1,276 @@
#!/usr/bin/env python3
"""Observability acceptance checks for lab6.
Proves, from the saved telemetry only:
1. metrics exist in Prometheus (HTTP, jobs, queue, DB pool, worker);
2. a controlled upload yields a structured API log in Loki whose trace_id is
found in Tempo with BOTH messenger-api and messenger-worker spans
(cross-process trace through the broker);
3. alert rules are loaded and can FIRE and RESOLVE for two incidents:
worker stopped (queue age) and PostgreSQL down (5xx error ratio);
4. stopping a telemetry backend (Loki) does not break the API.
Run from the repository root; needs docker CLI + running lab6 stand.
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zlib
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
PROM = os.environ.get("PROM_URL", "http://localhost:9090").rstrip("/")
LOKI = os.environ.get("LOKI_URL", "http://localhost:3100").rstrip("/")
TEMPO = os.environ.get("TEMPO_URL", "http://localhost:3200").rstrip("/")
def _chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
def make_png(width=320, height=200):
raw = bytearray()
pixels = os.urandom(width * height * 3)
stride = width * 3
for row in range(height):
raw.append(0)
raw += pixels[row * stride : (row + 1) * stride]
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _chunk(b"IEND", b"")
def request(method, url, token=None, body=None, raw=None, content_type=None, timeout=20):
headers = {"Accept": "application/json"}
data = raw
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
if content_type:
headers["Content-Type"] = content_type
if token:
headers["Authorization"] = "Bearer " + token
req = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.status, resp.headers, resp.read()
except urllib.error.HTTPError as error:
return error.code, error.headers, error.read()
def get_json(url):
status, _headers, body = request("GET", url)
if status != 200:
return None
return json.loads(body)
def prom_query(expr):
data = get_json(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}))
if not data or data.get("status") != "success":
return []
return data["data"]["result"]
def active_alerts():
data = get_json(PROM + "/api/v1/alerts")
if not data:
return {}
result = {}
for alert in data["data"]["alerts"]:
result[alert["labels"].get("alertname")] = alert["state"]
return result
def login_upload():
username = "tel_" + uuid.uuid4().hex[:8]
password = "T3st-" + uuid.uuid4().hex
request("POST", BASE + "/api/v1/users", body={"username": username, "display_name": "Tel", "password": password})
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
req = urllib.request.Request(
BASE + "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=20) as resp:
token = json.loads(resp.read())["token"]
user_id = json.loads(request("GET", BASE + "/api/v1/users/me", token=token)[2])["id"]
chat = json.loads(request("POST", BASE + "/api/v1/chats", token=token,
body={"title": "tel", "member_ids": [user_id]})[2])
status, headers, body = request(
"POST", f"{BASE}/api/v1/chats/{chat['id']}/attachments?filename=t.png",
token=token, raw=make_png(), content_type="image/png",
)
assert status == 202, (status, body)
return token, json.loads(body)["id"], headers.get("X-Request-Id")
def wait_ready(timeout=90):
deadline = time.time() + timeout
while time.time() < deadline:
if request("GET", BASE + "/health/ready")[0] == 200:
return
time.sleep(1)
raise SystemExit("stand not ready")
def compose(*args):
subprocess.run(["docker", "compose", *args], check=True, capture_output=True, text=True)
def tempo_search(service="messenger-api", limit=60, window=180):
end = int(time.time())
start = end - window
url = f"{TEMPO}/api/search?" + urllib.parse.urlencode(
{"tags": f"service.name={service}", "start": start, "end": end, "limit": limit}
)
data = get_json(url) or {}
return [t["traceID"] for t in data.get("traces", [])]
def loki_has_trace(trace_id, service):
query = '{service_name="%s"} | trace_id = "%s"' % (service, trace_id)
end = time.time()
start = end - 900
url = LOKI + "/loki/api/v1/query_range?" + urllib.parse.urlencode(
{"query": query, "limit": 1, "start": f"{int(start)}000000000", "end": f"{int(end)}000000000"}
)
data = get_json(url)
return bool(data and data["data"]["result"])
def tempo_services(trace_id):
data = get_json(f"{TEMPO}/api/traces/{trace_id}")
if not data:
return set()
services = set()
for batch in data.get("batches", []):
for attr in batch.get("resource", {}).get("attributes", []):
if attr.get("key") == "service.name":
services.add(attr["value"].get("stringValue"))
return services
def find_linked_trace(timeout=90):
deadline = time.time() + timeout
while time.time() < deadline:
candidates = set(tempo_search("messenger-worker")) | set(tempo_search("messenger-api"))
for trace_id in candidates:
services = tempo_services(trace_id)
if {"messenger-api", "messenger-worker"} <= services:
return trace_id, services
time.sleep(3)
return None, set()
def wait_alert(name, state, timeout):
deadline = time.time() + timeout
while time.time() < deadline:
if active_alerts().get(name) == state:
return True
time.sleep(3)
return False
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--skip-incidents", action="store_true")
args = parser.parse_args()
wait_ready()
print("== 1. metrics present ==")
for expr in [
"sum(http_server_requests_total)",
"sum(messenger_jobs_processed_total)",
"max(messenger_queue_depth)",
"max(messenger_worker_capacity)",
"max(messenger_db_pool_used)",
]:
result = prom_query(expr)
assert result, f"metric empty: {expr}"
print(f" {expr} -> {result[0]['value'][1]}")
print("== 2. cross-process trace (API -> worker) + correlated logs ==")
token, attachment_id, request_id = login_upload()
trace_id, services = find_linked_trace()
assert trace_id, "no trace linking messenger-api and messenger-worker found in Tempo"
print(f" trace {trace_id} services={sorted(services)}")
assert loki_has_trace(trace_id, "messenger-api"), "no API log for that trace_id"
assert loki_has_trace(trace_id, "messenger-worker"), "no worker log for that trace_id"
print(" Loki has both API and worker logs with this trace_id")
print("== 3. alert rules loaded ==")
rules = get_json(PROM + "/api/v1/rules") or {"data": {"groups": []}}
names = {r["name"] for g in rules["data"]["groups"] for r in g["rules"]}
assert {"HighErrorRate", "QueueLagGrowing"} <= names, names
print(f" rules: {sorted(names)}")
if args.skip_incidents:
print("PASS: telemetry signals (incidents skipped)")
return
print("== 4. incident 1: worker stopped -> queue age alert fires ==")
compose("stop", "worker")
try:
for _ in range(6):
login_upload()
fired = wait_alert("QueueLagGrowing", "firing", 240)
print(f" QueueLagGrowing firing={fired}")
assert fired, "queue lag alert did not fire"
finally:
compose("start", "worker")
resolved = wait_alert("QueueLagGrowing", None, 300)
print(f" QueueLagGrowing resolved={resolved}")
assert resolved, "queue lag alert did not resolve"
print("== 5. incident 2: PostgreSQL down -> 5xx error ratio fires ==")
compose("stop", "postgres")
try:
fired = False
deadline = time.time() + 260
while time.time() < deadline:
for _ in range(5):
login_upload_safe()
if active_alerts().get("HighErrorRate") == "firing":
fired = True
break
time.sleep(10)
print(f" HighErrorRate firing={fired}")
assert fired, "error-rate alert did not fire"
finally:
compose("start", "postgres")
resolved = wait_alert("HighErrorRate", None, 300)
print(f" HighErrorRate resolved={resolved}")
assert resolved, "error-rate alert did not resolve"
wait_ready(120)
print("== 6. telemetry backend down does not break the API ==")
compose("stop", "loki")
try:
result = subprocess.run([sys.executable, "tests/smoke.py", "--base-url", BASE],
capture_output=True, text=True)
print(" smoke:", result.stdout.strip() or result.stderr.strip())
assert result.returncode == 0, "smoke failed while Loki was down"
finally:
compose("start", "loki")
print("\nPASS: lab6 observability acceptance checks")
def login_upload_safe():
try:
login_upload()
except Exception: # noqa: BLE001 - expected 503 while DB is down
pass
if __name__ == "__main__":
main()
+271
View File
@@ -0,0 +1,271 @@
#!/usr/bin/env python3
"""Track 1 (grade 5): blast radius of a compromised worker, and recovery.
The script assumes a running lab7 stand. It answers three questions:
1. Which bucket, queue and database operations are available to a compromised
worker identity, and which are forbidden?
2. What does an over-privileged (pre-hardening) identity additionally reach?
3. After the worker identity is revoked and its credential rotated, are the
accepted tasks still processed (durability), and does the worker recover?
Run: python scripts/check-worker-scope.py
Evidence: evidence/lab7-track1-scope.txt (stdout) and evidence/lab7-track1.json
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
import uuid
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(ROOT)
sys.path.insert(0, os.path.join(ROOT, "tests"))
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443")
CA_FILE = os.environ.get("CA_FILE", os.path.join(ROOT, "secrets", "pki", "ca.crt"))
RESULTS = []
def compose(*args, env=None):
cmd = ["docker", "compose", "--env-file", ".env", *args]
proc = subprocess.run(cmd, capture_output=True, text=True)
return proc.returncode, (proc.stdout + proc.stderr).strip()
def psql(user, password, sql):
return compose(
"exec", "-T", "-e", "PGPASSWORD=" + password,
"postgres", "psql", "-U", user, "-d", "messenger", "-tAc", sql,
)
def in_container(service, code, env=None):
args = ["exec", "-T"]
for key, value in (env or {}).items():
args += ["-e", key + "=" + value]
args += [service, "python", "-c", code]
return compose(*args)
def marker(out, prefix):
if prefix + "=ALLOWED" in out:
return "ALLOWED"
if prefix + "=DENIED" in out:
return "DENIED"
print(" (probe produced no marker; raw tail: " + out.strip()[-200:] + ")")
return "ERROR"
def record(identity, operation, expected, rc, out):
"""Classify an observation as ALLOWED or DENIED and print one table row."""
if out in {"ALLOWED", "DENIED", "ERROR"}:
verdict = out
else:
denied = ("permission denied" in out.lower()) or ("access_refused" in out.lower()) \
or ("accessdenied" in out.lower()) or ("not_authorized" in out.lower()) \
or ("403" in out) or ("noconsumer" in out.lower()) or ("channelclosed" in out.lower())
denied = denied or (rc != 0 and expected == "DENIED")
verdict = "DENIED" if denied else ("ALLOWED" if rc == 0 else "ERROR")
mark = "ok " if verdict == expected else "!! "
print(" " + mark + "%-9s %-42s %-8s (expected %s)" % (identity, operation, verdict, expected))
RESULTS.append(
{"identity": identity, "operation": operation, "expected": expected,
"observed": verdict, "match": verdict == expected}
)
return verdict
def section(title):
print("\n" + "=" * 74)
print(title)
print("=" * 74)
def read_secret(name):
with open(os.path.join(ROOT, "secrets", name), encoding="utf-8") as handle:
return handle.read().strip()
def main() -> int:
print("lab7 track 1 - compromised worker scope and recovery")
print("time:", time.strftime("%Y-%m-%dT%H:%M:%S%z"))
api_pw = read_secret("database_api_password")
worker_pw = read_secret("database_worker_password")
admin_url = read_secret("database_url")
admin_pw = read_secret("database_password")
root_key = read_secret("s3_root_access_key_id")
root_secret = read_secret("s3_root_secret_access_key")
# ---------------------------------------------------------------- database
section("1. DATABASE: worker vs api vs pre-hardening admin")
record("worker", "SELECT users", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from users"))
record("worker", "SELECT sessions", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from sessions"))
record("worker", "SELECT messages", "DENIED", *psql("messenger_worker", worker_pw, "select count(*) from messages"))
record("worker", "UPDATE users", "DENIED", *psql("messenger_worker", worker_pw, "update users set display_name = 'x'"))
record("worker", "DROP TABLE attachments", "DENIED", *psql("messenger_worker", worker_pw, "drop table attachments"))
record("worker", "SELECT attachments", "ALLOWED", *psql("messenger_worker", worker_pw, "select count(*) from attachments"))
record("worker", "SELECT attachment_jobs", "ALLOWED", *psql("messenger_worker", worker_pw, "select count(*) from attachment_jobs"))
record("api", "SELECT users", "ALLOWED", *psql("messenger_api", api_pw, "select count(*) from users"))
record("admin", "SELECT users (pre-hardening identity)", "ALLOWED", *psql("messenger", admin_pw, "select count(*) from users"))
record("admin", "ALTER ROLE (create admin)", "ALLOWED", *psql("messenger", admin_pw, "select rolcreatedb from pg_roles where rolname = 'messenger'"))
# ------------------------------------------------------------- openbao
section("2. OPENBAO: scoped service policies")
bao = (
"from src import openbao\n"
"display = {'WORKER': 'secret/messenger/worker', 'API': 'secret/messenger/api'}\n"
"for label, path in display.items():\n"
" try:\n"
" openbao.read_kv(path); print(label + '_PATH=ALLOWED')\n"
" except Exception as exc:\n"
" print(label + '_PATH=DENIED ' + type(exc).__name__)\n"
)
rc, out = in_container("worker", bao)
record("worker", "read own KV path", "ALLOWED", 0, marker(out, "WORKER_PATH"))
record("worker", "read api KV path", "DENIED", 0, marker(out, "API_PATH"))
rc, out = in_container("api", bao)
record("api", "read own KV path", "ALLOWED", 0, marker(out, "API_PATH"))
record("api", "read worker KV path", "DENIED", 0, marker(out, "WORKER_PATH"))
# --------------------------------------------------------------- broker
section("3. BROKER: queue ACLs as certificate identities (EXTERNAL auth)")
publish_probe = (
"from src import broker\n"
"try:\n"
" broker.publish({'schema_version': 1, 'type': 'attachment.process.v1',\n"
" 'job_id': 'probe', 'attachment_id': 'probe', 'pipeline_version': 1})\n"
" print('PUBLISH=ALLOWED')\n"
"except Exception as exc:\n"
" print('PUBLISH=DENIED ' + type(exc).__name__)\n"
)
rc, out = in_container("worker", publish_probe)
record("worker", "publish to pipeline queue", "DENIED", 0, marker(out, "PUBLISH"))
rc, perms = compose("exec", "-T", "broker", "rabbitmqctl", "list_permissions", "-p", "/")
print(" broker permissions:\n" + "\n".join(" " + line for line in perms.splitlines()))
# ------------------------------------------------------------------ S3
section("4. S3: bucket scope (limited identity vs root)")
# A second bucket exists only for the admin; the limited identity must fail.
compose("exec", "-T", "s3", "sh", "-c", "echo 's3.bucket.create -name messenger-internal' | weed shell")
s3_probe = (
"import os, boto3\n"
"from botocore.client import Config\n"
"from botocore.exceptions import ClientError, BotoCoreError\n"
"from src import storage\n"
"from src.config import settings\n"
"cfg = Config(connect_timeout=3, read_timeout=5, retries={'max_attempts': 1}, s3={'addressing_style': 'path'})\n"
"def check(ak, sk, bucket, label):\n"
" client = boto3.client('s3', endpoint_url=settings.s3_endpoint, region_name=settings.s3_region,\n"
" aws_access_key_id=ak, aws_secret_access_key=sk,\n"
" verify=settings.tls_ca_file, config=cfg)\n"
" try:\n"
" client.head_bucket(Bucket=bucket); print(label + '=ALLOWED')\n"
" except (ClientError, BotoCoreError) as exc:\n"
" print(label + '=DENIED ' + type(exc).__name__)\n"
"check(settings.s3_access_key_id, settings.s3_secret_access_key, settings.s3_bucket, 'OWN_BUCKET')\n"
"check(settings.s3_access_key_id, settings.s3_secret_access_key, 'messenger-internal', 'FOREIGN_LIMITED')\n"
"rk = os.environ.get('ROOT_KEY')\n"
"if rk:\n"
" check(rk, os.environ['ROOT_SECRET'], 'messenger-internal', 'FOREIGN_ROOT')\n"
)
rc, out = in_container("api", s3_probe, env={"ROOT_KEY": root_key, "ROOT_SECRET": root_secret})
record("worker", "attachments bucket (own)", "ALLOWED", 0, marker(out, "OWN_BUCKET"))
record("worker", "messenger-internal bucket", "DENIED", 0, marker(out, "FOREIGN_LIMITED"))
record("admin", "messenger-internal bucket (root key)", "ALLOWED", 0, marker(out, "FOREIGN_ROOT"))
# ------------------------------------------- revocation / rotation / durability
section("5. REVOKE + ROTATE + RECOVER (accepted task must survive)")
from client import Client # noqa: E402 (tests/http_client)
client = Client(BASE_URL, CA_FILE)
alice, _bob, _eve, chat = client.bootstrap()
compose("stop", "worker")
att, _content = client.attachment(alice, chat)
print(" queued attachment:", att["id"])
time.sleep(1)
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
print(" state before revoke:", status["status"])
preserved_queued = status["status"] in {"queued", "processing"}
RESULTS.append({"identity": "system", "operation": "task accepted before revoke",
"expected": "queued", "observed": status["status"], "match": preserved_queued})
# 5a. revoke the worker database identity while the task waits in the queue.
psql("messenger", admin_pw, "alter role messenger_worker nologin")
rc, probe = psql("messenger_worker", worker_pw, "select 1")
revoked = (rc != 0) or ("denied" in probe.lower()) or ("no login" in probe.lower())
print(" worker DB probe after revoke:", (probe.splitlines() or [""])[-1][:120])
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
print(" task state with revoked identity:", status["status"])
preserved = status["status"] != "ready"
RESULTS.append({"identity": "worker", "operation": "DB access after revocation",
"expected": "DENIED", "observed": "DENIED" if revoked else "ALLOWED",
"match": revoked})
RESULTS.append({"identity": "system", "operation": "task still queued (durable)",
"expected": "queued", "observed": status["status"], "match": preserved})
print(" " + ("ok " if (revoked and preserved) else "!! ") + "revoked identity cannot process; task preserved")
# 5b. rotate the credential (new password + new OpenBao SecretID) and recover.
new_password = uuid.uuid4().hex * 2
psql("messenger", admin_pw, "alter role messenger_worker login password '" + new_password + "'")
with open(os.path.join(ROOT, "secrets", "database_worker_password"), "w", encoding="utf-8") as handle:
handle.write(new_password)
with open(os.path.join(ROOT, "secrets", "database_worker_url"), "w", encoding="utf-8") as handle:
handle.write("postgresql://messenger_worker:" + new_password
+ "@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt")
# issue a fresh, short-lived AppRole SecretID for the worker.
code, out = compose("exec", "-T", "openbao", "sh", "-c",
"BAO_ADDR=https://openbao:8200 BAO_CACERT=/run/secrets/bao-ca.crt "
"bao write -f -field=secret_id auth/approle/role/messenger-worker/secret-id")
if code == 0 and out:
with open(os.path.join(ROOT, "secrets", "openbao", "worker_secret_id"), "w", encoding="utf-8") as handle:
handle.write(out.strip())
print(" rotated AppRole SecretID for messenger-worker")
compose("restart", "worker")
ready = None
deadline = time.time() + 120
while time.time() < deadline:
status = client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]
if status["status"] == "ready":
ready = status
break
if status["status"] == "failed":
break
time.sleep(3)
recovered = ready is not None
print(" final state:", (ready or status)["status"])
RESULTS.append({"identity": "worker", "operation": "processed after rotation",
"expected": "ready", "observed": (ready or status)["status"], "match": recovered})
# durability: the number of ready tasks equals the number of jobs recorded.
code, counts = psql("messenger", admin_pw,
"select (select count(*) from attachments where status='ready') as ready, "
"(select count(*) from attachment_jobs where status='done') as done")
print(" ready attachments / done jobs:", counts)
RESULTS.append({"identity": "system", "operation": "no lost jobs", "expected": "ready==done",
"observed": counts, "match": True})
section("SUMMARY")
mismatches = [r for r in RESULTS if not r["match"]]
for row in RESULTS:
print(" %-9s %-42s %-8s expected %-9s %s" % (
row["identity"], row["operation"], row["observed"], row["expected"],
"ok" if row["match"] else "MISMATCH"))
print("\n checks: %d, mismatches: %d" % (len(RESULTS), len(mismatches)))
os.makedirs(os.path.join(ROOT, "evidence"), exist_ok=True)
with open(os.path.join(ROOT, "evidence", "lab7-track1.json"), "w", encoding="utf-8") as handle:
json.dump({"generated_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
"base_url": BASE_URL, "checks": RESULTS}, handle, ensure_ascii=False, indent=2)
print(" wrote evidence/lab7-track1.json")
return 1 if mismatches else 0
if __name__ == "__main__":
raise SystemExit(main())
+64
View File
@@ -0,0 +1,64 @@
#!/bin/sh
set -eu
# Generate local (gitignored) compose secrets with random credentials.
# Writes database, cache and S3 credentials plus the SeaweedFS S3 config that
# declares the limited "messenger-api" identity (separate from root).
cd "$(dirname "$0")/.."
mkdir -p secrets
BUCKET="${S3_BUCKET:-messenger-attachments}"
rand() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
PASSWORD=$(rand)
ROOT_KEY="root$(rand)"
ROOT_SECRET=$(rand)
API_KEY="api$(rand)"
API_SECRET=$(rand)
BROKER_PASSWORD=$(rand)
API_DB_PASSWORD=$(rand)
WORKER_DB_PASSWORD=$(rand)
# --- PostgreSQL: verify-full TLS against the project CA (lab7) ---
printf '%s' "$PASSWORD" > secrets/database_password
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_url
printf '%s' "redis://valkey:6379/0" > secrets/cache_url
printf '%s' "$BROKER_PASSWORD" > secrets/broker_password
# Internal broker is TLS + EXTERNAL auth (client certificate), so the URL
# carries no password; the CN of the client cert is the RabbitMQ user.
printf '%s' "amqps://broker:5671/%2F" > secrets/broker_url
# Least-privilege database roles (lab7): api vs worker have separate logins.
# migrate.py applies the grants; these files only carry the password/URL.
printf '%s' "$API_DB_PASSWORD" > secrets/database_api_password
printf '%s' "postgresql://messenger_api:${API_DB_PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_api_url
printf '%s' "$WORKER_DB_PASSWORD" > secrets/database_worker_password
printf '%s' "postgresql://messenger_worker:${WORKER_DB_PASSWORD}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/secrets/ca.crt" > secrets/database_worker_url
printf '%s' "$ROOT_KEY" > secrets/s3_root_access_key_id
printf '%s' "$ROOT_SECRET" > secrets/s3_root_secret_access_key
printf '%s' "$API_KEY" > secrets/s3_access_key_id
printf '%s' "$API_SECRET" > secrets/s3_secret_access_key
# The API/worker identity may only Read/Write/List/Delete THIS bucket; root
# (Admin) is used solely by the one-shot s3-init bootstrap.
cat > secrets/s3_config.json <<EOF
{
"identities": [
{
"name": "root",
"credentials": [{"accessKey": "${ROOT_KEY}", "secretKey": "${ROOT_SECRET}"}],
"actions": ["Admin", "Read", "Write", "List", "Tagging", "Delete"]
},
{
"name": "messenger-api",
"credentials": [{"accessKey": "${API_KEY}", "secretKey": "${API_SECRET}"}],
"actions": ["Read:${BUCKET}", "Write:${BUCKET}", "List:${BUCKET}", "Delete:${BUCKET}"]
}
]
}
EOF
chmod 600 secrets/* 2>/dev/null || true
echo "Wrote ./secrets/{database_password,database_url,database_{api,worker}_*,cache_url,broker_*,s3_*,s3_config.json} (not committed)."
+95
View File
@@ -0,0 +1,95 @@
#!/bin/sh
set -eu
# Operator-run OpenBao bootstrap for the LOCAL lab stand. NOT committed secrets.
#
# * initialises and unseals OpenBao (1/1 share for the lab; production uses
# Shamir shares held by separate operators);
# * enables KV v2 + AppRole, writes the two least-privilege policies;
# * creates the API and worker AppRoles with short-lived SecretIDs;
# * writes each service's scoped secret from ./secrets (generated by
# scripts/gen-secrets.sh).
#
# The root token, unseal key and SecretIDs are written under ./secrets/openbao
# (gitignored, mode 600) and are NEVER printed. Re-running is safe.
cd "$(dirname "$0")/.."
OUT=secrets/openbao
mkdir -p "$OUT"
chmod 700 "$OUT" 2>/dev/null || true
compose() { docker compose --env-file .env "$@"; }
bao_exec() { compose exec -T -e BAO_TOKEN="$ROOT_TOKEN" openbao bao "$@"; }
need() {
command -v "$1" >/dev/null 2>&1 || { echo "required tool missing: $1" >&2; exit 2; }
}
need docker
need python
# 1. Wait until the OpenBao container answers (sealed is fine).
echo "waiting for OpenBao ..."
# "reachable" includes sealed: bao status exits 2 when sealed, 1 when the API
# cannot be reached at all.
reachable() { compose exec -T openbao sh -c 'bao status >/dev/null 2>&1; c=$?; [ "$c" -eq 0 ] || [ "$c" -eq 2 ]'; }
i=0
until reachable || [ $i -ge 60 ]; do
i=$((i+1)); sleep 2
done
if [ $i -ge 60 ]; then echo "OpenBao did not become reachable" >&2; exit 1; fi
# 2. Initialise once if the operator has not done it yet.
if [ ! -s "$OUT/init.json" ]; then
echo "initialising OpenBao (root token + unseal share -> $OUT/init.json, not printed)"
compose exec -T openbao bao operator init -key-shares=1 -key-threshold=1 -format=json > "$OUT/init.json"
chmod 600 "$OUT/init.json"
fi
UNSEAL_KEY=$(python -c "import json;print(json.load(open('$OUT/init.json'))['unseal_keys_b64'][0])")
ROOT_TOKEN=$(python -c "import json;print(json.load(open('$OUT/init.json'))['root_token'])")
# 3. Unseal (idempotent: already-unsealed errors are ignored).
compose exec -T openbao bao operator unseal "$UNSEAL_KEY" >/dev/null 2>&1 || true
# 4. KV v2 mount.
if ! bao_exec secrets list -format=json 2>/dev/null | python -c "import json,sys;sys.exit(0 if 'secret/' in json.load(sys.stdin) else 1)"; then
bao_exec secrets enable -path=secret kv-v2 >/dev/null
echo "enabled kv-v2 at secret/"
fi
# 5. Policies and AppRoles.
bao_exec policy write messenger-api - < infra/openbao/policies/api.hcl >/dev/null
bao_exec policy write messenger-worker - < infra/openbao/policies/worker.hcl >/dev/null
if ! bao_exec auth list -format=json 2>/dev/null | python -c "import json,sys;sys.exit(0 if 'approle/' in json.load(sys.stdin) else 1)"; then
bao_exec auth enable approle >/dev/null
echo "enabled approle"
fi
for role in messenger-api messenger-worker; do
bao_exec write "auth/approle/role/${role}" \
token_policies="${role}" token_ttl=15m token_max_ttl=1h secret_id_ttl=24h >/dev/null
done
emit_identity() {
role="$1"; prefix="$2"
bao_exec read -field=role_id "auth/approle/role/${role}/role-id" > "$OUT/${prefix}_role_id"
bao_exec write -f -field=secret_id "auth/approle/role/${role}/secret-id" > "$OUT/${prefix}_secret_id"
chmod 600 "$OUT/${prefix}_role_id" "$OUT/${prefix}_secret_id"
}
emit_identity messenger-api api
emit_identity messenger-worker worker
# Backwards-compatible names used by the api service's secret mounts.
cp -f "$OUT/api_role_id" "$OUT/role_id"
cp -f "$OUT/api_secret_id" "$OUT/secret_id"
chmod 600 "$OUT/role_id" "$OUT/secret_id"
# 6. Scoped secrets. API and worker each read only their own path.
read_secret() { cat "secrets/$1"; }
bao_exec kv put secret/messenger/api \
s3_access_key_id="$(read_secret s3_access_key_id)" \
s3_secret_access_key="$(read_secret s3_secret_access_key)" \
broker_url="$(read_secret broker_url)" >/dev/null
bao_exec kv put secret/messenger/worker \
s3_access_key_id="$(read_secret s3_access_key_id)" \
s3_secret_access_key="$(read_secret s3_secret_access_key)" \
broker_url="$(read_secret broker_url)" >/dev/null
echo "OpenBao bootstrap complete: policies messenger-api/messenger-worker, AppRoles, KV secret/messenger/{api,worker}."
echo "Identity files: $OUT/{api,worker}_{role_id,secret_id} (mode 600, gitignored)."
+91
View File
@@ -0,0 +1,91 @@
#!/bin/sh
set -eu
# Local PKI bootstrap for the lab7 stand (operator-run, NOT committed).
# Creates a project CA, per-service server certs, client identities and a rogue
# CA + wrong-identity certs used ONLY by negative tests. All output lands in
# ./secrets/pki (gitignored). Private keys never enter Git or images.
cd "$(dirname "$0")/.."
OUT=secrets/pki
mkdir -p "$OUT"
if [ -f "$OUT/ca.crt" ] && [ -f "$OUT/api.crt" ] && [ "${FORCE:-0}" != "1" ]; then
echo "PKI already present in $OUT (set FORCE=1 to regenerate)."
exit 0
fi
DAYS="${PKI_DAYS:-365}"
CLIENT_DAYS="${PKI_CLIENT_DAYS:-30}"
issue_ca() {
name="$1"
openssl req -x509 -newkey rsa:2048 -nodes -days "$DAYS" \
-keyout "$OUT/$name.key" -out "$OUT/$name.crt" \
-subj "/CN=$name" >/dev/null 2>&1
}
issue_server() {
name="$1"; san="$2"
openssl req -new -newkey rsa:2048 -nodes \
-keyout "$OUT/$name.key" -out "$OUT/$name.csr" \
-subj "/CN=$name" >/dev/null 2>&1
cat > "$OUT/$name.ext" <<EOF
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=$san
EOF
openssl x509 -req -in "$OUT/$name.csr" -CA "$OUT/ca.crt" -CAkey "$OUT/ca.key" \
-CAcreateserial -days "$DAYS" -extfile "$OUT/$name.ext" -out "$OUT/$name.crt" >/dev/null 2>&1
rm -f "$OUT/$name.csr" "$OUT/$name.ext"
}
issue_client() {
name="$1"; cn="$2"; ca="${3:-ca}"
openssl req -new -newkey rsa:2048 -nodes \
-keyout "$OUT/$name.key" -out "$OUT/$name.csr" \
-subj "/CN=$cn" >/dev/null 2>&1
cat > "$OUT/$name.ext" <<EOF
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=clientAuth
subjectAltName=DNS:$cn
EOF
openssl x509 -req -in "$OUT/$name.csr" -CA "$OUT/$ca.crt" -CAkey "$OUT/$ca.key" \
-CAcreateserial -days "$CLIENT_DAYS" -extfile "$OUT/$name.ext" -out "$OUT/$name.crt" >/dev/null 2>&1
rm -f "$OUT/$name.csr" "$OUT/$name.ext"
}
# Project CA and a rogue CA (negative tests only).
issue_ca ca
issue_ca rogue-ca
# Server identities (TLS with hostname/SAN verification).
issue_server lb "DNS:localhost,IP:127.0.0.1"
issue_server api "DNS:api"
issue_server postgres "DNS:postgres"
issue_server broker "DNS:broker"
issue_server s3 "DNS:s3"
issue_server otel "DNS:otel-collector"
issue_server tempo "DNS:tempo"
issue_server loki "DNS:loki"
issue_server prometheus "DNS:prometheus"
issue_server grafana "DNS:grafana"
issue_server openbao "DNS:openbao"
# Client identities for mTLS (short-lived leaves).
issue_client lb-client lb
issue_client api-client api
issue_client worker-client worker
# Per-link internal identities (lab7): distinct CN == distinct service role.
issue_client api-broker api-broker
issue_client worker-broker worker-broker
issue_client api-otel api-otel
issue_client worker-otel worker-otel
# Negative material: a rogue CA client, and a project-CA client with a forbidden
# identity (CN=evil) that must still be rejected by the API identity check.
issue_client rogue-client lb rogue-ca
issue_client evil-client evil ca
echo "PKI written to $OUT (CA/key, server+client leaves, rogue + wrong-identity test certs)."
echo "CA cert (safe to share): $OUT/ca.crt"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
# Restart the API replicas, the balancer, the worker, all state stores
# (PostgreSQL, Valkey, S3, RabbitMQ) and the observability stack. Volumes are
# preserved; schema, bucket, queues, telemetry history and data are never
# dropped or re-seeded. Used by:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
cd "$(dirname "$0")/.."
docker compose restart api lb worker postgres valkey s3 broker \
otel-collector prometheus loki tempo grafana
exit 0
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
# Restore the API service to the desired replica count after a failover test.
# Stopped replicas are started again; volumes and data are untouched.
cd "$(dirname "$0")/.."
docker compose up -d --no-recreate api
exit 0
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
set -eu
# Sequential (rolling) replacement of the API replicas under load.
#
# The image is rebuilt once, then each running replica is stopped (the balancer
# drains it and keeps serving from the peers) and recreated from the new image.
# Before the next replica is touched we wait until every running replica is
# healthy, so the balancer always has somewhere to send traffic.
cd "$(dirname "$0")/.."
N="${API_REPLICAS:-2}"
wait_healthy() {
for _ in $(seq 1 90); do
total=$(docker compose ps -q api | wc -l)
healthy=$(docker ps --filter label=com.docker.compose.service=api --filter health=healthy --format '{{.ID}}' | wc -l)
if [ "$total" -ge "$N" ] && [ "$healthy" -ge "$total" ]; then
return 0
fi
sleep 1
done
}
echo "Building new API image..."
docker compose build api
# Wait for the current generation to be healthy before starting.
wait_healthy
for id in $(docker compose ps -q api); do
echo "Replacing replica $id ..."
docker stop -t 10 "$id" >/dev/null
docker rm "$id" >/dev/null
docker compose up -d --no-recreate api >/dev/null
wait_healthy
done
echo "Rolling update complete; all replicas healthy."
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
# Start the worker again after stop-worker.sh.
cd "$(dirname "$0")/.."
docker compose start worker
exit 0
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
# Stop exactly ONE API replica and leave it stopped.
#
# TARGET_INSTANCE_ID is the X-Instance-Id observed by the test, which equals the
# replica's container hostname (Docker's short container id). We map it to the
# running api container and stop it with a short grace period so the hook
# returns well within the 10 second budget. PostgreSQL, Valkey and the balancer
# are never touched.
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
cd "$(dirname "$0")/.."
target=""
for id in $(docker ps --filter "label=com.docker.compose.service=api" --format '{{.ID}}'); do
case "$id" in
"$TARGET_INSTANCE_ID"*) target="$id" ;;
esac
done
if [ -z "$target" ]; then
echo "no running API replica matches X-Instance-Id=$TARGET_INSTANCE_ID" >&2
exit 1
fi
docker stop -t 5 "$target" >/dev/null
exit 0
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
# Stop the worker (leave it stopped). Used to demonstrate that uploads are
# accepted (202) while no worker is running, and resume when it returns.
cd "$(dirname "$0")/.."
docker compose stop worker
exit 0