forked from mtusi2026/mtusi2026lab7
340 lines
12 KiB
Python
340 lines
12 KiB
Python
"""Measured PKI lifecycle under bounded public HTTPS message/upload load."""
|
|
|
|
import argparse
|
|
import csv
|
|
import json
|
|
import socket
|
|
import ssl
|
|
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
|
|
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()
|
|
|
|
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 = 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_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 = 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_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}
|
|
deadline = time.monotonic() + 120
|
|
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)
|
|
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"
|
|
)
|
|
report["complete"] = True
|
|
except BaseException as error:
|
|
report["failure_type"] = type(error).__name__
|
|
raise
|
|
finally:
|
|
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
|
|
save()
|
|
if lb_stopped:
|
|
compose("up", "-d", "--no-deps", "identity-lb")
|
|
if bao_sealed:
|
|
pki.recover_bao()
|
|
print(
|
|
"PASS: measured renewal, working-key/leaf rotation, revocation, expiry, seal recovery and CA rollover"
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|