Implement TLS identities, scoped OpenBao access and worker security study

This commit is contained in:
2026-11-16 11:57:32 +03:00
parent 20afc2c790
commit 32795a92ac
78 changed files with 8798 additions and 19 deletions
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Shared-replica login window and real weak-hash rehash regression."""
import base64
import json
import subprocess
import sys
import time
from pathlib import Path
from argon2 import PasswordHasher
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
def sql(query):
result = subprocess.run(
[
"docker",
"compose",
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-At",
"-v",
"ON_ERROR_STOP=1",
],
cwd=ROOT,
input=query,
text=True,
capture_output=True,
check=True,
)
return result.stdout.strip()
def main():
c = Client("https://localhost:8447", str(ROOT / "secrets/ca.pem"))
actor = c.user("rehash")
password = actor["registration"]["password"]
weak = PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1).hash(password)
sql("UPDATE users SET password_hash='" + weak + "' WHERE id='" + actor["id"] + "';")
authorization = (
"Basic "
+ base64.b64encode((actor["registration"]["username"] + ":" + password).encode()).decode()
)
c.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": authorization},
schema="Session",
)
upgraded = sql("SELECT password_hash FROM users WHERE id='" + actor["id"] + "';")
check(
upgraded != weak and "$m=65536,t=2,p=1$" in upgraded,
"successful login did not upgrade hash",
)
time.sleep(10.2)
wrong = (
"Basic "
+ base64.b64encode((actor["registration"]["username"] + ":incorrect").encode()).decode()
)
rows = []
for _ in range(12):
response = c.call(
"POST", "/api/v1/auth/sessions", expected=[401, 429], headers={"Authorization": wrong}
)
rows.append(
{
"status": response["status"],
"instance": response["headers"]["X-Instance-Id"],
"retry_after": response["headers"].get("Retry-After"),
"milliseconds": round(response["elapsed"] * 1000, 3),
}
)
sql(
"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE user_id='"
+ actor["id"]
+ "';"
)
expiry_rows = []
for _ in range(4):
expired = c.call("GET", "/api/v1/users/me", expected=401, actor=actor)
expiry_rows.append(
{"status": expired["status"], "instance": expired["headers"]["X-Instance-Id"]}
)
result = {
"weak_hash_upgraded": True,
"expired_session_requests": expiry_rows,
"expired_session_denied_both_replicas": len({r["instance"] for r in expiry_rows}) >= 2,
"configured_memory_kib": 65536,
"time_cost": 2,
"parallelism": 1,
"requests": rows,
"distinct_api_instances": len({r["instance"] for r in rows}),
"passed": len({r["instance"] for r in expiry_rows}) >= 2
and sum(r["status"] == 401 for r in rows) == 10
and all(r["status"] == 429 and r["retry_after"] == "10" for r in rows[10:])
and len({r["instance"] for r in rows}) >= 2,
}
(ROOT / "evidence/auth-budget.json").write_text(json.dumps(result, indent=2) + "\n")
check(result["passed"], "shared login window failed")
print(json.dumps({k: v for k, v in result.items() if k != "requests"}))
if __name__ == "__main__":
main()
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Accepted jobs survive worker identity revoke + working-secret rotation."""
import hashlib
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
def docker(*args):
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True).strip()
def images():
ids = docker("ps", "-q", "api", "worker").split()
return sorted(
set(
subprocess.check_output(
["docker", "inspect", "--format", "{{.Image}}", *ids], text=True
).split()
)
)
def main():
c = Client("https://localhost:8447", str(ROOT / "secrets/ca.pem"))
alice, bob, _, chat = c.bootstrap()
before = images()
docker("stop", "worker")
accepted = [c.attachment(alice, chat) for _ in range(3)]
start = time.monotonic()
rotate = subprocess.run(
[sys.executable, "scripts/rotate_identity.py"], cwd=ROOT, text=True, capture_output=True
)
check(rotate.returncode == 0, "operator rotation failed; inspect private operator execution")
errors = 0
deadline = time.monotonic() + 90
pending = {a[0]["id"] for a in accepted}
while pending and time.monotonic() < deadline:
for att, _ in accepted:
if att["id"] not in pending:
continue
result = c.call(
"GET",
"/api/v1/attachments/" + att["id"],
expected=[200, 503],
actor=alice,
schema=None,
)
if result["status"] == 503:
errors += 1
else:
body = json.loads(result["bytes"])
check(body["status"] != "failed", "accepted task became failed")
if body["status"] == "ready":
pending.remove(att["id"])
time.sleep(0.2)
check(not pending, "accepted jobs did not recover")
rows = []
for att, original in accepted:
downloaded = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)[
"bytes"
]
thumbnail = c.call(
"GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", actor=bob
)["bytes"]
sha = hashlib.sha256(original).hexdigest()
rows.append(
{
"attachment_id": att["id"],
"original_sha256": sha,
"download_sha256": hashlib.sha256(downloaded).hexdigest(),
"thumbnail_sha256": hashlib.sha256(thumbnail).hexdigest(),
"thumbnail_nonempty": bool(thumbnail),
"accepted_original_sha_matches": sha == att["sha256"],
}
)
after = images()
result = {
"accepted_jobs": 3,
"ready_jobs": len(rows),
"recovery_seconds": round(time.monotonic() - start, 3),
"observed_api_503": errors,
"images_before": before,
"images_after": after,
"image_unchanged": before == after,
"rows": rows,
"passed": before == after
and all(
r["original_sha256"] == r["download_sha256"]
and r["thumbnail_nonempty"]
and r["accepted_original_sha_matches"]
for r in rows
),
}
(ROOT / "evidence/compromise-recovery.json").write_text(json.dumps(result, indent=2) + "\n")
check(result["passed"], "recovery invariant failed")
print(json.dumps({k: v for k, v in result.items() if k != "rows"}))
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Fail closed after the service-auth lease expires, then bounded recovery."""
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
def operator(action):
subprocess.run(
[sys.executable, "scripts/bao_operator.py", action],
cwd=ROOT,
check=True,
capture_output=True,
)
def main():
c = Client("https://localhost:8447", str(ROOT / "secrets/ca.pem"))
actor = c.user("sealed")
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
start = time.monotonic()
operator("seal")
rows = []
try:
while time.monotonic() - start < 33:
live = c.call("GET", "/health/live", schema="Health")
response = c.call(
"GET", "/api/v1/users/me", expected=[200, 503], actor=actor
)
rows.append(
{
"seconds": round(time.monotonic() - start, 3),
"live": live["status"],
"business": response["status"],
}
)
time.sleep(1)
check(rows[-1]["business"] == 503, "service used credentials beyond lease")
finally:
unseal_start = time.monotonic()
operator("unseal")
for _ in range(20):
response = c.call("GET", "/health/ready", expected=[200, 503])
if response["status"] == 200:
break
time.sleep(0.25)
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
result = {
"lease_seconds": 30,
"local_cache_max_seconds": 29,
"rows": rows,
"first_business_503_seconds": next(
(r["seconds"] for r in rows if r["business"] == 503), None
),
"recovery_seconds": round(time.monotonic() - unseal_start, 3),
"passed": rows[-1]["business"] == 503 and response["status"] == 200,
}
(ROOT / "evidence/sealed-expiry.json").write_text(json.dumps(result, indent=2) + "\n")
check(result["passed"], "recovery failed")
print(json.dumps({k: v for k, v in result.items() if k != "rows"}))
if __name__ == "__main__":
main()