lab7: HTTPS+mTLS, OpenBao AppRole, Argon2id, rate limits, hardening

This commit is contained in:
2026-11-19 20:48:27 +03:00
parent 20afc2c790
commit 5e98b1b5af
67 changed files with 3169 additions and 87 deletions
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""lab5 failure drills: broker restart durability and bounded retry.
A) Stop the worker, accept an upload, restart the broker (persistent volume),
start the worker: the accepted job still becomes ready.
B) Accept an upload while the worker is down, stop S3, start the worker:
transient failures exhaust MAX_JOB_ATTEMPTS and the attachment ends as
failed with a safe error_code. S3 is restored afterwards.
"""
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, arguments, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def compose(*args):
subprocess.run(COMPOSE + list(args), cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def wait_status(c, actor, att, wanted, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
row = c.call("GET", "/api/v1/attachments/" + att["id"], actor=actor, schema="Attachment")["json"]
if row["status"] in wanted:
return row
time.sleep(0.5)
raise AssertionError("attachment did not reach " + repr(wanted))
def main():
args = arguments("lab5 failure drills")
c = Client(args.base_url, args.ca_file, timeout=10)
alice, bob, _eve, chat = c.bootstrap()
print("A. broker restart keeps accepted work")
compose("stop", "worker")
try:
att, _content = c.attachment(alice, chat)
compose("restart", "broker")
deadline = time.monotonic() + 90
while True:
try:
c.call("GET", "/health/ready", schema="Health")
break
except Exception:
check(time.monotonic() < deadline, "API did not recover after broker restart")
time.sleep(0.5)
compose("up", "-d", "--no-deps", "worker")
started = time.monotonic()
ready = c.wait_ready(bob, att, wait_seconds=90)
print(json.dumps({
"scenario": "broker_restart",
"attachment_id": att["id"],
"status": ready["status"],
"seconds_to_ready": round(time.monotonic() - started, 3),
}, ensure_ascii=False))
check(ready["status"] == "ready", "job lost after broker restart")
finally:
compose("up", "-d", "--no-deps", "worker")
print("B. bounded retry ends in a safe failed state")
compose("stop", "worker")
try:
att, _content = c.attachment(alice, chat)
compose("stop", "s3")
compose("up", "-d", "--no-deps", "worker")
failed = wait_status(c, bob, att, {"failed"}, seconds=180)
print(json.dumps({
"scenario": "retry_exhausted",
"attachment_id": att["id"],
"status": failed["status"],
"error_code": failed["error_code"],
}, ensure_ascii=False))
check(failed["error_code"] in ("processing_failed", "invalid_image"), "unsafe error_code")
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 409, actor=bob)
finally:
compose("up", "-d", "s3")
compose("up", "-d", "--no-deps", "worker")
deadline = time.monotonic() + 60
while True:
try:
c.call("GET", "/health/ready", schema="Health")
break
except Exception:
check(time.monotonic() < deadline, "S3 did not recover")
time.sleep(0.5)
print("PASS: broker durability and bounded retry demonstrated.")
if __name__ == "__main__":
run(main)
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Demonstrate the lab5 acceptance scenario without hiding infrastructure steps.
Worker stopped -> upload returns 202 queued -> message references the chat
attachment -> API replicas restarted -> worker started -> the same job
reaches ready with a contract-compliant JPEG thumbnail.
The script prints only synthetic IDs and timings. It never prints tokens.
"""
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, arguments, check, run # noqa: E402
COMPOSE = ["docker", "compose", "--env-file", ".env"]
def compose(*args):
subprocess.run(COMPOSE + list(args), cwd=ROOT, check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main():
args = arguments("lab5 worker-outage demonstration")
c = Client(args.base_url, args.ca_file, timeout=10)
alice, bob, _eve, chat = c.bootstrap()
print("1. stop worker")
compose("stop", "worker")
try:
print("2. upload with worker down")
att, content = c.attachment(alice, chat)
check(att["status"] == "queued", "queued expected after upload")
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
check(meta["status"] in ("queued", "processing"), "still unprocessed while worker is down")
pending = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 409, actor=bob)
check(pending["status"] == 409, "content must be 409 while queued")
print("3. attach the queued attachment to a message")
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"]
check(msg["attachment_ids"] == [att["id"]], "message lost the attachment")
print("4. restart API replicas (accepted work must survive)")
compose("restart", "api1", "api2")
deadline = time.monotonic() + 90
while True:
try:
c.call("GET", "/health/ready", schema="Health")
break
except Exception:
check(time.monotonic() < deadline, "API did not recover")
time.sleep(0.5)
print("5. start worker")
compose("up", "-d", "--no-deps", "worker")
started = time.monotonic()
ready = c.wait_ready(bob, att, wait_seconds=90)
elapsed = round(time.monotonic() - started, 3)
check(ready["status"] == "ready", "job did not reach ready")
variants = [v for v in ready["variants"] if v["name"] == "thumbnail"]
check(len(variants) == 1, "expected exactly one thumbnail")
v = variants[0]
check((v["width"], v["height"]) == (256, 160), "thumbnail dimensions differ")
thumb = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", actor=bob)
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail must be JPEG")
from image_probe import jpeg_size
check(jpeg_size(thumb["bytes"]) == (256, 160), "actual JPEG size differs")
print(json.dumps({
"attachment_id": att["id"],
"message_id": msg["id"],
"status_after_worker_restart": ready["status"],
"thumbnail": {"width": v["width"], "height": v["height"],
"size_bytes": v["size_bytes"], "sha256": v["sha256"]},
"seconds_from_worker_start_to_ready": elapsed,
}, ensure_ascii=False))
print("PASS: queued job completed after API and worker restart.")
finally:
compose("up", "-d", "--no-deps", "worker")
if __name__ == "__main__":
run(main)
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Operator bootstrap for OpenBao (lab7).
Run AFTER `docker compose up -d openbao` and BEFORE starting the API:
python scripts/openbao_bootstrap.py
It initializes OpenBao (once), unseals it, creates the KV v2 path, writes the
runtime credentials that are already in ./secrets, installs the scoped policy,
enables AppRole and writes role_id/secret_id files for the application.
Operator-held material (unseal key, root token) is written to
./secrets/openbao_init.json and never leaves this machine. The application
never sees it. Delete ./secrets/openbao_init.json only after moving unseal
material to a safe place.
"""
import base64
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
ENV = ["docker", "compose", "--env-file", ".env"]
INIT_FILE = ROOT / "secrets" / "openbao_init.json"
def read(name: str) -> str:
return (ROOT / "secrets" / name).read_text().strip()
def bao(*args: str, stdin: str | None = None, token: str | None = None):
command = ENV + ["exec", "-T"]
if token:
command += ["-e", f"BAO_TOKEN={token}"]
command += ["openbao", "bao", *args]
return subprocess.run(command, cwd=ROOT, input=stdin, text=True, capture_output=True)
def wait_for_container() -> None:
for _ in range(60):
probe = bao("status")
if probe.returncode in (0, 2):
return
time.sleep(1)
raise SystemExit("OpenBao container is not reachable: " + probe.stderr.strip())
def status() -> dict:
probe = bao("status", "-format=json")
try:
return json.loads(probe.stdout)
except ValueError:
return {"initialized": False, "sealed": True}
def ensure_initialized() -> tuple[str, str]:
current = status()
if not current.get("initialized", False):
if INIT_FILE.exists():
raise SystemExit("OpenBao is uninitialized but secrets/openbao_init.json exists; "
"refusing to overwrite operator material")
init = bao("operator", "init", "-format=json", "-key-shares=1", "-key-threshold=1")
if init.returncode != 0:
raise SystemExit("operator init failed: " + init.stderr.strip())
data = json.loads(init.stdout)
INIT_FILE.write_text(json.dumps(data, indent=2))
INIT_FILE.chmod(0o600)
print("OpenBao initialized; unseal key and root token saved to secrets/openbao_init.json")
data = json.loads(INIT_FILE.read_text())
key = data["unseal_keys_b64"][0]
token = data["root_token"]
return key, token
def ensure_unsealed(key: str) -> None:
if status().get("sealed", True):
unseal = bao("operator", "unseal", key)
if unseal.returncode != 0:
raise SystemExit("unseal failed: " + unseal.stderr.strip())
print("OpenBao unsealed")
def ensure_kv(token: str) -> None:
mounts = bao("secrets", "list", "-format=json", token=token)
existing = json.loads(mounts.stdout or "{}")
if "kv/" not in existing:
enable = bao("secrets", "enable", "-path=kv", "-version=2", "kv", token=token)
if enable.returncode != 0:
raise SystemExit("kv enable failed: " + enable.stderr.strip())
print("Enabled kv v2 at kv/")
def write_runtime_secrets(token: str) -> None:
pg_password = read("postgres_password.txt")
broker_user = read("broker_user.txt")
broker_password = read("broker_password.txt")
database_url = ("postgresql+psycopg://messenger:" + pg_password +
"@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt")
broker_url = f"amqps://{broker_user}:{broker_password}@broker:5671/"
write = bao("kv", "put", "kv/messenger",
f"database_url={database_url}",
f"s3_access_key_id={read('s3_access_key_id.txt')}",
f"s3_secret_access_key={read('s3_secret_access_key.txt')}",
f"broker_url={broker_url}",
token=token)
if write.returncode != 0:
raise SystemExit("kv put failed: " + write.stderr.strip())
print("Wrote kv/messenger")
def install_policy(token: str) -> None:
policy = (ROOT / "infra" / "openbao" / "policy-messenger.hcl").read_text()
write = bao("policy", "write", "messenger", "-", stdin=policy, token=token)
if write.returncode != 0:
raise SystemExit("policy write failed: " + write.stderr.strip())
print("Installed policy messenger")
def ensure_approle(token: str) -> None:
enable = bao("auth", "enable", "approle", token=token)
if enable.returncode != 0 and "path is already in use" not in (enable.stderr or ""):
if "already enabled" not in (enable.stderr or ""):
raise SystemExit("approle enable failed: " + enable.stderr.strip())
role = bao("write", "auth/approle/role/messenger",
"token_ttl=1h", "token_max_ttl=4h", "secret_id_ttl=24h",
"policies=messenger", token=token)
if role.returncode != 0:
raise SystemExit("approle role failed: " + role.stderr.strip())
role_id = bao("read", "-field=role_id", "auth/approle/role/messenger/role-id", token=token)
secret_id = bao("write", "-f", "-field=secret_id", "auth/approle/role/messenger/secret-id", token=token)
if role_id.returncode != 0 or secret_id.returncode != 0:
raise SystemExit("could not issue AppRole credentials")
(ROOT / "secrets" / "openbao_role_id.txt").write_text(role_id.stdout.strip())
(ROOT / "secrets" / "openbao_secret_id.txt").write_text(secret_id.stdout.strip())
print("Issued AppRole role_id/secret_id")
def self_check(role_id: str, secret_id: str) -> None:
login = bao("write", "-format=json", "auth/approle/login",
f"role_id={role_id}", f"secret_id={secret_id}")
if login.returncode != 0:
raise SystemExit("AppRole login self-check failed: " + login.stderr.strip())
token = json.loads(login.stdout)["auth"]["client_token"]
read_back = bao("kv", "get", "-format=json", "kv/messenger", token=token)
if read_back.returncode != 0:
raise SystemExit("policy cannot read kv/messenger: " + read_back.stderr.strip())
forbidden = bao("kv", "get", "-format=json", "kv/other", token=token)
if forbidden.returncode == 0:
raise SystemExit("policy unexpectedly reads kv/other")
print("AppRole login and scoped policy verified (kv/other denied)")
def main() -> None:
wait_for_container()
key, root = ensure_initialized()
ensure_unsealed(key)
ensure_kv(root)
write_runtime_secrets(root)
install_policy(root)
ensure_approle(root)
self_check((ROOT / "secrets" / "openbao_role_id.txt").read_text().strip(),
(ROOT / "secrets" / "openbao_secret_id.txt").read_text().strip())
print("OpenBao bootstrap complete. Start the rest: docker compose up -d")
if __name__ == "__main__":
main()
+78
View File
@@ -0,0 +1,78 @@
#!/bin/sh
# Local lab7 PKI bootstrap. Never commit pki/: the CA key and leaf keys are
# operator-held material. Run from the repository root (Git Bash on Windows).
set -eu
# Git Bash on Windows rewrites arguments that look like Unix paths (e.g. the
# openssl -subj value). Keep the arguments byte-exact.
export MSYS_NO_PATHCONV=1
DAYS=825
PKI=${PKI_DIR:-pki}
mkdir -p "$PKI"
cd "$PKI"
if [ -f ca.crt ]; then
echo "PKI already exists in $PKI; delete it to regenerate."
exit 0
fi
write_ext() {
# $1 file, $2 san
cat > "$1" <<EOF
basicConstraints=CA:FALSE
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth,clientAuth
subjectAltName=$2
EOF
}
echo "==> CA"
openssl genrsa -out ca.key 4096 >/dev/null 2>&1
openssl req -x509 -new -key ca.key -sha256 -days $DAYS \
-subj "/CN=mtusi-lab7-local-ca" \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out ca.crt >/dev/null 2>&1
issue() {
# $1 name, $2 CN, $3 SAN
openssl genrsa -out "$1.key" 2048 >/dev/null 2>&1
openssl req -new -key "$1.key" -subj "/CN=$2" -out "$1.csr" >/dev/null 2>&1
write_ext "$1.ext" "$3"
openssl x509 -req -in "$1.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
-days $DAYS -sha256 -extfile "$1.ext" -out "$1.crt" >/dev/null 2>&1
rm -f "$1.csr" "$1.ext"
chmod 600 "$1.key" 2>/dev/null || true
}
echo "==> leaf certificates"
issue server "localhost" "DNS:localhost,IP:127.0.0.1"
issue lb "lb" "DNS:lb"
issue gateway "api-gateway" "DNS:api-gw1,DNS:api-gw2,DNS:localhost"
issue postgres "postgres" "DNS:postgres"
issue minio "s3" "DNS:s3,DNS:minio,DNS:localhost"
issue broker "broker" "DNS:broker"
issue otel "otel-collector" "DNS:otel-collector"
issue openbao "openbao" "DNS:openbao,IP:127.0.0.1"
issue other "other-service" "DNS:other-service"
# A second, untrusted CA and a client certificate signed by it: used by the
# negative mTLS test (valid chain, but the wrong root).
echo "==> foreign CA (negative test only)"
openssl genrsa -out foreign-ca.key 2048 >/dev/null 2>&1
openssl req -x509 -new -key foreign-ca.key -sha256 -days $DAYS \
-subj "/CN=foreign-ca" \
-addext "basicConstraints=critical,CA:TRUE" \
-addext "keyUsage=critical,keyCertSign,cRLSign" \
-out foreign-ca.crt >/dev/null 2>&1
openssl genrsa -out foreign-client.key 2048 >/dev/null 2>&1
openssl req -new -key foreign-client.key -subj "/CN=foreign-client" -out foreign-client.csr >/dev/null 2>&1
write_ext foreign-client.ext "DNS:foreign-client"
openssl x509 -req -in foreign-client.csr -CA foreign-ca.crt -CAkey foreign-ca.key \
-CAcreateserial -days $DAYS -sha256 -extfile foreign-client.ext -out foreign-client.crt >/dev/null 2>&1
rm -f foreign-client.csr foreign-client.ext
rm -f ca.srl foreign-ca.srl
echo "PKI ready in $PKI/"
ls -1 *.crt
+2
View File
@@ -0,0 +1,2 @@
@echo off
"C:\Program Files\Git\bin\bash.exe" "%~dp0pki.sh"
Executable → Regular
View File
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
# Restart the stores and the OpenBao node. OpenBao comes back sealed, so the
# documented operator step is to re-run the bootstrap (idempotent unseal)
# before the API replicas need their secrets again.
docker compose --env-file .env restart postgres s3 broker openbao
if command -v py >/dev/null 2>&1; then
py -3 scripts/openbao_bootstrap.py
else
python scripts/openbao_bootstrap.py
fi
docker compose --env-file .env restart api1 api2 api-gw1 api-gw2 worker lb
+2
View File
@@ -0,0 +1,2 @@
@echo off
"C:\Program Files\Git\bin\bash.exe" "%~dp0restart.sh"
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Negative/positive checks for the lab7 trust matrix.
Covers:
* LB -> API mTLS: no client cert, foreign CA, trusted CA but wrong identity,
correct LB identity;
* external HTTPS: untrusted CA is rejected (make test-security also covers it);
* OpenBao: the application policy reads only kv/messenger and is denied
elsewhere; the AppRole login works with the issued credentials.
Run from the repository root after the stand is up:
python scripts/security_internal.py
"""
import json
import ssl
import sys
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PKI = ROOT / "pki"
CA = str(PKI / "ca.crt")
GATEWAY_URL = "https://localhost:9443/health/live"
OPENBAO = "https://127.0.0.1:8200"
def client_context(cert: str | None, key: str | None = None) -> ssl.SSLContext:
ctx = ssl.create_default_context(cafile=CA)
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
if cert:
ctx.load_cert_chain(certfile=str(PKI / cert), keyfile=str(PKI / (key or cert.replace(".crt", ".key"))))
return ctx
def get(url: str, ctx: ssl.SSLContext, token: str | None = None):
headers = {"X-Vault-Token": token} if token else {}
request = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
return response.status, response.read().decode()[:200]
except urllib.error.HTTPError as error:
return error.code, error.read().decode()[:200]
except (ssl.SSLError, urllib.error.URLError) as error:
return None, type(error).__name__ + ": " + str(getattr(error, "reason", error))
def attempt(label: str, cert: str | None, expected, key: str | None = None):
ctx = client_context(cert, key)
status, body = get(GATEWAY_URL, ctx)
ok = (status in expected) if isinstance(expected, (list, tuple, set)) else (status == expected)
print(f"{'PASS' if ok else 'FAIL'} {label}: status={status} detail={body[:80]}")
return ok
def openbao_checks() -> bool:
role_id = (ROOT / "secrets" / "openbao_role_id.txt").read_text().strip()
secret_id = (ROOT / "secrets" / "openbao_secret_id.txt").read_text().strip()
ctx = client_context(None)
login = urllib.request.Request(
OPENBAO + "/v1/auth/approle/login",
data=json.dumps({"role_id": role_id, "secret_id": secret_id}).encode(),
headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(login, context=ctx, timeout=10) as response:
token = json.loads(response.read())["auth"]["client_token"]
own_status, _ = get(OPENBAO + "/v1/kv/data/messenger", ctx, token)
other_status, _ = get(OPENBAO + "/v1/kv/data/other", ctx, token)
ok = own_status == 200 and other_status == 403
print(f"{'PASS' if ok else 'FAIL'} openbao policy: own={own_status} forbidden={other_status}")
return ok
def main() -> None:
if not (PKI / "ca.crt").exists():
raise SystemExit("PKI is missing: run scripts/pki.sh first")
results = [
attempt("no client certificate", None, [400, 495, 496, 497, None]),
attempt("foreign CA certificate", "foreign-client.crt", [400, 403, 495, 496, 497, None]),
attempt("trusted CA, wrong identity", "other.crt", [403]),
attempt("trusted CA, LB identity", "lb.crt", [200]),
]
results.append(openbao_checks())
if not all(results):
raise SystemExit("security checks failed")
print("PASS: trust matrix negatives and positives verified")
if __name__ == "__main__":
main()
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""Check the shared login rate limit (429 + Retry-After) over HTTPS."""
import base64
import json
import ssl
import sys
import urllib.error
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
CA = str(ROOT / "pki" / "ca.crt")
BASE = "https://localhost:8443"
def call(method, path, body=None, headers=None):
ctx = ssl.create_default_context(cafile=CA)
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(BASE + path, data=data, method=method,
headers={"Content-Type": "application/json", **(headers or {})})
try:
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
return response.status, dict(response.headers), response.read()
except urllib.error.HTTPError as error:
return error.code, dict(error.headers), error.read()
def main():
username = "rl_" + uuid.uuid4().hex[:10]
password = "T3st-" + uuid.uuid4().hex
status, _, _ = call("POST", "/api/v1/users",
{"username": username, "display_name": "Rate limit", "password": password})
assert status == 201, status
bad = base64.b64encode((username + ":wrong-password-123").encode()).decode()
results = []
for _ in range(6):
status, headers, body = call("POST", "/api/v1/auth/sessions",
headers={"Authorization": "Basic " + bad})
retry_after = headers.get("Retry-After") or headers.get("retry-after")
results.append((status, retry_after))
print("attempts:", results)
limited = results[-1][0] == 429 and results[-1][1] is not None
earlier = all(code == 401 for code, _ in results[:5])
if not (limited and earlier):
raise SystemExit("login rate limit did not behave as expected")
print("PASS: login rate limit returns 429 with Retry-After after repeated failures")
if __name__ == "__main__":
main()
Executable → Regular
View File
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?}"
case "$TARGET_INSTANCE_ID" in
api-1) SVC=api1 ;;
api-2) SVC=api2 ;;
*) echo "unknown instance alias: $TARGET_INSTANCE_ID" >&2; exit 1 ;;
esac
docker compose --env-file .env stop "$SVC"
+2
View File
@@ -0,0 +1,2 @@
@echo off
"C:\Program Files\Git\bin\bash.exe" "%~dp0stop-one.sh"