forked from mtusi2026/mtusi2026lab7
test(security): automate lifecycle and login budget measurements
This commit is contained in:
@@ -22,7 +22,7 @@ def prepare():
|
||||
values = {
|
||||
"DATABASE_URL": "postgresql://messenger:"
|
||||
+ quote(raw["postgres_password"], safe="")
|
||||
+ "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/run/identity/current/key.pem",
|
||||
+ "@postgres:5443/messenger?sslmode=verify-full&gssencmode=disable&sslrootcert=/trust/ca.pem&sslcert=/run/identity/current/cert.pem&sslkey=/tmp/operator-client.key",
|
||||
"BROKER_URL": "rediss://admin:"
|
||||
+ raw["broker_admin"]
|
||||
+ "@broker:6380/0",
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
"""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()
|
||||
+2
-31
@@ -87,8 +87,8 @@ def sql(query, *, database="messenger"):
|
||||
|
||||
def cache(command_name, *args):
|
||||
script = (
|
||||
'export REDISCLI_AUTH="$(cat /run/secrets/cache_password)"; '
|
||||
'exec valkey-cli "$@"'
|
||||
'export REDISCLI_AUTH="$(cat /run/secrets/cache_admin)"; '
|
||||
'exec valkey-cli --user admin "$@"'
|
||||
)
|
||||
return compose(
|
||||
"exec", "-T", "cache", "sh", "-c", script, "sh", command_name, *args
|
||||
@@ -137,35 +137,6 @@ def auth(session):
|
||||
return {"Authorization": "Bearer " + session["token"]}
|
||||
|
||||
|
||||
def extra_api(*, ttl=3600, pool_size=1):
|
||||
name = "mtusi-lab6-test-" + uuid4().hex[:10]
|
||||
compose(
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"-e",
|
||||
"SESSION_TTL_SECONDS=" + str(ttl),
|
||||
"-e",
|
||||
"DB_POOL_SIZE=" + str(pool_size),
|
||||
"-p",
|
||||
"127.0.0.1::8080",
|
||||
"api",
|
||||
)
|
||||
try:
|
||||
info = json.loads(command(["docker", "inspect", name]))[0]
|
||||
base = (
|
||||
"http://127.0.0.1:"
|
||||
+ info["NetworkSettings"]["Ports"]["8080/tcp"][0]["HostPort"]
|
||||
)
|
||||
ready(base)
|
||||
return name, base
|
||||
except Exception:
|
||||
command(["docker", "rm", "-f", name])
|
||||
raise
|
||||
|
||||
|
||||
def instances():
|
||||
data = {}
|
||||
for role in ["api", "postgres", "cache"]:
|
||||
|
||||
+127
-22
@@ -37,23 +37,57 @@ def save_incomplete():
|
||||
atexit.register(save_incomplete)
|
||||
|
||||
|
||||
def redact(text, cwd):
|
||||
def values(value):
|
||||
if isinstance(value, dict):
|
||||
for item in value.values():
|
||||
yield from values(item)
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
yield from values(item)
|
||||
elif isinstance(value, str) and len(value) >= 12:
|
||||
yield value
|
||||
|
||||
for folder in [cwd / "secrets", cwd / "operator"]:
|
||||
for path in folder.rglob("*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
try:
|
||||
raw = path.read_text().strip()
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if path.suffix == ".json":
|
||||
try:
|
||||
for value in values(json.loads(raw)):
|
||||
text = text.replace(value, "<private-value>")
|
||||
except ValueError:
|
||||
pass
|
||||
if len(raw) >= 12:
|
||||
text = text.replace(raw, "<private-file>")
|
||||
return (
|
||||
text.replace(str(cwd), "<clean-clone>")
|
||||
.replace(str(ROOT), "<repository>")
|
||||
.replace(str(Path.home()), "<home>")
|
||||
)
|
||||
|
||||
|
||||
def run(args, *, cwd, env, expected=0):
|
||||
print("CHECK: " + redact(" ".join(args[:3]), cwd), flush=True)
|
||||
result = subprocess.run(
|
||||
args, cwd=cwd, env=env, capture_output=True, text=True
|
||||
)
|
||||
|
||||
def redact(text):
|
||||
return (
|
||||
text.replace(str(cwd), "<clean-clone>")
|
||||
.replace(str(ROOT), "<repository>")
|
||||
.replace(str(Path.home()), "<home>")
|
||||
)
|
||||
|
||||
if result.returncode != expected:
|
||||
if "receipt" in PROGRESS:
|
||||
PROGRESS["receipt"]["failed_action"] = redact(" ".join(args))
|
||||
raise RuntimeError(redact(result.stdout + result.stderr))
|
||||
return redact(result.stdout.strip())
|
||||
PROGRESS["receipt"]["failed_action"] = redact(" ".join(args), cwd)
|
||||
raise RuntimeError(redact(result.stdout + result.stderr, cwd))
|
||||
return redact(result.stdout.strip(), cwd)
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(("127.0.0.1", 0))
|
||||
return reservation.getsockname()[1]
|
||||
|
||||
|
||||
def main():
|
||||
@@ -70,7 +104,7 @@ def main():
|
||||
["git", "rev-parse", "HEAD"], cwd=ROOT, text=True
|
||||
).strip()
|
||||
identity = uuid4().hex[:10]
|
||||
project = "mtusi-lab6-clean-" + identity
|
||||
project = "mtusi-lab7-clean-" + identity
|
||||
with socket.socket() as reservation:
|
||||
reservation.bind(("127.0.0.1", 0))
|
||||
public_port = str(reservation.getsockname()[1])
|
||||
@@ -80,9 +114,12 @@ def main():
|
||||
env = {
|
||||
**os.environ,
|
||||
"COMPOSE_PROJECT_NAME": project,
|
||||
"API_IMAGE": "mtusi-messenger:lab6-clean-" + identity,
|
||||
"API_IMAGE": "mtusi-messenger:lab7-clean-" + identity,
|
||||
"PUBLIC_PORT": public_port,
|
||||
"GRAFANA_PORT": grafana_port,
|
||||
"BASE_URL": "https://localhost:" + public_port,
|
||||
"BAO_PORT": str(free_port()),
|
||||
"S3_ADMIN_PORT": str(free_port()),
|
||||
"VCS_REF": sha,
|
||||
"COMPOSE_FILE": "compose.yaml:compose.test.yaml",
|
||||
"NO_PROXY": "localhost,127.0.0.1",
|
||||
@@ -96,8 +133,8 @@ def main():
|
||||
"fixed_host_port_for_restart": int(public_port),
|
||||
}
|
||||
PROGRESS.update(receipt=receipt, output=output)
|
||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab6-clean-") as temporary:
|
||||
clone = Path(temporary) / "lab6"
|
||||
with tempfile.TemporaryDirectory(prefix="mtusi-lab7-clean-") as temporary:
|
||||
clone = Path(temporary) / "lab7"
|
||||
run(
|
||||
[
|
||||
"git",
|
||||
@@ -123,11 +160,12 @@ def main():
|
||||
run(["make", "bootstrap"], cwd=clone, env=env)
|
||||
try:
|
||||
run(
|
||||
["docker", "compose", "up", "-d", "--build", "--wait"],
|
||||
[".venv/bin/python", "-m", "scripts.up_security", "--build"],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
env["BASE_URL"] = "http://127.0.0.1:" + public_port
|
||||
env["BASE_URL"] = "https://localhost:" + public_port
|
||||
env["CA_FILE"] = str(clone / "trust/ca.pem")
|
||||
receipt["smoke"] = run(
|
||||
["make", "test", "BASE_URL=" + env["BASE_URL"]],
|
||||
cwd=clone,
|
||||
@@ -136,18 +174,40 @@ def main():
|
||||
receipt["http_tests"] = run(
|
||||
[".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env
|
||||
)
|
||||
receipt["login_budget"] = run(
|
||||
[
|
||||
".venv/bin/python",
|
||||
"-m",
|
||||
"scripts.verify_login_budget",
|
||||
"--output",
|
||||
"evidence/clean-login-budget.json",
|
||||
],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
receipt["public_security"] = run(
|
||||
[
|
||||
"make",
|
||||
"test-security",
|
||||
"PYTHON=.venv/bin/python",
|
||||
"BASE_URL=" + env["BASE_URL"],
|
||||
],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
)
|
||||
for module, extra in [
|
||||
("verify_security", []),
|
||||
("verify_telemetry", []),
|
||||
(
|
||||
"verify_observability_persistence",
|
||||
["--causal-evidence", "evidence/clean-telemetry.json"],
|
||||
),
|
||||
]:
|
||||
name = (
|
||||
"telemetry"
|
||||
if module == "verify_telemetry"
|
||||
else "observability-persistence"
|
||||
)
|
||||
name = {
|
||||
"verify_security": "security",
|
||||
"verify_telemetry": "telemetry",
|
||||
"verify_observability_persistence": "observability-persistence",
|
||||
}[module]
|
||||
run(
|
||||
[
|
||||
".venv/bin/python",
|
||||
@@ -267,8 +327,53 @@ def main():
|
||||
["git", "fsck", "--full"], cwd=clone, env=env
|
||||
)
|
||||
receipt["checks_completed"] = True
|
||||
except BaseException:
|
||||
receipt["partial_evidence"] = {}
|
||||
for name in [
|
||||
"security",
|
||||
"login-budget",
|
||||
"telemetry",
|
||||
"observability-persistence",
|
||||
"cluster",
|
||||
"pipeline",
|
||||
"cleanup",
|
||||
"gc-seed",
|
||||
]:
|
||||
partial = clone / "evidence" / ("clean-" + name + ".json")
|
||||
if partial.exists():
|
||||
receipt["partial_evidence"][name] = json.loads(
|
||||
redact(partial.read_text(), clone)
|
||||
)
|
||||
receipt["failure_diagnostics"] = {}
|
||||
for label, arguments in [
|
||||
("services", ["ps", "-a", "--format", "json"]),
|
||||
(
|
||||
"logs",
|
||||
[
|
||||
"logs",
|
||||
"--no-color",
|
||||
"--tail",
|
||||
"60",
|
||||
"api",
|
||||
"s3",
|
||||
"migrate",
|
||||
"cache",
|
||||
],
|
||||
),
|
||||
]:
|
||||
diagnostic = subprocess.run(
|
||||
["docker", "compose", *arguments],
|
||||
cwd=clone,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
receipt["failure_diagnostics"][label] = redact(
|
||||
diagnostic.stdout + diagnostic.stderr, clone
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
assert project.startswith("mtusi-lab6-clean-")
|
||||
assert project.startswith("mtusi-lab7-clean-")
|
||||
run(
|
||||
["docker", "compose", "down", "--volumes", "--remove-orphans"],
|
||||
cwd=clone,
|
||||
|
||||
@@ -15,6 +15,7 @@ import httpx
|
||||
|
||||
from scripts import cluster
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready, sql
|
||||
from scripts.tls_client import FreshTrustTransport
|
||||
|
||||
|
||||
def snapshot():
|
||||
@@ -148,7 +149,12 @@ def main():
|
||||
apis = [c for c in initial if c["role"] == "api"]
|
||||
assert len(apis) == 2 and len({c["pid"] for c in apis}) == 2
|
||||
report["before"] = initial
|
||||
with httpx.Client(base_url=BASE, trust_env=False, timeout=8) as client:
|
||||
with httpx.Client(
|
||||
base_url=BASE,
|
||||
trust_env=False,
|
||||
timeout=8,
|
||||
transport=FreshTrustTransport(),
|
||||
) as client:
|
||||
user, _, session = actor(client)
|
||||
r = client.post(
|
||||
"/api/v1/chats",
|
||||
@@ -165,7 +171,10 @@ def main():
|
||||
|
||||
def repeat(_):
|
||||
with httpx.Client(
|
||||
base_url=BASE, trust_env=False, timeout=8
|
||||
base_url=BASE,
|
||||
trust_env=False,
|
||||
timeout=8,
|
||||
transport=FreshTrustTransport(),
|
||||
) as c:
|
||||
r = c.post(
|
||||
path,
|
||||
@@ -321,6 +330,8 @@ def main():
|
||||
hook,
|
||||
"--base-url",
|
||||
BASE,
|
||||
"--ca-file",
|
||||
str(ROOT / "trust/ca.pem"),
|
||||
],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Real old-hash migration and shared login admission/resource measurement."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import statistics
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import UTC, datetime
|
||||
from uuid import uuid4
|
||||
|
||||
import httpx
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
from scripts.stand import BASE, ROOT, command, compose, ready, sql
|
||||
from scripts.tls_client import FreshTrustTransport
|
||||
|
||||
|
||||
def resources():
|
||||
ids = compose("ps", "-q", "api").split()
|
||||
result = []
|
||||
for cid in ids:
|
||||
raw = command(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
cid,
|
||||
"python",
|
||||
"-c",
|
||||
"import json,pathlib;p=pathlib.Path('/sys/fs/cgroup');print(json.dumps({'memory_current':int((p/'memory.current').read_text()),'cpu_stat':dict(line.split() for line in (p/'cpu.stat').read_text().splitlines())}))",
|
||||
]
|
||||
)
|
||||
info = json.loads(command(["docker", "inspect", cid]))[0]
|
||||
result.append(
|
||||
{
|
||||
"container": cid[:12],
|
||||
"cpu_nano": info["HostConfig"]["NanoCpus"],
|
||||
"memory_limit": info["HostConfig"]["Memory"],
|
||||
**json.loads(raw),
|
||||
}
|
||||
)
|
||||
assert len(result) == 2
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", default="evidence/login-budget-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,
|
||||
"measurements": [],
|
||||
}
|
||||
with httpx.Client(
|
||||
base_url=BASE,
|
||||
transport=FreshTrustTransport(),
|
||||
trust_env=False,
|
||||
timeout=12,
|
||||
) as client:
|
||||
try:
|
||||
ready(timeout=90)
|
||||
username = "legacy_" + uuid4().hex[:20]
|
||||
password = "Synthetic-password-" + uuid4().hex
|
||||
r = client.post(
|
||||
"/api/v1/users",
|
||||
json={
|
||||
"username": username,
|
||||
"display_name": "Synthetic migration",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 201
|
||||
uid = r.json()["id"]
|
||||
previous = PasswordHasher(
|
||||
time_cost=2, memory_cost=19456, parallelism=1
|
||||
).hash(password)
|
||||
sql(
|
||||
"UPDATE users SET password_hash='"
|
||||
+ previous
|
||||
+ "' WHERE id='"
|
||||
+ uid
|
||||
+ "'"
|
||||
)
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(username, password + "-wrong"),
|
||||
)
|
||||
assert r.status_code == 401
|
||||
assert (
|
||||
sql("SELECT password_hash FROM users WHERE id='" + uid + "'")
|
||||
== previous
|
||||
)
|
||||
began = time.monotonic()
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(username, password),
|
||||
)
|
||||
assert r.status_code == 201
|
||||
elapsed = time.monotonic() - began
|
||||
current = sql(
|
||||
"SELECT password_hash FROM users WHERE id='" + uid + "'"
|
||||
)
|
||||
assert current != previous and "$m=65536,t=3,p=4$" in current
|
||||
assert PasswordHasher().verify(current, password)
|
||||
report["rehash"] = {
|
||||
"old_parameters": "argon2id m=19456KiB,t=2,p=1",
|
||||
"new_parameters": "argon2id m=65536KiB,t=3,p=4",
|
||||
"wrong_password_kept_old_hash": True,
|
||||
"valid_login_updated_hash": True,
|
||||
"valid_login_seconds_including_rehash": round(elapsed, 6),
|
||||
}
|
||||
# Operator resets only synthetic limiter state to define a known
|
||||
# initial burst. No API/rate configuration is changed for the test.
|
||||
sql("TRUNCATE login_buckets")
|
||||
report["before"] = resources()
|
||||
stop = threading.Event()
|
||||
health = []
|
||||
|
||||
def healthy():
|
||||
while not stop.is_set():
|
||||
t = time.monotonic()
|
||||
response = client.get("/health/ready")
|
||||
health.append(
|
||||
{
|
||||
"status": response.status_code,
|
||||
"seconds": time.monotonic() - t,
|
||||
}
|
||||
)
|
||||
stop.wait(0.25)
|
||||
|
||||
observer = threading.Thread(target=healthy)
|
||||
observer.start()
|
||||
started = time.monotonic()
|
||||
|
||||
def login(i):
|
||||
name = (
|
||||
"absent_"
|
||||
+ hashlib.sha256((username + str(i)).encode()).hexdigest()[
|
||||
:20
|
||||
]
|
||||
)
|
||||
t = time.monotonic()
|
||||
r = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
auth=httpx.BasicAuth(name, password),
|
||||
)
|
||||
result = {
|
||||
"status": r.status_code,
|
||||
"seconds": time.monotonic() - t,
|
||||
"instance": r.headers.get("x-instance-id"),
|
||||
"retry_after": r.headers.get("retry-after"),
|
||||
}
|
||||
assert r.status_code in {401, 429}
|
||||
if r.status_code == 429:
|
||||
assert int(r.headers["retry-after"]) >= 1
|
||||
return result
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
report["measurements"] = list(pool.map(login, range(72)))
|
||||
finally:
|
||||
stop.set()
|
||||
observer.join(15)
|
||||
duration = time.monotonic() - started
|
||||
report["after"] = resources()
|
||||
admitted = [
|
||||
x for x in report["measurements"] if x["status"] == 401
|
||||
]
|
||||
limited = [x for x in report["measurements"] if x["status"] == 429]
|
||||
assert limited and admitted
|
||||
assert len(admitted) <= 8 + int(2 * duration) + 1
|
||||
assert len({x["instance"] for x in report["measurements"]}) == 2
|
||||
assert health and all(x["status"] == 200 for x in health)
|
||||
buckets = int(
|
||||
sql(
|
||||
"SELECT count(*) FROM login_buckets WHERE bucket<>'global'"
|
||||
)
|
||||
)
|
||||
assert buckets == len(admitted), (
|
||||
"Rejected random accounts must not allocate buckets"
|
||||
)
|
||||
report["flood"] = {
|
||||
"requests": 72,
|
||||
"concurrency": 12,
|
||||
"seconds": round(duration, 6),
|
||||
"statuses": dict(
|
||||
Counter(str(x["status"]) for x in report["measurements"])
|
||||
),
|
||||
"both_replicas_observed": True,
|
||||
"new_account_buckets": buckets,
|
||||
"shared_admission_bound": 8 + int(2 * duration) + 1,
|
||||
"limited_median_seconds": statistics.median(
|
||||
x["seconds"] for x in limited
|
||||
),
|
||||
"admitted_median_seconds": statistics.median(
|
||||
x["seconds"] for x in admitted
|
||||
),
|
||||
"health": health,
|
||||
"cpu_usage_seconds": sum(
|
||||
int(a["cpu_stat"]["usage_usec"])
|
||||
- int(b["cpu_stat"]["usage_usec"])
|
||||
for a, b in zip(
|
||||
report["after"], report["before"], strict=True
|
||||
)
|
||||
)
|
||||
/ 1e6,
|
||||
"memory_measurement": "cgroup current before/after, not a peak measurement",
|
||||
}
|
||||
report["complete"] = True
|
||||
finally:
|
||||
output.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: old-hash upgrade, shared pre-KDF rate limit and measured login resource budget"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -21,6 +21,8 @@ os.environ.setdefault("no_proxy", "localhost,127.0.0.1")
|
||||
from scripts.stand import BASE, ROOT, actor, auth, command, compose, ready
|
||||
|
||||
PREFIX = """import io,json,hashlib,time,urllib.request
|
||||
from src.operator_runtime import prepare_key
|
||||
prepare_key()
|
||||
from uuid import UUID,uuid4
|
||||
from psycopg.types.json import Jsonb
|
||||
from src.pipeline import database,broker,envelope,STREAM,GROUP
|
||||
@@ -32,6 +34,9 @@ db,store,queue=database(),ObjectStore(),broker()
|
||||
|
||||
|
||||
def inside(code):
|
||||
from scripts.operator_task import prepare
|
||||
|
||||
prepare()
|
||||
cid = compose("ps", "-q", "controller").split()[0]
|
||||
return json.loads(
|
||||
command(
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from scripts.bootstrap_security import (
|
||||
OPERATOR,
|
||||
SECRET,
|
||||
key_bytes,
|
||||
make_root,
|
||||
@@ -12,7 +14,8 @@ from scripts.bootstrap_security import (
|
||||
sign_leaf,
|
||||
write_private,
|
||||
)
|
||||
from scripts.stand import ROOT, command, compose
|
||||
from scripts.stand import ROOT, command
|
||||
from scripts.verify_clean import redact
|
||||
|
||||
|
||||
def main():
|
||||
@@ -32,23 +35,43 @@ def main():
|
||||
mode=0o644,
|
||||
)
|
||||
write_private(fixture / "foreign/key.pem", key_bytes(key), mode=0o644)
|
||||
result = json.loads(
|
||||
compose(
|
||||
for name in ["cert.pem", "key.pem"]:
|
||||
write_private(
|
||||
fixture / "operator" / name,
|
||||
(OPERATOR / "client" / name).read_bytes(),
|
||||
mode=0o644,
|
||||
)
|
||||
process = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--profile",
|
||||
"operator",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"operator-probe",
|
||||
)
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
result = json.loads(process.stdout)
|
||||
except ValueError:
|
||||
result = {"complete": False}
|
||||
result["probe_exit_code"] = process.returncode
|
||||
if process.returncode:
|
||||
result["failure"] = redact(process.stderr, ROOT)
|
||||
result.update(
|
||||
date=datetime.now(UTC).isoformat(),
|
||||
source_commit=command(["git", "rev-parse", "HEAD"]),
|
||||
)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
assert result["complete"]
|
||||
assert process.returncode == 0 and result["complete"], (
|
||||
"Security probe failed; see saved receipt"
|
||||
)
|
||||
print(
|
||||
"PASS: real mTLS identities, server CA/hostname, closed plaintext boundaries and worker least privilege"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user