forked from mtusi2026/mtusi2026lab7
481 lines
18 KiB
Python
481 lines
18 KiB
Python
"""Measured PKI lifecycle under bounded public HTTPS message/upload load."""
|
|
|
|
import argparse
|
|
import csv
|
|
import json
|
|
import math
|
|
import socket
|
|
import ssl
|
|
import threading
|
|
import time
|
|
from collections import Counter
|
|
from datetime import UTC, datetime
|
|
from urllib.parse import urlsplit
|
|
|
|
import httpx
|
|
|
|
from scripts import pki
|
|
from scripts.bao_operator import Operator
|
|
from scripts.bootstrap_security import TRUST
|
|
from scripts.credentials import repair, rotate_s3
|
|
from scripts.research_slo import Workload
|
|
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
|
from scripts.tls_client import FreshTrustTransport
|
|
|
|
|
|
def images():
|
|
ids = compose("ps", "-q").split()
|
|
return {
|
|
c["Name"]: c["Image"]
|
|
for c in json.loads(command(["docker", "inspect", *ids]))
|
|
}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--output", default="evidence/pki-research-first.json")
|
|
args = parser.parse_args()
|
|
output = ROOT / args.output
|
|
assert not output.exists(), "Choose a new receipt path"
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
report = {
|
|
"date": datetime.now(UTC).isoformat(),
|
|
"source_commit": command(["git", "rev-parse", "HEAD"]),
|
|
"complete": False,
|
|
"profile": {
|
|
"messages_per_second": 4,
|
|
"upload_every_seconds": 5,
|
|
"max_inflight": 16,
|
|
},
|
|
"phases": [],
|
|
}
|
|
started = time.time()
|
|
load = None
|
|
resource_stop = threading.Event()
|
|
resource_thread = None
|
|
lb_stopped = False
|
|
bao_sealed = False
|
|
with httpx.Client(
|
|
base_url=BASE,
|
|
transport=FreshTrustTransport(),
|
|
timeout=8,
|
|
trust_env=False,
|
|
) as client:
|
|
|
|
def save():
|
|
report["elapsed_seconds"] = round(time.time() - started, 3)
|
|
output.write_text(
|
|
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
|
)
|
|
|
|
def phase(name, action):
|
|
load.phase = name
|
|
entry = {"name": name, "started_at": time.time()}
|
|
report["phases"].append(entry)
|
|
save()
|
|
try:
|
|
entry["result"] = action()
|
|
finally:
|
|
entry["ended_at"] = time.time()
|
|
entry["seconds"] = round(
|
|
entry["ended_at"] - entry["started_at"], 3
|
|
)
|
|
save()
|
|
|
|
try:
|
|
ready(timeout=90)
|
|
report["images_before"] = images()
|
|
user, _, session = actor(client)
|
|
headers = auth(session)
|
|
r = client.post(
|
|
"/api/v1/chats",
|
|
headers=headers,
|
|
json={"title": "PKI lifecycle", "member_ids": [user["id"]]},
|
|
)
|
|
assert r.status_code == 201
|
|
chat = r.json()["id"]
|
|
load = Workload(client, headers, chat)
|
|
load.start()
|
|
resource_ids = compose(
|
|
"ps", "-q", "api", "worker", "otel", "openbao"
|
|
).split()
|
|
report["resource_limits"] = [
|
|
{
|
|
"role": info["Config"]["Labels"][
|
|
"com.docker.compose.service"
|
|
],
|
|
"container": info["Name"],
|
|
"cpu_nano": info["HostConfig"]["NanoCpus"],
|
|
"memory_bytes": info["HostConfig"]["Memory"],
|
|
}
|
|
for info in json.loads(
|
|
command(["docker", "inspect", *resource_ids])
|
|
)
|
|
]
|
|
report["resource_measurement"] = (
|
|
"Docker stats snapshots: 15-second delay plus command duration; "
|
|
"CPU 100% is one core; memory is sampled usage, not an absolute peak"
|
|
)
|
|
report["resource_samples"] = []
|
|
|
|
def sample_resources():
|
|
while not resource_stop.is_set():
|
|
began = time.time()
|
|
phase = load.phase
|
|
try:
|
|
raw = command(
|
|
[
|
|
"docker",
|
|
"stats",
|
|
"--no-stream",
|
|
"--format",
|
|
"json",
|
|
*resource_ids,
|
|
]
|
|
)
|
|
observations = [
|
|
json.loads(line) for line in raw.splitlines()
|
|
]
|
|
report["resource_samples"].append(
|
|
{
|
|
"started_at": began,
|
|
"ended_at": time.time(),
|
|
"phase": phase,
|
|
"containers": observations,
|
|
}
|
|
)
|
|
except Exception as error:
|
|
report.setdefault(
|
|
"resource_sampling_errors", []
|
|
).append(
|
|
{
|
|
"at": began,
|
|
"error_type": type(error).__name__,
|
|
}
|
|
)
|
|
resource_stop.wait(15)
|
|
|
|
resource_thread = threading.Thread(target=sample_resources)
|
|
resource_thread.start()
|
|
|
|
def renewal():
|
|
before = pki.metadata()
|
|
time.sleep(100)
|
|
after = pki.metadata()
|
|
roles = set(before) - {"migrate"}
|
|
assert roles and all(
|
|
before[r]["serial"] != after[r]["serial"] for r in roles
|
|
)
|
|
events = compose(
|
|
"logs",
|
|
"--no-color",
|
|
"--since",
|
|
datetime.fromtimestamp(started, UTC).isoformat(),
|
|
"identity-api",
|
|
)
|
|
assert '"event":"identity.token_renewed"' in events
|
|
return {
|
|
"before": before,
|
|
"after": after,
|
|
"all_active_serials_changed": True,
|
|
"api_token_renewed": True,
|
|
}
|
|
|
|
phase("automatic_renewal", renewal)
|
|
|
|
def secret_rotation():
|
|
operator = Operator()
|
|
try:
|
|
return rotate_s3(operator)
|
|
finally:
|
|
operator.close()
|
|
|
|
phase("working_s3_key_rotation", secret_rotation)
|
|
|
|
def revocation():
|
|
operator = Operator()
|
|
try:
|
|
repair(operator, "lb")
|
|
old = pki.preserve_lb()
|
|
repair(operator, "lb")
|
|
pki.fixture_check("lb")
|
|
return pki.revoke(operator, old)
|
|
finally:
|
|
operator.close()
|
|
|
|
phase("leaf_reissue_and_revocation", revocation)
|
|
|
|
def expiry():
|
|
nonlocal lb_stopped
|
|
compose("stop", "identity-lb")
|
|
lb_stopped = True
|
|
leaf = pki.metadata()["lb"]
|
|
wait_seconds = max(0, leaf["expires_at"] - time.time() + 3)
|
|
time.sleep(wait_seconds)
|
|
target = urlsplit(BASE)
|
|
context = ssl.create_default_context(cafile=TRUST / "ca.pem")
|
|
try:
|
|
with socket.create_connection(
|
|
(target.hostname, target.port), timeout=5
|
|
) as raw:
|
|
with context.wrap_socket(
|
|
raw, server_hostname=target.hostname
|
|
):
|
|
pass
|
|
except ssl.SSLCertVerificationError as error:
|
|
assert error.verify_code == 10, (
|
|
"Expected expired certificate"
|
|
)
|
|
else:
|
|
raise AssertionError(
|
|
"Expired server certificate was accepted"
|
|
)
|
|
recovery_started_at = time.time()
|
|
recovery = time.monotonic()
|
|
operator = Operator()
|
|
try:
|
|
repair(operator, "lb")
|
|
finally:
|
|
operator.close()
|
|
compose("up", "-d", "--no-deps", "identity-lb")
|
|
lb_stopped = False
|
|
ready(timeout=60)
|
|
return {
|
|
"leaf": leaf,
|
|
"waited_seconds": round(wait_seconds, 3),
|
|
"expired_certificate_verified_denied": True,
|
|
"recovery_started_at": recovery_started_at,
|
|
"recovery_ready_at": time.time(),
|
|
"recovery_seconds": round(time.monotonic() - recovery, 3),
|
|
}
|
|
|
|
phase("expiry_without_plaintext_fallback", expiry)
|
|
|
|
def sealed():
|
|
nonlocal bao_sealed
|
|
operator = Operator()
|
|
try:
|
|
operator.authorized("POST", "sys/seal", {})
|
|
bao_sealed = True
|
|
finally:
|
|
operator.close()
|
|
time.sleep(70)
|
|
status, error_type = None, None
|
|
try:
|
|
status = client.get(
|
|
"/api/v1/users/me", headers=headers
|
|
).status_code
|
|
assert status == 503, (
|
|
"Expired secret snapshot must fail closed"
|
|
)
|
|
except httpx.HTTPError as error:
|
|
error_type = type(error).__name__
|
|
recovery_started_at = time.time()
|
|
recovery = time.monotonic()
|
|
pki.recover_bao()
|
|
bao_sealed = False
|
|
ready(timeout=120)
|
|
return {
|
|
"sealed_seconds": 70,
|
|
"status_after_secret_expiry": status,
|
|
"tls_transport_failure": error_type,
|
|
"recovery_started_at": recovery_started_at,
|
|
"recovery_ready_at": time.time(),
|
|
"recovery_seconds": round(time.monotonic() - recovery, 3),
|
|
"explicit_operator_recovery": True,
|
|
}
|
|
|
|
phase("sealed_openbao_bounded_cache", sealed)
|
|
phase("dual_trust_ca_rollover", pki.rollover)
|
|
phase("recovered_steady", lambda: time.sleep(30))
|
|
load.close()
|
|
load.stop.set()
|
|
# Preserve every observed acknowledgement; ambiguous requests are
|
|
# counted separately and never presented as acknowledged writes.
|
|
messages = {row[5] for row in load.requests if row[2] == 201}
|
|
found, cursor = set(), None
|
|
while True:
|
|
r = client.get(
|
|
f"/api/v1/chats/{chat}/messages",
|
|
headers=headers,
|
|
params={
|
|
"limit": 100,
|
|
**({"cursor": cursor} if cursor else {}),
|
|
},
|
|
)
|
|
assert r.status_code == 200
|
|
page = r.json()
|
|
found.update(item["id"] for item in page["items"])
|
|
cursor = page["next_cursor"]
|
|
if not cursor:
|
|
break
|
|
assert messages <= found
|
|
accepted = [row for row in load.uploads if row[2] == 202]
|
|
pending = {row[3] for row in accepted}
|
|
drain_started = time.monotonic()
|
|
# Expiry/seal can accumulate work and duplicate wakeups. Allow a
|
|
# bounded drain window for this backlog; every accepted upload must
|
|
# still reach ready, without resetting its durable state.
|
|
report["drain"] = {
|
|
"maximum_seconds": 600,
|
|
"accepted_uploads": len(accepted),
|
|
"initial_pending_to_check": len(pending),
|
|
}
|
|
deadline = drain_started + 600
|
|
failed = set()
|
|
while pending and time.monotonic() < deadline:
|
|
for identity in list(pending):
|
|
r = client.get(
|
|
"/api/v1/attachments/" + identity, headers=headers
|
|
)
|
|
assert r.status_code == 200
|
|
state = r.json()["status"]
|
|
if state == "ready":
|
|
pending.remove(identity)
|
|
elif state == "failed":
|
|
failed.add(identity)
|
|
if failed:
|
|
# Replay is an explicit audited operator action after the
|
|
# seal experiment; never change DB job state directly.
|
|
from scripts.operator_task import run
|
|
|
|
for identity in failed:
|
|
from scripts.stand import sql
|
|
|
|
job = sql(
|
|
"SELECT id FROM jobs WHERE attachment_id='"
|
|
+ identity
|
|
+ "' ORDER BY pipeline_version DESC LIMIT 1"
|
|
)
|
|
run(
|
|
"replay",
|
|
"--job-id",
|
|
job,
|
|
"--operator",
|
|
"synthetic-research",
|
|
"--reason",
|
|
"PKI research recovery after controlled seal",
|
|
)
|
|
failed.clear()
|
|
time.sleep(1)
|
|
report["drain"].update(
|
|
elapsed_seconds=round(time.monotonic() - drain_started, 3),
|
|
remaining=len(pending),
|
|
)
|
|
assert not pending, "Accepted upload not ready after recovery"
|
|
for row in accepted[:: max(1, len(accepted) // 5)]:
|
|
r = client.get(
|
|
"/api/v1/attachments/" + row[3] + "/content",
|
|
headers=headers,
|
|
)
|
|
assert r.status_code == 200 and r.content == load.raw
|
|
report["preservation"] = {
|
|
"acknowledged_messages": len(messages),
|
|
"accepted_uploads": len(accepted),
|
|
"all_acknowledged_messages_present": True,
|
|
"all_accepted_uploads_ready": True,
|
|
"sampled_original_bytes_unchanged": True,
|
|
}
|
|
report["images_after"] = images()
|
|
assert report["images_before"] == report["images_after"], (
|
|
"Lifecycle must not rebuild/replace images"
|
|
)
|
|
assert report["resource_samples"], "No measured CPU/RAM samples"
|
|
report["complete"] = True
|
|
except BaseException as error:
|
|
report["failure_type"] = type(error).__name__
|
|
raise
|
|
finally:
|
|
resource_stop.set()
|
|
if resource_thread is not None:
|
|
resource_thread.join(15)
|
|
if resource_thread.is_alive():
|
|
report["resource_sampler_did_not_stop"] = True
|
|
if load is not None:
|
|
load.close()
|
|
report["request_statuses"] = dict(
|
|
Counter(str(row[2]) for row in load.requests)
|
|
)
|
|
report["upload_statuses"] = dict(
|
|
Counter(str(row[2]) for row in load.uploads)
|
|
)
|
|
with output.with_name(output.stem + "-requests.csv").open(
|
|
"w"
|
|
) as stream:
|
|
writer = csv.writer(stream)
|
|
writer.writerow(
|
|
[
|
|
"started_at",
|
|
"phase",
|
|
"status",
|
|
"duration_seconds",
|
|
"trace_id",
|
|
"message_id",
|
|
]
|
|
)
|
|
writer.writerows(load.requests)
|
|
report["uploads"] = load.uploads
|
|
if load is not None:
|
|
for entry in report["phases"]:
|
|
ended = entry.get("ended_at", time.time())
|
|
rows = [
|
|
r
|
|
for r in load.requests
|
|
if entry["started_at"] <= r[0] < ended
|
|
]
|
|
latencies = sorted(r[3] for r in rows if r[2] == 201)
|
|
entry["measured_requests"] = {
|
|
"count": len(rows),
|
|
"statuses": dict(Counter(str(r[2]) for r in rows)),
|
|
"failed_http_or_transport": sum(
|
|
r[2] not in {201, -1} for r in rows
|
|
),
|
|
"client_backpressure_drops": sum(
|
|
r[2] == -1 for r in rows
|
|
),
|
|
"successful_p95_seconds": latencies[
|
|
math.ceil(0.95 * len(latencies)) - 1
|
|
]
|
|
if latencies
|
|
else None,
|
|
}
|
|
result = entry.get("result")
|
|
if (
|
|
isinstance(result, dict)
|
|
and "recovery_started_at" in result
|
|
):
|
|
recovery = result["recovery_started_at"]
|
|
ends = [
|
|
r[0] + r[3]
|
|
for r in load.requests
|
|
if r[2] == 201 and r[0] >= recovery
|
|
]
|
|
result[
|
|
"first_observed_business_write_after_recovery_start_seconds"
|
|
] = round(min(ends) - recovery, 6) if ends else None
|
|
save()
|
|
try:
|
|
if bao_sealed:
|
|
pki.recover_bao()
|
|
if lb_stopped:
|
|
operator = Operator()
|
|
try:
|
|
repair(operator, "lb")
|
|
finally:
|
|
operator.close()
|
|
compose("up", "-d", "--no-deps", "identity-lb")
|
|
except Exception as cleanup_error:
|
|
report["recovery_cleanup_error_type"] = type(
|
|
cleanup_error
|
|
).__name__
|
|
save()
|
|
if report["complete"]:
|
|
raise
|
|
print(
|
|
"PASS: measured renewal, working-key/leaf rotation, revocation, expiry, seal recovery and CA rollover"
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|