forked from mtusi2026/mtusi2026lab7
Implement lab7 security and compromised worker recovery evidence
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from tls_matrix import context
|
||||
|
||||
|
||||
def request(role, path, body=None, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = urllib.request.Request(
|
||||
"https://openbao:8200/v1/" + path,
|
||||
None if body is None else json.dumps(body).encode(),
|
||||
headers,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=context(role), timeout=3) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def denied(role, path, token, body=None):
|
||||
try:
|
||||
request(role, path, body, token)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403
|
||||
return
|
||||
raise AssertionError("Scoped policy did not deny operation")
|
||||
|
||||
|
||||
def main():
|
||||
results = {}
|
||||
old = None
|
||||
started = time.monotonic()
|
||||
for role in ("api", "worker", "dispatcher"):
|
||||
auth = request(role, "auth/cert/login", {"name": role})["auth"]
|
||||
token = auth["client_token"]
|
||||
assert 0 < auth["lease_duration"] <= 60
|
||||
assert auth["policies"] == [role]
|
||||
data = request(role, "secret/data/" + role, token=token)["data"]["data"]
|
||||
assert data["postgres_user"] == role
|
||||
for other in {"api", "worker", "dispatcher"} - {role}:
|
||||
denied(role, "secret/data/" + other, token)
|
||||
denied(
|
||||
role, "sys/policies/acl/escape", token, {"policy": 'path "*" {capabilities=["sudo"]}'}
|
||||
)
|
||||
denied(role, "secret/data/" + role, token, {"data": {"escape": "denied"}})
|
||||
results[role] = dict(
|
||||
ttl=auth["lease_duration"],
|
||||
only_own_path=True,
|
||||
other_secrets_denied=True,
|
||||
policy_write_denied=True,
|
||||
secret_write_denied=True,
|
||||
)
|
||||
if old is None:
|
||||
old = (role, token)
|
||||
else:
|
||||
request(role, "auth/token/revoke-self", {}, token)
|
||||
time.sleep(max(0, 63 - (time.monotonic() - started)))
|
||||
denied(old[0], "secret/data/" + old[0], old[1])
|
||||
print(json.dumps(dict(status="PASS", policies=results, expired_token_rejected=True), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,63 @@
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from client import check, run
|
||||
from pipeline_support import broker, compose, wait_for
|
||||
|
||||
|
||||
def snapshot():
|
||||
groups = [
|
||||
dict(zip(row[::2], row[1::2]))
|
||||
for row in json.loads(broker("XINFO", "GROUPS", "attachment-jobs"))
|
||||
]
|
||||
return {
|
||||
"entries": json.loads(broker("XRANGE", "attachment-jobs", "-", "+")),
|
||||
"groups": [
|
||||
{key: value for key, value in group.items() if key != "consumers"} for group in groups
|
||||
],
|
||||
"consumer_counts": [group["consumers"] for group in groups],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
compose("stop", "worker", "dispatcher")
|
||||
try:
|
||||
before = snapshot()
|
||||
started = time.monotonic()
|
||||
compose("restart", "broker")
|
||||
wait_for(lambda: broker("PING") == "PONG")
|
||||
after = snapshot()
|
||||
check(before["entries"] == after["entries"], "AOF restart changed stream entries")
|
||||
check(
|
||||
before["groups"] == after["groups"],
|
||||
"AOF restart changed delivery cursor or pending state",
|
||||
)
|
||||
unauthenticated = compose("exec", "-T", "broker", "redis-cli", "-p", "16379", "PING")
|
||||
check("NOAUTH" in unauthenticated, "Unauthenticated broker access accepted")
|
||||
default = json.loads(broker("ACL", "GETUSER", "default"))
|
||||
permissions = dict(zip(default[::2], default[1::2]))
|
||||
check("off" in permissions["flags"], "Default broker user enabled")
|
||||
check(not permissions["passwords"], "Default broker credentials configured")
|
||||
logs = compose("logs", "--since", "30s", "broker")
|
||||
check("CRITICAL" not in logs, "AOF loading reported errors")
|
||||
report = dict(
|
||||
status="PASS",
|
||||
stream_and_consumer_groups_identical=True,
|
||||
stream_entries=len(after["entries"]),
|
||||
consumer_counts_before=before["consumer_counts"],
|
||||
consumer_counts_after=after["consumer_counts"],
|
||||
consumer_metadata="Idle consumers without any delivered message may disappear on restart; cursor, pending count, entries-read and lag are compared exactly.",
|
||||
no_authentication_returns="NOAUTH",
|
||||
default_user_disabled_without_password=True,
|
||||
aof_replay_errors=0,
|
||||
restart_seconds=round(time.monotonic() - started, 3),
|
||||
explanation="Redis 7.4 AOF MULTI replay uses default ACL. Disabled passwordless-without-nopass default has internal permissions, but cannot authenticate. Runtime roles remain restricted.",
|
||||
)
|
||||
Path("evidence/broker-recovery.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
finally:
|
||||
compose("start", "worker", "dispatcher")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,104 @@
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
from client import Client, check
|
||||
from provision import compose
|
||||
from bootstrap import ROOT, write
|
||||
from stack_operator import stop_one
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt", timeout=3)
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
instances = {c.call("GET", "/health/ready")["headers"]["X-Instance-Id"] for _ in range(12)}
|
||||
check(len(instances) == 2, "Expected two active replicas")
|
||||
existing = c.message(actor, chat, "confirmed-before-other-failure")["json"]
|
||||
target = next(
|
||||
value
|
||||
for value in compose("ps", "-q", "api").splitlines()
|
||||
if subprocess.check_output(["docker", "inspect", "--format", "{{.Name}}", value])
|
||||
.decode()
|
||||
.strip()
|
||||
.endswith("-api-1")
|
||||
)
|
||||
alias = (
|
||||
subprocess.check_output(["docker", "exec", target, "cat", "/tmp/instance-id"])
|
||||
.decode()
|
||||
.strip()
|
||||
)
|
||||
os.environ["TARGET_INSTANCE_ID"] = alias
|
||||
started = time.monotonic()
|
||||
|
||||
def writer(index):
|
||||
local = Client(
|
||||
base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt", timeout=3
|
||||
)
|
||||
confirmed = []
|
||||
errors = 0
|
||||
n = 0
|
||||
while time.monotonic() - started < 15:
|
||||
key = uuid.uuid4().hex
|
||||
text = f"other-{index}-{n}"
|
||||
for _ in range(2):
|
||||
try:
|
||||
confirmed.append(local.message(actor, chat, text, key)["json"])
|
||||
break
|
||||
except Exception:
|
||||
errors += 1
|
||||
n += 1
|
||||
return confirmed, errors
|
||||
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
||||
futures = [pool.submit(writer, i) for i in range(4)]
|
||||
time.sleep(1)
|
||||
stop_one()
|
||||
results = [f.result() for f in futures]
|
||||
confirmed = [row for rows, _ in results for row in rows]
|
||||
check(bool(confirmed), "No successful concurrent writes")
|
||||
visible = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
if cursor:
|
||||
path += "&cursor=" + __import__("urllib.parse", fromlist=["quote"]).quote(cursor)
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
visible += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
ids = {row["id"] for row in visible}
|
||||
check(all(row["id"] in ids for row in confirmed + [existing]), "Confirmed message lost")
|
||||
check(len({row["text"] for row in visible}) == len(visible), "Retry duplicated message")
|
||||
check(
|
||||
alias
|
||||
not in {c.call("GET", "/health/ready")["headers"]["X-Instance-Id"] for _ in range(10)},
|
||||
"Stopped process still served requests",
|
||||
)
|
||||
result = dict(
|
||||
status="PASS",
|
||||
stopped_replica="api-1",
|
||||
concurrency=4,
|
||||
duration_seconds=round(time.monotonic() - started, 3),
|
||||
confirmed_writes=len(confirmed),
|
||||
failed_attempts=sum(n for _, n in results),
|
||||
confirmed_preserved=True,
|
||||
duplicate_effects=0,
|
||||
stopped_alias_absent=True,
|
||||
)
|
||||
write(ROOT / "evidence/failover-other.json", json.dumps(result, indent=2) + "\n")
|
||||
print(json.dumps(result, indent=2))
|
||||
finally:
|
||||
compose("start", "--wait", "--wait-timeout", "120", "api")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,314 @@
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
from client import Client, check, run
|
||||
from observe import trace_for, upload
|
||||
from pipeline_support import COMPOSE, compose, ready_api, sql, wait_ready
|
||||
from telemetry_support import logs, save, spans, states, value, wait_until
|
||||
|
||||
|
||||
API_ALERTS = ["ApiHighErrorRate", "ApiBurnFast", "ApiBurnSlow"]
|
||||
READY_ALERTS = ["ReadyBurnFast", "ReadyBurnSlow"]
|
||||
|
||||
|
||||
class Traffic:
|
||||
def __init__(self, actor):
|
||||
self.actor = actor
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.counts = {}
|
||||
self.error = None
|
||||
self.slowest_ok = 0
|
||||
|
||||
def run(self):
|
||||
client = Client(timeout=12)
|
||||
while not self.stop.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = client.call(
|
||||
"GET", "/api/v1/users/me", actor=self.actor, expected=[200, 503]
|
||||
)
|
||||
status = response["status"]
|
||||
elapsed = time.monotonic() - started
|
||||
with self.lock:
|
||||
self.counts[status] = self.counts.get(status, 0) + 1
|
||||
if status == 200:
|
||||
self.slowest_ok = max(self.slowest_ok, elapsed)
|
||||
else:
|
||||
self.error = response["headers"]["X-Request-Id"]
|
||||
except Exception as error:
|
||||
with self.lock:
|
||||
name = type(error).__name__
|
||||
self.counts[name] = self.counts.get(name, 0) + 1
|
||||
self.stop.wait(0.2)
|
||||
|
||||
@contextmanager
|
||||
def start(self, clients=6):
|
||||
with ThreadPoolExecutor(max_workers=clients) as pool:
|
||||
workers = [pool.submit(self.run) for _ in range(clients)]
|
||||
try:
|
||||
yield self
|
||||
finally:
|
||||
self.stop.set()
|
||||
for worker in workers:
|
||||
worker.result()
|
||||
|
||||
def snapshot(self):
|
||||
with self.lock:
|
||||
return dict(self.counts)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_lock(seconds):
|
||||
command = "psql -v ON_ERROR_STOP=1 -U operator -d messenger -At"
|
||||
with subprocess.Popen(
|
||||
COMPOSE + ["exec", "-T", "db", "sh", "-c", command],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
) as process:
|
||||
process.stdin.write(
|
||||
f"SET application_name='lab6-incident'; BEGIN; LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE; "
|
||||
f"SELECT pg_sleep({seconds}); ROLLBACK;\n"
|
||||
)
|
||||
process.stdin.close()
|
||||
try:
|
||||
wait_until(
|
||||
lambda: sql(
|
||||
"SELECT count(*) FROM pg_stat_activity WHERE application_name='lab6-incident'"
|
||||
" AND wait_event='PgSleep';"
|
||||
)
|
||||
== "1",
|
||||
15,
|
||||
"database lock not acquired",
|
||||
)
|
||||
yield time.monotonic()
|
||||
finally:
|
||||
sql(
|
||||
"SELECT pg_cancel_backend(pid) FROM pg_stat_activity"
|
||||
" WHERE application_name='lab6-incident' AND state='active';"
|
||||
)
|
||||
process.wait(timeout=15)
|
||||
|
||||
|
||||
def monitor(names, firing, timeout, started):
|
||||
samples = []
|
||||
|
||||
reached = set()
|
||||
target = "firing" if firing else "inactive"
|
||||
|
||||
def check_state():
|
||||
snapshot = states()
|
||||
samples.append(
|
||||
{
|
||||
"seconds": round(time.monotonic() - started, 2),
|
||||
"states": {name: snapshot[name] for name in names},
|
||||
}
|
||||
)
|
||||
reached.update(name for name in names if snapshot[name] == target)
|
||||
return (
|
||||
len(reached) == len(names)
|
||||
if firing
|
||||
else all(snapshot[name] == target for name in names)
|
||||
)
|
||||
|
||||
wait_until(check_state, timeout, "unexpected alert states: " + str(names))
|
||||
return samples
|
||||
|
||||
|
||||
def find_failed_dependency(request_id, since):
|
||||
trace_id = wait_until(lambda: trace_for(request_id, since), 35, "DB incident log missing")
|
||||
|
||||
def dependency():
|
||||
try:
|
||||
rows = spans(trace_id)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
for row in rows:
|
||||
if row["name"] == "postgres.session.lookup":
|
||||
duration = (int(row["endTimeUnixNano"]) - int(row["startTimeUnixNano"])) / 1e9
|
||||
if duration >= 3:
|
||||
return {
|
||||
"trace_id": trace_id,
|
||||
"request_id": request_id,
|
||||
"dependency": row["name"],
|
||||
"duration_seconds": duration,
|
||||
"status": row.get("status"),
|
||||
}
|
||||
return None
|
||||
|
||||
return wait_until(dependency, 35, "slow PostgreSQL span missing")
|
||||
|
||||
|
||||
def database_incidents(actor):
|
||||
with Traffic(actor).start() as traffic:
|
||||
time.sleep(15)
|
||||
wait_until(lambda: traffic.snapshot().get(200, 0) >= 35, 15, "no warm traffic")
|
||||
before = traffic.snapshot().get(503, 0)
|
||||
with session_lock(3) as started:
|
||||
canceled = sql(
|
||||
"SELECT pg_cancel_backend(pid) FROM (SELECT pid FROM pg_stat_activity"
|
||||
" WHERE wait_event_type='Lock' AND query LIKE '%sessions%' LIMIT 1) AS blocked;"
|
||||
)
|
||||
check(canceled == "t", "short incident did not cancel a DB read")
|
||||
brief = []
|
||||
for _ in range(17):
|
||||
brief.append({"seconds": round(time.monotonic() - started, 2), "states": states()})
|
||||
time.sleep(1)
|
||||
short_errors = traffic.snapshot().get(503, 0) - before
|
||||
check(short_errors > 0, "short fault produced no observed errors")
|
||||
check(
|
||||
not any(sample["states"][name] == "firing" for sample in brief for name in API_ALERTS),
|
||||
"short burst fired an API alert",
|
||||
)
|
||||
since = time.time() - 2
|
||||
with session_lock(85) as started:
|
||||
detection = monitor(API_ALERTS, True, 75, started)
|
||||
request_id = traffic.error
|
||||
released = time.monotonic()
|
||||
recovery = monitor(API_ALERTS, False, 95, released)
|
||||
check(
|
||||
traffic.snapshot().get(200, 0) > 30 and traffic.snapshot().get(503, 0) > short_errors,
|
||||
"sustained incident did not affect HTTP",
|
||||
)
|
||||
sample = find_failed_dependency(request_id, since)
|
||||
return {
|
||||
"traffic_clients": 6,
|
||||
"short": {"503_count": short_errors, "samples": brief, "alert_firings": 0},
|
||||
"sustained": {
|
||||
"firing": detection,
|
||||
"resolved": recovery,
|
||||
"bounded_lock_seconds": 85,
|
||||
"traffic_statuses": traffic.snapshot(),
|
||||
"cause": sample,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def queue_incident(client, actor, chat):
|
||||
compose("stop", "worker")
|
||||
started = time.monotonic()
|
||||
attachments = []
|
||||
try:
|
||||
for index in range(16):
|
||||
attachments.append(upload(client, actor, chat, "lag-" + str(index))["json"])
|
||||
provisional = monitor(["AttachmentQueueLag"], True, 45, started)
|
||||
peak = {
|
||||
"age_seconds": value("max(lab_queue_oldest_seconds)"),
|
||||
"backlog": value("max(lab_queue_depth)"),
|
||||
"reported_capacity": value("sum(lab_worker_capacity)"),
|
||||
}
|
||||
check(peak["backlog"] >= 16, "observability reported no backlog")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
released = time.monotonic()
|
||||
for attachment in attachments:
|
||||
wait_ready(client, actor, attachment)
|
||||
drain = round(time.monotonic() - released, 2)
|
||||
ready_firing = monitor(READY_ALERTS, True, 45, released)
|
||||
resolved = monitor(["AttachmentQueueLag"], False, 30, released)
|
||||
ready_resolved = monitor(READY_ALERTS, False, 90, released)
|
||||
return {
|
||||
"accepted": len(attachments),
|
||||
"queue_firing": provisional,
|
||||
"peak": peak,
|
||||
"drained_seconds": drain,
|
||||
"ready_burn_firing": ready_firing,
|
||||
"queue_resolved": resolved,
|
||||
"ready_burn_resolved": ready_resolved,
|
||||
"all_ready": True,
|
||||
}
|
||||
|
||||
|
||||
def collector_snapshot():
|
||||
metric = "otelcol_exporter_send_failed_log_records_total"
|
||||
return {
|
||||
"send_failed_logs": value("sum(" + metric + '{exporter="otlphttp/loki"})'),
|
||||
"queue_size": value('max(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'),
|
||||
"queue_capacity": value('max(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'),
|
||||
"rss_bytes": value("otelcol_process_memory_rss_bytes"),
|
||||
}
|
||||
|
||||
|
||||
def backend_incident(client, actor, chat):
|
||||
before = collector_snapshot()
|
||||
acknowledged = []
|
||||
samples = []
|
||||
compose("stop", "loki")
|
||||
started = time.monotonic()
|
||||
try:
|
||||
for index in range(30):
|
||||
acknowledged.append(
|
||||
client.message(actor, chat, "backend proof " + str(index))["json"]["id"]
|
||||
)
|
||||
if index % 3 == 0:
|
||||
samples.append(collector_snapshot())
|
||||
time.sleep(0.7)
|
||||
samples.append(collector_snapshot())
|
||||
finally:
|
||||
compose("start", "loki")
|
||||
page = client.call(
|
||||
"GET", f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=actor, schema="MessagePage"
|
||||
)["json"]
|
||||
check(
|
||||
set(acknowledged) <= {item["id"] for item in page["items"]},
|
||||
"message loss during telemetry outage",
|
||||
)
|
||||
after = collector_snapshot()
|
||||
failed = (
|
||||
max([after["send_failed_logs"], *[s["send_failed_logs"] for s in samples]])
|
||||
- before["send_failed_logs"]
|
||||
)
|
||||
check(failed > 0, "Collector exporter drops were not observed")
|
||||
wait_until(loki_ready, 75, "Loki failed to recover")
|
||||
since = time.time() - 2
|
||||
response = client.message(actor, chat, "telemetry restored")
|
||||
restored_trace = wait_until(
|
||||
lambda: trace_for(response["headers"]["X-Request-Id"], since),
|
||||
45,
|
||||
"new business log not exported after Loki recovery",
|
||||
)
|
||||
return {
|
||||
"confirmed_and_read": len(acknowledged),
|
||||
"seconds": round(time.monotonic() - started, 2),
|
||||
"collector_before": before,
|
||||
"collector_samples": samples,
|
||||
"collector_after": after,
|
||||
"failed_export_log_records_delta": failed,
|
||||
"restored_trace_id": restored_trace,
|
||||
}
|
||||
|
||||
|
||||
def loki_ready():
|
||||
try:
|
||||
logs('{service_name="messenger-api"}', limit=1)
|
||||
return True
|
||||
except (HTTPError, URLError, TimeoutError):
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(timeout=12)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
mode = os.getenv("INCIDENT", "all")
|
||||
if mode in ("all", "db"):
|
||||
save("database-incident.json", database_incidents(actor))
|
||||
print("PASS short DB burst and sustained slowdown: real alerts and DB trace", flush=True)
|
||||
if mode in ("all", "queue"):
|
||||
save("queue-incident.json", queue_incident(client, actor, chat))
|
||||
print("PASS stopped worker: backlog, firing/resolved and slow READY burn", flush=True)
|
||||
if mode in ("all", "backend"):
|
||||
save("backend-incident.json", backend_incident(client, actor, chat))
|
||||
print("PASS stopped Loki: bounded telemetry failure and saved business writes", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,185 @@
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, fault, job, ready_api, wait_ready
|
||||
from telemetry_support import fetch, logs, prom, save, spans, wait_until
|
||||
|
||||
|
||||
def upload(client, actor, chat, name):
|
||||
return client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename={name}.png",
|
||||
actor=actor,
|
||||
raw=Path("tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
expected=202,
|
||||
schema="Attachment",
|
||||
)
|
||||
|
||||
|
||||
def trace_for(request_id, since):
|
||||
rows = logs('{service_name="messenger-api"} | request_id="' + request_id + '"', since)
|
||||
for row in rows:
|
||||
trace_id = row["stream"].get("trace_id")
|
||||
for entry in row["values"]:
|
||||
metadata = entry[2] if len(entry) > 2 else {}
|
||||
trace_id = trace_id or metadata.get("trace_id")
|
||||
if trace_id:
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
|
||||
def complete_trace(trace_id):
|
||||
try:
|
||||
rows = spans(trace_id)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
required = {
|
||||
"POST /api/v1/chats/{chat_id}/attachments",
|
||||
"attachments publish",
|
||||
"attachments consume",
|
||||
"s3.staging.read",
|
||||
"postgres.publish_result",
|
||||
}
|
||||
return (
|
||||
rows
|
||||
if required <= {row["name"] for row in rows}
|
||||
and sum(row["name"] == "attachments consume" for row in rows) >= 2
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def verify_trace(rows):
|
||||
indexed = {s["spanId"]: s for s in rows}
|
||||
consumers = [s for s in rows if s["name"] == "attachments consume"]
|
||||
assert len(consumers) >= 2, "retry absent from trace"
|
||||
for consumer in consumers:
|
||||
producer = indexed[consumer["parentSpanId"]]
|
||||
assert producer["name"] == "attachments publish", "consumer parent is not producer"
|
||||
assert (
|
||||
indexed[producer["parentSpanId"]]["kind"] == "SPAN_KIND_SERVER"
|
||||
or str(indexed[producer["parentSpanId"]]["kind"]) == "2"
|
||||
)
|
||||
return [
|
||||
{
|
||||
key: row.get(key)
|
||||
for key in ("name", "service", "spanId", "parentSpanId", "kind", "status")
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def verify_metrics():
|
||||
names = [
|
||||
"lab_http_requests_total",
|
||||
"lab_http_duration_seconds_bucket",
|
||||
"lab_jobs_total",
|
||||
"lab_job_duration_seconds_bucket",
|
||||
"lab_ready_duration_seconds_bucket",
|
||||
"lab_queue_depth",
|
||||
"lab_queue_oldest_seconds",
|
||||
"lab_db_pool_connections",
|
||||
"lab_worker_busy",
|
||||
"lab_worker_capacity",
|
||||
"lab_process_cpu_seconds_total",
|
||||
"lab_process_rss_bytes",
|
||||
]
|
||||
return wait_until(
|
||||
lambda: collect_metrics(names),
|
||||
50,
|
||||
"required metric series missing",
|
||||
)
|
||||
|
||||
|
||||
def collect_metrics(names):
|
||||
result = prom('{__name__=~"' + "|".join(names) + '"}')
|
||||
present = {row["metric"]["__name__"] for row in result}
|
||||
if present != set(names):
|
||||
return None
|
||||
forbidden = {
|
||||
"user_id",
|
||||
"chat_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"request_id",
|
||||
"filename",
|
||||
"url",
|
||||
}
|
||||
for row in result:
|
||||
assert not forbidden & set(row["metric"]), "forbidden metric attributes"
|
||||
return {
|
||||
name: {
|
||||
"series": sum(row["metric"]["__name__"] == name for row in result),
|
||||
"label_keys": sorted(
|
||||
{
|
||||
key
|
||||
for row in result
|
||||
if row["metric"]["__name__"] == name
|
||||
for key in row["metric"]
|
||||
}
|
||||
),
|
||||
}
|
||||
for name in names
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(timeout=12)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
marker = "proof" + uuid.uuid4().hex
|
||||
client.message(actor, chat, marker)
|
||||
since = time.time() - 2
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
response = upload(client, actor, chat, marker)
|
||||
attachment = response["json"]
|
||||
fault(attachment, "before_effects", "transient")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
wait_ready(client, actor, attachment)
|
||||
check(job(attachment)["attempt"] == 2, "proof job did not retry")
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
trace_id = wait_until(
|
||||
lambda: trace_for(request_id, since), 45, "API request ID missing from Loki"
|
||||
)
|
||||
rows = wait_until(lambda: complete_trace(trace_id), 60, "correlated trace missing from Tempo")
|
||||
worker_logs = wait_until(
|
||||
lambda: logs('{service_name="messenger-worker"} | trace_id="' + trace_id + '"', since),
|
||||
30,
|
||||
"worker logs missing for trace",
|
||||
)
|
||||
events = sorted({entry[1] for row in worker_logs for entry in row["values"]})
|
||||
check("worker.retry" in events and "worker.ready" in events, "retry/ready logs missing")
|
||||
check(
|
||||
not logs('{service_name=~"messenger-.+"} |= "' + marker + '"', since - 10),
|
||||
"sensitive marker in logs",
|
||||
)
|
||||
check(marker not in str(rows), "sensitive marker in trace")
|
||||
check(
|
||||
fetch("/api/dashboards/uid/messenger-lab6")["dashboard"]["title"] == "Messenger Lab 6",
|
||||
"dashboard not provisioned",
|
||||
)
|
||||
save(
|
||||
"signal-link.json",
|
||||
{
|
||||
"trace_id": trace_id,
|
||||
"request_id": request_id,
|
||||
"spans": verify_trace(rows),
|
||||
"worker_events": events,
|
||||
"marker_absent": True,
|
||||
},
|
||||
)
|
||||
save("metric-inventory.json", verify_metrics())
|
||||
print(
|
||||
"PASS real upload -> publish -> consumer retry -> S3/DB; Loki/Tempo/Prometheus via Grafana"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,15 @@
|
||||
from client import run
|
||||
from pipeline_faults import Experiment
|
||||
|
||||
|
||||
def main():
|
||||
experiment = Experiment()
|
||||
experiment.fenced_without_dispatcher()
|
||||
print(
|
||||
"PASS expired worker without dispatcher: no premature ACK; pending/index retained; recovery publishes exactly one result on attempt 2",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,133 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, sql, ready_api, wait_ready, wait_for, operator, COMPOSE
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
|
||||
def eligibility(c, a, chat, attachment):
|
||||
sql(
|
||||
"create function proof_message_guard() returns trigger language plpgsql as $$ begin if NEW.chat_id='"
|
||||
+ chat["id"]
|
||||
+ "'::uuid then perform pg_sleep(4); end if; return NEW; end; $$; create trigger proof_message_guard before insert on messages for each row execute function proof_message_guard();"
|
||||
)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(c.message, a, chat, "guard", None, [attachment["id"]])
|
||||
wait_for(
|
||||
lambda: sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")
|
||||
!= "0",
|
||||
10,
|
||||
)
|
||||
code = """import psycopg
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.config import Settings
|
||||
try:
|
||||
with Repository(Settings()).connection() as db:
|
||||
db.execute("SET lock_timeout='250ms'")
|
||||
db.execute("UPDATE attachments SET status='FAILED',error_code='injected_failure' WHERE id=%s",('ATTACHMENT',))
|
||||
except psycopg.errors.LockNotAvailable:
|
||||
print('blocked_by_message_transaction',flush=True)
|
||||
else:
|
||||
raise AssertionError('status changed between validation and commit')
|
||||
""".replace(
|
||||
"ATTACHMENT", attachment["id"]
|
||||
)
|
||||
output = compose("exec", "-T", "dispatcher", "python", "-c", code)
|
||||
check(output == "blocked_by_message_transaction", "status guard missing")
|
||||
check(
|
||||
request.result()["json"]["attachment_ids"] == [attachment["id"]],
|
||||
"message not created",
|
||||
)
|
||||
finally:
|
||||
sql("drop trigger proof_message_guard on messages; drop function proof_message_guard();")
|
||||
sql(
|
||||
"begin;update attachments set status='FAILED',error_code='injected_failure' where id='"
|
||||
+ attachment["id"]
|
||||
+ "';update processing_jobs set status='FAILED',error_code='injected_failure' where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';commit;"
|
||||
)
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
409,
|
||||
actor=a,
|
||||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
operator("replay", attachment)
|
||||
print(
|
||||
"PASS message eligibility: status UPDATE blocked until Message COMMIT; subsequent FAILED attachment rejected with 409",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def download_guard(c, actor, attachment, body):
|
||||
code = """import time
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.config import Settings
|
||||
with Repository(Settings()).connection() as db:
|
||||
db.execute('SELECT pg_advisory_xact_lock(741204)')
|
||||
print('cleanup_locked',flush=True)
|
||||
time.sleep(4)
|
||||
"""
|
||||
holder = subprocess.Popen(
|
||||
COMPOSE + ["exec", "-T", "dispatcher", "python", "-c", code],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
check(holder.stdout.readline().strip() == "cleanup_locked", "cleanup fence not acquired")
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(
|
||||
c.call,
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
200,
|
||||
None,
|
||||
actor,
|
||||
)
|
||||
wait_for(
|
||||
lambda: sql(
|
||||
"select count(*) from pg_stat_activity where wait_event='advisory' and query ilike '%pg_advisory_xact_lock_shared(741204)%';"
|
||||
)
|
||||
!= "0",
|
||||
3,
|
||||
"download did not wait on cleanup fence",
|
||||
)
|
||||
check(not request.done(), "download bypassed cleanup fence")
|
||||
_, errors = holder.communicate(timeout=10)
|
||||
check(holder.returncode == 0, "cleanup holder failed")
|
||||
check(request.result(timeout=10)["bytes"] == body, "download changed bytes")
|
||||
check(
|
||||
sql("select pg_try_advisory_xact_lock(741204);") == "t",
|
||||
"download leaked transaction fence",
|
||||
)
|
||||
finally:
|
||||
if holder.poll() is None:
|
||||
holder.kill()
|
||||
holder.wait()
|
||||
print(
|
||||
"PASS download/cleanup barrier: content waits for exclusive cleanup, returns identical bytes, releases shared fence",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
attachment, body = c.attachment(a, chat)
|
||||
eligibility(c, a, chat, attachment)
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
wait_ready(c, a, attachment)
|
||||
download_guard(c, b, attachment, body)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,142 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import ready_api, wait_ready, metadata, compose, broker, sql
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
png = Path("tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=proof.png"
|
||||
|
||||
def upload(data=png, mime="image/png", expected=202):
|
||||
return c.call(
|
||||
"POST",
|
||||
path,
|
||||
expected,
|
||||
actor=a,
|
||||
raw=data,
|
||||
headers={"Content-Type": mime},
|
||||
schema="Attachment" if expected == 202 else None,
|
||||
)
|
||||
|
||||
compose("stop", "worker")
|
||||
attachment = upload()["json"]
|
||||
check(attachment["status"] == "queued", "upload response not queued snapshot")
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=b)
|
||||
c.message(a, chat, "", attachments=[attachment["id"]])
|
||||
compose("start", "worker")
|
||||
result = wait_ready(c, b, attachment)
|
||||
verify(c, b, attachment, png, result)
|
||||
print(
|
||||
"PASS queued snapshot, link before ready, 409 before worker; original + 3 variants",
|
||||
flush=True,
|
||||
)
|
||||
negative(c, a, e, chat, attachment, upload, png)
|
||||
fixtures(c, a, b, upload)
|
||||
concurrent(c, a, chat, attachment)
|
||||
print("PASS core pipeline contract", flush=True)
|
||||
|
||||
|
||||
def verify(c, actor, attachment, original, result):
|
||||
base = "/api/v1/attachments/" + attachment["id"] + "/content"
|
||||
check(c.call("GET", base, actor=actor)["bytes"] == original, "original changed")
|
||||
check(
|
||||
{v["name"] for v in result["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"variant set differs",
|
||||
)
|
||||
for variant in result["variants"]:
|
||||
response = c.call("GET", base + "?variant=" + variant["name"], actor=actor)
|
||||
check(
|
||||
hashlib.sha256(response["bytes"]).hexdigest() == variant["sha256"], "variant checksum"
|
||||
)
|
||||
check(len(response["bytes"]) == variant["size_bytes"], "variant size")
|
||||
check(response["headers"].get_content_type() == variant["content_type"], "variant MIME")
|
||||
with Image.open(io.BytesIO(response["bytes"])) as image:
|
||||
check(image.size == (variant["width"], variant["height"]), "variant dimensions")
|
||||
check(not image.getexif(), "EXIF retained")
|
||||
|
||||
|
||||
def negative(c, a, e, chat, attachment, upload, png):
|
||||
upload(png[:33], expected=415)
|
||||
upload(png, "image/jpeg", 415)
|
||||
upload(b"x" * 10485761, expected=413)
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=..%2Fx.png",
|
||||
400,
|
||||
actor=a,
|
||||
raw=png,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
for suffix in ("", "/content"):
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + suffix, 404, actor=e)
|
||||
other = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=a,
|
||||
body={"title": "other", "member_ids": [a["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other["id"] + "/messages",
|
||||
404,
|
||||
actor=a,
|
||||
body={"text": "x", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS bytes/corruption/MIME/filename/ACL/cross-chat negatives", flush=True)
|
||||
|
||||
|
||||
def fixtures(c, a, b, upload):
|
||||
output = io.BytesIO()
|
||||
Image.new("RGBA", (8, 4), (255, 0, 0, 0)).save(output, format="PNG")
|
||||
attachment = upload(output.getvalue())["json"]
|
||||
result = wait_ready(c, b, attachment)
|
||||
data = c.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", actor=b
|
||||
)["bytes"]
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
check(
|
||||
image.size == (8, 4) and min(image.getpixel((0, 0))) >= 250, "alpha/upscale incorrect"
|
||||
)
|
||||
output = io.BytesIO()
|
||||
image = Image.new("RGB", (80, 40), (20, 80, 160))
|
||||
exif = image.getexif()
|
||||
exif[274] = 6
|
||||
image.save(output, format="JPEG", exif=exif)
|
||||
attachment = upload(output.getvalue(), "image/jpeg")["json"]
|
||||
result = wait_ready(c, b, attachment)
|
||||
thumb = next(v for v in result["variants"] if v["name"] == "thumbnail")
|
||||
check((thumb["width"], thumb["height"]) == (40, 80), "EXIF orientation ignored")
|
||||
verify(c, b, attachment, output.getvalue(), result)
|
||||
print("PASS alpha white, no small-image enlargement, EXIF rotation, crop and WebP", flush=True)
|
||||
|
||||
|
||||
def concurrent(c, a, chat, attachment):
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
def send(_):
|
||||
return c.message(a, chat, "concurrent", key=key, attachments=[attachment["id"]])
|
||||
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
replies = list(pool.map(send, range(24)))
|
||||
check(len({r["json"]["id"] for r in replies}) == 1, "duplicate message effects")
|
||||
check(
|
||||
len({r["headers"]["X-Instance-Id"] for r in replies}) == 2, "two API replicas not observed"
|
||||
)
|
||||
print("PASS 24 concurrent requests across 2 API replicas; single message effect", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,373 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import (
|
||||
compose,
|
||||
sql,
|
||||
broker,
|
||||
wait_for,
|
||||
ready_api,
|
||||
metadata,
|
||||
wait_ready,
|
||||
job,
|
||||
payload,
|
||||
inject_duplicate,
|
||||
fault,
|
||||
fault_hit,
|
||||
operator,
|
||||
manifest,
|
||||
events,
|
||||
)
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Experiment:
|
||||
def __init__(self):
|
||||
ready_api()
|
||||
self.client = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
self.actor, self.member, self.outsider, self.chat = self.client.bootstrap()
|
||||
self.body = Path("tests/fixtures/sample.png").read_bytes()
|
||||
self.rows = []
|
||||
self.accepted = []
|
||||
|
||||
def upload(self, body=None, expected=202):
|
||||
response = self.client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + self.chat["id"] + "/attachments?filename=fault.png",
|
||||
expected,
|
||||
actor=self.actor,
|
||||
raw=self.body if body is None else body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment" if expected == 202 or isinstance(expected, list) else None,
|
||||
)
|
||||
if response["status"] == 202:
|
||||
self.accepted.append(response["json"]["id"])
|
||||
return response["json"]
|
||||
return response
|
||||
|
||||
def run_case(self, name, action):
|
||||
started = time.monotonic()
|
||||
action()
|
||||
row = {"scenario": name, "result": "PASS", "seconds": round(time.monotonic() - started, 3)}
|
||||
self.rows.append(row)
|
||||
print(json.dumps(row), flush=True)
|
||||
Path("evidence/pipeline-faults.json").write_text(json.dumps(self.rows, indent=2))
|
||||
|
||||
def settled(self, attachment):
|
||||
wait_ready(self.client, self.actor, attachment, 120)
|
||||
check(events(attachment, "ready") == 1, "multiple published effects")
|
||||
check(
|
||||
int(
|
||||
sql(
|
||||
"select count(*) from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
)
|
||||
== 3,
|
||||
"duplicate variants",
|
||||
)
|
||||
data = self.client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=self.member
|
||||
)["bytes"]
|
||||
check(data == self.body, "original changed")
|
||||
|
||||
def prepare(self, point, action, count=1):
|
||||
compose("stop", "worker")
|
||||
attachment = self.upload()
|
||||
fault(attachment, point, action, count)
|
||||
compose("start", "worker")
|
||||
return attachment
|
||||
|
||||
def durability(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
accepted = [self.upload() for _ in range(2)]
|
||||
for attachment in accepted:
|
||||
self.client.message(self.actor, self.chat, "", attachments=[attachment["id"]])
|
||||
check(job(attachment)["status"] == "QUEUED", "worker ran while stopped")
|
||||
check(
|
||||
sql(
|
||||
"select published_at IS NULL from processing_outbox where job_id='"
|
||||
+ job(attachment)["job_id"]
|
||||
+ "';"
|
||||
)
|
||||
== "t",
|
||||
"unexpected publish",
|
||||
)
|
||||
compose("restart", "api")
|
||||
ready_api()
|
||||
fault(accepted[0], "before_publish", "crash")
|
||||
compose("start", "dispatcher")
|
||||
wait_for(lambda: fault_hit(accepted[0], "before_publish"))
|
||||
wait_for(
|
||||
lambda: all(
|
||||
job(a)["job_id"] in broker("XRANGE", "attachment-jobs", "-", "+") for a in accepted
|
||||
)
|
||||
)
|
||||
before = broker("XLEN", "attachment-jobs")
|
||||
time.sleep(12)
|
||||
check(
|
||||
broker("XLEN", "attachment-jobs") == before,
|
||||
"watchdog multiplied queued broker messages",
|
||||
)
|
||||
compose("restart", "broker")
|
||||
wait_for(lambda: broker("PING") == "PONG")
|
||||
history = broker("XRANGE", "attachment-jobs", "-", "+")
|
||||
check(all(job(a)["job_id"] in history for a in accepted), "broker restart lost messages")
|
||||
compose("start", "worker")
|
||||
for attachment in accepted:
|
||||
self.settled(attachment)
|
||||
print(
|
||||
"durability: 202 -> outbox COMMIT without publisher; API restart; publish; broker restart while worker stopped; same jobs ready",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
def publisher_confirm_window(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
attachment = self.upload()
|
||||
fault(attachment, "after_publish", "crash")
|
||||
compose("start", "dispatcher")
|
||||
wait_for(lambda: fault_hit(attachment, "after_publish"))
|
||||
compose("start", "worker")
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(self.object_count(attachment) == 4, "publisher crash duplicated effect")
|
||||
|
||||
def duplicates(self):
|
||||
attachment = self.upload()
|
||||
self.settled(attachment)
|
||||
value = payload(attachment)
|
||||
before = manifest(attachment)
|
||||
attempt = job(attachment)["attempt"]
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(lambda _: inject_duplicate(value), range(24)))
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0")
|
||||
check(
|
||||
manifest(attachment) == before and job(attachment)["attempt"] == attempt,
|
||||
"ready duplicate executed",
|
||||
)
|
||||
check(self.object_count(attachment) == 4, "duplicate S3 object set")
|
||||
|
||||
def object_count(self, attachment):
|
||||
code = (
|
||||
"from pipeline.storage import Storage;from pipeline.config import Settings;s=Storage(Settings());print(len(s.client.list_objects_v2(Bucket=s.settings.bucket,Prefix='results/"
|
||||
+ attachment["id"]
|
||||
+ "/').get('Contents',[])))"
|
||||
)
|
||||
return int(compose("exec", "-T", "dispatcher", "python", "-c", code))
|
||||
|
||||
def crash(self, point):
|
||||
attachment = self.prepare(point, "crash")
|
||||
wait_for(lambda: fault_hit(attachment, point), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(self.object_count(attachment) == 4, "crash redelivery multiplied S3 objects")
|
||||
expected = 2 if point in ("before_effects", "after_effects") else 1
|
||||
check(job(attachment)["attempt"] == expected, "unexpected managed attempt count")
|
||||
|
||||
def lease_fencing(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: events(attachment, "fenced_stale_result") >= 1, 30)
|
||||
check(job(attachment)["attempt"] == 2, "lease did not recover work")
|
||||
check(self.object_count(attachment) == 4, "lease recovery multiplied objects")
|
||||
|
||||
def timeout_recovery(self):
|
||||
attachment = self.prepare("before_effects", "timeout")
|
||||
wait_for(lambda: fault_hit(attachment, "before_effects"), 60)
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: events(attachment, "worker_timeout") >= 1, 40)
|
||||
check(self.object_count(attachment) == 4, "timeout recovery multiplied effects")
|
||||
|
||||
def fenced_without_dispatcher(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
compose("stop", "dispatcher")
|
||||
try:
|
||||
time.sleep(13)
|
||||
check(job(attachment)["status"] == "PROCESSING", "test did not hold recovery window")
|
||||
check(events(attachment, "ready") == 0, "expired worker published result")
|
||||
check(
|
||||
int(broker("XLEN", "attachment-jobs")) >= 1,
|
||||
"unfinished current delivery acknowledged",
|
||||
)
|
||||
check(
|
||||
int(broker("HLEN", "job-publications")) >= 1, "unfinished publication index removed"
|
||||
)
|
||||
finally:
|
||||
compose("start", "dispatcher")
|
||||
self.settled(attachment)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(
|
||||
job(attachment)["attempt"] == 2, "lease recovery did not schedule next managed attempt"
|
||||
)
|
||||
check(self.object_count(attachment) == 4, "recovery multiplied S3 effects")
|
||||
Path("evidence/fenced-pending.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"attachment_id": attachment["id"],
|
||||
"unfinished_delivery_retained": True,
|
||||
"recovered_attempt": 2,
|
||||
"one_manifest": True,
|
||||
"s3_objects": 4,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
def version_fencing(self):
|
||||
attachment = self.prepare("after_effects", "pause")
|
||||
wait_for(lambda: fault_hit(attachment, "after_effects"), 60)
|
||||
old = payload(attachment)
|
||||
operator("upgrade", attachment, 2)
|
||||
wait_ready(self.client, self.actor, attachment, 90)
|
||||
check(job(attachment)["pipeline_version"] == 2, "new version missing")
|
||||
before = manifest(attachment)
|
||||
wait_for(lambda: events(attachment, "fenced_stale_result") >= 1, 30)
|
||||
new = payload(attachment)
|
||||
for value in [new, old, new, old, old]:
|
||||
inject_duplicate(value)
|
||||
wait_for(lambda: broker("XLEN", "attachment-jobs") == "0", 60)
|
||||
check(manifest(attachment) == before, "old result overwrote new version")
|
||||
check("/v2/" in before and "/v1/" not in before, "wrong manifest version")
|
||||
check(events(attachment, "ready") == 1, "old in-flight version published")
|
||||
|
||||
def failure_replay(self, action):
|
||||
attachment = self.prepare("before_effects", action, 3 if action == "transient" else 1)
|
||||
wait_for(lambda: metadata(self.client, self.actor, attachment)["status"] == "failed", 90)
|
||||
result = metadata(self.client, self.actor, attachment)
|
||||
check(
|
||||
result["error_code"]
|
||||
== ("retry_exhausted" if action == "transient" else "invalid_image"),
|
||||
"unsafe failure code",
|
||||
)
|
||||
original = job(attachment)
|
||||
check(
|
||||
original["attempt"] == (3 if action == "transient" else 1), "retry budget not enforced"
|
||||
)
|
||||
self.client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=self.actor
|
||||
)
|
||||
response = operator("replay", attachment)
|
||||
check(response["replayed"], "replay rejected")
|
||||
self.settled(attachment)
|
||||
check(job(attachment)["job_id"] == original["job_id"], "replay replaced logical job")
|
||||
check(job(attachment)["attempt"] == original["attempt"] + 1, "attempt counter reset")
|
||||
before = manifest(attachment)
|
||||
check(not operator("replay", attachment)["replayed"], "successful job replayed")
|
||||
check(manifest(attachment) == before, "noop replay changed effect")
|
||||
|
||||
def backpressure(self):
|
||||
compose("stop", "worker", "dispatcher")
|
||||
output = io.BytesIO()
|
||||
Image.frombytes("RGB", (800, 600), os.urandom(800 * 600 * 3)).save(output, format="PNG")
|
||||
body = output.getvalue()
|
||||
samples = []
|
||||
sample_errors = []
|
||||
done = threading.Event()
|
||||
|
||||
def sample():
|
||||
while not done.is_set():
|
||||
try:
|
||||
value = compose(
|
||||
"stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}} {{.CPUPerc}}"
|
||||
)
|
||||
check(bool(value), "empty stats sample")
|
||||
samples.append(value)
|
||||
except Exception as error:
|
||||
sample_errors.append(type(error).__name__)
|
||||
return
|
||||
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(
|
||||
pool.map(lambda _: self.upload(body, expected=[202, 503]), range(10))
|
||||
)
|
||||
accepted = [r for r in responses if "id" in r]
|
||||
check(len(accepted) == 6, "admission capacity not atomic across replicas")
|
||||
started = time.monotonic()
|
||||
compose("start", "dispatcher", "worker")
|
||||
latencies = []
|
||||
for attachment in accepted:
|
||||
wait_ready(self.client, self.actor, attachment, 90)
|
||||
latencies.append(time.monotonic() - started)
|
||||
finally:
|
||||
done.set()
|
||||
sampler.join()
|
||||
check(not sample_errors and samples, "memory sampling failed")
|
||||
check(any("worker" in value for value in samples), "worker RSS not sampled")
|
||||
summary = {
|
||||
"accepted": len(accepted),
|
||||
"rejected": 10 - len(accepted),
|
||||
"concurrency": 10,
|
||||
"image_bytes": len(body),
|
||||
"seconds_to_observed_ready": latencies,
|
||||
"stats_samples": samples,
|
||||
"method": "closed loop; sequential polls overestimate early completions",
|
||||
}
|
||||
Path("evidence/backpressure.json").write_text(json.dumps(summary, indent=2))
|
||||
print(
|
||||
"backpressure: 6 accepted, 4 rejected with 503, accepted jobs drained after recovery",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
experiment = Experiment()
|
||||
experiment.run_case("commit_publish_api_broker_restart", experiment.durability)
|
||||
experiment.run_case("publish_confirm_db_mark_crash", experiment.publisher_confirm_window)
|
||||
experiment.run_case("24_concurrent_duplicate_deliveries", experiment.duplicates)
|
||||
for point in ["before_effects", "after_effects", "after_commit", "before_ack"]:
|
||||
experiment.run_case("crash_" + point, lambda point=point: experiment.crash(point))
|
||||
experiment.run_case("expired_lease_fences_old_worker", experiment.lease_fencing)
|
||||
experiment.run_case("hard_process_timeout_recovery", experiment.timeout_recovery)
|
||||
experiment.run_case("new_version_then_stale_reordered_jobs", experiment.version_fencing)
|
||||
experiment.run_case(
|
||||
"permanent_failure_explicit_replay", lambda: experiment.failure_replay("permanent")
|
||||
)
|
||||
experiment.run_case(
|
||||
"bounded_retry_explicit_replay", lambda: experiment.failure_replay("transient")
|
||||
)
|
||||
experiment.run_case("two_replica_atomic_backpressure_recovery", experiment.backpressure)
|
||||
wait_for(
|
||||
lambda: sql(
|
||||
"select count(*) from attachments where status='READY' and staging_key IS NOT NULL;"
|
||||
)
|
||||
== "0",
|
||||
90,
|
||||
"ready staging not cleaned",
|
||||
)
|
||||
ids = ",".join("'" + value + "'" for value in experiment.accepted)
|
||||
missing = sql(
|
||||
"select count(*) from attachments a left join processing_jobs j on j.attachment_id=a.id and j.pipeline_version=a.pipeline_version left join processing_outbox o using(job_id) where a.id in ("
|
||||
+ ids
|
||||
+ ") and (j.job_id is null or o.job_id is null or a.status not in ('READY','FAILED') or j.status<>a.status);"
|
||||
)
|
||||
check(missing == "0", "confirmed task lost or not terminal")
|
||||
Path("evidence/accepted-jobs.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"accepted_ids": experiment.accepted,
|
||||
"count": len(experiment.accepted),
|
||||
"missing_or_nonterminal": int(missing),
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
print(
|
||||
"PASS staging cleaned after safe result publication; no confirmed job lost; all pipeline fault invariants",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,39 @@
|
||||
from client import Client, check, run
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
body = Path("tests/fixtures/sample.png").read_bytes()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
for name in ["a" * 255, "\U0001f600" * 255]:
|
||||
attachment = c.call(
|
||||
"POST",
|
||||
path + quote(name),
|
||||
202,
|
||||
actor=a,
|
||||
raw=body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(attachment["filename"] == name, "filename changed")
|
||||
c.wait_ready(a, attachment)
|
||||
result = c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=b)
|
||||
check(result["bytes"] == body, "Unicode filename download failed")
|
||||
c.call(
|
||||
"POST",
|
||||
path + quote("\U0001f600" * 256),
|
||||
400,
|
||||
actor=a,
|
||||
raw=body,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
print(
|
||||
"PASS filename code-point limits: 255 ASCII and 255 emoji -> 202 and download 200; 256 emoji -> 400; long Content-Disposition accepted by LB"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,53 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import threading
|
||||
import uuid
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, ready_api, sql
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
limit = int(compose("exec", "-T", "api", "printenv", "MAX_MESSAGES_PER_CHAT"))
|
||||
check(1 <= limit <= 10000, "unexpected test history capacity")
|
||||
sql(
|
||||
"insert into messages(id,chat_id,sender_id,text,created_at) "
|
||||
"select gen_random_uuid(),'" + chat["id"] + "','" + actor["id"] + "','seed',now() "
|
||||
"from generate_series(1," + str(limit - 1) + ");"
|
||||
)
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def send(_):
|
||||
barrier.wait()
|
||||
return client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
[201, 413],
|
||||
actor=actor,
|
||||
body={"text": "last slot", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
instances = {item["headers"].get("X-Instance-Id") for item in responses}
|
||||
check(
|
||||
len(instances) == 2 and None not in instances,
|
||||
"last-slot race did not reach both API replicas",
|
||||
)
|
||||
confirmed = [item for item in responses if item["status"] == 201]
|
||||
rejected = [item for item in responses if item["status"] == 413]
|
||||
check(len(confirmed) == 1 and len(rejected) == 9, "history capacity raced across API replicas")
|
||||
check(
|
||||
int(sql("select count(*) from messages where chat_id='" + chat["id"] + "';")) == limit,
|
||||
"history capacity exceeded in DB",
|
||||
)
|
||||
print(
|
||||
"PASS history last-slot race: 10 simultaneous unique POSTs, exactly 1 committed and 9 rejected with 413; DB count equals configured limit"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,135 @@
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, sql, broker, ready_api, wait_ready, wait_for, metadata, job
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
|
||||
|
||||
def execute(code, data=None):
|
||||
return compose("run", "--rm", "--no-deps", "-T", "pipeline-diagnostics", "-c", code, data=data)
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
c = Client(base_url="https://127.0.0.1:8443", timeout=30)
|
||||
a, b, e, chat = c.bootstrap()
|
||||
protected, original = c.attachment(a, chat)
|
||||
wait_ready(c, a, protected)
|
||||
key = sql("select object_key from attachments where id='" + protected["id"] + "';")
|
||||
status = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"minio",
|
||||
"curl",
|
||||
"-s",
|
||||
"--cacert",
|
||||
"/pki/ca.crt",
|
||||
"-o",
|
||||
"/dev/null",
|
||||
"-w",
|
||||
"%{http_code}",
|
||||
"https://localhost:9000/messenger-attachments/" + key,
|
||||
)
|
||||
check(status == "403", "bucket permits anonymous access")
|
||||
print("PASS anonymous direct S3 GET of existing original returns 403", flush=True)
|
||||
compose("stop", "worker")
|
||||
attachment, _ = c.attachment(a, chat)
|
||||
code = r"""import hashlib,struct,zlib
|
||||
from pipeline.storage import Storage
|
||||
from pipeline.config import Settings
|
||||
from pipeline.repository import Repository
|
||||
s=Settings();storage=Storage(s);repo=Repository(s)
|
||||
def chunk(kind,data):return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff)
|
||||
compressor=zlib.compressobj();parts=[];row=b'\0'+b'\0'*(7000*3)
|
||||
for _ in range(7000):parts.append(compressor.compress(row))
|
||||
parts.append(compressor.flush())
|
||||
data=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',7000,7000,8,2,0,0,0))+chunk(b'IDAT',b''.join(parts))+chunk(b'IEND',b'')
|
||||
with repo.connection() as db:
|
||||
item=db.execute('select staging_key from attachments where id=%s',('ATTACHMENT',)).fetchone()
|
||||
storage.client.put_object(Bucket=s.bucket,Key=item['staging_key'],Body=data,ContentType='image/png')
|
||||
db.execute('update attachments set size_bytes=%s,checksum=%s where id=%s',(len(data),hashlib.sha256(data).hexdigest(),'ATTACHMENT'))
|
||||
print('injected 49-million-pixel complete PNG into trusted staging with matching metadata')
|
||||
""".replace(
|
||||
"ATTACHMENT", attachment["id"]
|
||||
)
|
||||
print(execute(code), flush=True)
|
||||
compose("start", "worker")
|
||||
wait_for(lambda: metadata(c, a, attachment)["status"] == "failed", 60)
|
||||
check(
|
||||
metadata(c, a, attachment)["error_code"] == "invalid_image",
|
||||
"worker pixel guard did not reject",
|
||||
)
|
||||
check(job(attachment)["attempt"] == 1, "permanent pixel error retried")
|
||||
check(
|
||||
sql(
|
||||
"select count(*) from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
== "0",
|
||||
"invalid image published variants",
|
||||
)
|
||||
print(
|
||||
"PASS worker independently rejects >40 million pixels before full decode; FAILED on first attempt",
|
||||
flush=True,
|
||||
)
|
||||
sql(
|
||||
"update attachments set updated_at=now()-interval '2 days' where id='"
|
||||
+ attachment["id"]
|
||||
+ "';"
|
||||
)
|
||||
fresh = "staging/fresh-proof-" + uuid.uuid4().hex
|
||||
code = r"""from pipeline.storage import Storage
|
||||
from pipeline.repository import Repository
|
||||
from pipeline.cleanup import Cleanup
|
||||
from pipeline.config import Settings
|
||||
s=Settings();storage=Storage(s);repo=Repository(s)
|
||||
storage.client.put_object(Bucket=s.bucket,Key='FRESH',Body=b'fresh-proof')
|
||||
Cleanup(repo,storage).run()
|
||||
storage.client.head_object(Bucket=s.bucket,Key='FRESH')
|
||||
print('fresh orphan retained by grace')
|
||||
storage.client.delete_object(Bucket=s.bucket,Key='FRESH')
|
||||
""".replace(
|
||||
"FRESH", fresh
|
||||
)
|
||||
print(execute(code), flush=True)
|
||||
check(
|
||||
metadata(c, a, attachment)["error_code"] == "staging_expired",
|
||||
"expired failed staging retained",
|
||||
)
|
||||
check(
|
||||
sql("select staging_key IS NULL from attachments where id='" + attachment["id"] + "';")
|
||||
== "t",
|
||||
"staging reference retained",
|
||||
)
|
||||
from pipeline_support import COMPOSE
|
||||
|
||||
command = COMPOSE + [
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"pipeline-admin",
|
||||
"replay",
|
||||
attachment["id"],
|
||||
]
|
||||
import subprocess
|
||||
|
||||
response = subprocess.run(command, capture_output=True, text=True, timeout=30)
|
||||
check(
|
||||
response.returncode != 0 and "staging_expired" in response.stderr, "expired replay accepted"
|
||||
)
|
||||
check(metadata(c, a, attachment)["status"] == "failed", "unsafe replay changed status")
|
||||
check(
|
||||
c.call("GET", "/api/v1/attachments/" + protected["id"] + "/content", actor=b)["bytes"]
|
||||
== original,
|
||||
"cleanup deleted referenced original",
|
||||
)
|
||||
print(
|
||||
"PASS expired failed staging cleaned; unsafe replay refused; referenced ready bytes retained",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,168 @@
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
from client import Client, check
|
||||
|
||||
COMPOSE = ["docker", "compose"]
|
||||
|
||||
|
||||
def compose(*args, data=None):
|
||||
result = subprocess.run(
|
||||
COMPOSE + list(args), input=data, text=True, capture_output=True, timeout=120
|
||||
)
|
||||
check(result.returncode == 0, "Compose operator action failed: " + args[0])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-At",
|
||||
data=statement,
|
||||
)
|
||||
|
||||
|
||||
def broker(*args):
|
||||
code = "import json,redis,sys;d=json.load(open('/audit-secrets/operator/credentials.json'));r=redis.Redis(host='broker',username='operator',password=d['broker_operator_password'],ssl=True,ssl_ca_certs='/audit-secrets/public/ca.crt',ssl_certfile='/audit-secrets/operator/service.crt',ssl_keyfile='/audit-secrets/operator/service.key',ssl_check_hostname=True,decode_responses=True);v=r.execute_command(*json.load(sys.stdin));print('PONG' if v is True else json.dumps(v) if isinstance(v,list) else v)"
|
||||
return compose("run", "--rm", "--no-deps", "-T", "audit", "-c", code, data=json.dumps(args))
|
||||
|
||||
|
||||
def wait_for(predicate, timeout=90, message="condition timed out"):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.25)
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
def ready_api():
|
||||
observed = set()
|
||||
|
||||
def probe():
|
||||
try:
|
||||
states = compose("ps", "--format", "{{.Health}}", "api").splitlines()
|
||||
if len(states) != 2 or any(state != "healthy" for state in states):
|
||||
return False
|
||||
response = Client(base_url="https://127.0.0.1:8443").call(
|
||||
"GET", "/health/ready", schema="Health"
|
||||
)
|
||||
observed.add(response["headers"].get("X-Instance-Id"))
|
||||
return len(observed - {None}) == 2
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
wait_for(probe, 120, "API not ready")
|
||||
|
||||
|
||||
def metadata(client, actor, attachment):
|
||||
return client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"], actor=actor, schema="Attachment"
|
||||
)["json"]
|
||||
|
||||
|
||||
def wait_ready(client, actor, attachment, timeout=90):
|
||||
def probe():
|
||||
value = metadata(client, actor, attachment)
|
||||
check(value["status"] != "failed", "attachment failed")
|
||||
return value["status"] == "ready"
|
||||
|
||||
wait_for(probe, timeout, "attachment not ready")
|
||||
return metadata(client, actor, attachment)
|
||||
|
||||
|
||||
def job(attachment):
|
||||
text = sql(
|
||||
"select row_to_json(j) from processing_jobs j where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' order by pipeline_version desc limit 1;"
|
||||
)
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def payload(attachment, version=None):
|
||||
row = job(attachment)
|
||||
text = sql("select payload from processing_outbox where job_id='" + row["job_id"] + "';")
|
||||
value = json.loads(text)
|
||||
if version is not None:
|
||||
value["pipeline_version"] = version
|
||||
return value
|
||||
|
||||
|
||||
def inject_duplicate(value):
|
||||
return broker("XADD", "attachment-jobs", "*", "job", json.dumps(value))
|
||||
|
||||
|
||||
def fault(attachment, point, action, count=1):
|
||||
version = job(attachment)["pipeline_version"]
|
||||
sql(
|
||||
"INSERT INTO pipeline_faults(attachment_id,pipeline_version,point,action,remaining) VALUES ('"
|
||||
+ attachment["id"]
|
||||
+ "',"
|
||||
+ str(version)
|
||||
+ ",'"
|
||||
+ point
|
||||
+ "','"
|
||||
+ action
|
||||
+ "',"
|
||||
+ str(count)
|
||||
+ ");"
|
||||
)
|
||||
|
||||
|
||||
def fault_hit(attachment, point):
|
||||
return (
|
||||
sql(
|
||||
"select coalesce(sum(hits),0) from pipeline_faults where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' and point='"
|
||||
+ point
|
||||
+ "';"
|
||||
)
|
||||
!= "0"
|
||||
)
|
||||
|
||||
|
||||
def operator(action, attachment, version=2):
|
||||
text = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"pipeline-admin",
|
||||
action,
|
||||
attachment["id"],
|
||||
"--version",
|
||||
str(version),
|
||||
)
|
||||
return json.loads(text)
|
||||
|
||||
|
||||
def manifest(attachment):
|
||||
return sql(
|
||||
"select name,object_key,sha256 from attachment_variants where attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' order by pipeline_version,name;"
|
||||
)
|
||||
|
||||
|
||||
def events(attachment, event):
|
||||
return int(
|
||||
sql(
|
||||
"select count(*) from pipeline_events e join processing_jobs j using(job_id) where j.attachment_id='"
|
||||
+ attachment["id"]
|
||||
+ "' and e.event='"
|
||||
+ event
|
||||
+ "';"
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,86 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, check, run
|
||||
from pipeline_support import compose, ready_api, sql, wait_for, wait_ready
|
||||
|
||||
|
||||
def staging_keys():
|
||||
code = """import json
|
||||
from pipeline.config import Settings
|
||||
from pipeline.storage import Storage
|
||||
s=Storage(Settings())
|
||||
print(json.dumps([o['Key'] for p in s.client.get_paginator('list_objects_v2').paginate(Bucket=s.settings.bucket,Prefix='staging/') for o in p.get('Contents',[])]))
|
||||
"""
|
||||
return set(json.loads(compose("exec", "-T", "dispatcher", "python", "-c", code)))
|
||||
|
||||
|
||||
def main():
|
||||
ready_api()
|
||||
client = Client(base_url="https://127.0.0.1:8443", timeout=45)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
filename = "crash-" + uuid.uuid4().hex + ".png"
|
||||
before = staging_keys()
|
||||
sql(
|
||||
"create function proof_upload_crash() returns trigger language plpgsql as $$ begin "
|
||||
"if NEW.filename='"
|
||||
+ filename
|
||||
+ "' then perform pg_sleep(45); end if; return NEW; end; $$; "
|
||||
"create trigger proof_upload_crash before insert on attachments "
|
||||
"for each row execute function proof_upload_crash();"
|
||||
)
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
request = pool.submit(
|
||||
client.call,
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + filename,
|
||||
202,
|
||||
actor=actor,
|
||||
raw=Path("tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
wait_for(
|
||||
lambda: sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")
|
||||
!= "0",
|
||||
15,
|
||||
"upload did not reach S3-before-COMMIT window",
|
||||
)
|
||||
orphan = staging_keys() - before
|
||||
check(len(orphan) == 1, "no staged source before attachment COMMIT")
|
||||
compose("kill", "-s", "SIGKILL", "api")
|
||||
try:
|
||||
request.result(timeout=20)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("killed upload returned a confirmed attachment")
|
||||
check(
|
||||
sql("select count(*) from attachments where filename='" + filename + "';") == "0",
|
||||
"uncommitted attachment survived process death",
|
||||
)
|
||||
for key in orphan:
|
||||
check(
|
||||
sql("select count(*) from attachments where staging_key='" + key + "';") == "0",
|
||||
"orphan unexpectedly referenced",
|
||||
)
|
||||
finally:
|
||||
sql("drop trigger proof_upload_crash on attachments; drop function proof_upload_crash();")
|
||||
compose("start", "api")
|
||||
ready_api()
|
||||
attachment, body = client.attachment(actor, chat)
|
||||
wait_ready(client, actor, attachment)
|
||||
downloaded = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", 200, actor=actor
|
||||
)
|
||||
check(downloaded["bytes"] == body, "upload after API recovery corrupted")
|
||||
print(
|
||||
"PASS SIGKILL after S3 PUT before DB COMMIT: no confirmed response, DB rolled back, staged orphan unreferenced; same session uploads after recovery"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,75 @@
|
||||
import json
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from tls_matrix import BASE, broker, context, deny_http, http
|
||||
|
||||
|
||||
def main():
|
||||
before = json.loads((BASE / "operator/worker-before.json").read_text())
|
||||
assert deny_http("otel-collector", 4318, "/v1/traces", "revoked-worker", "POST", b"{}") in (
|
||||
400,
|
||||
"tls_rejected",
|
||||
)
|
||||
try:
|
||||
assert not broker("revoked-worker")
|
||||
except (ssl.SSLError, ConnectionResetError):
|
||||
pass
|
||||
req = urllib.request.Request(
|
||||
"https://openbao:8200/v1/auth/cert/login",
|
||||
json.dumps({"name": "worker"}).encode(),
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req, context=context("revoked-worker"), timeout=3)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 400 or error.code == 403
|
||||
else:
|
||||
raise AssertionError("Revoked worker authenticated to OpenBao")
|
||||
try:
|
||||
psycopg.connect(
|
||||
host="db",
|
||||
dbname="messenger",
|
||||
user=before["postgres_user"],
|
||||
password=before["postgres_password"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert=str(BASE / "public/ca.crt"),
|
||||
connect_timeout=3,
|
||||
)
|
||||
except psycopg.OperationalError as error:
|
||||
assert "password authentication failed" in str(error)
|
||||
else:
|
||||
raise AssertionError("Old database secret accepted")
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url="https://minio:9000",
|
||||
aws_access_key_id=before["s3_access_key_id"],
|
||||
aws_secret_access_key=before["s3_secret_access_key"],
|
||||
verify=str(BASE / "public/ca.crt"),
|
||||
)
|
||||
try:
|
||||
s3.list_objects_v2(Bucket="messenger-attachments", MaxKeys=1)
|
||||
except ClientError as error:
|
||||
assert error.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
||||
else:
|
||||
raise AssertionError("Disabled S3 credentials accepted")
|
||||
result = {
|
||||
"status": "PASS",
|
||||
"fresh_connections": True,
|
||||
"old_certificate_collector_denied": True,
|
||||
"old_certificate_broker_with_current_password_denied": True,
|
||||
"old_certificate_bao_auth_denied": True,
|
||||
"old_postgres_password_denied": True,
|
||||
"disabled_s3_key_denied": True,
|
||||
"tls_resumption": "gateway tickets and cache disabled",
|
||||
}
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,135 @@
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from argon2 import PasswordHasher
|
||||
from client import Client, check
|
||||
from provision import compose
|
||||
from bootstrap import ROOT, write
|
||||
from security_lifecycle import wait, ready
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-At",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
stdin=statement,
|
||||
).strip()
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt")
|
||||
wait(lambda: ready(client), 120)
|
||||
actor = client.user("passwordproof")
|
||||
basic = base64.b64encode(
|
||||
(actor["registration"]["username"] + ":" + actor["registration"]["password"]).encode()
|
||||
).decode()
|
||||
old = PasswordHasher(
|
||||
time_cost=2, memory_cost=16384, parallelism=1, hash_len=32, salt_len=16
|
||||
).hash(actor["registration"]["password"])
|
||||
sql("UPDATE users SET password_hash='" + old + "' WHERE id='" + actor["id"] + "';")
|
||||
latency = []
|
||||
replicas = set()
|
||||
for _ in range(12):
|
||||
start = time.monotonic()
|
||||
response = client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
schema="Session",
|
||||
)
|
||||
latency.append(1000 * (time.monotonic() - start))
|
||||
replicas.add(response["headers"]["X-Instance-Id"])
|
||||
parameters = sql(
|
||||
"SELECT split_part(password_hash,'$',4) FROM users WHERE id='" + actor["id"] + "';"
|
||||
)
|
||||
check(parameters == "m=19456,t=2,p=1", "Successful login did not upgrade hash")
|
||||
sql(
|
||||
"UPDATE sessions SET expires_at=created_at+interval '1 microsecond' WHERE user_id='"
|
||||
+ actor["id"]
|
||||
+ "';"
|
||||
)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
remaining = 60 - time.time() % 60
|
||||
if remaining < 10:
|
||||
time.sleep(remaining + 0.1)
|
||||
sql("DELETE FROM login_budget;")
|
||||
bad = base64.b64encode(
|
||||
(actor["registration"]["username"] + ":invalid-password").encode()
|
||||
).decode()
|
||||
|
||||
def request(_):
|
||||
local = Client(base_url="https://127.0.0.1:8443", ca_file="secrets/public/ca.crt")
|
||||
r = local.call(
|
||||
"POST", "/api/v1/auth/sessions", (401, 429), headers={"Authorization": "Basic " + bad}
|
||||
)
|
||||
if r["status"] == 429:
|
||||
check(int(r["headers"]["Retry-After"]) >= 1, "Retry-After missing")
|
||||
return r["status"], r["headers"]["X-Instance-Id"]
|
||||
|
||||
start = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
|
||||
values = list(pool.map(request, range(72)))
|
||||
check({r for _, r in values} == replicas and len(replicas) == 2, "Both replicas not exercised")
|
||||
counts = Counter(code for code, _ in values)
|
||||
check(counts[429] >= 12 and counts[401] > 0, "Shared budget did not bound attempts")
|
||||
check(sql("SELECT max(attempts) FROM login_budget;") == "61", "Shared counter did not saturate")
|
||||
result = dict(
|
||||
status="PASS",
|
||||
argon2id=dict(
|
||||
memory_kib=19456,
|
||||
iterations=2,
|
||||
parallelism=1,
|
||||
salt_bytes=16,
|
||||
hash_bytes=32,
|
||||
rehash_on_success=True,
|
||||
),
|
||||
login_measurement=dict(
|
||||
samples=12,
|
||||
end_to_end_ms=dict(
|
||||
p50=round(statistics.median(latency), 3),
|
||||
p95=round(sorted(latency)[math.ceil(0.95 * len(latency)) - 1], 3),
|
||||
),
|
||||
api_cpu_limit=1,
|
||||
api_memory_mib=512,
|
||||
),
|
||||
dos_budget=dict(
|
||||
global_per_minute=60,
|
||||
per_replica_hash_slots=2,
|
||||
replicas=2,
|
||||
max_simultaneous_kdf_memory_mib=76,
|
||||
attempts=72,
|
||||
concurrency=8,
|
||||
duration_seconds=round(time.monotonic() - start, 3),
|
||||
statuses=dict(counts),
|
||||
shared_saturating_counter=61,
|
||||
retry_after=True,
|
||||
),
|
||||
expiry_rejected=True,
|
||||
limitations="fixed global minute window; at a window boundary up to 120 admissions; global protection may deny legitimate users during abuse; latency includes HTTP/TLS/DB",
|
||||
)
|
||||
write(ROOT / "evidence/security-auth.json", json.dumps(result, indent=2) + "\n")
|
||||
sql("DELETE FROM login_budget;")
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
from bootstrap import PRIVATE, ROOT, write
|
||||
from provision import compose
|
||||
|
||||
|
||||
def database_baseline():
|
||||
script = """BEGIN;
|
||||
CREATE ROLE baseline_worker SUPERUSER NOLOGIN;
|
||||
SET LOCAL ROLE baseline_worker;
|
||||
SELECT count(*) FROM users;
|
||||
SELECT count(*) FROM sessions;
|
||||
DELETE FROM messages WHERE false;
|
||||
CREATE TABLE baseline_rollback_probe(id int);
|
||||
ROLLBACK;
|
||||
"""
|
||||
compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
stdin=script,
|
||||
)
|
||||
return dict(
|
||||
isolation="transaction rolled back; NOLOGIN role",
|
||||
read_password_table=True,
|
||||
read_session_table=True,
|
||||
delete_messages_permission=True,
|
||||
ddl=True,
|
||||
)
|
||||
|
||||
|
||||
def broker_baseline():
|
||||
name = "lab7-isolated-broker-" + uuid.uuid4().hex[:8]
|
||||
image = (
|
||||
"redis:7.4-alpine@sha256:8da19c7399dca900c6822a1cf30f9d2285585e2c4b457ff4095b0f4500054d3f"
|
||||
)
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"-d",
|
||||
"--name",
|
||||
name,
|
||||
"--network",
|
||||
"none",
|
||||
"--memory",
|
||||
"64m",
|
||||
"--cpus",
|
||||
"0.2",
|
||||
image,
|
||||
"redis-server",
|
||||
"--bind",
|
||||
"127.0.0.1",
|
||||
"--save",
|
||||
"",
|
||||
"--appendonly",
|
||||
"no",
|
||||
],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
for command in [
|
||||
("SET", "foreign-secret", "synthetic"),
|
||||
("GET", "foreign-secret"),
|
||||
("FLUSHALL",),
|
||||
]:
|
||||
result = (
|
||||
subprocess.check_output(["docker", "exec", name, "redis-cli", *command])
|
||||
.decode()
|
||||
.strip()
|
||||
)
|
||||
assert result in ("OK", "synthetic")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, check=True)
|
||||
return dict(
|
||||
isolation="separate disposable network-none container, no volumes",
|
||||
foreign_keys=True,
|
||||
flush_all=True,
|
||||
)
|
||||
|
||||
|
||||
def s3_baseline():
|
||||
data = json.loads((PRIVATE / "operator/credentials.json").read_text())
|
||||
name = "baseline-" + uuid.uuid4().hex[:8]
|
||||
bucket = "lab7-" + name
|
||||
password = __import__("secrets").token_hex(24)
|
||||
policy = dict(
|
||||
Version="2012-10-17",
|
||||
Statement=[
|
||||
dict(
|
||||
Effect="Allow",
|
||||
Action=["s3:*"],
|
||||
Resource=["arn:aws:s3:::" + bucket, "arn:aws:s3:::" + bucket + "/*"],
|
||||
)
|
||||
],
|
||||
)
|
||||
write(ROOT / "infra/security/policies/baseline-s3.json", json.dumps(policy))
|
||||
prefix = f"set -eu\nmc alias set local https://minio:9000 {data['minio_root_user']} {data['minio_root_password']} >/dev/null\n"
|
||||
setup = (
|
||||
prefix
|
||||
+ f"mc mb local/{bucket} >/dev/null\nmc admin user add local {name} {password} >/dev/null\nmc admin policy create local {name} /policies/baseline-s3.json >/dev/null\nmc admin policy attach local {name} --user {name} >/dev/null\n"
|
||||
)
|
||||
write(
|
||||
PRIVATE / "operator/baseline.json",
|
||||
json.dumps(dict(access=name, secret=password, bucket=bucket)),
|
||||
)
|
||||
try:
|
||||
compose("run", "--rm", "--no-deps", "-T", "s3-admin", stdin=setup)
|
||||
code = "import boto3,json;d=json.load(open('/audit-secrets/operator/baseline.json'));s=boto3.client('s3',endpoint_url='https://minio:9000',aws_access_key_id=d['access'],aws_secret_access_key=d['secret'],verify='/audit-secrets/public/ca.crt');s.put_object(Bucket=d['bucket'],Key='admin/synthetic',Body=b'synthetic');assert s.get_object(Bucket=d['bucket'],Key='admin/synthetic')['Body'].read()==b'synthetic';s.delete_object(Bucket=d['bucket'],Key='admin/synthetic');print('PASS broad prefix operations in disposable bucket')"
|
||||
compose("run", "--rm", "--no-deps", "-T", "audit", "-c", code)
|
||||
finally:
|
||||
cleanup = (
|
||||
prefix
|
||||
+ f"mc admin user rm local {name} >/dev/null\nmc admin policy rm local {name} >/dev/null\nmc rb --force local/{bucket} >/dev/null\n"
|
||||
)
|
||||
compose("run", "--rm", "--no-deps", "-T", "s3-admin", stdin=cleanup)
|
||||
(ROOT / "infra/security/policies/baseline-s3.json").unlink()
|
||||
(PRIVATE / "operator/baseline.json").unlink()
|
||||
return dict(
|
||||
isolation="disposable private bucket and temporary principal",
|
||||
arbitrary_prefix_put_get_delete=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
baseline = dict(database=database_baseline(), broker=broker_baseline(), s3=s3_baseline())
|
||||
script = (ROOT / "student-tests/worker_rights.py").read_bytes()
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "--index", "1", "worker", "python", "-"],
|
||||
input=script,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
restricted = json.loads(result.stdout)
|
||||
output = dict(
|
||||
status="PASS",
|
||||
baseline=baseline,
|
||||
least_privilege=restricted,
|
||||
interpretation="Reproduces broad lab6 permissions in isolated resources; production lab7 privileges are never broadened. Worker can still corrupt pipeline metadata/results, exhaust its processing budget and read image originals; revocation is needed in addition to least privilege.",
|
||||
)
|
||||
write(ROOT / "evidence/worker-compromise.json", json.dumps(output, indent=2) + "\n")
|
||||
print(json.dumps(output, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
from bootstrap import PRIVATE, ROOT, write
|
||||
from capture import private_values
|
||||
from provision import compose
|
||||
|
||||
|
||||
def main():
|
||||
ids = compose("ps", "-q").splitlines()
|
||||
containers = json.loads(subprocess.check_output(["docker", "inspect", *ids]))
|
||||
rows = []
|
||||
for item in containers:
|
||||
role = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
host = item["HostConfig"]
|
||||
assert not host["Privileged"] and host["NetworkMode"] != "host"
|
||||
assert not any("docker.sock" in mount["Destination"] for mount in item["Mounts"])
|
||||
assert host["Memory"] > 0 and (host["NanoCpus"] > 0 or host["CpuQuota"] > 0)
|
||||
ports = host.get("PortBindings") or {}
|
||||
for bindings in ports.values():
|
||||
for binding in bindings or []:
|
||||
assert binding["HostIp"] == "127.0.0.1"
|
||||
if role in ("api", "worker", "dispatcher") or role.endswith("-agent"):
|
||||
uid = (
|
||||
subprocess.check_output(["docker", "exec", item["Id"], "id", "-u"]).decode().strip()
|
||||
)
|
||||
assert uid != "0" and host["ReadonlyRootfs"]
|
||||
assert "ALL" in host["CapDrop"] and "no-new-privileges:true" in host["SecurityOpt"]
|
||||
assert not ports
|
||||
assert not any(
|
||||
"operator" in mount.get("Source", "").replace("\\", "/").split("/")
|
||||
for mount in item["Mounts"]
|
||||
)
|
||||
for value in private_values():
|
||||
assert value not in str(item["Config"]["Env"])
|
||||
rows.append(
|
||||
dict(
|
||||
role=role,
|
||||
container=item["Name"].lstrip("/"),
|
||||
image=item["Image"],
|
||||
user=item["Config"]["User"],
|
||||
read_only=host["ReadonlyRootfs"],
|
||||
cap_drop=host["CapDrop"],
|
||||
security_opt=host["SecurityOpt"],
|
||||
memory_bytes=host["Memory"],
|
||||
nano_cpus=host["NanoCpus"],
|
||||
published=ports,
|
||||
mount_destinations=[m["Destination"] for m in item["Mounts"]],
|
||||
)
|
||||
)
|
||||
assert sum(r["role"] == "api" for r in rows) == 2
|
||||
assert sum(r["role"] == "worker" for r in rows) == 2
|
||||
logs = compose(
|
||||
"logs",
|
||||
"--no-color",
|
||||
"--since",
|
||||
"30m",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"api-agent",
|
||||
"worker-agent",
|
||||
"dispatcher-agent",
|
||||
)
|
||||
assert not any(v in logs for v in private_values())
|
||||
assert "-----BEGIN PRIVATE KEY-----" not in logs
|
||||
paths = ["README.md", "COURSE.md", "CONTRIBUTING.md", "MAINTAINERS.md", "Makefile", "lab.json"]
|
||||
paths += (
|
||||
subprocess.check_output(
|
||||
["git", "ls-tree", "-r", "--name-only", "20afc2c", "tests", "contracts"], cwd=ROOT
|
||||
)
|
||||
.decode()
|
||||
.splitlines()
|
||||
)
|
||||
protected = []
|
||||
for name in paths:
|
||||
if name == "contracts/trust-matrix.md":
|
||||
continue
|
||||
before = subprocess.check_output(["git", "show", "20afc2c:" + name], cwd=ROOT)
|
||||
actual = (ROOT / name).read_bytes()
|
||||
assert before.replace(b"\r\n", b"\n") == actual.replace(b"\r\n", b"\n"), name
|
||||
protected.append(dict(path=name, sha256=hashlib.sha256(actual).hexdigest()))
|
||||
engine = json.loads(
|
||||
subprocess.check_output(["docker", "info", "--format", "{{json .}}"], cwd=ROOT)
|
||||
)
|
||||
inventory = dict(
|
||||
status="PASS",
|
||||
host=dict(
|
||||
platform=platform.platform(),
|
||||
logical_cpus=os.cpu_count(),
|
||||
docker_cpus=engine["NCPU"],
|
||||
docker_memory_bytes=engine["MemTotal"],
|
||||
docker_version=engine["ServerVersion"],
|
||||
),
|
||||
containers=rows,
|
||||
no_private_values_in_environment_or_recent_logs=True,
|
||||
unchanged_contract_and_public_tests=protected,
|
||||
trust_matrix="required student-filled exception",
|
||||
)
|
||||
write(ROOT / "evidence/security-inventory.json", json.dumps(inventory, indent=2) + "\n")
|
||||
print(
|
||||
"PASS actual container hardening, two API and two workers, no published replica ports, scoped mounts, secret-free environments/logs, original contracts and public tests"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,236 @@
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
|
||||
import bootstrap
|
||||
from bootstrap import PRIVATE, ROOT, write
|
||||
from provision import bao, compose, initialize_bao, initialize_db, initialize_s3, prepare
|
||||
from client import Client, check
|
||||
from cryptography import x509
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"db",
|
||||
"psql",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-At",
|
||||
stdin=statement,
|
||||
).strip()
|
||||
|
||||
|
||||
def wait(predicate, timeout=90):
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < timeout:
|
||||
if predicate():
|
||||
return round(time.monotonic() - started, 3)
|
||||
time.sleep(1)
|
||||
raise AssertionError("Recovery deadline exceeded")
|
||||
|
||||
|
||||
def ready(client):
|
||||
try:
|
||||
return client.call("GET", "/health/ready")["status"] == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def identity_images():
|
||||
result = {}
|
||||
for role in ("api", "worker", "dispatcher"):
|
||||
ids = compose("ps", "-a", "-q", role).splitlines()
|
||||
result[role] = sorted(
|
||||
{
|
||||
json.loads(__import__("subprocess").check_output(["docker", "inspect", value]))[0][
|
||||
"Image"
|
||||
]
|
||||
for value in ids
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def minio_disable(identity):
|
||||
operator = json.loads((PRIVATE / "operator/credentials.json").read_text())
|
||||
script = f"set -eu\nmc alias set local https://minio:9000 {operator['minio_root_user']} {operator['minio_root_password']} >/dev/null\nmc admin user disable local {identity} >/dev/null\n"
|
||||
compose("run", "--rm", "--no-deps", "-T", "s3-admin", stdin=script)
|
||||
|
||||
|
||||
def revoke_and_rotate():
|
||||
path = PRIVATE / "operator/credentials.json"
|
||||
data = json.loads(path.read_text())
|
||||
old = data["roles"]["worker"].copy()
|
||||
write(PRIVATE / "operator/worker-before.json", json.dumps(old))
|
||||
shutil.copytree(PRIVATE / "worker", PRIVATE / "revoked-worker", dirs_exist_ok=True)
|
||||
old_cert = x509.load_pem_x509_certificate((PRIVATE / "worker/service.crt").read_bytes())
|
||||
root = json.loads((PRIVATE / "operator/bao-init.json").read_text())["root_token"]
|
||||
bao("auth/cert/certs/worker", token=root, method="DELETE")
|
||||
minio_disable(old["s3_access_key_id"])
|
||||
values = data["roles"]["worker"]
|
||||
values.update(
|
||||
postgres_password=secrets.token_hex(24),
|
||||
s3_access_key_id="worker-" + secrets.token_hex(4),
|
||||
s3_secret_access_key=secrets.token_hex(24),
|
||||
broker_user="worker-" + secrets.token_hex(4),
|
||||
broker_password=secrets.token_hex(24),
|
||||
)
|
||||
write(path, json.dumps(data))
|
||||
initialize_db()
|
||||
sql(
|
||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='worker' AND pid<>pg_backend_pid();"
|
||||
)
|
||||
key, ca = bootstrap.authority()
|
||||
old_crl = x509.load_pem_x509_crl((PRIVATE / "public/ca.crl").read_bytes())
|
||||
serials = {entry.serial_number for entry in old_crl} | {old_cert.serial_number}
|
||||
bootstrap.crl(key, ca, serials)
|
||||
bootstrap.leaf("worker", key, ca)
|
||||
prepare()
|
||||
initialize_s3()
|
||||
bao("auth/cert/crls/lab7", {"crl": (PRIVATE / "public/ca.crl").read_text()}, root)
|
||||
initialize_bao()
|
||||
compose("exec", "-T", "gateway", "nginx", "-s", "reload")
|
||||
compose("restart", "broker")
|
||||
output = compose("run", "--rm", "--no-deps", "-T", "audit", "/checks/revocation_probe.py")
|
||||
result = json.loads(output)
|
||||
check(result["status"] == "PASS", "Old credentials still work")
|
||||
return result
|
||||
|
||||
|
||||
def expiry_probe():
|
||||
key, ca = bootstrap.authority()
|
||||
original = bootstrap.PRIVATE
|
||||
try:
|
||||
bootstrap.PRIVATE = PRIVATE / "operator/expiry"
|
||||
bootstrap.leaf("worker", key, ca, minutes=0)
|
||||
finally:
|
||||
bootstrap.PRIVATE = original
|
||||
shutil.copytree(
|
||||
PRIVATE / "operator/expiry/worker", PRIVATE / "expired-worker", dirs_exist_ok=True
|
||||
)
|
||||
time.sleep(1)
|
||||
command = "import sys;sys.path.insert(0,'/checks');from tls_matrix import deny_http;assert deny_http('otel-collector',4318,'/v1/traces','expired-worker','POST',b'{}') in (400,'tls_rejected');print('PASS expired allowed-role certificate rejected')"
|
||||
return compose("run", "--rm", "--no-deps", "-T", "audit", "-c", command).strip()
|
||||
|
||||
|
||||
def sealed_bao(client, actor):
|
||||
init = json.loads((PRIVATE / "operator/bao-init.json").read_text())
|
||||
started = time.monotonic()
|
||||
bao("sys/seal", {}, init["root_token"])
|
||||
try:
|
||||
elapsed = wait(lambda: not ready(client), 50)
|
||||
client.call("GET", "/health/live")
|
||||
response = client.call("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
check(
|
||||
response["json"]["error"]["code"] == "unavailable",
|
||||
"Expiry must be bounded and explicit",
|
||||
)
|
||||
finally:
|
||||
bao("sys/unseal", {"key": init["keys"][0]})
|
||||
recovery = wait(lambda: ready(client), 30)
|
||||
client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
return dict(
|
||||
readiness_fail_closed_seconds=elapsed,
|
||||
recovery_seconds=recovery,
|
||||
liveness=200,
|
||||
existing_session_survives=True,
|
||||
total_seconds=round(time.monotonic() - started, 3),
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(base_url="https://127.0.0.1:8443", ca_file=str(PRIVATE / "public/ca.crt"))
|
||||
wait(lambda: ready(client), 120)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
before = identity_images()
|
||||
compose("stop", "worker")
|
||||
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
attachments = []
|
||||
for _ in range(10):
|
||||
value = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=security.png",
|
||||
202,
|
||||
actor=actor,
|
||||
raw=png,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(value["status"] == "queued", "Expected durable queued snapshot")
|
||||
attachments.append(value)
|
||||
print("Accepted ten durable jobs before revocation", flush=True)
|
||||
started = time.monotonic()
|
||||
revoked = revoke_and_rotate()
|
||||
expected = json.loads((PRIVATE / "operator/credentials.json").read_text())["roles"]["worker"][
|
||||
"s3_access_key_id"
|
||||
]
|
||||
|
||||
def refreshed():
|
||||
code = (
|
||||
"import json;assert json.load(open('/runtime/secrets.json'))['s3_access_key_id']=='"
|
||||
+ expected
|
||||
+ "'"
|
||||
)
|
||||
try:
|
||||
compose("exec", "-T", "worker-agent", "python", "-c", code)
|
||||
return True
|
||||
except RuntimeError:
|
||||
return False
|
||||
|
||||
wait(refreshed, 30)
|
||||
compose("start", "worker")
|
||||
for attachment in attachments:
|
||||
final = client.wait_ready(actor, attachment)
|
||||
check(len(final["variants"]) == 3, "Variant set not complete")
|
||||
content = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=actor
|
||||
)["bytes"]
|
||||
check(
|
||||
hashlib.sha256(content).digest() == hashlib.sha256(png).digest(),
|
||||
"Confirmed original corrupted",
|
||||
)
|
||||
recovery = round(time.monotonic() - started, 3)
|
||||
check(before == identity_images(), "Rotation rebuilt workload images")
|
||||
ids = ",".join("'" + item["id"] + "'" for item in attachments)
|
||||
rows = sql(
|
||||
"SELECT count(*),count(DISTINCT attachment_id) FROM attachment_variants WHERE attachment_id IN ("
|
||||
+ ids
|
||||
+ ");"
|
||||
)
|
||||
check(rows == "30|10", "Duplicate or missing published effects")
|
||||
expiry = expiry_probe()
|
||||
sealed = sealed_bao(client, actor)
|
||||
result = dict(
|
||||
status="PASS",
|
||||
track=1,
|
||||
confirmed_jobs=10,
|
||||
ready_after_revoke=10,
|
||||
originals_sha256_verified=10,
|
||||
manifest_rows=30,
|
||||
distinct_attachments=10,
|
||||
revocation=revoked,
|
||||
recovery_seconds=recovery,
|
||||
images_unchanged=True,
|
||||
expiry=expiry,
|
||||
sealed_bao=sealed,
|
||||
limitations="single host; in-flight requests finish within their existing operation budgets; static KV credentials require explicit downstream revocation",
|
||||
)
|
||||
write(ROOT / "evidence/security-lifecycle.json", json.dumps(result, indent=2) + "\n")
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
import ssl
|
||||
import base64
|
||||
|
||||
from client import check
|
||||
|
||||
|
||||
GRAFANA = os.getenv("GRAFANA_URL", "https://127.0.0.1:13007")
|
||||
EVIDENCE = Path("evidence")
|
||||
|
||||
|
||||
def fetch(path, **params):
|
||||
suffix = "?" + urlencode(params) if params else ""
|
||||
password = Path("secrets/operator/grafana_password").read_text().strip()
|
||||
auth = base64.b64encode(("admin:" + password).encode()).decode()
|
||||
request = Request(GRAFANA + path + suffix, headers={"Authorization": "Basic " + auth})
|
||||
context = ssl.create_default_context(cafile="secrets/public/ca.crt")
|
||||
with urlopen(request, timeout=8, context=context) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def datasource(name, path, **params):
|
||||
return fetch(f"/api/datasources/proxy/uid/{name}{path}", **params)
|
||||
|
||||
|
||||
def prom(expression):
|
||||
response = datasource("prometheus", "/api/v1/query", query=expression)
|
||||
check(response["status"] == "success", "PromQL query failed")
|
||||
return response["data"]["result"]
|
||||
|
||||
|
||||
def value(expression, default=0.0):
|
||||
values = prom(expression)
|
||||
return float(values[0]["value"][1]) if values else default
|
||||
|
||||
|
||||
def states():
|
||||
return {
|
||||
row["name"]: row["state"]
|
||||
for row in datasource("prometheus", "/api/v1/rules")["data"]["groups"][0]["rules"]
|
||||
}
|
||||
|
||||
|
||||
def logs(query, since=None, limit=100):
|
||||
result = datasource(
|
||||
"loki",
|
||||
"/loki/api/v1/query_range",
|
||||
query=query,
|
||||
start=int((since or time.time() - 180) * 1e9),
|
||||
limit=limit,
|
||||
)
|
||||
return result["data"]["result"]
|
||||
|
||||
|
||||
def spans(trace_id):
|
||||
trace = datasource("tempo", "/api/traces/" + trace_id)
|
||||
return [
|
||||
dict(
|
||||
span,
|
||||
service=next(
|
||||
a["value"]["stringValue"]
|
||||
for a in batch["resource"]["attributes"]
|
||||
if a["key"] == "service.name"
|
||||
),
|
||||
)
|
||||
for batch in trace.get("batches", trace.get("resourceSpans", []))
|
||||
for scope in batch["scopeSpans"]
|
||||
for span in scope["spans"]
|
||||
]
|
||||
|
||||
|
||||
def save(name, data):
|
||||
(EVIDENCE / name).write_text(
|
||||
json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def wait_until(probe, timeout, description):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
result = probe()
|
||||
if result:
|
||||
return result
|
||||
time.sleep(1)
|
||||
raise AssertionError(description)
|
||||
@@ -0,0 +1,168 @@
|
||||
from http.client import HTTPResponse, RemoteDisconnected
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
BASE = Path("/audit-secrets")
|
||||
|
||||
|
||||
def context(role=None, trust=True):
|
||||
ctx = (
|
||||
ssl.create_default_context(cafile=str(BASE / "public/ca.crt"))
|
||||
if trust
|
||||
else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
)
|
||||
if role:
|
||||
ctx.load_cert_chain(str(BASE / role / "service.crt"), str(BASE / role / "service.key"))
|
||||
return ctx
|
||||
|
||||
|
||||
def http(
|
||||
host, port, path, role=None, method="GET", body=b"", trust=True, hostname=None, headers=None
|
||||
):
|
||||
with socket.create_connection((host, port), timeout=4) as raw:
|
||||
with context(role, trust).wrap_socket(raw, server_hostname=hostname or host) as connection:
|
||||
request = (
|
||||
f"{method} {path} HTTP/1.1\r\nHost: {hostname or host}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n".encode()
|
||||
+ body
|
||||
)
|
||||
if headers:
|
||||
extra = "".join(k + ": " + v + "\r\n" for k, v in headers.items()).encode()
|
||||
request = request.replace(b"\r\n\r\n", b"\r\n" + extra + b"\r\n", 1)
|
||||
connection.sendall(request)
|
||||
response = HTTPResponse(connection)
|
||||
response.begin()
|
||||
data = response.read()
|
||||
return response.status, data
|
||||
|
||||
|
||||
def deny_http(*args, **kwargs):
|
||||
try:
|
||||
status, _ = http(*args, **kwargs)
|
||||
except (ssl.SSLError, ConnectionResetError, RemoteDisconnected):
|
||||
return "tls_rejected"
|
||||
assert status in (400, 401, 403), f"Expected identity rejection, received {status}"
|
||||
return status
|
||||
|
||||
|
||||
def broker(role, host="broker", port=6379, identity="worker"):
|
||||
values = json.loads((BASE / "operator/credentials.json").read_text())["roles"][identity]
|
||||
with socket.create_connection((host, port), timeout=4) as raw:
|
||||
with context(role).wrap_socket(raw, server_hostname=host) as connection:
|
||||
username = values["broker_user"] if host == "broker" else "api"
|
||||
password = values["broker_password"] if host == "broker" else values["cache_password"]
|
||||
command = f"AUTH {username} {password}\r\nPING\r\n".encode()
|
||||
connection.sendall(command)
|
||||
result = connection.recv(1024)
|
||||
if b"+OK" in result and b"+PONG" not in result:
|
||||
result += connection.recv(1024)
|
||||
return b"+PONG" in result
|
||||
|
||||
|
||||
def main():
|
||||
result = {}
|
||||
addresses = sorted(
|
||||
{row[4][0] for row in socket.getaddrinfo("api", 8443, type=socket.SOCK_STREAM)}
|
||||
)
|
||||
assert len(addresses) == 2, "Expected two separate API addresses"
|
||||
for index, address in enumerate(addresses):
|
||||
assert http(address, 8443, "/health/ready", "lb", hostname="api")[0] == 200
|
||||
result["api_" + str(index + 1)] = {
|
||||
"valid_lb": 200,
|
||||
"no_certificate": deny_http(address, 8443, "/health/ready", hostname="api"),
|
||||
"wrong_identity_same_ca": deny_http(
|
||||
address, 8443, "/health/ready", "intruder", hostname="api"
|
||||
),
|
||||
"foreign_ca": deny_http(address, 8443, "/health/ready", "foreign", hostname="api"),
|
||||
}
|
||||
for role in ("api", "worker", "dispatcher"):
|
||||
assert http("otel-collector", 4318, "/v1/traces", role, "POST", b"{}")[0] == 200
|
||||
result["collector"] = {
|
||||
"allowed_roles": ["api", "worker", "dispatcher"],
|
||||
"no_certificate": deny_http(
|
||||
"otel-collector", 4318, "/v1/traces", method="POST", body=b"{}"
|
||||
),
|
||||
"wrong_identity_same_ca": deny_http(
|
||||
"otel-collector", 4318, "/v1/traces", "intruder", "POST", b"{}"
|
||||
),
|
||||
"foreign_ca": deny_http("otel-collector", 4318, "/v1/traces", "foreign", "POST", b"{}"),
|
||||
}
|
||||
assert broker("worker")
|
||||
for role in (None, "intruder", "foreign"):
|
||||
try:
|
||||
assert not broker(role), "Unauthorized broker certificate accepted"
|
||||
except (ssl.SSLError, ConnectionResetError):
|
||||
pass
|
||||
result["broker"] = {
|
||||
"valid_worker": True,
|
||||
"no_certificate_denied": True,
|
||||
"foreign_ca_denied": True,
|
||||
"wrong_identity_with_correct_password_denied": True,
|
||||
}
|
||||
for host, port, path, role in [
|
||||
("prometheus", 9090, "/api/v1/status/buildinfo", "grafana"),
|
||||
("loki", 3100, "/ready", "grafana"),
|
||||
("tempo", 3200, "/ready", "grafana"),
|
||||
("otel-collector", 8889, "/metrics", "prometheus"),
|
||||
]:
|
||||
deadline = time.monotonic() + 35
|
||||
status = http(host, port, path, role)[0]
|
||||
while status == 503 and time.monotonic() < deadline:
|
||||
time.sleep(1)
|
||||
status = http(host, port, path, role)[0]
|
||||
assert status == 200, (host, port, status)
|
||||
result[host + ":" + str(port)] = {
|
||||
"allowed": role,
|
||||
"wrong_worker": deny_http(host, port, path, "worker"),
|
||||
"no_certificate": deny_http(host, port, path),
|
||||
}
|
||||
assert broker("api", "redis", 6380, "api")
|
||||
for denied_role in (None, "worker", "foreign"):
|
||||
try:
|
||||
assert not broker(denied_role, "redis", 6380, "api")
|
||||
except (ssl.SSLError, ConnectionResetError):
|
||||
pass
|
||||
result["redis_cache"] = dict(
|
||||
valid_api=True,
|
||||
no_certificate_denied=True,
|
||||
wrong_worker_with_correct_cache_password_denied=True,
|
||||
foreign_ca_denied=True,
|
||||
)
|
||||
import base64
|
||||
|
||||
password = (BASE / "operator/grafana_password").read_text().strip()
|
||||
auth = base64.b64encode(("admin:" + password).encode()).decode()
|
||||
assert http("grafana", 3000, "/api/datasources")[0] == 401
|
||||
assert (
|
||||
http("grafana", 3000, "/api/datasources", headers={"Authorization": "Basic " + auth})[0]
|
||||
== 200
|
||||
)
|
||||
result["grafana_admin"] = dict(anonymous_denied=401, authenticated_tls=200)
|
||||
assert http("openbao", 8200, "/v1/sys/seal-status")[0] == 200
|
||||
assert http("minio", 9000, "/minio/health/ready")[0] == 200
|
||||
for host, port, path in [
|
||||
("lb", 8443, "/health/ready"),
|
||||
("minio", 9000, "/minio/health/ready"),
|
||||
("openbao", 8200, "/v1/sys/seal-status"),
|
||||
]:
|
||||
for kwargs in ({"trust": False}, {"hostname": "untrusted.invalid"}):
|
||||
try:
|
||||
http(host, port, path, **kwargs)
|
||||
except ssl.SSLCertVerificationError:
|
||||
continue
|
||||
raise AssertionError("Server trust verification did not fail")
|
||||
result["server_trust"] = "untrusted CA and hostname rejected on ingress/S3/OpenBao"
|
||||
for port in (16379, 16380, 14318, 19090, 13100, 13200, 18888, 18889, 13000):
|
||||
try:
|
||||
socket.create_connection(("gateway", port), timeout=2).close()
|
||||
except ConnectionRefusedError:
|
||||
continue
|
||||
raise AssertionError("Local plaintext backend externally reachable")
|
||||
result["plaintext_bypass"] = "nine loopback backend ports inaccessible from application network"
|
||||
print(json.dumps({"status": "PASS", "matrix": result}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,178 @@
|
||||
import json
|
||||
import uuid
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
import redis
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
from pipeline.config import credentials
|
||||
|
||||
|
||||
def denied_sql(db, statement):
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute(statement)
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
return True
|
||||
raise AssertionError("Database operation unexpectedly allowed")
|
||||
|
||||
|
||||
def verify_broker_transport():
|
||||
with socket.create_connection(("broker", 6379), timeout=3) as connection:
|
||||
connection.sendall(b"PING\r\n")
|
||||
try:
|
||||
response = connection.recv(64)
|
||||
except ConnectionResetError:
|
||||
response = b""
|
||||
assert response == b"" or response.startswith(b"\x15"), "Plaintext broker command accepted"
|
||||
for trust, hostname in ((False, "broker"), (True, "untrusted.invalid")):
|
||||
context = (
|
||||
ssl.create_default_context(cafile="/pki/ca.crt")
|
||||
if trust
|
||||
else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
)
|
||||
context.load_cert_chain("/identity/service.crt", "/identity/service.key")
|
||||
try:
|
||||
with socket.create_connection(("broker", 6379), timeout=3) as connection:
|
||||
context.wrap_socket(connection, server_hostname=hostname).close()
|
||||
except ssl.SSLCertVerificationError:
|
||||
continue
|
||||
raise AssertionError("Broker certificate verification bypassed")
|
||||
|
||||
|
||||
def main():
|
||||
values = credentials()
|
||||
verify_broker_transport()
|
||||
connection = dict(
|
||||
host="db",
|
||||
dbname="messenger",
|
||||
user=values["postgres_user"],
|
||||
password=values["postgres_password"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert="/pki/ca.crt",
|
||||
connect_timeout=3,
|
||||
)
|
||||
for override, expected in [
|
||||
({"sslmode": "disable"}, "no encryption"),
|
||||
(
|
||||
{"host": "untrusted.invalid", "hostaddr": socket.gethostbyname("db")},
|
||||
"does not match host name",
|
||||
),
|
||||
({"sslrootcert": "/etc/ssl/certs/ca-certificates.crt"}, "certificate verify failed"),
|
||||
]:
|
||||
try:
|
||||
psycopg.connect(**(connection | override))
|
||||
except psycopg.OperationalError as error:
|
||||
assert expected in str(error), type(error).__name__
|
||||
else:
|
||||
raise AssertionError("PostgreSQL TLS boundary bypassed")
|
||||
with psycopg.connect(
|
||||
host="db",
|
||||
dbname="messenger",
|
||||
user=values["postgres_user"],
|
||||
password=values["postgres_password"],
|
||||
sslmode="verify-full",
|
||||
sslrootcert="/pki/ca.crt",
|
||||
connect_timeout=3,
|
||||
) as db:
|
||||
assert db.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone()[0]
|
||||
db.execute("SELECT job_id FROM processing_jobs LIMIT 1")
|
||||
assert denied_sql(db, "SELECT password_hash FROM users LIMIT 1")
|
||||
assert denied_sql(db, "SELECT token_hash FROM sessions LIMIT 1")
|
||||
assert denied_sql(db, "DELETE FROM messages WHERE false")
|
||||
assert denied_sql(db, "CREATE TABLE worker_escape_probe(id int)")
|
||||
assert denied_sql(db, "ALTER ROLE worker SUPERUSER")
|
||||
assert denied_sql(db, "SELECT chat_id,owner_id FROM attachments LIMIT 1")
|
||||
assert denied_sql(db, "UPDATE attachments SET chat_id=chat_id WHERE false")
|
||||
queue = redis.Redis(
|
||||
host="broker",
|
||||
username=values["broker_user"],
|
||||
password=values["broker_password"],
|
||||
ssl=True,
|
||||
ssl_ca_certs="/pki/ca.crt",
|
||||
ssl_certfile="/identity/service.crt",
|
||||
ssl_keyfile="/identity/service.key",
|
||||
ssl_check_hostname=True,
|
||||
socket_timeout=3,
|
||||
)
|
||||
assert queue.ping()
|
||||
assert queue.hget("job-publications", "security-probe-nonexistent") is None
|
||||
for operation in [
|
||||
lambda: queue.flushall(),
|
||||
lambda: queue.get("foreign-secret"),
|
||||
lambda: queue.xadd("attachment-jobs", {"security-probe": "denied"}),
|
||||
]:
|
||||
try:
|
||||
operation()
|
||||
except redis.exceptions.NoPermissionError:
|
||||
continue
|
||||
raise AssertionError("Broker operation unexpectedly allowed")
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url="https://minio:9000",
|
||||
aws_access_key_id=values["s3_access_key_id"],
|
||||
aws_secret_access_key=values["s3_secret_access_key"],
|
||||
verify="/pki/ca.crt",
|
||||
)
|
||||
key = "results/security-probe-" + uuid.uuid4().hex
|
||||
s3.put_object(Bucket="messenger-attachments", Key=key, Body=b"synthetic")
|
||||
assert s3.get_object(Bucket="messenger-attachments", Key=key)["Body"].read() == b"synthetic"
|
||||
for operation in [
|
||||
lambda: s3.put_object(
|
||||
Bucket="messenger-attachments", Key="admin/forbidden", Body=b"synthetic"
|
||||
),
|
||||
lambda: s3.delete_object(Bucket="messenger-attachments", Key=key),
|
||||
lambda: s3.create_bucket(Bucket="worker-escape-probe-forbidden"),
|
||||
lambda: s3.list_objects_v2(Bucket="messenger-attachments", Prefix="admin/"),
|
||||
]:
|
||||
try:
|
||||
operation()
|
||||
except ClientError as error:
|
||||
assert error.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
||||
continue
|
||||
raise AssertionError("S3 operation unexpectedly allowed")
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
status="PASS",
|
||||
identity=values["postgres_user"],
|
||||
database=dict(
|
||||
tls=True,
|
||||
plaintext_denied=True,
|
||||
wrong_hostname_denied=True,
|
||||
foreign_ca_denied=True,
|
||||
read_jobs=True,
|
||||
users_denied=True,
|
||||
sessions_denied=True,
|
||||
message_delete_denied=True,
|
||||
ddl_denied=True,
|
||||
superuser_denied=True,
|
||||
ownership_columns_denied=True,
|
||||
),
|
||||
broker=dict(
|
||||
mtls=True,
|
||||
plaintext_denied=True,
|
||||
wrong_hostname_denied=True,
|
||||
foreign_ca_denied=True,
|
||||
read_index=True,
|
||||
flush_denied=True,
|
||||
foreign_key_denied=True,
|
||||
producer_denied=True,
|
||||
),
|
||||
s3=dict(
|
||||
results_put_get=True,
|
||||
admin_prefix_denied=True,
|
||||
result_delete_denied=True,
|
||||
bucket_admin_denied=True,
|
||||
prefix_enumeration_denied=True,
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user