forked from mtusi2026/mtusi2026lab7
90 lines
4.1 KiB
Python
90 lines
4.1 KiB
Python
import argparse
|
|
import concurrent.futures
|
|
import json
|
|
import os
|
|
import ssl
|
|
import statistics
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
|
|
def _single_login_attempt(url: str, ssl_ctx: ssl.SSLContext, username: str, password: str, timeout: float) -> tuple[int, float]:
|
|
body = json.dumps({"username": username, "password": password}).encode("utf-8")
|
|
req = urllib.request.Request(
|
|
url,
|
|
data=body,
|
|
headers={"Content-Type": "application/json"},
|
|
method="POST",
|
|
)
|
|
t0 = time.perf_counter()
|
|
try:
|
|
with urllib.request.urlopen(req, context=ssl_ctx, timeout=timeout) as resp:
|
|
status = resp.status
|
|
except urllib.error.HTTPError as exc:
|
|
status = exc.code
|
|
except (urllib.error.URLError, ssl.SSLError, OSError):
|
|
status = 0
|
|
elapsed_ms = (time.perf_counter() - t0) * 1000.0
|
|
return status, elapsed_ms
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Measure login endpoint latency, throughput, and 429 rate-limit behavior.")
|
|
parser.add_argument("--url", default=os.getenv("LOGIN_URL", "https://localhost:8443/api/v1/auth/sessions"))
|
|
parser.add_argument("--ca-file", default=os.getenv("CA_FILE", "./infra/certs/ca.crt"))
|
|
parser.add_argument("--username", default=os.getenv("TEST_LOGIN_USER", "nonexistent_user"))
|
|
parser.add_argument("--password", default=os.getenv("TEST_LOGIN_PASSWORD", "WrongPassword123!"))
|
|
parser.add_argument("--requests", type=int, default=45)
|
|
parser.add_argument("--concurrency", type=int, default=8)
|
|
parser.add_argument("--timeout", type=float, default=10.0)
|
|
parser.add_argument("--out", default="evidence/login-dos.txt")
|
|
args = parser.parse_args()
|
|
|
|
ca_path = Path(args.ca_file)
|
|
ctx = ssl.create_default_context(cafile=str(ca_path)) if ca_path.exists() else ssl.create_default_context()
|
|
|
|
results: list[tuple[int, float]] = []
|
|
wall_start = time.perf_counter()
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, args.concurrency)) as pool:
|
|
futures = [
|
|
pool.submit(_single_login_attempt, args.url, ctx, args.username, args.password, args.timeout)
|
|
for _ in range(args.requests)
|
|
]
|
|
for fut in concurrent.futures.as_completed(futures):
|
|
results.append(fut.result())
|
|
wall_elapsed_s = max(time.perf_counter() - wall_start, 1e-6)
|
|
|
|
statuses = [s for s, _ in results]
|
|
latencies = [ms for _, ms in results]
|
|
|
|
non_429_latencies = [ms for s, ms in results if s != 429]
|
|
limited_429_latencies = [ms for s, ms in results if s == 429]
|
|
|
|
def _pct(vals: list[float], p: float) -> float:
|
|
if not vals:
|
|
return 0.0
|
|
ordered = sorted(vals)
|
|
idx = min(len(ordered) - 1, max(0, int(round((p / 100.0) * (len(ordered) - 1)))))
|
|
return round(ordered[idx], 2)
|
|
|
|
lines = [
|
|
f"url={args.url}",
|
|
f"total_requests={len(results)} concurrency={args.concurrency} wall_time_s={wall_elapsed_s:.3f}",
|
|
f"effective_throughput_rps={len(results) / wall_elapsed_s:.2f}",
|
|
f"status_401={statuses.count(401)} status_429={statuses.count(429)} status_200={statuses.count(200)} other_or_err={sum(1 for s in statuses if s not in (200, 401, 429))}",
|
|
f"all_latencies_ms: p50={round(statistics.median(latencies), 2) if latencies else 0.0} p95={_pct(latencies, 95)} max={round(max(latencies), 2) if latencies else 0.0}",
|
|
f"non_429_argon2_path_ms: count={len(non_429_latencies)} p50={round(statistics.median(non_429_latencies), 2) if non_429_latencies else 0.0} p95={_pct(non_429_latencies, 95)} max={round(max(non_429_latencies), 2) if non_429_latencies else 0.0}",
|
|
f"rate_limited_429_ms: count={len(limited_429_latencies)} p50={round(statistics.median(limited_429_latencies), 2) if limited_429_latencies else 0.0} p95={_pct(limited_429_latencies, 95)} max={round(max(limited_429_latencies), 2) if limited_429_latencies else 0.0}",
|
|
]
|
|
|
|
report = "\n".join(lines)
|
|
out_path = Path(args.out)
|
|
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
out_path.write_text(report + "\n", encoding="utf-8")
|
|
print(report)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |