This commit is contained in:
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
postgres_query() {
|
||||
role=$1
|
||||
password_file=$2
|
||||
sql=$3
|
||||
docker compose exec -T postgres sh -ec \
|
||||
"export PGPASSWORD=\$(cat /run/secrets/$password_file); psql -v ON_ERROR_STOP=1 'host=postgres port=5432 dbname=messenger user=$role sslmode=verify-full sslrootcert=/run/secrets/tls_ca' -Atc '$sql'"
|
||||
}
|
||||
|
||||
[ "$(postgres_query messenger_api postgres_api_password 'SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()')" = t ] || {
|
||||
printf '%s\n' "PostgreSQL API connection is not TLS" >&2
|
||||
exit 1
|
||||
}
|
||||
postgres_query messenger_api postgres_api_password 'SELECT 1 FROM users LIMIT 1' >/dev/null
|
||||
if postgres_query messenger_worker postgres_worker_password 'SELECT 1 FROM users LIMIT 1' >/dev/null 2>&1; then
|
||||
printf '%s\n' "Worker can read the users table" >&2
|
||||
exit 1
|
||||
fi
|
||||
if postgres_query messenger_dispatcher postgres_dispatcher_password 'SELECT 1 FROM users LIMIT 1' >/dev/null 2>&1; then
|
||||
printf '%s\n' "Dispatcher can read the users table" >&2
|
||||
exit 1
|
||||
fi
|
||||
postgres_query messenger_dispatcher postgres_dispatcher_password \
|
||||
'SELECT status FROM attachments WHERE false FOR UPDATE' >/dev/null
|
||||
postgres_query messenger_dispatcher postgres_dispatcher_password \
|
||||
'UPDATE attachments SET updated_at = updated_at WHERE false' >/dev/null
|
||||
if postgres_query messenger_dispatcher postgres_dispatcher_password \
|
||||
'DELETE FROM attachments WHERE false' >/dev/null 2>&1; then
|
||||
printf '%s\n' "Dispatcher can delete attachment metadata" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: PostgreSQL verify-full and role GRANTs permit dispatcher recovery but deny unrelated/destructive access"
|
||||
|
||||
docker compose exec -T redis sh -ec '
|
||||
password=$(cat /run/secrets/redis_api_password)
|
||||
REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 ping | grep -qx PONG
|
||||
REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 set chat:v2:grade4 ok | grep -qx OK
|
||||
REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 del chat:v2:grade4 >/dev/null
|
||||
REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 acl list 2>&1 | grep -q NOPERM
|
||||
REDISCLI_AUTH="$password" redis-cli --user api -h 127.0.0.1 set outside:key denied 2>&1 | grep -q NOPERM
|
||||
'
|
||||
printf '%s\n' "PASS: Redis API ACL permits cache prefix only and denies ACL administration"
|
||||
|
||||
permissions=$(docker compose exec -T broker rabbitmqctl list_permissions -p / -q)
|
||||
printf '%s\n' "$permissions" | awk -F '\t' '$1 == "dispatcher" && $2 == "^attachment[.]process[.]v1$" && $3 == "^amq[.]default$" && $4 == "^$" {found=1} END {exit !found}'
|
||||
printf '%s\n' "$permissions" | awk -F '\t' '$1 == "worker" && $2 == "^attachment[.]process[.]v1$" && $3 == "^$" && $4 == "^attachment[.]process[.]v1$" {found=1} END {exit !found}'
|
||||
printf '%s\n' "PASS: RabbitMQ dispatcher/worker permissions match the single attachment queue"
|
||||
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-3 asynchronous durability scenario against the local Compose stack."""
|
||||
import hashlib
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
from image_probe import jpeg_size
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
command = ["docker", "compose"]
|
||||
if (ROOT / ".env").exists():
|
||||
command += ["--env-file", ".env"]
|
||||
command += list(args)
|
||||
subprocess.run(command, cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def sql(statement):
|
||||
command = ["docker", "compose"]
|
||||
if (ROOT / ".env").exists():
|
||||
command += ["--env-file", ".env"]
|
||||
command += ["exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atc", statement]
|
||||
return subprocess.run(command, cwd=ROOT, check=True, text=True,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 worker-stop and broker-restart durability scenario")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
linked = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(linked["attachment_ids"] == [attachment["id"]], "queued attachment was not linkable")
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob)
|
||||
|
||||
# Accepted staging, DB intent and durable queue must survive both API and
|
||||
# broker restart while no worker is available.
|
||||
compose("restart", "api", "broker")
|
||||
compose("up", "-d", "--wait", "api", "broker")
|
||||
compose("restart", "dispatcher")
|
||||
snapshot = client.call("GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment")["json"]
|
||||
check(snapshot["status"] in ("queued", "processing"), "accepted job disappeared or failed during restart")
|
||||
|
||||
compose("start", "worker")
|
||||
ready = client.wait_ready(bob, snapshot)
|
||||
downloaded = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
|
||||
check(downloaded["bytes"] == original, "original changed after asynchronous recovery")
|
||||
variants = [item for item in ready["variants"] if item["name"] == "thumbnail"]
|
||||
check(len(variants) == 1, "recovery did not produce exactly one thumbnail")
|
||||
variant = variants[0]
|
||||
thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=bob)
|
||||
check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == variant["sha256"], "thumbnail checksum mismatch")
|
||||
check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch")
|
||||
|
||||
# Force a redelivery of the same logical job. Deterministic keys and the
|
||||
# variant primary key must turn it into the same effect, not a duplicate.
|
||||
attachment_id = attachment["id"]
|
||||
sql("UPDATE attachment_jobs SET status='queued', published_at=NULL, error_code=NULL WHERE attachment_id='" + attachment_id + "'")
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
if sql("SELECT status FROM attachment_jobs WHERE attachment_id='" + attachment_id + "'") == "succeeded":
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise AssertionError("redelivered job did not finish")
|
||||
count = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + attachment_id + "' AND name='thumbnail'")
|
||||
check(count == "1", "redelivery created duplicate variants")
|
||||
after_duplicate = client.call("GET", "/api/v1/attachments/" + attachment_id, actor=bob, schema="Attachment")["json"]
|
||||
repeated = [item for item in after_duplicate["variants"] if item["name"] == "thumbnail"]
|
||||
check(len(repeated) == 1 and repeated[0]["sha256"] == variant["sha256"], "redelivery changed the logical result")
|
||||
# A transient storage failure is retried a bounded number of times and
|
||||
# ends with a stable, non-sensitive API error code.
|
||||
compose("stop", "worker")
|
||||
failed_attachment, _ = client.attachment(alice, chat)
|
||||
failed_id = failed_attachment["id"]
|
||||
client.message(alice, chat, "", attachments=[failed_id])
|
||||
sql("UPDATE attachments SET staging_key='staging/" + failed_id + "/missing' WHERE id='" + failed_id + "'")
|
||||
compose("start", "worker")
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
failed_snapshot = client.call("GET", "/api/v1/attachments/" + failed_id, actor=bob, schema="Attachment")["json"]
|
||||
if failed_snapshot["status"] == "failed":
|
||||
break
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
raise AssertionError("job did not reach failed after bounded retries")
|
||||
check(failed_snapshot["error_code"] == "retry_exhausted", "unsafe or unexpected final error code")
|
||||
retry_state = sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" + failed_id + "'")
|
||||
check(retry_state == "5:failed", "job did not stop at configured retry limit")
|
||||
client.call("GET", "/api/v1/attachments/" + failed_id + "/content", 409, actor=bob)
|
||||
|
||||
print("PASS: durable recovery, idempotent redelivery and bounded final failure verified.")
|
||||
finally:
|
||||
compose("up", "-d", "api", "broker", "dispatcher", "worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box attachment validation and exact contract-boundary checks."""
|
||||
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
from attachment_memory import cleanup, noisy_png, png_chunk
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def exact_size_png(sample, target_size=MAX_BYTES):
|
||||
check(sample.endswith(png_chunk(b"IEND", b"")), "sample PNG has no final IEND")
|
||||
prefix, iend = sample[:-12], sample[-12:]
|
||||
filler_size = target_size - len(prefix) - len(iend) - 12
|
||||
check(filler_size >= 0, "sample PNG is larger than boundary")
|
||||
result = prefix + png_chunk(b"ruSt", bytes(filler_size)) + iend
|
||||
check(len(result) == target_size, "exact-size PNG construction failed")
|
||||
return result
|
||||
|
||||
|
||||
def exact_pixel_png(width=10_000, height=4_000):
|
||||
compressor = zlib.compressobj(level=9)
|
||||
row = bytes(1 + width * 3)
|
||||
parts = []
|
||||
for _ in range(height):
|
||||
chunk = compressor.compress(row)
|
||||
if chunk:
|
||||
parts.append(chunk)
|
||||
parts.append(compressor.flush())
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
+ png_chunk(b"IDAT", b"".join(parts))
|
||||
+ png_chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def config_only_png(width, height):
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
)
|
||||
|
||||
|
||||
def upload(client, actor, chat, filename, payload, expected, schema=None):
|
||||
return client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename),
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=payload,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(os.environ.get("BASE_URL"), None, timeout=30)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
sample = open(os.path.join(os.path.dirname(__file__), "fixtures", "sample.png"), "rb").read()
|
||||
|
||||
try:
|
||||
boundary = exact_size_png(sample)
|
||||
response = upload(client, alice, chat, "exact-10mib.png", boundary, 202, "Attachment")
|
||||
attachment = client.wait_ready(alice, response["json"], wait_seconds=90)
|
||||
check(attachment["size_bytes"] == MAX_BYTES, "10 MiB boundary size changed")
|
||||
downloaded = client.call(
|
||||
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
|
||||
200, actor=alice,
|
||||
)["bytes"]
|
||||
check(downloaded == boundary, "10 MiB original changed after round trip")
|
||||
|
||||
pixels = exact_pixel_png()
|
||||
pixel_response = upload(client, alice, chat, "exact-40m-pixels.png", pixels, 202, "Attachment")
|
||||
client.wait_ready(alice, pixel_response["json"], wait_seconds=90)
|
||||
|
||||
upload(client, alice, chat, "over-pixels.png", config_only_png(20_000, 10_000), 413)
|
||||
upload(client, alice, chat, "truncated.png", sample[:33], 415)
|
||||
|
||||
corrupted = noisy_png()
|
||||
check(len(corrupted) > 70_000, "corruption fixture is too small")
|
||||
corrupted = bytearray(corrupted)
|
||||
corrupted[70_000] ^= 0xff
|
||||
upload(client, alice, chat, "corrupt-after-prefix.png", bytes(corrupted), 415)
|
||||
|
||||
upload(client, alice, chat, "%20%20%20", sample, 400)
|
||||
upload(client, alice, chat, "c1%C2%85.png", sample, 400)
|
||||
upload(client, alice, chat, "invalid-%FF.png", sample, 400)
|
||||
print("PASS: exact byte/pixel boundaries, complete decode, and filename validation are correct.")
|
||||
finally:
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent real PNG uploads with Docker API-container memory sampling."""
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def png_chunk(kind, payload):
|
||||
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload))
|
||||
|
||||
|
||||
def noisy_png(width=2048, height=1024):
|
||||
rows = bytearray()
|
||||
for _ in range(height):
|
||||
rows.append(0)
|
||||
rows.extend(os.urandom(width * 3))
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
|
||||
+ png_chunk(b"IDAT", zlib.compress(bytes(rows), level=0))
|
||||
+ png_chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def bytes_from_docker(value):
|
||||
number, unit = value.split()[0], value.split()[0][-3:]
|
||||
if unit in {"KiB", "MiB", "GiB"}:
|
||||
number = value.split()[0][:-3]
|
||||
else:
|
||||
unit = "B"
|
||||
factor = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}[unit]
|
||||
return int(float(number) * factor)
|
||||
|
||||
|
||||
def api_container_ids():
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "ps", "-q", "api"],
|
||||
check=True, text=True, capture_output=True,
|
||||
)
|
||||
return [line for line in result.stdout.splitlines() if line]
|
||||
|
||||
|
||||
def sample_memory(container_ids, stop_event, peaks):
|
||||
while not stop_event.is_set():
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}", *container_ids],
|
||||
check=False, text=True, capture_output=True,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
for line in result.stdout.splitlines():
|
||||
name, usage = line.split("\t", 1)
|
||||
current = bytes_from_docker(usage.split(" / ", 1)[0])
|
||||
peaks[name] = max(peaks.get(name, 0), current)
|
||||
stop_event.wait(0.05)
|
||||
|
||||
|
||||
def cleanup(chat_id, user_ids):
|
||||
object_script = (
|
||||
'root_user="$(cat /run/secrets/minio_root_user)"\n'
|
||||
'root_password="$(cat /run/secrets/minio_root_password)"\n'
|
||||
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
|
||||
'mc rm --recursive --force "local/${S3_BUCKET}/attachments/' + chat_id + '/" >/dev/null 2>&1 || true\n'
|
||||
)
|
||||
subprocess.run(
|
||||
["docker", "compose", "run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", object_script],
|
||||
check=True,
|
||||
)
|
||||
quoted_users = ",".join("'%s'" % value for value in user_ids)
|
||||
sql = f"""
|
||||
BEGIN;
|
||||
DELETE FROM messages WHERE chat_id = '{chat_id}';
|
||||
DELETE FROM attachments WHERE chat_id = '{chat_id}';
|
||||
DELETE FROM sessions WHERE user_id IN ({quoted_users});
|
||||
DELETE FROM chat_members WHERE chat_id = '{chat_id}';
|
||||
DELETE FROM chats WHERE id = '{chat_id}';
|
||||
DELETE FROM users WHERE id IN ({quoted_users});
|
||||
COMMIT;
|
||||
"""
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "postgres", "sh", "-ec",
|
||||
"export PGPASSWORD=$(cat /run/secrets/postgres_admin_password); "
|
||||
"exec psql -v ON_ERROR_STOP=1 -U lab7_admin -d messenger",
|
||||
],
|
||||
input=sql, text=True, check=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
concurrency = 12
|
||||
base_url = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
client = Client(base_url, None, timeout=30)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
payload = noisy_png()
|
||||
stop_event = threading.Event()
|
||||
peaks = {}
|
||||
sampler = threading.Thread(
|
||||
target=sample_memory,
|
||||
args=(api_container_ids(), stop_event, peaks),
|
||||
daemon=True,
|
||||
)
|
||||
sampler.start()
|
||||
started = time.monotonic()
|
||||
|
||||
def upload(index):
|
||||
response = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=memory-%02d.png" % (chat["id"], index),
|
||||
202,
|
||||
actor=alice,
|
||||
raw=payload,
|
||||
headers={"Content-Type": "image/png", "X-Load-Id": uuid.uuid4().hex},
|
||||
schema="Attachment",
|
||||
)
|
||||
return response["headers"]["X-Instance-Id"]
|
||||
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
instances = list(pool.map(upload, range(concurrency)))
|
||||
elapsed = time.monotonic() - started
|
||||
stop_event.set()
|
||||
sampler.join(timeout=10)
|
||||
check(len(set(instances)) >= 2, "uploads did not exercise both API replicas")
|
||||
check(len(peaks) >= 2, "memory was not sampled for both API replicas")
|
||||
summary = {
|
||||
"concurrency": concurrency,
|
||||
"payload_bytes": len(payload),
|
||||
"total_uploaded_bytes": len(payload) * concurrency,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_uploads": len(instances),
|
||||
"api_instances_observed": len(set(instances)),
|
||||
"peak_memory_bytes_by_container": peaks,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, sort_keys=True))
|
||||
print("PASS: concurrent attachment uploads remained within configured API memory limits.")
|
||||
finally:
|
||||
stop_event.set()
|
||||
sampler.join(timeout=10)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare client timings with Prometheus histogram quantiles and buckets."""
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=10):
|
||||
query = "?" + urllib.parse.urlencode(params, doseq=True) if params else ""
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def percentile(values, quantile):
|
||||
ordered = sorted(values)
|
||||
return ordered[max(0, math.ceil(quantile * len(ordered)) - 1)]
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
assert results, expression
|
||||
return float(results[0]["value"][1])
|
||||
|
||||
|
||||
def histogram_boundaries(base_url, metric_name):
|
||||
payload = json_get(
|
||||
base_url,
|
||||
"/api/v1/series",
|
||||
{"match[]": metric_name + "_bucket"},
|
||||
)
|
||||
assert payload["status"] == "success", payload
|
||||
return {series["le"] for series in payload["data"]}
|
||||
|
||||
|
||||
def comparable(observed, telemetry, lower=0.2, upper=5.0):
|
||||
ratio = telemetry / observed
|
||||
assert lower <= ratio <= upper, (observed, telemetry, ratio)
|
||||
return ratio
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--timeout", type=int, default=120)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=20)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
try:
|
||||
warmup_started = time.monotonic()
|
||||
warmup = client.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=calibration-warmup.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
client.wait_ready(alice, warmup, args.timeout)
|
||||
assert time.monotonic() > warmup_started
|
||||
# Histograms are cumulative. Ensure Prometheus has scraped a baseline
|
||||
# before the measured jobs, otherwise all jobs may land in the first
|
||||
# sample and increase() correctly has no earlier value to subtract.
|
||||
time.sleep(12)
|
||||
|
||||
attachment_started = {}
|
||||
|
||||
def upload(index):
|
||||
local = Client(args.base_url, timeout=20)
|
||||
started = time.monotonic()
|
||||
attachment = local.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=calibration-{index}.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
attachment_started[attachment["id"]] = started
|
||||
return attachment
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
|
||||
attachments = list(pool.map(upload, range(12)))
|
||||
ready_seconds = []
|
||||
for attachment in attachments:
|
||||
client.wait_ready(alice, attachment, args.timeout)
|
||||
ready_seconds.append(
|
||||
time.monotonic() - attachment_started[attachment["id"]]
|
||||
)
|
||||
|
||||
http_seconds = []
|
||||
for _ in range(400):
|
||||
response = client.call("GET", "/api/v1/chats", actor=alice)
|
||||
http_seconds.append(response["elapsed"])
|
||||
|
||||
time.sleep(12)
|
||||
http_metric = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"histogram_quantile(0.95, sum by (le) "
|
||||
"(increase(messenger_http_server_duration_seconds_bucket[2m])))",
|
||||
)
|
||||
worker_metric = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"histogram_quantile(0.95, sum by (le) "
|
||||
"(increase(messenger_worker_job_duration_seconds_bucket[2m])))",
|
||||
)
|
||||
ready_metric = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"histogram_quantile(0.95, sum by (le) "
|
||||
"(increase(messenger_attachment_ready_duration_seconds_bucket[2m])))",
|
||||
)
|
||||
client_http_p95 = percentile(http_seconds, 0.95)
|
||||
client_ready_p95 = percentile(ready_seconds, 0.95)
|
||||
|
||||
http_boundaries = histogram_boundaries(
|
||||
args.prometheus_url, "messenger_http_server_duration_seconds"
|
||||
)
|
||||
worker_boundaries = histogram_boundaries(
|
||||
args.prometheus_url, "messenger_worker_job_duration_seconds"
|
||||
)
|
||||
ready_boundaries = histogram_boundaries(
|
||||
args.prometheus_url, "messenger_attachment_ready_duration_seconds"
|
||||
)
|
||||
assert {"0.005", "0.01", "0.05", "0.1", "1.0"}.issubset(
|
||||
http_boundaries
|
||||
), http_boundaries
|
||||
assert {"0.05", "0.1", "0.25", "1.0", "10.0"}.issubset(
|
||||
worker_boundaries
|
||||
), worker_boundaries
|
||||
assert {"0.1", "0.25", "1.0", "10.0", "120.0"}.issubset(
|
||||
ready_boundaries
|
||||
), ready_boundaries
|
||||
assert 0 < http_metric < 1, http_metric
|
||||
assert 0 < worker_metric < 10, worker_metric
|
||||
assert 0 < ready_metric < 10, ready_metric
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"samples": {
|
||||
"http": len(http_seconds),
|
||||
"attachments": len(ready_seconds),
|
||||
},
|
||||
"http_p95_seconds": {
|
||||
"client": client_http_p95,
|
||||
"prometheus": http_metric,
|
||||
"ratio": comparable(client_http_p95, http_metric),
|
||||
},
|
||||
"ready_p95_seconds": {
|
||||
"client_polling_upper_bound": client_ready_p95,
|
||||
"prometheus": ready_metric,
|
||||
"ratio": comparable(
|
||||
client_ready_p95, ready_metric, lower=0.1, upper=5.0
|
||||
),
|
||||
},
|
||||
"worker_p95_seconds": worker_metric,
|
||||
"boundaries": {
|
||||
"http": sorted(http_boundaries),
|
||||
"worker": sorted(worker_boundaries),
|
||||
"ready": sorted(ready_boundaries),
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-4 fault injection and media pipeline verification."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
from image_probe import jpeg_size
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, capture=False, check_result=True):
|
||||
command = ["docker", "compose"]
|
||||
if (ROOT / ".env").exists():
|
||||
command += ["--env-file", ".env"]
|
||||
command += list(args)
|
||||
return subprocess.run(
|
||||
command,
|
||||
cwd=ROOT,
|
||||
check=check_result,
|
||||
text=capture,
|
||||
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE if capture else subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def sql(statement):
|
||||
result = compose(
|
||||
"exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-Atc", statement,
|
||||
capture=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def restart_count(service):
|
||||
container_id = compose("ps", "-q", service, capture=True).stdout.strip()
|
||||
check(bool(container_id), service + " container is not running")
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{.RestartCount}}", container_id],
|
||||
check=True,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
)
|
||||
return int(result.stdout.strip())
|
||||
|
||||
|
||||
def wait_until(predicate, timeout, description):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
last = predicate()
|
||||
if last:
|
||||
return last
|
||||
time.sleep(0.2)
|
||||
raise AssertionError(description + "; last=" + repr(last))
|
||||
|
||||
|
||||
def wait_failed(client, actor, attachment, timeout=30):
|
||||
current = attachment
|
||||
|
||||
def poll():
|
||||
nonlocal current
|
||||
current = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"],
|
||||
actor=actor,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
return current if current["status"] == "failed" else None
|
||||
|
||||
return wait_until(poll, timeout, "attachment did not become failed")
|
||||
|
||||
|
||||
def webp_size(data):
|
||||
check(
|
||||
len(data) >= 30 and data[:4] == b"RIFF" and data[8:12] == b"WEBP",
|
||||
"optimized output is not a WebP RIFF container",
|
||||
)
|
||||
chunk = data[12:16]
|
||||
payload = data[20:]
|
||||
if chunk == b"VP8 ":
|
||||
marker = payload.find(b"\x9d\x01\x2a")
|
||||
check(marker >= 0 and len(payload) >= marker + 7, "invalid VP8 frame")
|
||||
width, height = struct.unpack_from("<HH", payload, marker + 3)
|
||||
return width & 0x3FFF, height & 0x3FFF
|
||||
if chunk == b"VP8L":
|
||||
check(len(payload) >= 5 and payload[0] == 0x2F, "invalid VP8L frame")
|
||||
bits = int.from_bytes(payload[1:5], "little")
|
||||
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
|
||||
if chunk == b"VP8X":
|
||||
check(len(payload) >= 10, "invalid VP8X frame")
|
||||
width = int.from_bytes(payload[4:7], "little") + 1
|
||||
height = int.from_bytes(payload[7:10], "little") + 1
|
||||
return width, height
|
||||
raise AssertionError("unsupported WebP primary chunk " + repr(chunk))
|
||||
|
||||
|
||||
def verify_variants(client, actor, ready, original):
|
||||
check(ready["status"] == "ready", "attachment is not ready")
|
||||
by_name = {item["name"]: item for item in ready["variants"]}
|
||||
check(
|
||||
set(by_name) == {"thumbnail", "crop", "optimized"},
|
||||
"ready attachment must contain exactly three level-4 variants",
|
||||
)
|
||||
expected = {
|
||||
"thumbnail": ("image/jpeg", (256, 160)),
|
||||
"crop": ("image/jpeg", (128, 128)),
|
||||
"optimized": ("image/webp", (320, 200)),
|
||||
}
|
||||
for name, (content_type, dimensions) in expected.items():
|
||||
metadata = by_name[name]
|
||||
check(
|
||||
(metadata["width"], metadata["height"]) == dimensions,
|
||||
name + " metadata dimensions mismatch",
|
||||
)
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + ready["id"] + "/content?variant=" + name,
|
||||
actor=actor,
|
||||
)
|
||||
check(
|
||||
downloaded["headers"].get_content_type() == content_type,
|
||||
name + " content type mismatch",
|
||||
)
|
||||
check(
|
||||
len(downloaded["bytes"]) == metadata["size_bytes"] and
|
||||
hashlib.sha256(downloaded["bytes"]).hexdigest() == metadata["sha256"],
|
||||
name + " checksum/size mismatch",
|
||||
)
|
||||
actual = (
|
||||
webp_size(downloaded["bytes"])
|
||||
if name == "optimized"
|
||||
else jpeg_size(downloaded["bytes"])
|
||||
)
|
||||
check(actual == dimensions, name + " actual dimensions mismatch")
|
||||
downloaded_original = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + ready["id"] + "/content",
|
||||
actor=actor,
|
||||
)["bytes"]
|
||||
check(downloaded_original == original, "original bytes changed")
|
||||
check(
|
||||
sql("SELECT staging_key IS NULL FROM attachments WHERE id='" + ready["id"] + "'") == "t",
|
||||
"successful processing did not safely clear staging",
|
||||
)
|
||||
|
||||
|
||||
def jobctl(*args, expect_success=True):
|
||||
result = compose(
|
||||
"run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl",
|
||||
"dispatcher", *args,
|
||||
capture=True,
|
||||
check_result=False,
|
||||
)
|
||||
if expect_success:
|
||||
check(result.returncode == 0, "jobctl failed: " + result.stderr)
|
||||
else:
|
||||
check(result.returncode != 0, "unsafe jobctl command unexpectedly succeeded")
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 grade-4 fault injection scenario")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
# Media pipeline: crop and optimized are real files with deterministic
|
||||
# metadata; optimized is not enlarged beyond the 320x200 fixture.
|
||||
baseline, original = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(bob, baseline)
|
||||
verify_variants(client, bob, ready, original)
|
||||
|
||||
# Crash after DB commit but before publish. The outbox row has no marker,
|
||||
# dispatcher restarts, publishes it, and no operator creates a second job.
|
||||
compose("stop", "worker")
|
||||
wait_until(
|
||||
lambda: sql("SELECT count(*) FROM attachment_jobs WHERE status='queued' AND published_at IS NULL") == "0",
|
||||
10,
|
||||
"outbox was not initially drained",
|
||||
)
|
||||
dispatcher_restarts = restart_count("dispatcher")
|
||||
compose("exec", "-T", "dispatcher", "touch", "/tmp/mtusi-fault-before-publish")
|
||||
outbox_attachment, outbox_original = client.attachment(alice, chat)
|
||||
wait_until(
|
||||
lambda: restart_count("dispatcher") > dispatcher_restarts,
|
||||
15,
|
||||
"dispatcher fault marker did not crash the process",
|
||||
)
|
||||
check(
|
||||
sql("SELECT count(*) FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "1",
|
||||
"outbox recovery created another logical job",
|
||||
)
|
||||
wait_until(
|
||||
lambda: sql("SELECT published_at IS NOT NULL FROM attachment_jobs WHERE attachment_id='" + outbox_attachment["id"] + "'") == "t",
|
||||
15,
|
||||
"outbox row was not published after dispatcher restart",
|
||||
)
|
||||
compose("start", "worker")
|
||||
outbox_ready = client.wait_ready(bob, outbox_attachment)
|
||||
verify_variants(client, bob, outbox_ready, outbox_original)
|
||||
|
||||
# Crash after all object writes and before the result transaction/ack.
|
||||
# Expire the lease explicitly to make the deterministic test fast.
|
||||
worker_restarts = restart_count("worker")
|
||||
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects")
|
||||
crashed_attachment, crashed_original = client.attachment(alice, chat)
|
||||
wait_until(
|
||||
lambda: restart_count("worker") > worker_restarts,
|
||||
20,
|
||||
"worker fault marker did not crash the process",
|
||||
)
|
||||
sql(
|
||||
"UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' "
|
||||
"WHERE attachment_id='" + crashed_attachment["id"] + "' AND status='processing'"
|
||||
)
|
||||
crashed_ready = client.wait_ready(bob, crashed_attachment)
|
||||
verify_variants(client, bob, crashed_ready, crashed_original)
|
||||
check(
|
||||
int(sql(
|
||||
"SELECT count(*) FROM attachment_job_events e JOIN attachment_jobs j USING(job_id) "
|
||||
"WHERE j.attachment_id='" + crashed_attachment["id"] + "' AND e.event_type='lease_recovered'"
|
||||
)) >= 1,
|
||||
"expired processing lease was not audited as recovered",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
|
||||
crashed_attachment["id"] + "'"
|
||||
) == "3",
|
||||
"crash/redelivery multiplied variants",
|
||||
)
|
||||
|
||||
# A trusted metadata integrity mismatch is permanent and fails on attempt 1.
|
||||
compose("stop", "worker")
|
||||
permanent, _ = client.attachment(alice, chat)
|
||||
sql(
|
||||
"UPDATE attachments SET sha256=decode(repeat('00',32),'hex') WHERE id='" +
|
||||
permanent["id"] + "'"
|
||||
)
|
||||
compose("start", "worker")
|
||||
permanent_failed = wait_failed(client, bob, permanent)
|
||||
check(permanent_failed["error_code"] == "invalid_image", "permanent error code mismatch")
|
||||
check(
|
||||
sql(
|
||||
"SELECT attempt || ':' || status FROM attachment_jobs WHERE attachment_id='" +
|
||||
permanent["id"] + "'"
|
||||
) == "1:failed",
|
||||
"permanent failure was retried",
|
||||
)
|
||||
|
||||
# A transient missing staging object consumes the bounded retry budget,
|
||||
# appears in the failed registry, and can be replayed only after staging is
|
||||
# restored. Replaying the resulting succeeded job must be rejected.
|
||||
compose("stop", "worker")
|
||||
transient, transient_original = client.attachment(alice, chat)
|
||||
transient_id = transient["id"]
|
||||
job_id = sql(
|
||||
"SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" + transient_id + "'"
|
||||
)
|
||||
original_staging = sql(
|
||||
"SELECT staging_key FROM attachments WHERE id='" + transient_id + "'"
|
||||
)
|
||||
sql(
|
||||
"UPDATE attachments SET staging_key='staging/" + transient_id +
|
||||
"/missing' WHERE id='" + transient_id + "'"
|
||||
)
|
||||
compose("start", "worker")
|
||||
transient_failed = wait_failed(client, bob, transient, timeout=40)
|
||||
check(transient_failed["error_code"] == "retry_exhausted", "transient final code mismatch")
|
||||
check(
|
||||
sql("SELECT attempt || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'") ==
|
||||
"5:failed",
|
||||
"transient failure did not stop at max attempts",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_job_events WHERE job_id='" + job_id +
|
||||
"' AND event_type='retry_scheduled'"
|
||||
) == "4",
|
||||
"transient retry audit count mismatch",
|
||||
)
|
||||
failed_registry = json.loads(jobctl("list-failed").stdout)
|
||||
check(any(item["job_id"] == job_id for item in failed_registry), "failed registry omitted job")
|
||||
|
||||
sql(
|
||||
"UPDATE attachments SET staging_key='" + original_staging +
|
||||
"' WHERE id='" + transient_id + "'"
|
||||
)
|
||||
replay = json.loads(jobctl("replay", job_id).stdout)
|
||||
check(replay["status"] == "queued" and replay["replay_count"] == 1, "replay was not audited")
|
||||
replay_ready = client.wait_ready(bob, transient_failed)
|
||||
verify_variants(client, bob, replay_ready, transient_original)
|
||||
jobctl("replay", job_id, expect_success=False)
|
||||
check(
|
||||
sql(
|
||||
"SELECT replay_count || ':' || status FROM attachment_jobs WHERE job_id='" + job_id + "'"
|
||||
) == "1:succeeded",
|
||||
"rejected replay changed a successful job",
|
||||
)
|
||||
|
||||
print(
|
||||
"PASS: level-4 variants, outbox crash recovery, lease recovery, "
|
||||
"backoff/failed registry and safe replay verified."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-5 track 2: repeatable versioned-pipeline idempotency experiment."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
from level4_resilience import compose, restart_count, sql, verify_variants, wait_until
|
||||
|
||||
|
||||
def jobctl(service, *args, expect_success=True):
|
||||
result = compose(
|
||||
"run", "--rm", "--no-deps", "--entrypoint", "/app/jobctl",
|
||||
service, *args,
|
||||
capture=True,
|
||||
check_result=False,
|
||||
)
|
||||
if expect_success:
|
||||
check(result.returncode == 0, "jobctl failed: " + result.stderr)
|
||||
else:
|
||||
check(result.returncode != 0, "fault-injection command unexpectedly succeeded")
|
||||
return result
|
||||
|
||||
|
||||
def job_id(attachment_id, version):
|
||||
return sql(
|
||||
"SELECT job_id::text FROM attachment_jobs WHERE attachment_id='" +
|
||||
attachment_id + "' AND pipeline_version=" + str(version)
|
||||
)
|
||||
|
||||
|
||||
def variant_hashes(attachment_id, version):
|
||||
rows = sql(
|
||||
"SELECT name || ':' || encode(sha256,'hex') FROM attachment_variants "
|
||||
"WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" +
|
||||
str(version) + " ORDER BY name"
|
||||
)
|
||||
return tuple(rows.splitlines()) if rows else ()
|
||||
|
||||
|
||||
def wait_pipeline(client, actor, attachment, version, timeout=45):
|
||||
current = attachment
|
||||
|
||||
def poll():
|
||||
nonlocal current
|
||||
current = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"],
|
||||
actor=actor,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
state = sql(
|
||||
"SELECT status || ':' || pipeline_version FROM attachments WHERE id='" +
|
||||
attachment["id"] + "'"
|
||||
)
|
||||
return current if current["status"] == "ready" and len(current["variants"]) == 3 and state == "ready:" + str(version) else None
|
||||
|
||||
return wait_until(poll, timeout, "pipeline v" + str(version) + " did not become ready")
|
||||
|
||||
|
||||
def expire_processing_lease(attachment_id, version):
|
||||
sql(
|
||||
"UPDATE attachment_jobs SET lease_until=CURRENT_TIMESTAMP-INTERVAL '1 second' "
|
||||
"WHERE attachment_id='" + attachment_id + "' AND pipeline_version=" +
|
||||
str(version) + " AND status='processing'"
|
||||
)
|
||||
|
||||
|
||||
def wait_queue_drained():
|
||||
return wait_until(
|
||||
lambda: sql(
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')"
|
||||
) == "0",
|
||||
20,
|
||||
"logical job queue did not drain",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab5 grade-5 versioned pipeline idempotency")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
# H1: a crash before the first object-store side effect loses neither the
|
||||
# confirmed upload nor its logical job. The final original must not exist
|
||||
# yet, demonstrated by the rejected v2 upgrade source read.
|
||||
before_restarts = restart_count("worker")
|
||||
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-before-objects")
|
||||
before, before_original = client.attachment(alice, chat)
|
||||
wait_until(
|
||||
lambda: restart_count("worker") > before_restarts,
|
||||
20,
|
||||
"worker did not crash before object writes",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT status FROM attachment_jobs WHERE attachment_id='" +
|
||||
before["id"] + "'"
|
||||
) == "processing",
|
||||
"before-side-effect crash did not leave a leased job",
|
||||
)
|
||||
rejected = jobctl("worker", "upgrade", before["id"], "2", expect_success=False)
|
||||
check(
|
||||
"upgrade source original is unavailable" in rejected.stderr,
|
||||
"before-side-effect crash unexpectedly published the final original",
|
||||
)
|
||||
expire_processing_lease(before["id"], 1)
|
||||
before_ready = wait_pipeline(client, bob, before, 1)
|
||||
verify_variants(client, bob, before_ready, before_original)
|
||||
|
||||
# H2: after an object side effect but before result COMMIT/ack, a new
|
||||
# pipeline can supersede the in-flight v1 job. The copied original is the
|
||||
# durable handoff for v2; v1 cannot publish metadata after the upgrade.
|
||||
after_restarts = restart_count("worker")
|
||||
compose("exec", "-T", "worker", "touch", "/tmp/mtusi-fault-after-objects")
|
||||
raced, raced_original = client.attachment(alice, chat)
|
||||
wait_until(
|
||||
lambda: restart_count("worker") > after_restarts,
|
||||
20,
|
||||
"worker did not crash after object writes",
|
||||
)
|
||||
v1_raced_job = job_id(raced["id"], 1)
|
||||
check(
|
||||
sql(
|
||||
"SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'"
|
||||
) == "processing",
|
||||
"after-side-effect crash did not preserve the leased v1 job",
|
||||
)
|
||||
upgraded = json.loads(jobctl("worker", "upgrade", raced["id"], "2").stdout)
|
||||
check(
|
||||
upgraded["pipeline_version"] == 2 and upgraded["status"] == "queued",
|
||||
"v2 upgrade did not create a queued versioned job",
|
||||
)
|
||||
raced_ready = wait_pipeline(client, bob, raced, 2)
|
||||
verify_variants(client, bob, raced_ready, raced_original)
|
||||
check(
|
||||
sql(
|
||||
"SELECT status FROM attachment_jobs WHERE job_id='" + v1_raced_job + "'"
|
||||
) == "superseded",
|
||||
"in-flight v1 job was not superseded",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
|
||||
raced["id"] + "' AND pipeline_version=1"
|
||||
) == "0",
|
||||
"stale v1 metadata committed after v2 became active",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_job_events WHERE job_id='" +
|
||||
v1_raced_job + "' AND event_type='superseded'"
|
||||
) == "1",
|
||||
"superseded in-flight pipeline was not audited",
|
||||
)
|
||||
|
||||
# H3: a completed v1 can be reprocessed by the distinct v2 profile. Both
|
||||
# version histories remain, while API reads only active v2.
|
||||
versioned, versioned_original = client.attachment(alice, chat)
|
||||
v1_ready = wait_pipeline(client, bob, versioned, 1)
|
||||
verify_variants(client, bob, v1_ready, versioned_original)
|
||||
v1_job = job_id(versioned["id"], 1)
|
||||
v1_hashes = variant_hashes(versioned["id"], 1)
|
||||
check(len(v1_hashes) == 3, "v1 variant history is incomplete")
|
||||
|
||||
upgraded = json.loads(jobctl("worker", "upgrade", versioned["id"], "2").stdout)
|
||||
v2_job = upgraded["job_id"]
|
||||
v2_ready = wait_pipeline(client, bob, versioned, 2)
|
||||
verify_variants(client, bob, v2_ready, versioned_original)
|
||||
v2_hashes = variant_hashes(versioned["id"], 2)
|
||||
check(len(v2_hashes) == 3, "v2 variant history is incomplete")
|
||||
check(v1_hashes != v2_hashes, "v1 and v2 profiles produced identical variant hashes")
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
|
||||
versioned["id"] + "'"
|
||||
) == "6",
|
||||
"version upgrade did not preserve both variant histories",
|
||||
)
|
||||
|
||||
# Duplicate v2 deliveries followed by a reordered stale v1 delivery are
|
||||
# all no-ops. Record the active result before injection and prove the old
|
||||
# job cannot overwrite it.
|
||||
active_before = variant_hashes(versioned["id"], 2)
|
||||
original_sha_before = hashlib.sha256(
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + versioned["id"] + "/content",
|
||||
actor=bob,
|
||||
)["bytes"]
|
||||
).hexdigest()
|
||||
jobctl("dispatcher", "inject", v2_job)
|
||||
jobctl("dispatcher", "inject", v2_job)
|
||||
jobctl("dispatcher", "inject", v1_job)
|
||||
time.sleep(2)
|
||||
wait_queue_drained()
|
||||
active_after = variant_hashes(versioned["id"], 2)
|
||||
original_sha_after = hashlib.sha256(
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + versioned["id"] + "/content",
|
||||
actor=bob,
|
||||
)["bytes"]
|
||||
).hexdigest()
|
||||
check(active_after == active_before, "duplicate/reordered delivery changed active v2 hashes")
|
||||
check(original_sha_after == original_sha_before, "duplicate/reordered delivery changed original")
|
||||
check(
|
||||
sql(
|
||||
"SELECT status || ':' || pipeline_version FROM attachments WHERE id='" +
|
||||
versioned["id"] + "'"
|
||||
) == "ready:2",
|
||||
"stale v1 delivery rolled back the active pipeline",
|
||||
)
|
||||
check(
|
||||
sql(
|
||||
"SELECT count(*) FROM attachment_variants WHERE attachment_id='" +
|
||||
versioned["id"] + "'"
|
||||
) == "6",
|
||||
"duplicate/reordered messages multiplied variant rows",
|
||||
)
|
||||
check(
|
||||
sql("SELECT status FROM attachment_jobs WHERE job_id='" + v2_job + "'") == "succeeded",
|
||||
"duplicate v2 delivery changed successful job state",
|
||||
)
|
||||
|
||||
print(
|
||||
"PASS: pipeline v1/v2 history, crash before/after side effect, "
|
||||
"superseded in-flight work, duplicate and reordered stale deliveries verified."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
api_containers=$(docker compose ps -q api)
|
||||
if [ -z "$api_containers" ]; then
|
||||
printf "%s\n" "no running API containers found" >&2
|
||||
exit 1
|
||||
fi
|
||||
for container_id in $api_containers; do
|
||||
docker exec "$container_id" sh -ec '
|
||||
test ! -e /run/secrets/minio_root_user
|
||||
test ! -e /run/secrets/minio_root_password
|
||||
! env | grep -Eq "^MINIO_ROOT_(USER|PASSWORD)="
|
||||
'
|
||||
done
|
||||
|
||||
docker compose run --rm --entrypoint /bin/sh minio-bootstrap -ec '
|
||||
root_user="$(cat /run/secrets/minio_root_user)"
|
||||
root_password="$(cat /run/secrets/minio_root_password)"
|
||||
api_user="$(cat /run/secrets/s3_api_access_key)"
|
||||
api_password="$(cat /run/secrets/s3_api_secret_key)"
|
||||
bucket="messenger-attachments"
|
||||
probe_key="policy-probe/object.txt"
|
||||
|
||||
mc alias set admin http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null
|
||||
mc alias set limited http://minio:9000 "$api_user" "$api_password" --api S3v4 >/dev/null
|
||||
|
||||
cleanup() {
|
||||
mc rm --force "admin/${bucket}/staging/${probe_key}" >/dev/null 2>&1 || true
|
||||
mc rm --force "admin/${bucket}/attachments/${probe_key}" >/dev/null 2>&1 || true
|
||||
mc rb --force "admin/forbidden-policy-probe" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
printf private-probe | mc pipe "limited/${bucket}/staging/${probe_key}" >/dev/null
|
||||
if mc cat "limited/${bucket}/staging/${probe_key}" >/dev/null 2>&1; then
|
||||
printf "%s\n" "API credentials unexpectedly read the staging prefix" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf ready-object | mc pipe "admin/${bucket}/attachments/${probe_key}" >/dev/null
|
||||
mc cat "limited/${bucket}/attachments/${probe_key}" >/dev/null
|
||||
if printf overwrite | mc pipe "limited/${bucket}/attachments/${probe_key}" >/dev/null 2>&1; then
|
||||
printf "%s\n" "API credentials unexpectedly wrote the attachments prefix" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if mc mb "limited/forbidden-policy-probe" >/dev/null 2>&1; then
|
||||
printf "%s\n" "limited API credentials unexpectedly created another bucket" >&2
|
||||
exit 1
|
||||
fi
|
||||
if wget -qO- "http://minio:9000/${bucket}/attachments/${probe_key}" >/dev/null 2>&1; then
|
||||
printf "%s\n" "anonymous HTTP GET unexpectedly read a private object" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mc rm --force "admin/${bucket}/staging/${probe_key}" >/dev/null
|
||||
mc rm --force "admin/${bucket}/attachments/${probe_key}" >/dev/null
|
||||
trap - EXIT INT TERM
|
||||
printf "%s\n" "PASS: API has no MinIO root credentials; staging is write-only, attachments are read-only, bucket creation and anonymous GET are denied."
|
||||
'
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fire and resolve the two grade-4 Prometheus alerts."""
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=10):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout, interval=2):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(interval)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def alert(prometheus_url, alert_name, state=None):
|
||||
payload = json_get(prometheus_url, "/api/v1/alerts")
|
||||
assert payload["status"] == "success", payload
|
||||
for item in payload["data"]["alerts"]:
|
||||
if item.get("labels", {}).get("alertname") != alert_name:
|
||||
continue
|
||||
if state is None or item.get("state") == state:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def alert_resolved(prometheus_url, alert_name):
|
||||
return alert(prometheus_url, alert_name) is None
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
results = payload["data"]["result"]
|
||||
return float(results[0]["value"][1]) if results else 0.0
|
||||
|
||||
|
||||
def trace_id_for_request(loki_url, request_id):
|
||||
payload = json_get(
|
||||
loki_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="messenger-api"}} | request_id="{request_id}"',
|
||||
"start": str(time.time_ns() - 10 * 60 * 1_000_000_000),
|
||||
"end": str(time.time_ns()),
|
||||
"direction": "backward",
|
||||
"limit": "20",
|
||||
},
|
||||
)
|
||||
for result in payload["data"]["result"]:
|
||||
trace_id = result.get("stream", {}).get("trace_id")
|
||||
if trace_id and len(trace_id) == 32:
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def db_error_span(tempo_url, trace_id):
|
||||
payload = json_get(tempo_url, f"/api/traces/{trace_id}")
|
||||
for batch in payload.get("batches", []):
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for span in scope.get("spans", []):
|
||||
if (
|
||||
span.get("name", "").startswith("postgresql.")
|
||||
and span.get("status", {}).get("code") == "STATUS_CODE_ERROR"
|
||||
):
|
||||
return span.get("name")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--timeout", type=int, default=150)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=15)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
postgres_paused = False
|
||||
queue_result = {}
|
||||
database_result = {}
|
||||
try:
|
||||
compose("stop", "worker")
|
||||
queue_started = time.monotonic()
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
response = client.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=queue-alert.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
queue_alert = wait_for(
|
||||
"queue lag alert firing",
|
||||
lambda: alert(
|
||||
args.prometheus_url, "MessengerQueueLagGrowing", "firing"
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
queue_result = {
|
||||
"firing_after_seconds": round(time.monotonic() - queue_started, 3),
|
||||
"depth": prometheus_scalar(args.prometheus_url, "max(messenger_queue_depth)"),
|
||||
"oldest_age_seconds": prometheus_scalar(
|
||||
args.prometheus_url, "max(messenger_queue_oldest_job_age_seconds)"
|
||||
),
|
||||
"state": queue_alert["state"],
|
||||
}
|
||||
compose("up", "-d", "worker")
|
||||
client.wait_ready(alice, response["json"], args.timeout)
|
||||
queue_recovery_started = time.monotonic()
|
||||
wait_for(
|
||||
"queue lag alert resolved",
|
||||
lambda: alert_resolved(args.prometheus_url, "MessengerQueueLagGrowing"),
|
||||
args.timeout,
|
||||
)
|
||||
queue_result["resolved_after_seconds"] = round(
|
||||
time.monotonic() - queue_recovery_started, 3
|
||||
)
|
||||
|
||||
compose("pause", "postgres")
|
||||
postgres_paused = True
|
||||
database_started = time.monotonic()
|
||||
request_ids = [str(uuid.uuid4()) for _ in range(8)]
|
||||
|
||||
def failed_request(request_id):
|
||||
isolated_client = Client(args.base_url, timeout=15)
|
||||
isolated_client.call(
|
||||
"GET",
|
||||
"/api/v1/chats",
|
||||
503,
|
||||
actor=alice,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
return request_id
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(failed_request, request_ids))
|
||||
db_alert = wait_for(
|
||||
"API high error rate alert firing",
|
||||
lambda: alert(
|
||||
args.prometheus_url, "MessengerAPIHighErrorRate", "firing"
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
database_result = {
|
||||
"firing_after_seconds": round(time.monotonic() - database_started, 3),
|
||||
"failed_requests": len(request_ids),
|
||||
"state": db_alert["state"],
|
||||
}
|
||||
compose("unpause", "postgres")
|
||||
postgres_paused = False
|
||||
wait_for(
|
||||
"API readiness after PostgreSQL recovery",
|
||||
lambda: client.call("GET", "/health/ready", schema="Health"),
|
||||
30,
|
||||
)
|
||||
trace_id = wait_for(
|
||||
"database failure correlated log",
|
||||
lambda: trace_id_for_request(args.loki_url, request_ids[0]),
|
||||
args.timeout,
|
||||
)
|
||||
error_span = wait_for(
|
||||
"database error span",
|
||||
lambda: db_error_span(args.tempo_url, trace_id),
|
||||
args.timeout,
|
||||
)
|
||||
database_result.update({"trace_id": trace_id, "error_span": error_span})
|
||||
database_recovery_started = time.monotonic()
|
||||
wait_for(
|
||||
"API high error rate alert resolved",
|
||||
lambda: alert_resolved(args.prometheus_url, "MessengerAPIHighErrorRate"),
|
||||
args.timeout,
|
||||
)
|
||||
database_result["resolved_after_seconds"] = round(
|
||||
time.monotonic() - database_recovery_started, 3
|
||||
)
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"queue_lag": queue_result,
|
||||
"database_outage": database_result,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
if postgres_paused:
|
||||
compose("unpause", "postgres", check=False)
|
||||
compose("up", "-d", "worker", check=False)
|
||||
wait_for(
|
||||
"PostgreSQL before cleanup",
|
||||
lambda: compose("exec", "-T", "postgres", "pg_isready", "-U", "messenger").returncode == 0,
|
||||
30,
|
||||
)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the grade-3 telemetry path after the public smoke test."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
TRACE_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
FORBIDDEN_LABELS = {
|
||||
"user_id",
|
||||
"chat_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"request_id",
|
||||
"url",
|
||||
"filename",
|
||||
"message_text",
|
||||
}
|
||||
REQUIRED_RESOURCE_LABELS = {
|
||||
"service_name",
|
||||
"service_version",
|
||||
"service_instance_id",
|
||||
"deployment_environment_name",
|
||||
}
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=5):
|
||||
query = ""
|
||||
if params:
|
||||
query = "?" + urllib.parse.urlencode(params)
|
||||
request = urllib.request.Request(base_url.rstrip("/") + path + query)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(2)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
if not results:
|
||||
return 0.0
|
||||
return float(results[0]["value"][1])
|
||||
|
||||
|
||||
def trace_id_from_loki(base_url, service_name):
|
||||
now = time.time_ns()
|
||||
payload = json_get(
|
||||
base_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="{service_name}"}}',
|
||||
"start": str(now - 30 * 60 * 1_000_000_000),
|
||||
"end": str(now),
|
||||
"direction": "backward",
|
||||
"limit": "100",
|
||||
},
|
||||
)
|
||||
assert payload["status"] == "success", payload
|
||||
for stream in payload["data"]["result"]:
|
||||
trace_id = stream.get("stream", {}).get("trace_id", "")
|
||||
if TRACE_ID.fullmatch(trace_id):
|
||||
return trace_id
|
||||
for value in stream.get("values", []):
|
||||
for candidate in value[1:]:
|
||||
if isinstance(candidate, str) and TRACE_ID.fullmatch(candidate.strip()):
|
||||
return candidate.strip()
|
||||
if isinstance(candidate, dict):
|
||||
trace_id = candidate.get("trace_id", "")
|
||||
if TRACE_ID.fullmatch(trace_id):
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||||
parser.add_argument("--timeout", type=int, default=90)
|
||||
args = parser.parse_args()
|
||||
|
||||
wait_for(
|
||||
"Grafana health",
|
||||
lambda: json_get(args.grafana_url, "/api/health").get("database") == "ok",
|
||||
args.timeout,
|
||||
)
|
||||
dashboard = wait_for(
|
||||
"provisioned dashboard",
|
||||
lambda: json_get(
|
||||
args.grafana_url,
|
||||
"/api/dashboards/uid/mtusi-lab7-grade3",
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 — Grade 3"
|
||||
|
||||
api_series = wait_for(
|
||||
"API metrics",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"count(messenger_http_server_requests_total)",
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
job_series = wait_for(
|
||||
"worker metrics",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"count(messenger_worker_jobs_total)",
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
series_payload = json_get(
|
||||
args.prometheus_url,
|
||||
"/api/v1/series",
|
||||
{"match[]": "messenger_http_server_requests_total"},
|
||||
)
|
||||
assert series_payload["status"] == "success"
|
||||
assert series_payload["data"]
|
||||
for labels in series_payload["data"]:
|
||||
leaked = FORBIDDEN_LABELS.intersection(labels)
|
||||
assert not leaked, f"forbidden metric labels: {sorted(leaked)}"
|
||||
missing = REQUIRED_RESOURCE_LABELS.difference(labels)
|
||||
assert not missing, f"missing resource labels: {sorted(missing)}"
|
||||
assert labels["deployment_environment_name"] == "lab"
|
||||
|
||||
api_trace_id = wait_for(
|
||||
"correlated API log",
|
||||
lambda: trace_id_from_loki(args.loki_url, "messenger-api"),
|
||||
args.timeout,
|
||||
)
|
||||
worker_trace_id = wait_for(
|
||||
"correlated worker log",
|
||||
lambda: trace_id_from_loki(args.loki_url, "messenger-worker"),
|
||||
args.timeout,
|
||||
)
|
||||
api_trace = json_get(args.tempo_url, f"/api/traces/{api_trace_id}")
|
||||
worker_trace = json_get(args.tempo_url, f"/api/traces/{worker_trace_id}")
|
||||
assert api_trace.get("batches"), "API trace not found in Tempo"
|
||||
assert worker_trace.get("batches"), "worker trace not found in Tempo"
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"api_metric_series": int(api_series),
|
||||
"worker_metric_series": int(job_series),
|
||||
"api_trace_id": api_trace_id,
|
||||
"worker_trace_id": worker_trace_id,
|
||||
"dashboard_uid": "mtusi-lab7-grade3",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify grade-4 metrics and one end-to-end upload trace."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=10):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout, interval=2):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(interval)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
return float(results[0]["value"][1]) if results else 0.0
|
||||
|
||||
|
||||
def trace_id_for_request(loki_url, request_id):
|
||||
payload = json_get(
|
||||
loki_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="messenger-api"}} | request_id="{request_id}"',
|
||||
"start": str(time.time_ns() - 10 * 60 * 1_000_000_000),
|
||||
"end": str(time.time_ns()),
|
||||
"direction": "backward",
|
||||
"limit": "20",
|
||||
},
|
||||
)
|
||||
assert payload["status"] == "success", payload
|
||||
for result in payload["data"]["result"]:
|
||||
trace_id = result.get("stream", {}).get("trace_id")
|
||||
if trace_id and len(trace_id) == 32:
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def flatten_trace(payload):
|
||||
services = set()
|
||||
spans = []
|
||||
for batch in payload.get("batches", []):
|
||||
attributes = batch.get("resource", {}).get("attributes", [])
|
||||
service = next(
|
||||
(
|
||||
item.get("value", {}).get("stringValue")
|
||||
for item in attributes
|
||||
if item.get("key") == "service.name"
|
||||
),
|
||||
None,
|
||||
)
|
||||
if service:
|
||||
services.add(service)
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for span in scope.get("spans", []):
|
||||
spans.append((service, span))
|
||||
return services, spans
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||||
parser.add_argument("--timeout", type=int, default=120)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=20)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
request_id = str(uuid.uuid4())
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
try:
|
||||
response = client.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=grade4.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png", "X-Request-Id": request_id},
|
||||
schema="Attachment",
|
||||
)
|
||||
attachment = client.wait_ready(alice, response["json"], args.timeout)
|
||||
trace_id = wait_for(
|
||||
"upload log correlation",
|
||||
lambda: trace_id_for_request(args.loki_url, request_id),
|
||||
args.timeout,
|
||||
)
|
||||
trace = wait_for(
|
||||
"complete upload trace",
|
||||
lambda: json_get(args.tempo_url, f"/api/traces/{trace_id}"),
|
||||
args.timeout,
|
||||
)
|
||||
services, spans = flatten_trace(trace)
|
||||
required_services = {
|
||||
"messenger-api",
|
||||
"messenger-dispatcher",
|
||||
"messenger-worker",
|
||||
}
|
||||
assert required_services.issubset(services), (required_services, services)
|
||||
kinds = {span.get("kind") for _, span in spans}
|
||||
assert "SPAN_KIND_PRODUCER" in kinds, kinds
|
||||
assert "SPAN_KIND_CONSUMER" in kinds, kinds
|
||||
assert any(span.get("name", "").startswith("s3.") for _, span in spans)
|
||||
assert any(span.get("name", "").startswith("postgresql.") for _, span in spans)
|
||||
|
||||
metric_checks = {
|
||||
"queue_depth": "count(messenger_queue_depth)",
|
||||
"queue_oldest_age": "count(messenger_queue_oldest_job_age_seconds)",
|
||||
"db_pool": "count(messenger_db_pool_connections)",
|
||||
"worker_busy": "count(messenger_worker_busy)",
|
||||
"worker_capacity": "count(messenger_worker_capacity)",
|
||||
"process_cpu": "count(messenger_process_cpu_time_seconds_total)",
|
||||
"process_memory": "count(messenger_process_memory_bytes)",
|
||||
"ready_histogram": "sum(messenger_attachment_ready_duration_seconds_count)",
|
||||
}
|
||||
metrics = {
|
||||
name: wait_for(
|
||||
name,
|
||||
lambda expression=expression: prometheus_scalar(
|
||||
args.prometheus_url, expression
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
for name, expression in metric_checks.items()
|
||||
}
|
||||
dashboard = json_get(
|
||||
args.grafana_url,
|
||||
"/api/dashboards/uid/mtusi-lab7-grade4",
|
||||
)
|
||||
assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 - Grade 4"
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"attachment_id": attachment["id"],
|
||||
"trace_id": trace_id,
|
||||
"services": sorted(services),
|
||||
"span_kinds": sorted(kinds),
|
||||
"span_count": len(spans),
|
||||
"metrics": metrics,
|
||||
"dashboard_uid": "mtusi-lab7-grade4",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify two bounded failures from saved metrics, logs and traces."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
TRACE_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=5):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
request = urllib.request.Request(base_url.rstrip("/") + path + query)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(2)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
return float(results[0]["value"][1]) if results else 0.0
|
||||
|
||||
|
||||
def incident_from_loki(base_url, service_name, filter_expression, predicate):
|
||||
now = time.time_ns()
|
||||
payload = json_get(
|
||||
base_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="{service_name}"}} | {filter_expression}',
|
||||
"start": str(now - 2 * 60 * 60 * 1_000_000_000),
|
||||
"end": str(now),
|
||||
"direction": "backward",
|
||||
"limit": "1000",
|
||||
},
|
||||
)
|
||||
assert payload["status"] == "success", payload
|
||||
for result in payload["data"]["result"]:
|
||||
attributes = result.get("stream", {})
|
||||
trace_id = attributes.get("trace_id", "")
|
||||
if predicate(attributes) and TRACE_ID.fullmatch(trace_id):
|
||||
return {
|
||||
"event": attributes.get("event"),
|
||||
"route": attributes.get("route"),
|
||||
"status_code": attributes.get("status_code"),
|
||||
"outcome": attributes.get("outcome"),
|
||||
"attempt": attributes.get("attempt"),
|
||||
"trace_id": trace_id,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def trace_exists(base_url, trace_id):
|
||||
payload = json_get(base_url, f"/api/traces/{trace_id}")
|
||||
return bool(payload.get("batches"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--timeout", type=int, default=90)
|
||||
args = parser.parse_args()
|
||||
|
||||
api_errors = wait_for(
|
||||
"API 5xx metric",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
'sum(messenger_http_server_requests_total{status_class="5xx"})',
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
worker_failures = wait_for(
|
||||
"failed worker metric",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
'sum(messenger_worker_jobs_total{outcome="failed"})',
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
storage_incident = wait_for(
|
||||
"MinIO outage log",
|
||||
lambda: incident_from_loki(
|
||||
args.loki_url,
|
||||
"messenger-api",
|
||||
'status_code="503"',
|
||||
lambda attrs: (
|
||||
attrs.get("status_code") == "503"
|
||||
and attrs.get("route")
|
||||
== "POST /api/v1/chats/{chat_id}/attachments"
|
||||
),
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
worker_incident = wait_for(
|
||||
"failed worker log",
|
||||
lambda: incident_from_loki(
|
||||
args.loki_url,
|
||||
"messenger-worker",
|
||||
'event="attachment_job_failed"',
|
||||
lambda attrs: (
|
||||
attrs.get("event") == "attachment_job_failed"
|
||||
and attrs.get("outcome") == "failed"
|
||||
),
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
wait_for(
|
||||
"MinIO outage trace",
|
||||
lambda: trace_exists(args.tempo_url, storage_incident["trace_id"]),
|
||||
args.timeout,
|
||||
)
|
||||
wait_for(
|
||||
"failed worker trace",
|
||||
lambda: trace_exists(args.tempo_url, worker_incident["trace_id"]),
|
||||
args.timeout,
|
||||
)
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"api_5xx_total": int(api_errors),
|
||||
"worker_failed_total": int(worker_failures),
|
||||
"storage_incident": storage_incident,
|
||||
"worker_incident": worker_incident,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that a retried attachment job remains in the original upload trace."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client
|
||||
from observability_grade4 import flatten_trace, trace_id_for_request, wait_for
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def start_existing_container(service):
|
||||
container_id = compose("ps", "-aq", service).stdout.strip()
|
||||
if not container_id:
|
||||
raise AssertionError(f"missing container for {service}")
|
||||
subprocess.run(
|
||||
["docker", "start", container_id],
|
||||
check=True,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def sql_scalar(statement):
|
||||
result = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-At",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
statement,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def json_get(base_url, path, timeout=10):
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def attempt_from_span(span):
|
||||
for item in span.get("attributes", []):
|
||||
if item.get("key") == "job.attempt":
|
||||
return int(item.get("value", {}).get("intValue", 0))
|
||||
return None
|
||||
|
||||
|
||||
def complete_retry_trace(tempo_url, trace_id):
|
||||
payload = json_get(tempo_url, f"/api/traces/{trace_id}")
|
||||
services, spans = flatten_trace(payload)
|
||||
consumers = [
|
||||
span for _, span in spans if span.get("kind") == "SPAN_KIND_CONSUMER"
|
||||
]
|
||||
producers = [
|
||||
span for _, span in spans if span.get("kind") == "SPAN_KIND_PRODUCER"
|
||||
]
|
||||
attempts = sorted(
|
||||
attempt
|
||||
for attempt in (attempt_from_span(span) for span in consumers)
|
||||
if attempt is not None
|
||||
)
|
||||
if len(consumers) < 2 or len(producers) < 2 or len(set(attempts)) < 2:
|
||||
return None
|
||||
return services, spans, attempts, consumers, producers
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--timeout", type=int, default=120)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=20)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
minio_stopped = False
|
||||
worker_stopped = False
|
||||
request_id = str(uuid.uuid4())
|
||||
try:
|
||||
compose("stop", "worker")
|
||||
worker_stopped = True
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
upload = client.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=retry-trace.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png", "X-Request-Id": request_id},
|
||||
schema="Attachment",
|
||||
)
|
||||
compose("stop", "minio")
|
||||
minio_stopped = True
|
||||
start_existing_container("worker")
|
||||
worker_stopped = False
|
||||
attachment_id = upload["json"]["id"]
|
||||
first_retry = wait_for(
|
||||
"first failed attempt",
|
||||
lambda: int(
|
||||
sql_scalar(
|
||||
"SELECT attempt FROM attachment_jobs "
|
||||
f"WHERE attachment_id='{attachment_id}'"
|
||||
)
|
||||
or "0"
|
||||
)
|
||||
>= 2,
|
||||
30,
|
||||
interval=0.05,
|
||||
)
|
||||
assert first_retry
|
||||
compose("up", "-d", "--wait", "minio")
|
||||
minio_stopped = False
|
||||
ready = client.wait_ready(alice, upload["json"], args.timeout)
|
||||
trace_id = wait_for(
|
||||
"upload trace id",
|
||||
lambda: trace_id_for_request(args.loki_url, request_id),
|
||||
args.timeout,
|
||||
)
|
||||
services, spans, attempts, consumers, producers = wait_for(
|
||||
"retry spans in the upload trace",
|
||||
lambda: complete_retry_trace(args.tempo_url, trace_id),
|
||||
args.timeout,
|
||||
)
|
||||
assert any(span.get("name", "").startswith("s3.") for _, span in spans)
|
||||
assert any(
|
||||
span.get("name", "").startswith("postgresql.") for _, span in spans
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"attachment_status": ready["status"],
|
||||
"trace_id": trace_id,
|
||||
"services": sorted(services),
|
||||
"attempts": attempts,
|
||||
"consumer_spans": len(consumers),
|
||||
"producer_spans": len(producers),
|
||||
"span_count": len(spans),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
if minio_stopped:
|
||||
compose("up", "-d", "--wait", "minio", check=False)
|
||||
if worker_stopped:
|
||||
try:
|
||||
start_existing_container("worker")
|
||||
except (AssertionError, subprocess.CalledProcessError):
|
||||
compose("up", "-d", "worker", check=False)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Executable
+88
@@ -0,0 +1,88 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
state_file="$project_root/.operator/openbao-init.json"
|
||||
cd "$project_root"
|
||||
|
||||
[ -s "$state_file" ] || { printf '%s\n' "OpenBao operator state is required" >&2; exit 1; }
|
||||
root_token=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["root_token"])' "$state_file")
|
||||
unseal_key=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1], encoding="utf-8"))["unseal_keys_b64"][0])' "$state_file")
|
||||
sealed_by_test=false
|
||||
|
||||
bao_root() {
|
||||
docker compose exec -T -e BAO_TOKEN="$root_token" openbao bao "$@"
|
||||
}
|
||||
|
||||
recover() {
|
||||
if [ "$sealed_by_test" = true ]; then
|
||||
docker compose exec -T openbao bao operator unseal "$unseal_key" >/dev/null 2>&1 || true
|
||||
docker compose up -d --no-deps --no-build --force-recreate api >/dev/null 2>&1 || true
|
||||
fi
|
||||
}
|
||||
trap recover EXIT HUP INT TERM
|
||||
|
||||
bao_root write auth/approle/role/grade4-lifecycle \
|
||||
token_policies=default,api token_ttl=10s token_max_ttl=24s \
|
||||
secret_id_ttl=5s secret_id_num_uses=1 >/dev/null
|
||||
role_id=$(bao_root read -field=role_id auth/approle/role/grade4-lifecycle/role-id)
|
||||
secret_id=$(bao_root write -f -field=secret_id auth/approle/role/grade4-lifecycle/secret-id)
|
||||
token=$(docker compose exec -T openbao bao write -field=token auth/approle/login \
|
||||
role_id="$role_id" secret_id="$secret_id")
|
||||
|
||||
if docker compose exec -T openbao bao write -field=token auth/approle/login \
|
||||
role_id="$role_id" secret_id="$secret_id" >/dev/null 2>&1; then
|
||||
printf '%s\n' "One-use SecretID was accepted twice" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: used SecretID is revoked"
|
||||
|
||||
sleep 4
|
||||
docker compose exec -T -e BAO_TOKEN="$token" openbao bao token renew -increment=10s >/dev/null
|
||||
sleep 7
|
||||
docker compose exec -T -e BAO_TOKEN="$token" openbao bao kv get secret/api >/dev/null
|
||||
printf '%s\n' "PASS: renewable token works past its original TTL"
|
||||
|
||||
sleep 14
|
||||
if docker compose exec -T -e BAO_TOKEN="$token" openbao bao kv get secret/api >/dev/null 2>&1; then
|
||||
printf '%s\n' "Token exceeded its maximum TTL" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: token expires at bounded maximum TTL"
|
||||
|
||||
bao_root delete auth/approle/role/grade4-lifecycle >/dev/null
|
||||
|
||||
curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
https://127.0.0.1:8443/health/live >/dev/null
|
||||
bao_root operator seal >/dev/null
|
||||
sealed_by_test=true
|
||||
curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
https://127.0.0.1:8443/health/live >/dev/null
|
||||
printf '%s\n' "PASS: running API keeps only already-loaded credentials while OpenBao is sealed"
|
||||
|
||||
role_id_api=$(cat secrets/openbao/api_role_id.txt)
|
||||
secret_id_api=$(cat secrets/openbao/api_secret_id.txt)
|
||||
if docker compose exec -T openbao bao write -field=token auth/approle/login \
|
||||
role_id="$role_id_api" secret_id="$secret_id_api" >/dev/null 2>&1; then
|
||||
printf '%s\n' "AppRole login succeeded while OpenBao was sealed" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker compose up -d --no-deps --no-build --force-recreate api >/dev/null
|
||||
sleep 4
|
||||
if [ -n "$(docker compose ps --status running -q api)" ]; then
|
||||
printf '%s\n' "Fresh API process remained running without OpenBao bootstrap" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: fresh API fails closed while OpenBao is sealed"
|
||||
|
||||
docker compose exec -T openbao bao operator unseal "$unseal_key" >/dev/null
|
||||
sealed_by_test=false
|
||||
docker compose up -d --no-deps --no-build --force-recreate api >/dev/null
|
||||
attempts=0
|
||||
until curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
https://127.0.0.1:8443/health/live >/dev/null 2>&1; do
|
||||
attempts=$((attempts + 1))
|
||||
[ "$attempts" -lt 40 ] || { printf '%s\n' "API did not recover after unseal" >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
printf '%s\n' "PASS: operator unseal restores AppRole bootstrap without image rebuild"
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
role_id=$(cat secrets/openbao/api_role_id.txt)
|
||||
secret_id=$(cat secrets/openbao/api_secret_id.txt)
|
||||
token=$(docker compose exec -T openbao bao write -field=token auth/approle/login \
|
||||
role_id="$role_id" secret_id="$secret_id")
|
||||
|
||||
bao_api() {
|
||||
docker compose exec -T -e BAO_TOKEN="$token" openbao bao "$@"
|
||||
}
|
||||
|
||||
bao_api kv get secret/api >/dev/null
|
||||
printf '%s\n' "PASS: API AppRole reads its own path"
|
||||
|
||||
if bao_api kv get secret/worker >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: API AppRole read worker path" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: API AppRole cannot read worker path"
|
||||
|
||||
if bao_api policy list >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: API AppRole listed policies" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: API AppRole cannot administer policies"
|
||||
|
||||
if bao_api kv put secret/api probe=denied >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: API AppRole wrote its read-only path" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: API AppRole cannot write secrets"
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify that login throttling is shared by both API replicas."""
|
||||
import base64
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Grade 3 shared login rate-limit check")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
actor = client.user("ratelimit")
|
||||
username = actor["registration"]["username"]
|
||||
bad = base64.b64encode((username + ":definitely-wrong").encode()).decode()
|
||||
headers = {"Authorization": "Basic " + bad}
|
||||
|
||||
instances = set()
|
||||
for _ in range(5):
|
||||
result = client.call("POST", "/api/v1/auth/sessions", 401, headers=headers)
|
||||
instances.add(result["headers"]["X-Instance-Id"])
|
||||
|
||||
blocked = client.call("POST", "/api/v1/auth/sessions", 429, headers=headers)
|
||||
instances.add(blocked["headers"]["X-Instance-Id"])
|
||||
retry_after = blocked["headers"].get("Retry-After", "")
|
||||
check(retry_after.isdigit() and int(retry_after) > 0, "invalid Retry-After")
|
||||
check(blocked["json"]["error"]["code"] == "rate_limited", "wrong 429 error code")
|
||||
check(len(instances) >= 2, "requests did not traverse both API replicas")
|
||||
print("PASS: login limit is shared across replicas and returns 429 with Retry-After.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inject isolated DB/S3 inconsistencies and prove reconciler dry-run/apply/repeat."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
USER_ID = "90000000-0000-4000-8000-000000000001"
|
||||
CHAT_ID = "90000000-0000-4000-8000-000000000002"
|
||||
MISSING_ID = "90000000-0000-4000-8000-000000000011"
|
||||
PROTECTED_ID = "90000000-0000-4000-8000-000000000012"
|
||||
FAILED_ID = "90000000-0000-4000-8000-000000000013"
|
||||
MESSAGE_ID = "90000000-0000-4000-8000-000000000021"
|
||||
PREFIX = "attachments/reconcile-integration"
|
||||
ORPHAN_KEY = PREFIX + "/orphan"
|
||||
FAILED_KEY = PREFIX + "/failed"
|
||||
|
||||
|
||||
def run(command, *, input_text=None, capture=False):
|
||||
result = subprocess.run(
|
||||
command,
|
||||
input=input_text,
|
||||
text=True,
|
||||
check=False,
|
||||
capture_output=capture,
|
||||
env=os.environ.copy(),
|
||||
)
|
||||
if result.returncode != 0:
|
||||
details = result.stderr.strip() if capture else "see command output"
|
||||
raise RuntimeError("command failed: %s: %s" % (command[0], details))
|
||||
return result.stdout if capture else ""
|
||||
|
||||
|
||||
def compose(*arguments, capture=False, input_text=None):
|
||||
return run(
|
||||
["docker", "compose", *arguments],
|
||||
input_text=input_text,
|
||||
capture=capture,
|
||||
)
|
||||
|
||||
|
||||
def database(sql):
|
||||
compose(
|
||||
"exec", "-T", "postgres",
|
||||
"psql", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger",
|
||||
input_text=sql,
|
||||
)
|
||||
|
||||
|
||||
def object_command(script):
|
||||
compose(
|
||||
"run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap",
|
||||
"-ec", script,
|
||||
)
|
||||
|
||||
|
||||
def clean_objects():
|
||||
object_command(
|
||||
'root_user="$(cat /run/secrets/minio_root_user)"\n'
|
||||
'root_password="$(cat /run/secrets/minio_root_password)"\n'
|
||||
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
|
||||
'mc rm --force "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null 2>&1 || true\n'
|
||||
'mc rm --force "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null 2>&1 || true\n'
|
||||
)
|
||||
|
||||
|
||||
def clean_database():
|
||||
database(f"""
|
||||
BEGIN;
|
||||
DELETE FROM messages WHERE id = '{MESSAGE_ID}';
|
||||
DELETE FROM attachments WHERE id IN ('{MISSING_ID}', '{PROTECTED_ID}', '{FAILED_ID}');
|
||||
DELETE FROM chat_members WHERE chat_id = '{CHAT_ID}';
|
||||
DELETE FROM chats WHERE id = '{CHAT_ID}';
|
||||
DELETE FROM users WHERE id = '{USER_ID}';
|
||||
COMMIT;
|
||||
""")
|
||||
|
||||
|
||||
def inject_database():
|
||||
database(f"""
|
||||
BEGIN;
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ('{USER_ID}', 'reconcile_fixture', 'Reconcile Fixture', 'not-used');
|
||||
INSERT INTO chats (id, title) VALUES ('{CHAT_ID}', 'Reconcile Integration');
|
||||
INSERT INTO chat_members (chat_id, user_id, position) VALUES ('{CHAT_ID}', '{USER_ID}', 0);
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type,
|
||||
size_bytes, sha256, width, height, status, error_code, created_at, updated_at
|
||||
) VALUES
|
||||
('{MISSING_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/missing', 'missing.png', 'image/png',
|
||||
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'),
|
||||
('{PROTECTED_ID}', '{CHAT_ID}', '{USER_ID}', '{PREFIX}/protected-missing', 'protected.png', 'image/png',
|
||||
7, decode(repeat('00', 32), 'hex'), 1, 1, 'ready', NULL, now() - interval '2 hours', now() - interval '2 hours'),
|
||||
('{FAILED_ID}', '{CHAT_ID}', '{USER_ID}', '{FAILED_KEY}', 'failed.png', 'image/png',
|
||||
7, decode(repeat('00', 32), 'hex'), 1, 1, 'failed', 'fixture_failed', now() - interval '2 hours', now() - interval '2 hours');
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{USER_ID}', 'protected attachment reference');
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
VALUES ('{MESSAGE_ID}', '{CHAT_ID}', '{PROTECTED_ID}', 0);
|
||||
COMMIT;
|
||||
""")
|
||||
|
||||
|
||||
def inject_objects():
|
||||
object_command(
|
||||
'root_user="$(cat /run/secrets/minio_root_user)"\n'
|
||||
'root_password="$(cat /run/secrets/minio_root_password)"\n'
|
||||
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
|
||||
'printf orphan | mc pipe "local/${S3_BUCKET}/' + ORPHAN_KEY + '" >/dev/null\n'
|
||||
'printf failed | mc pipe "local/${S3_BUCKET}/' + FAILED_KEY + '" >/dev/null\n'
|
||||
)
|
||||
|
||||
|
||||
def reconcile(apply=False):
|
||||
command = [
|
||||
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
|
||||
"--grace-period", "1s",
|
||||
]
|
||||
if apply:
|
||||
command.append("--apply")
|
||||
output = compose(*command, capture=True)
|
||||
return json.loads(output)
|
||||
|
||||
|
||||
def kinds(result):
|
||||
return {issue["kind"] for issue in result["issues"]}
|
||||
|
||||
|
||||
def fixture_issues(result):
|
||||
return [issue for issue in result["issues"] if issue["object_key"].startswith(PREFIX)]
|
||||
|
||||
|
||||
def main():
|
||||
clean_objects()
|
||||
clean_database()
|
||||
try:
|
||||
inject_database()
|
||||
inject_objects()
|
||||
time.sleep(2)
|
||||
|
||||
dry_run = reconcile(False)
|
||||
expected = {
|
||||
"orphan_object", "missing_object", "referenced_missing_object", "failed_object",
|
||||
}
|
||||
if kinds({"issues": fixture_issues(dry_run)}) != expected:
|
||||
raise RuntimeError("dry-run did not detect all injected inconsistencies")
|
||||
if dry_run["deleted_objects"] or dry_run["failed_attachments"]:
|
||||
raise RuntimeError("dry-run performed mutations")
|
||||
|
||||
applied = reconcile(True)
|
||||
applied_fixture = fixture_issues(applied)
|
||||
applied_actions = {issue["kind"]: issue["action"] for issue in applied_fixture}
|
||||
expected_actions = {
|
||||
"orphan_object": "deleted",
|
||||
"failed_object": "deleted",
|
||||
"missing_object": "marked_failed",
|
||||
"referenced_missing_object": "manual_repair_required",
|
||||
}
|
||||
if applied_actions != expected_actions:
|
||||
raise RuntimeError("fixture apply actions differ: %s" % applied_actions)
|
||||
|
||||
repeated = reconcile(True)
|
||||
if repeated["deleted_objects"] or repeated["failed_attachments"]:
|
||||
raise RuntimeError("repeated apply was not mutation-idempotent")
|
||||
protected = [issue for issue in fixture_issues(repeated) if issue.get("protected")]
|
||||
if len(protected) != 1 or protected[0]["action"] != "manual_repair_required":
|
||||
raise RuntimeError("referenced missing attachment was not protected")
|
||||
|
||||
print(json.dumps({
|
||||
"dry_run_issues": len(dry_run["issues"]),
|
||||
"apply_fixture_deleted_objects": sum(
|
||||
issue["action"] == "deleted" for issue in applied_fixture
|
||||
),
|
||||
"apply_fixture_failed_attachments": sum(
|
||||
issue["action"] == "marked_failed" for issue in applied_fixture
|
||||
),
|
||||
"repeat_mutations": repeated["deleted_objects"] + repeated["failed_attachments"],
|
||||
"protected_manual_issues": len(protected),
|
||||
"scanned_attachments": applied["scanned_attachments"],
|
||||
"scanned_objects": applied["scanned_objects"],
|
||||
"duration_ms": applied["duration_ms"],
|
||||
}, ensure_ascii=False))
|
||||
print("PASS: real PostgreSQL/MinIO reconciliation is dry-run safe, idempotent and reference-aware.")
|
||||
finally:
|
||||
clean_objects()
|
||||
clean_database()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure real PostgreSQL/MinIO reconciler traversal at two inventory sizes."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
PREFIX = "attachments/reconcile-scale"
|
||||
|
||||
|
||||
def compose(*arguments, capture=False):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *arguments],
|
||||
check=False,
|
||||
text=True,
|
||||
capture_output=capture,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError(result.stderr.strip() if capture else "docker compose command failed")
|
||||
return result.stdout if capture else ""
|
||||
|
||||
|
||||
def object_command(script):
|
||||
compose("run", "--rm", "--entrypoint", "/bin/sh", "minio-bootstrap", "-ec", script)
|
||||
|
||||
|
||||
def clean():
|
||||
object_command(
|
||||
'root_user="$(cat /run/secrets/minio_root_user)"\n'
|
||||
'root_password="$(cat /run/secrets/minio_root_password)"\n'
|
||||
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
|
||||
'mc rm --recursive --force "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null 2>&1 || true\n'
|
||||
)
|
||||
|
||||
|
||||
def create(count):
|
||||
object_command(
|
||||
'root_user="$(cat /run/secrets/minio_root_user)"\n'
|
||||
'root_password="$(cat /run/secrets/minio_root_password)"\n'
|
||||
'mc alias set local http://minio:9000 "$root_user" "$root_password" --api S3v4 >/dev/null\n'
|
||||
'mkdir -p /tmp/reconcile-scale\n'
|
||||
'index=0\n'
|
||||
'while [ "$index" -lt ' + str(count) + ' ]; do\n'
|
||||
' printf x > "/tmp/reconcile-scale/object-${index}"\n'
|
||||
' index=$((index + 1))\n'
|
||||
'done\n'
|
||||
'mc cp --recursive /tmp/reconcile-scale/ "local/${S3_BUCKET}/' + PREFIX + '/" >/dev/null\n'
|
||||
)
|
||||
|
||||
|
||||
def dry_run():
|
||||
started = time.monotonic()
|
||||
output = compose(
|
||||
"run", "--rm", "--entrypoint", "/app/reconciler", "api",
|
||||
"--grace-period", "1s",
|
||||
capture=True,
|
||||
)
|
||||
elapsed = time.monotonic() - started
|
||||
result = json.loads(output)
|
||||
return {
|
||||
"scanned_attachments": result["scanned_attachments"],
|
||||
"scanned_objects": result["scanned_objects"],
|
||||
"issues": len(result["issues"]),
|
||||
"reconciler_duration_ms": result["duration_ms"],
|
||||
"container_start_and_run_ms": round(elapsed * 1000),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
measurements = []
|
||||
clean()
|
||||
try:
|
||||
for count in (100, 1000):
|
||||
clean()
|
||||
create(count)
|
||||
time.sleep(2)
|
||||
measurement = dry_run()
|
||||
measurement["injected_orphan_objects"] = count
|
||||
if measurement["issues"] < count:
|
||||
raise RuntimeError("reconciler did not observe all scale fixtures")
|
||||
measurements.append(measurement)
|
||||
print(json.dumps({"measurements": measurements}, ensure_ascii=False))
|
||||
print("PASS: reconciler traversal cost measured on real PostgreSQL/MinIO inventories.")
|
||||
finally:
|
||||
clean()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
curl_from_test() {
|
||||
docker compose --profile tests run --rm --no-deps --entrypoint curl security-test "$@"
|
||||
}
|
||||
|
||||
expect_tls_rejection() {
|
||||
name=$1
|
||||
shift
|
||||
if curl_from_test --silent --show-error --fail --cacert /run/secrets/ca.crt \
|
||||
"$@" https://api:8444/health/live >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: $name was accepted" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: $name rejected"
|
||||
}
|
||||
|
||||
expect_tls_rejection "missing client certificate"
|
||||
expect_tls_rejection "client certificate from foreign CA" \
|
||||
--cert /run/secrets/foreign-client.crt --key /run/secrets/foreign-client.key
|
||||
expect_tls_rejection "trusted certificate with forbidden identity" \
|
||||
--cert /run/secrets/wrong-client.crt --key /run/secrets/wrong-client.key
|
||||
|
||||
curl_from_test --silent --show-error --fail --cacert /run/secrets/ca.crt \
|
||||
--cert /run/secrets/lb-client.crt --key /run/secrets/lb-client.key \
|
||||
https://api:8444/health/live >/dev/null
|
||||
printf '%s\n' "PASS: allowed LB identity accepted"
|
||||
|
||||
# `docker compose port` in Compose v5 reports `invalid IP:0` even for an
|
||||
# unbound EXPOSE port, so verify the effective runtime bindings directly.
|
||||
for container_id in $(docker compose ps -q api); do
|
||||
bindings=$(docker inspect "$container_id" --format '{{json .NetworkSettings.Ports}}')
|
||||
case "$bindings" in
|
||||
*'"HostPort"'*)
|
||||
printf '%s\n' "FAIL: API port is published and bypasses ingress" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
printf '%s\n' "PASS: API replicas have no published bypass port"
|
||||
|
||||
prometheus_url="https://127.0.0.1:${PROMETHEUS_PORT:-19090}/-/ready"
|
||||
if curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
"$prometheus_url" >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: telemetry backend accepted a client without identity" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: telemetry backend rejects a missing client identity"
|
||||
|
||||
if curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
--cert secrets/pki/lb-client.crt --key secrets/pki/lb-client.key \
|
||||
"$prometheus_url" >/dev/null 2>&1; then
|
||||
printf '%s\n' "FAIL: telemetry backend accepted the LB identity" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: telemetry backend rejects a trusted but unauthorized identity"
|
||||
|
||||
curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
--cert secrets/pki/grafana-client.crt --key secrets/pki/grafana-client.key \
|
||||
"$prometheus_url" >/dev/null
|
||||
printf '%s\n' "PASS: telemetry backend accepts the scoped Grafana identity"
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
./tests/security_grade3.sh
|
||||
|
||||
run_test_shell() {
|
||||
docker compose --profile tests run --rm --no-deps --entrypoint sh security-test -ec "$1"
|
||||
}
|
||||
|
||||
expect_broker_denied() {
|
||||
name=$1
|
||||
cert_args=$2
|
||||
if run_test_shell "printf 'AMQP\\000\\000\\011\\001' | timeout 5 openssl s_client -quiet -verify_return_error -CAfile /run/secrets/ca.crt -servername dependency-gateway $cert_args -connect dependency-gateway:5671 2>/dev/null | grep -a -q AMQPLAIN"; then
|
||||
printf '%s\n' "FAIL: broker accepted $name" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: broker rejected $name"
|
||||
}
|
||||
|
||||
expect_broker_allowed() {
|
||||
name=$1
|
||||
cert=$2
|
||||
key=$3
|
||||
run_test_shell "printf 'AMQP\\000\\000\\011\\001' | timeout 5 openssl s_client -quiet -verify_return_error -CAfile /run/secrets/ca.crt -servername dependency-gateway -cert $cert -key $key -connect dependency-gateway:5671 2>/dev/null | grep -a -q AMQPLAIN"
|
||||
printf '%s\n' "PASS: broker accepted scoped $name identity"
|
||||
}
|
||||
|
||||
expect_broker_denied "missing client certificate" ""
|
||||
expect_broker_denied "same-CA intruder identity" "-cert /run/secrets/wrong-client.crt -key /run/secrets/wrong-client.key"
|
||||
expect_broker_denied "API identity without a broker edge" "-cert /run/secrets/api-client.crt -key /run/secrets/api-client.key"
|
||||
expect_broker_allowed worker /run/secrets/worker-client.crt /run/secrets/worker-client.key
|
||||
expect_broker_allowed dispatcher /run/secrets/dispatcher-client.crt /run/secrets/dispatcher-client.key
|
||||
|
||||
otel_status() {
|
||||
cert_args=$1
|
||||
run_test_shell "curl --silent --show-error --output /dev/null --write-out '%{http_code}' --cacert /run/secrets/ca.crt $cert_args -H 'Content-Type: application/x-protobuf' --data-binary '' https://telemetry-gateway:4318/v1/traces"
|
||||
}
|
||||
|
||||
if status=$(otel_status "" 2>/dev/null) && [ "$status" = 200 ]; then
|
||||
printf '%s\n' "FAIL: Collector accepted a missing client certificate" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: Collector rejected a missing client certificate"
|
||||
|
||||
status=$(otel_status "--cert /run/secrets/wrong-client.crt --key /run/secrets/wrong-client.key")
|
||||
if [ "$status" != 403 ]; then
|
||||
printf '%s\n' "FAIL: Collector wrong same-CA identity returned HTTP $status, expected 403" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: Collector rejected a same-CA intruder identity"
|
||||
|
||||
for identity in api worker dispatcher; do
|
||||
status=$(otel_status "--cert /run/secrets/$identity-client.crt --key /run/secrets/$identity-client.key")
|
||||
if [ "$status" != 200 ]; then
|
||||
printf '%s\n' "FAIL: Collector rejected $identity with HTTP $status" >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "PASS: Collector accepted scoped $identity identity"
|
||||
done
|
||||
|
||||
for service in api worker dispatcher; do
|
||||
for container_id in $(docker compose ps -q "$service"); do
|
||||
readonly=$(docker inspect -f '{{.HostConfig.ReadonlyRootfs}}' "$container_id")
|
||||
no_new_privileges=$(docker inspect -f '{{json .HostConfig.SecurityOpt}}' "$container_id")
|
||||
cap_drop=$(docker inspect -f '{{json .HostConfig.CapDrop}}' "$container_id")
|
||||
[ "$readonly" = true ] || { printf '%s\n' "FAIL: $service root filesystem is writable" >&2; exit 1; }
|
||||
printf '%s' "$no_new_privileges" | grep -q 'no-new-privileges' || { printf '%s\n' "FAIL: $service lacks no-new-privileges" >&2; exit 1; }
|
||||
printf '%s' "$cap_drop" | grep -q 'ALL' || { printf '%s\n' "FAIL: $service does not drop all capabilities" >&2; exit 1; }
|
||||
done
|
||||
done
|
||||
printf '%s\n' "PASS: application containers are read-only, no-new-privileges, cap-drop=ALL"
|
||||
|
||||
worker_id=$(docker compose ps -q worker)
|
||||
worker_memory=$(docker inspect -f '{{.HostConfig.Memory}}' "$worker_id")
|
||||
worker_nano_cpus=$(docker inspect -f '{{.HostConfig.NanoCpus}}' "$worker_id")
|
||||
worker_environment=$(docker inspect -f '{{json .Config.Env}}' "$worker_id")
|
||||
[ "$worker_memory" -eq 536870912 ] || { printf '%s\n' "FAIL: worker memory limit is $worker_memory" >&2; exit 1; }
|
||||
[ "$worker_nano_cpus" -eq 1000000000 ] || { printf '%s\n' "FAIL: worker CPU limit is $worker_nano_cpus" >&2; exit 1; }
|
||||
printf '%s' "$worker_environment" | grep -q 'WORKER_CONCURRENCY=1' || { printf '%s\n' "FAIL: worker concurrency is not 1" >&2; exit 1; }
|
||||
printf '%s' "$worker_environment" | grep -q 'JOB_TIMEOUT_SECONDS=60' || { printf '%s\n' "FAIL: worker timeout is not 60s" >&2; exit 1; }
|
||||
printf '%s' "$worker_environment" | grep -q 'GOMEMLIMIT=448MiB' || { printf '%s\n' "FAIL: worker Go memory limit is not 448MiB" >&2; exit 1; }
|
||||
printf '%s\n' "PASS: worker has 512 MiB RAM, 1 CPU, concurrency=1, GOMEMLIMIT=448MiB and 60s job timeout"
|
||||
@@ -0,0 +1,369 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-5 SLO experiment: short burst, sustained failure and ready latency."""
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client, Failure
|
||||
from observability_alerts import db_error_span
|
||||
from observability_grade4 import trace_id_for_request
|
||||
|
||||
|
||||
API_ALERTS = {"MessengerAPIBurnRateFast", "MessengerAPIBurnRateSlow"}
|
||||
READY_ALERTS = {
|
||||
"MessengerAttachmentReadyBurnRateFast",
|
||||
"MessengerAttachmentReadyBurnRateSlow",
|
||||
}
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def start_existing_container(service):
|
||||
container_id = compose("ps", "-aq", service).stdout.strip()
|
||||
if not container_id:
|
||||
raise AssertionError(f"missing container for {service}")
|
||||
subprocess.run(
|
||||
["docker", "start", container_id],
|
||||
check=True,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=10):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout, interval=1):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(interval)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def active_alerts(prometheus_url, names):
|
||||
payload = json_get(prometheus_url, "/api/v1/alerts")
|
||||
assert payload["status"] == "success", payload
|
||||
return {
|
||||
item["labels"]["alertname"]: item["state"]
|
||||
for item in payload["data"]["alerts"]
|
||||
if item.get("labels", {}).get("alertname") in names
|
||||
}
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
return float(results[0]["value"][1]) if results else 0.0
|
||||
|
||||
|
||||
def wait_firing(prometheus_url, names, started, timeout):
|
||||
detected = {}
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
states = active_alerts(prometheus_url, names)
|
||||
now = time.monotonic()
|
||||
for name in names:
|
||||
if states.get(name) == "firing" and name not in detected:
|
||||
detected[name] = round(now - started, 3)
|
||||
if set(detected) == set(names):
|
||||
return detected
|
||||
time.sleep(1)
|
||||
raise AssertionError(f"alerts did not fire: {detected}, current={states}")
|
||||
|
||||
|
||||
def observe_no_alert(prometheus_url, names, duration):
|
||||
observed = []
|
||||
max_short = 0.0
|
||||
max_long = 0.0
|
||||
deadline = time.monotonic() + duration
|
||||
while time.monotonic() < deadline:
|
||||
states = active_alerts(prometheus_url, names)
|
||||
if states:
|
||||
observed.append(states)
|
||||
max_short = max(
|
||||
max_short,
|
||||
prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_30s"),
|
||||
)
|
||||
max_long = max(
|
||||
max_long,
|
||||
prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_5m"),
|
||||
)
|
||||
time.sleep(1)
|
||||
assert not observed, f"false positive burn-rate alerts: {observed}"
|
||||
return {"pending_or_firing": 0, "max_30s_ratio": max_short, "max_5m_ratio": max_long}
|
||||
|
||||
|
||||
def parallel_successes(base_url, actor, count, concurrency=16):
|
||||
def request(_):
|
||||
local = Client(base_url, timeout=10)
|
||||
return local.call("GET", "/api/v1/chats", actor=actor)["status"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
statuses = list(pool.map(request, range(count)))
|
||||
assert set(statuses) == {200}, set(statuses)
|
||||
|
||||
|
||||
def parallel_failures(base_url, actor, count):
|
||||
request_ids = [str(uuid.uuid4()) for _ in range(count)]
|
||||
|
||||
def request(request_id):
|
||||
local = Client(base_url, timeout=15)
|
||||
local.call(
|
||||
"GET",
|
||||
"/api/v1/chats",
|
||||
503,
|
||||
actor=actor,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
return request_id
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool:
|
||||
return list(pool.map(request, request_ids))
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||||
parser.add_argument("--timeout", type=int, default=150)
|
||||
args = parser.parse_args()
|
||||
|
||||
dashboard = json_get(
|
||||
args.grafana_url, "/api/dashboards/uid/mtusi-lab7-grade5"
|
||||
)
|
||||
assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 - Grade 5 SLO"
|
||||
|
||||
client = Client(args.base_url, timeout=20)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
postgres_paused = False
|
||||
worker_stopped = False
|
||||
api_result = {}
|
||||
ready_result = {}
|
||||
try:
|
||||
parallel_successes(args.base_url, alice, 400)
|
||||
time.sleep(6)
|
||||
|
||||
compose("pause", "postgres")
|
||||
postgres_paused = True
|
||||
brief_request_ids = parallel_failures(args.base_url, alice, 4)
|
||||
compose("unpause", "postgres")
|
||||
postgres_paused = False
|
||||
parallel_successes(args.base_url, alice, 100)
|
||||
false_positive = observe_no_alert(args.prometheus_url, API_ALERTS, 25)
|
||||
|
||||
compose("pause", "postgres")
|
||||
postgres_paused = True
|
||||
incident_started = time.monotonic()
|
||||
stop_errors = threading.Event()
|
||||
failure_ids = []
|
||||
failure_lock = threading.Lock()
|
||||
|
||||
def error_stream(worker_id):
|
||||
local = Client(args.base_url, timeout=15)
|
||||
completed = 0
|
||||
while not stop_errors.is_set():
|
||||
request_id = str(uuid.uuid4())
|
||||
try:
|
||||
result = local.call(
|
||||
"GET",
|
||||
"/api/v1/chats",
|
||||
[200, 503],
|
||||
actor=alice,
|
||||
headers={"X-Request-Id": request_id},
|
||||
)
|
||||
if result["status"] == 503:
|
||||
with failure_lock:
|
||||
failure_ids.append(request_id)
|
||||
completed += 1
|
||||
except Failure:
|
||||
if not stop_errors.is_set():
|
||||
raise
|
||||
return completed
|
||||
|
||||
pool = concurrent.futures.ThreadPoolExecutor(max_workers=8)
|
||||
futures = [pool.submit(error_stream, index) for index in range(8)]
|
||||
try:
|
||||
detection = wait_firing(
|
||||
args.prometheus_url, API_ALERTS, incident_started, args.timeout
|
||||
)
|
||||
finally:
|
||||
if postgres_paused:
|
||||
compose("unpause", "postgres", check=False)
|
||||
postgres_paused = False
|
||||
stop_errors.set()
|
||||
failure_count = sum(future.result(timeout=30) for future in futures)
|
||||
pool.shutdown(wait=True)
|
||||
assert failure_ids, "sustained incident produced no 503"
|
||||
|
||||
recovery_started = time.monotonic()
|
||||
parallel_successes(args.base_url, alice, 900)
|
||||
wait_for(
|
||||
"API burn-rate alerts resolved",
|
||||
lambda: not active_alerts(args.prometheus_url, API_ALERTS),
|
||||
args.timeout,
|
||||
)
|
||||
trace_id = wait_for(
|
||||
"sustained DB incident log",
|
||||
lambda: trace_id_for_request(args.loki_url, failure_ids[0]),
|
||||
args.timeout,
|
||||
)
|
||||
error_span = wait_for(
|
||||
"sustained DB incident trace",
|
||||
lambda: db_error_span(args.tempo_url, trace_id),
|
||||
args.timeout,
|
||||
)
|
||||
api_result = {
|
||||
"brief_spike_failures": len(brief_request_ids),
|
||||
"false_positive": false_positive,
|
||||
"sustained_failures": failure_count,
|
||||
"detection_seconds": detection,
|
||||
"recovery_seconds": round(time.monotonic() - recovery_started, 3),
|
||||
"trace_id": trace_id,
|
||||
"root_cause_span": error_span,
|
||||
}
|
||||
print(
|
||||
json.dumps({"phase": "api_slo", **api_result}, ensure_ascii=False),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
wait_for(
|
||||
"clean attachment alert state before ready experiment",
|
||||
lambda: not active_alerts(args.prometheus_url, READY_ALERTS),
|
||||
args.timeout,
|
||||
)
|
||||
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
|
||||
def upload(index, prefix):
|
||||
local = Client(args.base_url, timeout=20)
|
||||
return local.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename={prefix}-{index}.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads:
|
||||
baseline_attachments = list(
|
||||
uploads.map(lambda index: upload(index, "slo-fast"), range(20))
|
||||
)
|
||||
for attachment in baseline_attachments:
|
||||
client.wait_ready(alice, attachment, args.timeout)
|
||||
|
||||
compose("stop", "worker")
|
||||
worker_stopped = True
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as uploads:
|
||||
slow_attachments = list(
|
||||
uploads.map(lambda index: upload(index, "slo-slow"), range(5))
|
||||
)
|
||||
time.sleep(12)
|
||||
start_existing_container("worker")
|
||||
worker_stopped = False
|
||||
for attachment in slow_attachments:
|
||||
client.wait_ready(alice, attachment, args.timeout)
|
||||
ready_incident_started = time.monotonic()
|
||||
ready_detection = wait_firing(
|
||||
args.prometheus_url, READY_ALERTS, ready_incident_started, args.timeout
|
||||
)
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads:
|
||||
recovery_attachments = list(
|
||||
uploads.map(lambda index: upload(index, "slo-recovery"), range(100))
|
||||
)
|
||||
for attachment in recovery_attachments:
|
||||
client.wait_ready(alice, attachment, args.timeout)
|
||||
ready_recovery_started = time.monotonic()
|
||||
wait_for(
|
||||
"attachment burn-rate alerts resolved",
|
||||
lambda: not active_alerts(args.prometheus_url, READY_ALERTS),
|
||||
args.timeout,
|
||||
)
|
||||
ready_result = {
|
||||
"baseline_fast": len(baseline_attachments),
|
||||
"slow_over_10s": len(slow_attachments),
|
||||
"recovery_fast": len(recovery_attachments),
|
||||
"detection_seconds": ready_detection,
|
||||
"recovery_seconds": round(
|
||||
time.monotonic() - ready_recovery_started, 3
|
||||
),
|
||||
"final_5m_slow_ratio": prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"messenger:sli_attachment_slow_ratio_5m",
|
||||
),
|
||||
}
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"api_slo": api_result,
|
||||
"attachment_ready_slo": ready_result,
|
||||
"dashboard_uid": "mtusi-lab7-grade5",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
if postgres_paused:
|
||||
compose("unpause", "postgres", check=False)
|
||||
if worker_stopped:
|
||||
try:
|
||||
start_existing_container("worker")
|
||||
except (AssertionError, subprocess.CalledProcessError):
|
||||
compose("up", "-d", "worker", check=False)
|
||||
wait_for(
|
||||
"PostgreSQL before cleanup",
|
||||
lambda: compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"pg_isready",
|
||||
"-U",
|
||||
"messenger",
|
||||
check=False,
|
||||
).returncode
|
||||
== 0,
|
||||
30,
|
||||
)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Executable
+71
@@ -0,0 +1,71 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
admin_psql() {
|
||||
docker compose exec -T postgres sh -ec '
|
||||
export PGPASSWORD=$(cat /run/secrets/postgres_admin_password)
|
||||
exec psql -v ON_ERROR_STOP=1 -U lab7_admin -d messenger -At
|
||||
'
|
||||
}
|
||||
|
||||
admin_psql <<'SQL'
|
||||
INSERT INTO login_rate_limits (identifier_hash, window_started_at, attempts)
|
||||
VALUES (decode(repeat('42', 32), 'hex'), CURRENT_TIMESTAMP - INTERVAL '1 day', 1)
|
||||
ON CONFLICT (identifier_hash) DO UPDATE
|
||||
SET window_started_at = EXCLUDED.window_started_at, attempts = EXCLUDED.attempts;
|
||||
|
||||
INSERT INTO login_rate_limits (identifier_hash, window_started_at, attempts)
|
||||
VALUES (decode(repeat('43', 32), 'hex'), CURRENT_TIMESTAMP, 4)
|
||||
ON CONFLICT (identifier_hash) DO UPDATE
|
||||
SET window_started_at = EXCLUDED.window_started_at, attempts = EXCLUDED.attempts;
|
||||
SQL
|
||||
|
||||
docker compose up -d --no-deps --no-build --force-recreate api ingress >/dev/null
|
||||
attempts=0
|
||||
until curl --silent --show-error --fail --cacert secrets/pki/ca.crt \
|
||||
https://127.0.0.1:${HTTPS_PORT:-8443}/health/live >/dev/null 2>&1; do
|
||||
attempts=$((attempts + 1))
|
||||
[ "$attempts" -lt 40 ] || {
|
||||
printf '%s\n' "API did not become ready for pruning test" >&2
|
||||
exit 1
|
||||
}
|
||||
sleep 1
|
||||
done
|
||||
|
||||
status=$(curl --silent --show-error --cacert secrets/pki/ca.crt \
|
||||
--user pruning-probe:wrong-password --output /dev/null --write-out '%{http_code}' \
|
||||
--request POST https://127.0.0.1:${HTTPS_PORT:-8443}/api/v1/auth/sessions)
|
||||
[ "$status" = 401 ] || {
|
||||
printf '%s\n' "Pruning probe returned HTTP $status, expected 401" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
remaining=$(admin_psql <<'SQL'
|
||||
SELECT count(*) FROM login_rate_limits
|
||||
WHERE identifier_hash = decode(repeat('42', 32), 'hex');
|
||||
SQL
|
||||
)
|
||||
[ "$remaining" = 0 ] || {
|
||||
printf '%s\n' "Expired login limiter row was not pruned" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
active_attempts=$(admin_psql <<'SQL'
|
||||
SELECT attempts FROM login_rate_limits
|
||||
WHERE identifier_hash = decode(repeat('43', 32), 'hex');
|
||||
SQL
|
||||
)
|
||||
[ "$active_attempts" = 4 ] || {
|
||||
printf '%s\n' "Active login limiter row was pruned or changed" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
admin_psql <<'SQL'
|
||||
DELETE FROM login_rate_limits
|
||||
WHERE identifier_hash = decode(repeat('43', 32), 'hex');
|
||||
SQL
|
||||
|
||||
printf '%s\n' "PASS: bounded pruning removes expired state and preserves active limiter windows"
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify contract responses and original durability during a real MinIO outage."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
|
||||
def compose(*arguments, **kwargs):
|
||||
return subprocess.run(["docker", "compose", *arguments], check=True, **kwargs)
|
||||
|
||||
|
||||
def wait_for_status(client, path, expected, timeout=20):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
return client.call("GET", path, expected=expected)
|
||||
except Failure as error:
|
||||
last_error = error
|
||||
time.sleep(0.25)
|
||||
raise Failure("%s did not reach %d: %s" % (path, expected, last_error))
|
||||
|
||||
|
||||
def restore_storage(client):
|
||||
compose("up", "-d", "--wait", "minio")
|
||||
compose("run", "--rm", "minio-bootstrap")
|
||||
wait_for_status(client, "/health/ready", 200, timeout=30)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(os.environ.get("BASE_URL"), None, timeout=15)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
storage_stopped = False
|
||||
|
||||
try:
|
||||
compose("stop", "minio")
|
||||
storage_stopped = True
|
||||
readiness = wait_for_status(client, "/health/ready", 503)
|
||||
check(readiness["elapsed"] < 5, "readiness exceeded its bounded timeout")
|
||||
|
||||
started = time.monotonic()
|
||||
failure = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=outage.png" % chat["id"],
|
||||
503,
|
||||
actor=alice,
|
||||
raw=original,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
elapsed = time.monotonic() - started
|
||||
check(failure["json"]["error"]["code"] == "unavailable", "wrong S3 outage error code")
|
||||
check(elapsed < 15, "upload outage response exceeded API/client timeout")
|
||||
|
||||
restore_storage(client)
|
||||
storage_stopped = False
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
downloaded = client.call(
|
||||
"GET", "/api/v1/attachments/%s/content" % attachment["id"],
|
||||
200, actor=alice,
|
||||
)["bytes"]
|
||||
check(downloaded == original, "existing original changed across MinIO outage")
|
||||
print(json.dumps({
|
||||
"readiness_503_seconds": round(readiness["elapsed"], 3),
|
||||
"upload_503_seconds": round(elapsed, 3),
|
||||
"original_bytes_verified": len(original),
|
||||
}, sort_keys=True))
|
||||
print("PASS: MinIO outage returns bounded JSON 503 and preserves existing originals.")
|
||||
finally:
|
||||
if storage_stopped:
|
||||
restore_storage(client)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prove bounded Collector degradation while Loki and Tempo are unavailable."""
|
||||
|
||||
import concurrent.futures
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
from attachment_memory import cleanup
|
||||
from client import Client
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=10):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout, interval=2):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = action()
|
||||
if value:
|
||||
return value
|
||||
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
||||
last_error = error
|
||||
time.sleep(interval)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
def prometheus_scalar(base_url, expression):
|
||||
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
||||
assert payload["status"] == "success", payload
|
||||
results = payload["data"]["result"]
|
||||
return float(results[0]["value"][1]) if results else 0.0
|
||||
|
||||
|
||||
def memory_bytes(value):
|
||||
match = re.match(r"([0-9.]+)([KMG]iB)", value.strip())
|
||||
if not match:
|
||||
raise ValueError(value)
|
||||
factors = {"KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}
|
||||
return int(float(match.group(1)) * factors[match.group(2)])
|
||||
|
||||
|
||||
def sample_collector_memory(stop_event, samples):
|
||||
container_id = compose("ps", "-q", "otel-collector").stdout.strip()
|
||||
while not stop_event.is_set():
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--format",
|
||||
"{{.MemUsage}}",
|
||||
container_id,
|
||||
],
|
||||
check=False,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
samples.append(memory_bytes(result.stdout.split("/", 1)[0]))
|
||||
stop_event.wait(0.5)
|
||||
|
||||
|
||||
def trace_id_for_request(loki_url, request_id):
|
||||
payload = json_get(
|
||||
loki_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="messenger-api"}} | request_id="{request_id}"',
|
||||
"start": str(time.time_ns() - 10 * 60 * 1_000_000_000),
|
||||
"end": str(time.time_ns()),
|
||||
"direction": "backward",
|
||||
"limit": "20",
|
||||
},
|
||||
)
|
||||
for result in payload["data"]["result"]:
|
||||
trace_id = result.get("stream", {}).get("trace_id")
|
||||
if trace_id and len(trace_id) == 32:
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
||||
parser.add_argument("--loki-url", default="http://localhost:3100")
|
||||
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
||||
parser.add_argument("--timeout", type=int, default=120)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=20)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
users = [alice["id"], bob["id"], eve["id"]]
|
||||
backends_stopped = False
|
||||
stop_event = threading.Event()
|
||||
memory_samples = []
|
||||
sampler = None
|
||||
try:
|
||||
failed_before = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_spans)",
|
||||
) + prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_log_records)",
|
||||
)
|
||||
accepted_before = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_receiver_accepted_spans) + sum(otelcol_receiver_accepted_log_records)",
|
||||
)
|
||||
compose("stop", "loki", "tempo")
|
||||
backends_stopped = True
|
||||
sampler = threading.Thread(
|
||||
target=sample_collector_memory,
|
||||
args=(stop_event, memory_samples),
|
||||
daemon=True,
|
||||
)
|
||||
sampler.start()
|
||||
|
||||
def request(index):
|
||||
local = Client(args.base_url, timeout=10)
|
||||
return local.call("GET", "/api/v1/chats", actor=alice)["status"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
statuses = list(pool.map(request, range(400)))
|
||||
assert set(statuses) == {200}, set(statuses)
|
||||
|
||||
content = open("tests/fixtures/sample.png", "rb").read()
|
||||
upload = client.call(
|
||||
"POST",
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=telemetry-outage.png',
|
||||
202,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
ready = client.wait_ready(alice, upload["json"], args.timeout)
|
||||
|
||||
wait_for(
|
||||
"expired Collector retry and counted telemetry loss",
|
||||
lambda: (
|
||||
prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_spans)",
|
||||
)
|
||||
+ prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_log_records)",
|
||||
)
|
||||
)
|
||||
> failed_before,
|
||||
75,
|
||||
)
|
||||
failed_after = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_spans)",
|
||||
) + prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_exporter_send_failed_log_records)",
|
||||
)
|
||||
accepted_after = prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
"sum(otelcol_receiver_accepted_spans) + sum(otelcol_receiver_accepted_log_records)",
|
||||
)
|
||||
queue_size = prometheus_scalar(
|
||||
args.prometheus_url, "max(otelcol_exporter_queue_size)"
|
||||
)
|
||||
queue_capacity = prometheus_scalar(
|
||||
args.prometheus_url, "max(otelcol_exporter_queue_capacity)"
|
||||
)
|
||||
assert queue_capacity == 256, queue_capacity
|
||||
assert queue_size <= queue_capacity, (queue_size, queue_capacity)
|
||||
assert accepted_after > accepted_before, (accepted_before, accepted_after)
|
||||
assert ready["status"] == "ready"
|
||||
|
||||
compose("up", "-d", "--wait", "loki", "tempo")
|
||||
backends_stopped = False
|
||||
recovery_request_id = str(uuid.uuid4())
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/chats",
|
||||
actor=alice,
|
||||
headers={"X-Request-Id": recovery_request_id},
|
||||
)
|
||||
recovery_trace_id = wait_for(
|
||||
"logs after telemetry backend recovery",
|
||||
lambda: trace_id_for_request(args.loki_url, recovery_request_id),
|
||||
args.timeout,
|
||||
)
|
||||
wait_for(
|
||||
"trace after telemetry backend recovery",
|
||||
lambda: json_get(args.tempo_url, f"/api/traces/{recovery_trace_id}").get(
|
||||
"batches"
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
stop_event.set()
|
||||
sampler.join(timeout=10)
|
||||
assert memory_samples, "Collector memory was not sampled"
|
||||
peak_memory = max(memory_samples)
|
||||
assert peak_memory < 256 * 1024**2, peak_memory
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"business_requests": len(statuses),
|
||||
"attachment_status": ready["status"],
|
||||
"accepted_signal_delta": int(accepted_after - accepted_before),
|
||||
"dropped_signal_delta": int(failed_after - failed_before),
|
||||
"collector_queue_size": queue_size,
|
||||
"collector_queue_capacity": queue_capacity,
|
||||
"collector_peak_memory_bytes": peak_memory,
|
||||
"collector_container_limit_bytes": 256 * 1024**2,
|
||||
"recovery_trace_id": recovery_trace_id,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
stop_event.set()
|
||||
if sampler:
|
||||
sampler.join(timeout=10)
|
||||
if backends_stopped:
|
||||
compose("up", "-d", "--wait", "loki", "tempo", check=False)
|
||||
cleanup(chat["id"], users)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$project_root"
|
||||
|
||||
temp_file=$(mktemp "${TMPDIR:-/tmp}/mtusi-lab7-telemetry.XXXXXX")
|
||||
case "$temp_file" in
|
||||
"${TMPDIR:-/tmp}"/mtusi-lab7-telemetry.*) ;;
|
||||
*) printf '%s\n' "Unexpected telemetry temporary file" >&2; exit 1 ;;
|
||||
esac
|
||||
trap 'rm -f "$temp_file"' EXIT HUP INT TERM
|
||||
|
||||
sentinel_user="leak_probe_user"
|
||||
sentinel_password="Telemetry-must-not-contain-this-7d91"
|
||||
credentials=$(printf '%s' "$sentinel_user:$sentinel_password" | base64 | tr -d '\n')
|
||||
status=$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' \
|
||||
--cacert secrets/pki/ca.crt -H "Authorization: Basic $credentials" \
|
||||
-X POST https://127.0.0.1:8443/api/v1/auth/sessions)
|
||||
[ "$status" = 401 ] || { printf '%s\n' "Login probe returned HTTP $status" >&2; exit 1; }
|
||||
|
||||
sleep 6
|
||||
end_ns=$(date +%s%N)
|
||||
start_ns=$((end_ns - 900000000000))
|
||||
curl --silent --show-error --fail --get \
|
||||
--cacert secrets/pki/ca.crt \
|
||||
--cert secrets/pki/grafana-client.crt --key secrets/pki/grafana-client.key \
|
||||
--data-urlencode 'query={service_name=~"messenger-.+"}' \
|
||||
--data-urlencode "start=$start_ns" --data-urlencode "end=$end_ns" \
|
||||
--data-urlencode 'limit=5000' \
|
||||
https://127.0.0.1:13100/loki/api/v1/query_range > "$temp_file"
|
||||
|
||||
grep -q '"status":"success"' "$temp_file" || {
|
||||
printf '%s\n' "Loki query did not succeed" >&2
|
||||
exit 1
|
||||
}
|
||||
if grep -Fq "$sentinel_password" "$temp_file" || grep -Fq "$credentials" "$temp_file"; then
|
||||
printf '%s\n' "Telemetry contains the login credential probe" >&2
|
||||
exit 1
|
||||
fi
|
||||
if grep -Eiq 'authorization|bearer[[:space:]]|basic[[:space:]]|password_hash|client_token|secret_id' "$temp_file"; then
|
||||
printf '%s\n' "Telemetry contains a forbidden credential field" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for secret_file in secrets/*.txt secrets/openbao/*.txt; do
|
||||
[ -f "$secret_file" ] || continue
|
||||
secret_value=$(cat "$secret_file")
|
||||
[ -n "$secret_value" ] || continue
|
||||
if grep -Fq "$secret_value" "$temp_file"; then
|
||||
printf '%s\n' "Telemetry contains a value from an ignored secret file" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' "PASS: Loki has structured events but no tested credentials, secret values or request bodies"
|
||||
Reference in New Issue
Block a user