forked from mtusi2026/mtusi2026lab7
Выполнить лабораторную 7 по безопасности мессенджера
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
"""Measure secure ingress rollover and lease expiry under a fixed local load."""
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT), str(ROOT / "tests")]
|
||||
from client import Client
|
||||
from scripts.operator import administrative_bao, operator_credentials, settings, unseal
|
||||
from scripts.pki import SECRETS, renew_edge
|
||||
|
||||
TRUST = SECRETS / "trust"
|
||||
RATE = 8
|
||||
WORKERS = 24
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, port, token):
|
||||
self.port = port
|
||||
self.token = token
|
||||
self.points = []
|
||||
self.pending = threading.BoundedSemaphore(WORKERS)
|
||||
self.stop = threading.Event()
|
||||
self.thread = threading.Thread(target=self.pump)
|
||||
|
||||
def sample(self, ca=None):
|
||||
started = time.monotonic()
|
||||
connection = None
|
||||
try:
|
||||
tls = ssl.create_default_context(cafile=str(ca or TRUST / "edge.crt"))
|
||||
connection = http.client.HTTPSConnection("localhost", self.port, context=tls, timeout=1.5)
|
||||
connection.request("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + self.token})
|
||||
with connection.getresponse() as response:
|
||||
response.read()
|
||||
result = str(response.status)
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
result = "expired_certificate" if exc.verify_code == 10 else "untrusted_certificate"
|
||||
except (OSError, http.client.HTTPException):
|
||||
result = "connection_error"
|
||||
finally:
|
||||
if connection:
|
||||
connection.close()
|
||||
return started, result, (time.monotonic() - started) * 1000
|
||||
|
||||
def request(self):
|
||||
try:
|
||||
self.points.append(self.sample())
|
||||
finally:
|
||||
self.pending.release()
|
||||
|
||||
def pump(self):
|
||||
with ThreadPoolExecutor(WORKERS) as pool:
|
||||
deadline = time.monotonic()
|
||||
while not self.stop.is_set():
|
||||
if self.pending.acquire(blocking=False):
|
||||
pool.submit(self.request)
|
||||
else:
|
||||
self.points.append((time.monotonic(), "client_queue_full", 0))
|
||||
deadline += 1 / RATE
|
||||
self.stop.wait(max(0, deadline - time.monotonic()))
|
||||
|
||||
def wait(self, expected, since, timeout):
|
||||
until = time.monotonic() + timeout
|
||||
while time.monotonic() < until:
|
||||
matches = [tick for tick, status, _ in self.points if tick >= since and status == expected]
|
||||
if matches:
|
||||
return round(min(matches) - since, 3)
|
||||
time.sleep(0.08)
|
||||
raise AssertionError(f"Timed out waiting for {expected}")
|
||||
|
||||
def summarize(self, start, end):
|
||||
points = [(status, elapsed) for tick, status, elapsed in self.points if start <= tick < end]
|
||||
status = Counter(status for status, _ in points)
|
||||
timings = sorted(duration for code, duration in points if code == "200")
|
||||
percentiles = ([round(timings[round((len(timings) - 1) * percentile)], 2)
|
||||
for percentile in (0.50, 0.95, 0.99)] if timings else [])
|
||||
return {"seconds": round(end - start, 3), "counts": dict(status),
|
||||
"success_rps": round(status["200"] / (end - start), 2),
|
||||
"error_pct": round(100 * (len(points) - status["200"]) / max(len(points), 1), 2),
|
||||
"success_p50_p95_p99_ms": percentiles}
|
||||
|
||||
|
||||
def pki(*arguments):
|
||||
subprocess.run([sys.executable, "scripts/pki.py", *arguments], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def run_experiment():
|
||||
port = int(settings().get("HTTPS_PORT", 8443))
|
||||
bao = administrative_bao()
|
||||
admin = operator_credentials()["root_token"]
|
||||
# Starting at A makes the experiment repeatable after a prior successful A → B rollover.
|
||||
pki("edge-trust", "edge-a")
|
||||
pki("edge-issue", "edge-a", "--reload")
|
||||
pki("edge-retire", "edge-a")
|
||||
client = Client(f"https://localhost:{port}", str(TRUST / "edge.crt"))
|
||||
time.sleep(3)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "PKI lifecycle synthetic checkpoint")["json"]["id"]
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
load = Load(port, alice["token"])
|
||||
load.thread.start()
|
||||
warmup = time.monotonic()
|
||||
phases = {}
|
||||
report = {"offered_rps": RATE, "max_concurrency": WORKERS, "phase": {}}
|
||||
try:
|
||||
# Keep the effects of the setup reload visible, outside the control window.
|
||||
time.sleep(10)
|
||||
start = time.monotonic()
|
||||
phases["warmup"] = (warmup, start)
|
||||
time.sleep(8)
|
||||
phases["baseline"] = (start, time.monotonic())
|
||||
|
||||
overlap = time.monotonic()
|
||||
pki("edge-trust", "edge-b")
|
||||
pki("edge-issue", "edge-b", "--lifetime", "16", "--reload")
|
||||
time.sleep(3)
|
||||
assert load.sample(TRUST / "edge-a.crt")[1] == "untrusted_certificate"
|
||||
assert load.sample(TRUST / "edge-b.crt")[1] == "200"
|
||||
pki("edge-retire", "edge-b")
|
||||
report["old_ca_only"] = "denied"
|
||||
time.sleep(3)
|
||||
phases["trust_overlap_and_cutover"] = (overlap, time.monotonic())
|
||||
|
||||
expiry_start = time.monotonic()
|
||||
report["expired_detected_after_s"] = load.wait("expired_certificate", expiry_start, 25)
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=1.5) as plain:
|
||||
plain.sendall(b"GET /health/live HTTP/1.0\r\nHost: localhost\r\n\r\n")
|
||||
try:
|
||||
assert b" 200 " not in plain.recv(256)
|
||||
except (ConnectionResetError, TimeoutError):
|
||||
pass
|
||||
report["plaintext_after_expiry"] = "denied"
|
||||
time.sleep(3)
|
||||
phases["short_leaf_expiry"] = (expiry_start, time.monotonic())
|
||||
recovery = time.monotonic()
|
||||
assert renew_edge("edge-b", 86400, 1800, True)
|
||||
report["leaf_recovery_after_s"] = load.wait("200", recovery, 15)
|
||||
time.sleep(5)
|
||||
phases["leaf_renewal"] = (recovery, time.monotonic())
|
||||
|
||||
outage = time.monotonic()
|
||||
bao.request("sys/seal", {}, admin, method="PUT")
|
||||
report["sealed_to_first_503_s"] = load.wait("503", outage, 65)
|
||||
time.sleep(3)
|
||||
phases["sealed_bao"] = (outage, time.monotonic())
|
||||
|
||||
recovery = time.monotonic()
|
||||
unseal(bao)
|
||||
report["unseal_to_first_200_s"] = load.wait("200", recovery, 45)
|
||||
time.sleep(7)
|
||||
phases["lease_recovery"] = (recovery, time.monotonic())
|
||||
client = Client(f"https://localhost:{port}", str(TRUST / "edge.crt"))
|
||||
response = client.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=alice, schema="MessagePage")
|
||||
assert original in {item["id"] for item in response["json"]["items"]}
|
||||
client.wait_ready(alice, attachment)
|
||||
retrieved = client.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=alice)
|
||||
assert retrieved["bytes"] == content
|
||||
report["previous_session_message_and_attachment"] = "verified"
|
||||
finally:
|
||||
load.stop.set()
|
||||
load.thread.join(timeout=5)
|
||||
if bao.request("sys/seal-status")["sealed"]:
|
||||
unseal(bao)
|
||||
pki("edge-trust", "edge-b")
|
||||
renew_edge("edge-b", 86400, 1800, True)
|
||||
|
||||
report["phase"] = {name: load.summarize(*interval) for name, interval in phases.items()}
|
||||
print(json.dumps(report, indent=2, ensure_ascii=False))
|
||||
for phase in report["phase"].values():
|
||||
assert "client_queue_full" not in phase["counts"], "load generator saturated"
|
||||
assert report["phase"]["short_leaf_expiry"]["counts"]["expired_certificate"] > 0
|
||||
assert report["phase"]["sealed_bao"]["counts"]["503"] > 0
|
||||
assert report["phase"]["baseline"]["error_pct"] == 0, "control window returned errors"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_experiment()
|
||||
Reference in New Issue
Block a user