feat(lab7): implement secure messenger infrastructure with TLS, OpenBao and observability

This commit is contained in:
2026-11-29 18:06:02 +03:00
parent 20afc2c790
commit c188a3beca
121 changed files with 10090 additions and 68 deletions
+56
View File
@@ -0,0 +1,56 @@
import statistics
import time
from argon2 import PasswordHasher, Type
PASSWORD = "Lab7-Benchmark-Password-2026"
ITERATIONS = 10
CONFIGURATIONS = [
("baseline", 19456, 2, 1),
("stronger", 32768, 3, 1),
("high-memory", 65536, 3, 1),
]
def benchmark(name, memory, time_cost, parallelism):
hasher = PasswordHasher(
memory_cost=memory,
time_cost=time_cost,
parallelism=parallelism,
hash_len=32,
salt_len=16,
type=Type.ID,
)
samples = []
# Warm-up, excluded from measurements.
sample_hash = hasher.hash(PASSWORD)
assert hasher.verify(sample_hash, PASSWORD)
for _ in range(ITERATIONS):
start = time.perf_counter()
password_hash = hasher.hash(PASSWORD)
elapsed = (time.perf_counter() - start) * 1000
assert hasher.verify(password_hash, PASSWORD)
assert password_hash.startswith("$argon2id$")
samples.append(elapsed)
print(
f"{name}: "
f"memory={memory} KiB, "
f"t={time_cost}, "
f"p={parallelism}, "
f"median={statistics.median(samples):.2f} ms, "
f"min={min(samples):.2f} ms, "
f"max={max(samples):.2f} ms"
)
if __name__ == "__main__":
for configuration in CONFIGURATIONS:
benchmark(*configuration)
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
import os
import secrets
import subprocess
from pathlib import Path
ENV_FILE = Path(".env")
ROLES = {
"messenger_api": "API_DB_PASSWORD",
"messenger_worker": "WORKER_DB_PASSWORD",
"messenger_dispatcher": "DISPATCHER_DB_PASSWORD",
}
def main():
if not ENV_FILE.is_file():
raise SystemExit("ERROR: .env not found")
lines = ENV_FILE.read_text(encoding="utf-8").splitlines()
existing_keys = {
line.split("=", 1)[0]
for line in lines
if "=" in line and not line.startswith("#")
}
for env_name in ROLES.values():
if env_name in existing_keys:
raise SystemExit(
f"ERROR: {env_name} already exists. "
"Refusing to overwrite credentials."
)
# Hexadecimal passwords are easy to use in connection URIs.
passwords = {
role: secrets.token_hex(32)
for role in ROLES
}
# Passwords are sent to psql via stdin.
# They are not passed as command-line arguments.
statements = ["BEGIN;"]
for role, password in passwords.items():
statements.append(
f"ALTER ROLE {role} "
f"WITH LOGIN PASSWORD '{password}';"
)
statements.append("COMMIT;")
sql = "\n".join(statements) + "\n"
command = [
"docker", "compose", "exec", "-T",
"db",
"psql",
"-X",
"-v", "ON_ERROR_STOP=1",
"-U", "messenger",
"-d", "messenger",
"-q",
]
result = subprocess.run(
command,
input=sql,
text=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.returncode != 0:
print("ERROR: PostgreSQL role configuration failed.")
print("Check database availability and permissions.")
raise SystemExit(1)
# Update the ignored local .env only after SQL succeeds.
# No secret values are printed.
with ENV_FILE.open("a", encoding="utf-8") as file:
file.write("\n# Lab7 scoped database credentials\n")
for role, env_name in ROLES.items():
file.write(f"{env_name}={passwords[role]}\n")
os.chmod(ENV_FILE, 0o600)
print("PASS: PostgreSQL service roles enabled.")
print("PASS: Independent credentials generated.")
print("PASS: Credentials saved to ignored .env.")
print("Secret values were not displayed.")
if __name__ == "__main__":
main()
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
BASE="$HOME/.local/share/mtusi2026lab7/pki"
DEST="$BASE/openbao-clients"
test -f "$BASE/ca.crt"
test -f "$BASE/ca.key"
mkdir -p "$DEST"
chmod 700 "$DEST"
for service in api1 api2 worker; do
cert="$DEST/${service}.crt"
key="$DEST/${service}.key"
if [[ -e "$cert" || -e "$key" ]]; then
echo "FAIL: certificate already exists for $service" >&2
exit 1
fi
done
for service in api1 api2 worker; do
name="lab7-openbao-${service}"
temp="$(mktemp -d "$DEST/.${service}.XXXXXX")"
openssl req \
-new \
-newkey rsa:3072 \
-nodes \
-keyout "$temp/client.key" \
-out "$temp/client.csr" \
-subj "/CN=$name" \
>/dev/null 2>&1
cat > "$temp/extensions.cnf" <<EOF
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature
extendedKeyUsage=clientAuth
subjectKeyIdentifier=hash
EOF
serial="0x$(openssl rand -hex 16)"
openssl x509 \
-req \
-in "$temp/client.csr" \
-CA "$BASE/ca.crt" \
-CAkey "$BASE/ca.key" \
-set_serial "$serial" \
-out "$temp/client.crt" \
-days 180 \
-sha256 \
-extfile "$temp/extensions.cnf" \
>/dev/null 2>&1
chmod 600 "$temp/client.key"
chmod 644 "$temp/client.crt"
mv "$temp/client.key" "$DEST/${service}.key"
mv "$temp/client.crt" "$DEST/${service}.crt"
rm -rf -- "$temp"
echo "PASS: OpenBao client certificate issued for $service"
done
echo "PASS: three separate OpenBao client identities created"
+236
View File
@@ -0,0 +1,236 @@
#!/usr/bin/env python3
"""Copy existing API/worker credentials to OpenBao KV v2."""
import hmac
import json
import os
import ssl
import stat
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
INIT_FILE = BASE / "operator/openbao-init.json"
CA_FILE = BASE / "pki/ca.crt"
BAO_URL = "https://localhost:8200"
SECRET_FIELDS = {
"api": (
"DATABASE_URL",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
"worker": (
"DATABASE_URL",
"RABBITMQ_USER",
"RABBITMQ_PASSWORD",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
}
def check(condition, message):
if not condition:
raise RuntimeError(message)
print("PASS:", message)
def request(method, path, token, context, payload=None):
data = None
if payload is not None:
data = json.dumps(payload).encode("utf-8")
headers = {"X-Vault-Token": token}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BAO_URL + path,
data=data,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(
req,
context=context,
timeout=15,
) as response:
body = response.read()
return (
response.status,
json.loads(body) if body else {},
)
except urllib.error.HTTPError as exc:
if exc.code == 404:
return 404, {}
# Do not print the response body or credentials.
raise RuntimeError(
"OpenBao request failed with HTTP {}".format(
exc.code
)
) from None
def equal_secrets(actual, expected):
if set(actual) != set(expected):
return False
return all(
isinstance(actual[key], str)
and hmac.compare_digest(actual[key], value)
for key, value in expected.items()
)
def main():
mode = stat.S_IMODE(INIT_FILE.stat().st_mode)
check(mode == 0o600, "Operator file permissions are 600")
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
context = ssl.create_default_context(
cafile=str(CA_FILE)
)
result = subprocess.run(
["docker", "compose", "config", "--format", "json"],
check=True,
capture_output=True,
text=True,
)
services = json.loads(result.stdout)["services"]
api1_env = services["api1"]["environment"]
api2_env = services["api2"]["environment"]
worker_env = services["worker"]["environment"]
check(
all(
api1_env.get(key) == api2_env.get(key)
for key in SECRET_FIELDS["api"]
),
"API1 and API2 credentials match",
)
environments = {
"api": api1_env,
"worker": worker_env,
}
values = {}
for role, fields in SECRET_FIELDS.items():
source = environments[role]
values[role] = {
key: source.get(key)
for key in fields
}
check(
all(
isinstance(value, str) and bool(value)
for value in values[role].values()
),
"{} credentials are configured".format(role),
)
# Check existing KV values before making changes.
existing = {}
for role in SECRET_FIELDS:
path = "/v1/lab7/data/{}/runtime".format(role)
status, response = request(
"GET",
path,
root_token,
context,
)
if status == 404:
existing[role] = False
continue
stored = response["data"]["data"]
check(
equal_secrets(stored, values[role]),
"{} existing secret matches Compose".format(role),
)
existing[role] = True
# New secrets are created only when absent.
# CAS=0 prevents accidental overwriting.
for role in SECRET_FIELDS:
if existing[role]:
print("PASS: {} secret already stored".format(role))
continue
path = "/v1/lab7/data/{}/runtime".format(role)
status, _ = request(
"POST",
path,
root_token,
context,
{
"options": {"cas": 0},
"data": values[role],
},
)
check(
status in (200, 204),
"{} runtime secret stored".format(role),
)
# Read back and compare without displaying values.
for role in SECRET_FIELDS:
path = "/v1/lab7/data/{}/runtime".format(role)
status, response = request(
"GET",
path,
root_token,
context,
)
check(
status == 200
and equal_secrets(
response["data"]["data"],
values[role],
),
"{} KV v2 readback verified".format(role),
)
print("PASS: OpenBao HTTPS certificate verified")
print("PASS: API and worker secrets separated")
print("PASS: no credential values printed")
print("PASS: working application configuration unchanged")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: secret bootstrap:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env bash
set -Eeuo pipefail
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
echo "FAIL: existing CA certificate or key is missing"
exit 1
fi
if [[ -e "$PKI_DIR/openbao.crt" || -e "$PKI_DIR/openbao.key" ]]; then
echo "FAIL: OpenBao TLS files already exist; refusing to overwrite"
exit 1
fi
umask 077
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:3072 \
-out "$WORK_DIR/openbao.key" 2>/dev/null
openssl req -new -sha256 \
-key "$WORK_DIR/openbao.key" \
-subj "/CN=openbao" \
-out "$WORK_DIR/openbao.csr"
cat > "$WORK_DIR/openbao.ext" <<'EOF'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:openbao,DNS:localhost,IP:127.0.0.1
EOF
openssl x509 -req -sha256 \
-in "$WORK_DIR/openbao.csr" \
-CA "$PKI_DIR/ca.crt" \
-CAkey "$PKI_DIR/ca.key" \
-CAserial "$PKI_DIR/ca.srl" \
-CAcreateserial \
-out "$WORK_DIR/openbao.crt" \
-days 365 \
-extfile "$WORK_DIR/openbao.ext"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname openbao \
"$WORK_DIR/openbao.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname localhost \
"$WORK_DIR/openbao.crt"
install -m 644 \
"$WORK_DIR/openbao.crt" \
"$PKI_DIR/openbao.crt"
# The OpenBao container runs with UID=100 and GID=1000.
sudo install -o 100 -g 1000 -m 600 \
"$WORK_DIR/openbao.key" \
"$PKI_DIR/openbao.key"
echo "PASS: OpenBao TLS certificate issued"
echo "PASS: existing CA trusted"
echo "PASS: SAN contains openbao and localhost"
echo "PASS: private key owned by UID=100 GID=1000"
echo "PASS: private key permissions are 600"
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
mkdir -p "$PKI_DIR"
chmod 700 "$PKI_DIR"
# Never overwrite an existing CA.
if [[ -e "$PKI_DIR/ca.key" || -e "$PKI_DIR/ca.crt" ]]; then
echo "ERROR: PKI already exists at $PKI_DIR"
echo "Refusing to replace existing keys."
exit 1
fi
for tool in openssl mktemp; do
command -v "$tool" >/dev/null || {
echo "Missing tool: $tool"
exit 1
}
done
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
create_ca() {
local prefix="$1"
local common_name="$2"
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:3072 \
-out "$PKI_DIR/$prefix.key" 2>/dev/null
openssl req -x509 -new -sha256 \
-days 365 \
-key "$PKI_DIR/$prefix.key" \
-out "$PKI_DIR/$prefix.crt" \
-subj "/CN=$common_name" \
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
-addext "keyUsage=critical,keyCertSign,cRLSign"
chmod 600 "$PKI_DIR/$prefix.key"
chmod 644 "$PKI_DIR/$prefix.crt"
}
create_leaf() {
local name="$1"
local common_name="$2"
local san="$3"
local usage="$4"
local ca_prefix="${5:-ca}"
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:2048 \
-out "$PKI_DIR/$name.key" 2>/dev/null
openssl req -new -sha256 \
-key "$PKI_DIR/$name.key" \
-out "$WORK_DIR/$name.csr" \
-subj "/CN=$common_name"
cat > "$WORK_DIR/$name.ext" <<EOF
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=$usage
subjectAltName=$san
EOF
openssl x509 -req -sha256 \
-in "$WORK_DIR/$name.csr" \
-CA "$PKI_DIR/$ca_prefix.crt" \
-CAkey "$PKI_DIR/$ca_prefix.key" \
-CAserial "$WORK_DIR/$ca_prefix.srl" \
-CAcreateserial \
-days 90 \
-out "$PKI_DIR/$name.crt" \
-extfile "$WORK_DIR/$name.ext" 2>/dev/null
chmod 600 "$PKI_DIR/$name.key"
chmod 644 "$PKI_DIR/$name.crt"
}
echo "Generating lab7 private CA..."
create_ca ca "MTUSI Lab7 Local CA"
echo "Generating HTTPS ingress certificate..."
create_leaf \
ingress \
localhost \
"DNS:localhost,IP:127.0.0.1" \
serverAuth
echo "Generating API server certificates..."
create_leaf \
api1 \
api1 \
"DNS:api1,DNS:messenger-api.internal" \
serverAuth
create_leaf \
api2 \
api2 \
"DNS:api2,DNS:messenger-api.internal" \
serverAuth
echo "Generating authorized LB client certificate..."
create_leaf \
lb-client \
lb.messenger.internal \
"DNS:lb.messenger.internal" \
clientAuth
echo "Generating unauthorized client identity..."
create_leaf \
unauthorized-client \
unauthorized.messenger.internal \
"DNS:unauthorized.messenger.internal" \
clientAuth
echo "Generating separate untrusted CA..."
create_ca rogue-ca "MTUSI Lab7 Untrusted Test CA"
create_leaf \
rogue-client \
rogue.messenger.internal \
"DNS:rogue.messenger.internal" \
clientAuth \
rogue-ca
echo "Verifying issued certificates..."
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname localhost \
"$PKI_DIR/ingress.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname api1 \
"$PKI_DIR/api1.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname api2 \
"$PKI_DIR/api2.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslclient \
"$PKI_DIR/lb-client.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslclient \
"$PKI_DIR/unauthorized-client.crt"
echo
echo "PASS: local CA and TLS certificates generated."
echo "PKI directory: $PKI_DIR"
echo "CA certificate: $PKI_DIR/ca.crt"
echo
echo "IMPORTANT:"
echo "- Never commit private keys."
echo "- Keep the CA private key operator-only."
echo "- Do not copy the PKI directory into Docker images."
echo "- Unauthorized and rogue certificates are test fixtures only."
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
echo "ERROR: Lab7 CA not found."
exit 1
fi
if [[ -e "$PKI_DIR/db.key" || -e "$PKI_DIR/db.crt" ]]; then
echo "ERROR: PostgreSQL certificate already exists."
echo "Refusing to overwrite existing credentials."
exit 1
fi
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
echo "Generating PostgreSQL private key..."
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:2048 \
-out "$WORK_DIR/db.key" 2>/dev/null
echo "Creating certificate signing request..."
openssl req -new -sha256 \
-key "$WORK_DIR/db.key" \
-out "$WORK_DIR/db.csr" \
-subj "/CN=db"
cat > "$WORK_DIR/db.ext" <<EOF
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:db
EOF
echo "Signing certificate with Lab7 CA..."
openssl x509 -req -sha256 \
-in "$WORK_DIR/db.csr" \
-CA "$PKI_DIR/ca.crt" \
-CAkey "$PKI_DIR/ca.key" \
-CAserial "$WORK_DIR/ca.srl" \
-CAcreateserial \
-days 90 \
-out "$WORK_DIR/db.crt" \
-extfile "$WORK_DIR/db.ext" 2>/dev/null
echo "Verifying CA and hostname..."
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname db \
"$WORK_DIR/db.crt"
install -m 600 "$WORK_DIR/db.key" "$PKI_DIR/db.key"
install -m 644 "$WORK_DIR/db.crt" "$PKI_DIR/db.crt"
echo
echo "PASS: PostgreSQL TLS certificate created."
echo "SAN: DNS:db"
echo "Private key retained outside Git."
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Create separate RabbitMQ service accounts without printing passwords."""
import os
import secrets
import subprocess
from pathlib import Path
ENV_FILE = Path(".env")
ACCOUNTS = {
"messenger_publisher": {
"env": "RABBITMQ_PUBLISHER_PASSWORD",
"configure": "^image_jobs$",
"write": r"^amq\.default$",
"read": "^$",
},
"messenger_consumer": {
"env": "RABBITMQ_CONSUMER_PASSWORD",
"configure": "^image_jobs$",
"write": "^$",
"read": "^image_jobs$",
},
}
def rabbitmqctl(*arguments, password=None):
command = [
"docker", "compose", "exec", "-T",
"rabbitmq", "rabbitmqctl",
*arguments,
]
result = subprocess.run(
command,
input=None if password is None else password + "\n",
text=True,
capture_output=True,
)
if result.returncode != 0:
raise RuntimeError(
"RabbitMQ command failed: " + arguments[0]
)
return result.stdout
def main():
if not ENV_FILE.is_file():
raise SystemExit("ERROR: .env not found")
contents = ENV_FILE.read_text(encoding="utf-8")
for account in ACCOUNTS.values():
key = account["env"]
if any(
line.strip().startswith(key + "=")
for line in contents.splitlines()
):
raise SystemExit(
f"ERROR: {key} already exists in .env"
)
try:
existing_users = rabbitmqctl("list_users")
except RuntimeError as exc:
raise SystemExit(str(exc))
for username in ACCOUNTS:
if any(
line.split("\t")[0].strip() == username
for line in existing_users.splitlines()
):
raise SystemExit(
f"ERROR: {username} already exists in RabbitMQ"
)
generated = {}
try:
for username, settings in ACCOUNTS.items():
password = secrets.token_hex(32)
rabbitmqctl(
"add_user", username,
password=password,
)
rabbitmqctl(
"set_permissions",
"-p", "/",
username,
settings["configure"],
settings["write"],
settings["read"],
)
generated[settings["env"]] = password
print(f"PASS: {username} created with scoped ACL")
except RuntimeError as exc:
print("ERROR:", exc)
print(
"RabbitMQ may contain partially created accounts. "
"Do not rerun automatically."
)
raise SystemExit(1)
with ENV_FILE.open("a", encoding="utf-8") as file:
file.write("\n# Lab7 RabbitMQ service credentials\n")
for key, password in generated.items():
file.write(f"{key}={password}\n")
os.chmod(ENV_FILE, 0o600)
print("PASS: RabbitMQ passwords stored in ignored .env")
print("PASS: No passwords printed")
print("Existing application credentials were not changed")
if __name__ == "__main__":
main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Generate scoped RustFS credentials in the local .env file."""
import os
import re
import secrets
from pathlib import Path
ENV_FILE = Path(__file__).resolve().parent.parent / ".env"
CREDENTIALS = {
"S3_API_ACCESS_KEY": "messenger_s3_api",
"S3_API_SECRET_KEY": secrets.token_hex(32),
"S3_WORKER_ACCESS_KEY": "messenger_s3_worker",
"S3_WORKER_SECRET_KEY": secrets.token_hex(32),
}
def main():
if not ENV_FILE.is_file():
raise SystemExit("FAIL: existing .env file not found")
original = ENV_FILE.read_text(encoding="utf-8")
existing = set(
re.findall(
r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=",
original,
flags=re.MULTILINE,
)
)
conflicts = existing.intersection(CREDENTIALS)
if conflicts:
print("FAIL: S3 service credentials already exist")
print("Existing variable names:", ", ".join(sorted(conflicts)))
print("Refusing to overwrite existing credentials")
raise SystemExit(1)
addition = "\n# Scoped RustFS IAM credentials\n"
for name, value in CREDENTIALS.items():
addition += f"{name}={value}\n"
prefix = "" if not original or original.endswith("\n") else "\n"
with ENV_FILE.open("a", encoding="utf-8") as file:
file.write(prefix + addition)
if os.name == "posix":
ENV_FILE.chmod(0o600)
print("PASS: API IAM credentials generated")
print("PASS: worker IAM credentials generated")
print("PASS: credentials saved to local .env")
print("PASS: existing S3 root credentials preserved")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
set -Eeuo pipefail
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
TLS_DIR="$PKI_DIR/rustfs-tls"
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
echo "FAIL: existing CA certificate or key is missing"
exit 1
fi
if [[ -e "$TLS_DIR/rustfs_cert.pem" || -e "$TLS_DIR/rustfs_key.pem" ]]; then
echo "FAIL: RustFS TLS files already exist; refusing to overwrite"
exit 1
fi
umask 077
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:3072 \
-out "$WORK_DIR/rustfs_key.pem" 2>/dev/null
openssl req -new -sha256 \
-key "$WORK_DIR/rustfs_key.pem" \
-subj "/CN=minio" \
-out "$WORK_DIR/rustfs.csr"
cat > "$WORK_DIR/rustfs.ext" <<'EOF'
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:minio
EOF
openssl x509 -req -sha256 \
-in "$WORK_DIR/rustfs.csr" \
-CA "$PKI_DIR/ca.crt" \
-CAkey "$PKI_DIR/ca.key" \
-CAserial "$PKI_DIR/ca.srl" \
-CAcreateserial \
-out "$WORK_DIR/rustfs_cert.pem" \
-days 365 \
-extfile "$WORK_DIR/rustfs.ext"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname minio \
"$WORK_DIR/rustfs_cert.pem"
mkdir -p "$TLS_DIR"
chmod 700 "$TLS_DIR"
install -m 644 \
"$WORK_DIR/rustfs_cert.pem" \
"$TLS_DIR/rustfs_cert.pem"
install -m 600 \
"$WORK_DIR/rustfs_key.pem" \
"$TLS_DIR/rustfs_key.pem"
# RustFS inside Docker runs with UID/GID 10001.
sudo chown 10001:10001 \
"$TLS_DIR/rustfs_cert.pem" \
"$TLS_DIR/rustfs_key.pem"
chmod 750 "$TLS_DIR"
echo "PASS: RustFS certificate issued and verified"
echo "PASS: SAN DNS:minio"
echo "PASS: RustFS private key owned by UID/GID 10001"
echo "TLS directory: $TLS_DIR"
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Configure scoped certificate authentication in OpenBao."""
import json
import ssl
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
URL = "https://localhost:8200/v1"
SERVICES = {
"api1": "messenger-api",
"api2": "messenger-api",
"worker": "messenger-worker",
}
def request(method, path, token, tls, payload=None):
headers = {"X-Vault-Token": token}
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
raw = response.read()
return json.loads(raw) if raw else {}
def main():
with (BASE / "operator/openbao-init.json").open(
encoding="utf-8"
) as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
methods = request(
"GET",
"/sys/auth",
root_token,
tls,
)
if "cert/" not in methods:
request(
"POST",
"/sys/auth/cert",
root_token,
tls,
{"type": "cert"},
)
print("PASS: certificate auth method enabled")
elif methods["cert/"]["type"] == "cert":
print("PASS: certificate auth method already enabled")
else:
raise RuntimeError("Unexpected auth method at cert/")
for service, policy in SERVICES.items():
certificate = (
BASE
/ "pki/openbao-clients"
/ f"{service}.crt"
).read_text(encoding="ascii")
request(
"POST",
f"/auth/cert/certs/lab7-{service}",
root_token,
tls,
{
"certificate": certificate,
"display_name": f"lab7-{service}",
"token_policies": [policy],
"token_no_default_policy": True,
"token_ttl": "1200s",
"token_max_ttl": "3600s",
"token_type": "service",
"token_num_uses": 0,
},
)
print(
f"PASS: {service} certificate registered "
f"with {policy} policy"
)
print("PASS: three scoped certificate identities configured")
print("PASS: no private keys or tokens printed")
if __name__ == "__main__":
try:
main()
except urllib.error.HTTPError as exc:
print(
f"FAIL: OpenBao HTTP {exc.code}",
file=sys.stderr,
)
raise SystemExit(1)
except Exception as exc:
print(
"FAIL: certificate auth configuration:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+150
View File
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
"""Issue a fresh one-time OpenBao AppRole bootstrap identity."""
import argparse
import json
import os
import ssl
import stat
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
OPERATOR = BASE / "operator"
INIT_FILE = OPERATOR / "openbao-init.json"
SERVICES = {
"api1": "messenger-api",
"api2": "messenger-api",
"worker": "messenger-worker",
}
def request(method, path, token, tls, payload=None):
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers = {"X-Vault-Token": token}
if body is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
"https://localhost:8200/v1" + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
data = response.read()
return json.loads(data) if data else {}
def write_private(path, value):
fd = os.open(
path,
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
0o600,
)
with os.fdopen(fd, "w", encoding="utf-8") as file:
file.write(value + "\n")
def main():
parser = argparse.ArgumentParser(
description="Issue one-time OpenBao bootstrap credentials"
)
parser.add_argument(
"service",
choices=sorted(SERVICES),
)
args = parser.parse_args()
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Operator file must have mode 600")
role = SERVICES[args.service]
destination = OPERATOR / "approle" / args.service
# Never overwrite credentials that may still be in use.
if destination.exists():
raise RuntimeError(
"Bootstrap directory already exists; refusing overwrite"
)
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
role_result = request(
"GET",
f"/auth/approle/role/{role}/role-id",
root_token,
tls,
)
role_id = role_result["data"]["role_id"]
secret_result = request(
"POST",
f"/auth/approle/role/{role}/secret-id",
root_token,
tls,
{},
)
secret_id = secret_result["data"]["secret_id"]
os.umask(0o077)
destination.mkdir(parents=True, mode=0o700)
try:
write_private(destination / "role-id", role_id)
write_private(destination / "secret-id", secret_id)
except Exception:
for name in ("role-id", "secret-id"):
(destination / name).unlink(missing_ok=True)
destination.rmdir()
raise
print(f"PASS: fresh bootstrap credentials issued for {args.service}")
print("PASS: separate AppRole identity used")
print("PASS: credentials stored outside Git")
print("PASS: credential files created with mode 600")
print("PASS: credential values not printed")
print("INFO: SecretID is valid for 30 minutes and one login")
if __name__ == "__main__":
try:
main()
except urllib.error.HTTPError as exc:
print(
f"FAIL: OpenBao returned HTTP {exc.code}",
file=sys.stderr,
)
raise SystemExit(1)
except Exception as exc:
print(
"FAIL: bootstrap issuance:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
echo "ERROR: Existing CA not found."
exit 1
fi
WORK_DIR="$(mktemp -d)"
trap 'rm -rf "$WORK_DIR"' EXIT
for name in api1 api2; do
echo "Reissuing certificate for $name..."
openssl genpkey \
-algorithm RSA \
-pkeyopt rsa_keygen_bits:2048 \
-out "$WORK_DIR/$name.key" 2>/dev/null
openssl req -new -sha256 \
-key "$WORK_DIR/$name.key" \
-out "$WORK_DIR/$name.csr" \
-subj "/CN=$name"
cat > "$WORK_DIR/$name.ext" <<EOF
basicConstraints=critical,CA:FALSE
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=serverAuth
subjectAltName=DNS:$name,DNS:messenger-api.internal
EOF
openssl x509 -req -sha256 \
-in "$WORK_DIR/$name.csr" \
-CA "$PKI_DIR/ca.crt" \
-CAkey "$PKI_DIR/ca.key" \
-CAcreateserial \
-days 90 \
-out "$WORK_DIR/$name.crt" \
-extfile "$WORK_DIR/$name.ext" 2>/dev/null
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname "$name" \
"$WORK_DIR/$name.crt"
openssl verify \
-CAfile "$PKI_DIR/ca.crt" \
-purpose sslserver \
-verify_hostname messenger-api.internal \
"$WORK_DIR/$name.crt"
cat "$WORK_DIR/$name.crt" "$WORK_DIR/$name.key" \
> "$WORK_DIR/$name.pem"
# Replace only after both hostname checks have passed.
install -m 600 "$WORK_DIR/$name.key" "$PKI_DIR/$name.key"
install -m 644 "$WORK_DIR/$name.crt" "$PKI_DIR/$name.crt"
install -m 600 "$WORK_DIR/$name.pem" "$PKI_DIR/$name.pem"
done
echo
echo "PASS: API certificates reissued with shared service SAN."
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""Replace previously issued OpenBao bootstrap credentials."""
import argparse
import json
import os
import runpy
import shutil
import ssl
import stat
import sys
import tempfile
import urllib.error
from pathlib import Path
HELPERS = runpy.run_path(
str(Path(__file__).with_name("issue-openbao-bootstrap.py"))
)
BASE = HELPERS["BASE"]
OPERATOR = HELPERS["OPERATOR"]
INIT_FILE = HELPERS["INIT_FILE"]
SERVICES = HELPERS["SERVICES"]
request = HELPERS["request"]
write_private = HELPERS["write_private"]
def main():
parser = argparse.ArgumentParser(
description="Reissue existing OpenBao AppRole credentials"
)
parser.add_argument("service", choices=sorted(SERVICES))
args = parser.parse_args()
role = SERVICES[args.service]
parent = OPERATOR / "approle"
destination = parent / args.service
if not destination.is_dir() or destination.is_symlink():
raise RuntimeError(
"Existing bootstrap directory required"
)
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Operator file must have mode 600")
old_role_file = destination / "role-id"
old_secret_file = destination / "secret-id"
for path in (old_role_file, old_secret_file):
if not path.is_file() or path.is_symlink():
raise RuntimeError("Invalid existing credential file")
old_secret_id = old_secret_file.read_text(
encoding="utf-8"
).strip()
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
role_result = request(
"GET",
f"/auth/approle/role/{role}/role-id",
root_token,
tls,
)
role_id = role_result["data"]["role_id"]
os.umask(0o077)
with tempfile.TemporaryDirectory(
prefix=f".{args.service}-new-",
dir=parent,
) as temp:
staging = Path(temp) / "credentials"
staging.mkdir(mode=0o700)
secret_result = request(
"POST",
f"/auth/approle/role/{role}/secret-id",
root_token,
tls,
{},
)
new_secret_id = secret_result["data"]["secret_id"]
try:
write_private(staging / "role-id", role_id)
write_private(staging / "secret-id", new_secret_id)
except Exception:
try:
request(
"POST",
f"/auth/approle/role/{role}/secret-id/destroy",
root_token,
tls,
{"secret_id": new_secret_id},
)
except Exception:
print(
"WARNING: unused new SecretID cleanup failed",
file=sys.stderr,
)
raise
backup = Path(temp) / "previous"
os.replace(destination, backup)
try:
os.replace(staging, destination)
except Exception:
os.replace(backup, destination)
raise
# The replacement is now installed.
# Revoke the previous SecretID if it is still valid.
try:
request(
"POST",
f"/auth/approle/role/{role}/secret-id/destroy",
root_token,
tls,
{"secret_id": old_secret_id},
)
except urllib.error.HTTPError as exc:
# A previously consumed SecretID may already be absent.
print(
f"INFO: previous SecretID cleanup HTTP {exc.code}"
)
shutil.rmtree(backup)
print(f"PASS: credentials reissued for {args.service}")
print("PASS: previous credential directory replaced")
print("PASS: new files stored outside Git")
print("PASS: credentials not printed")
print("INFO: new SecretID expires in 30 minutes")
print("INFO: new SecretID supports one authentication")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: reissuance:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
echo "[1/5] Stopping API sidecars and application services"
docker compose stop \
api1-mtls api2-mtls \
api1 api2 worker dispatcher
echo "[2/5] Restarting persistent dependencies"
docker compose restart db minio rabbitmq
echo "[3/5] Waiting for PostgreSQL and RabbitMQ"
docker compose up -d --no-deps --wait db rabbitmq
echo "[4/5] Starting application services"
docker compose up -d --no-deps dispatcher worker
docker compose up -d --no-deps --wait api1 api2
echo "[5/5] Recreating mTLS sidecars"
docker compose up -d --no-deps --force-recreate \
api1-mtls api2-mtls
echo "PASS: services restarted without removing volumes"
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
if [[ -z "${TARGET_INSTANCE_ID:-}" ]]; then
echo "FAIL: TARGET_INSTANCE_ID is missing" >&2
exit 1
fi
for service in api1 api2; do
instance_id=$(
docker compose exec -T "$service" python -c '
import urllib.request
with urllib.request.urlopen(
"http://127.0.0.1:8080/health/live",
timeout=2,
) as response:
print(response.headers.get("X-Instance-Id", ""))
' 2>/dev/null
) || continue
if [[ "$instance_id" == "$TARGET_INSTANCE_ID" ]]; then
echo "Stopping replica: $service"
docker compose stop -t 2 \
"${service}-mtls" "$service"
echo "PASS: target replica stopped"
exit 0
fi
done
echo "FAIL: target API instance not found" >&2
exit 1
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
import os
import sys
import psycopg
ROLE_TESTS = {
"messenger_api": {
"allowed": [
("read users", "SELECT id FROM public.users LIMIT 0"),
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
],
"denied": [
("read migration history",
"SELECT * FROM public.schema_migrations LIMIT 0"),
("create tables",
"CREATE TABLE public.lab7_acl_test (id integer)"),
],
},
"messenger_worker": {
"allowed": [
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
("read attachments", "SELECT id FROM public.attachments LIMIT 0"),
("read variants", "SELECT * FROM public.attachment_variants LIMIT 0"),
],
"denied": [
("read users", "SELECT * FROM public.users LIMIT 0"),
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
("read messages", "SELECT * FROM public.messages LIMIT 0"),
],
},
"messenger_dispatcher": {
"allowed": [
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
],
"denied": [
("read users", "SELECT * FROM public.users LIMIT 0"),
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
("read messages", "SELECT * FROM public.messages LIMIT 0"),
("read attachments", "SELECT * FROM public.attachments LIMIT 0"),
],
},
}
def run_query(conn, label, sql, should_succeed):
# Every test runs in its own transaction.
# All changes are rolled back, even if an unexpected
# permission grants the operation.
try:
with conn.transaction():
with conn.cursor() as cursor:
cursor.execute(sql)
if should_succeed:
print(f"PASS: allowed - {label}")
else:
print(f"FAIL: forbidden operation succeeded - {label}")
return False
except psycopg.errors.InsufficientPrivilege:
if should_succeed:
print(f"FAIL: allowed operation denied - {label}")
return False
print(f"PASS: denied - {label}")
return True
except psycopg.Error as exc:
print(f"FAIL: unexpected SQL error - {label}")
print(f"SQLSTATE: {exc.sqlstate}")
return False
return should_succeed
def main():
url = os.environ["DATABASE_URL"]
if "sslmode=verify-full" not in url:
raise SystemExit("FAIL: sslmode=verify-full not configured")
passed = True
# Autocommit allows each conn.transaction() to be independent.
with psycopg.connect(url, autocommit=True) as conn:
role, encrypted, version = conn.execute("""
SELECT current_user, ssl, version
FROM pg_stat_ssl
WHERE pid = pg_backend_pid()
""").fetchone()
print(f"PostgreSQL role: {role}")
print(f"TLS encrypted: {encrypted}")
print(f"TLS version: {version}")
if not encrypted or role not in ROLE_TESTS:
raise SystemExit("FAIL: unexpected role or TLS state")
tests = ROLE_TESTS[role]
for label, sql in tests["allowed"]:
if not run_query(conn, label, sql, True):
passed = False
for label, sql in tests["denied"]:
if not run_query(conn, label, sql, False):
passed = False
if passed:
print(f"PASS: all ACL tests for {role}")
else:
print(f"FAIL: ACL tests for {role}")
sys.exit(1)
if __name__ == "__main__":
main()
+175
View File
@@ -0,0 +1,175 @@
import base64
import json
import subprocess
import time
import urllib.error
import urllib.request
import uuid
BASE_URL = "http://127.0.0.1:8080"
def docker(*args):
subprocess.run(
["docker", "compose", *args],
check=True,
)
def request(method, path, body=None, headers=None):
request_headers = dict(headers or {})
if isinstance(body, dict):
body = json.dumps(body).encode("utf-8")
request_headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BASE_URL + path,
data=body,
headers=request_headers,
method=method,
)
started = time.monotonic()
try:
with urllib.request.urlopen(req, timeout=5) as response:
response.read()
return response.status, time.monotonic() - started
except urllib.error.HTTPError as exc:
exc.read()
return exc.code, time.monotonic() - started
except (urllib.error.URLError, TimeoutError) as exc:
return type(exc).__name__, time.monotonic() - started
def login_header(username, password):
encoded = base64.b64encode(
f"{username}:{password}".encode("utf-8")
).decode("ascii")
return {
"Authorization": f"Basic {encoded}"
}
def wait_for_recovery(headers):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
status, duration = request(
"POST",
"/api/v1/auth/sessions",
body=b"",
headers=headers,
)
if status == 201:
print(
f"Recovery: HTTP 201, {duration:.3f}s",
flush=True,
)
return
time.sleep(2)
raise RuntimeError(
"Authentication did not recover after DB restart"
)
def main():
suffix = uuid.uuid4().hex[:12]
username = "lab6_db_" + suffix
password = "IncidentTest_" + suffix
status, duration = request(
"POST",
"/api/v1/users",
body={
"username": username,
"display_name": "DB incident test",
"password": password,
},
)
if status != 201:
raise RuntimeError(
f"Cannot create test user: HTTP {status}"
)
headers = login_header(username, password)
status, _ = request(
"POST",
"/api/v1/auth/sessions",
body=b"",
headers=headers,
)
if status != 201:
raise RuntimeError(
f"Baseline login failed: HTTP {status}"
)
print("Baseline: authentication HTTP 201", flush=True)
observed_failures = 0
print("INCIDENT START: stopping PostgreSQL", flush=True)
try:
docker("stop", "db")
for attempt in range(1, 6):
status, duration = request(
"POST",
"/api/v1/auth/sessions",
body=b"",
headers=headers,
)
print(
f"Probe {attempt}: status={status}, "
f"duration={duration:.3f}s",
flush=True,
)
if status != 201:
observed_failures += 1
time.sleep(2)
finally:
print(
"INCIDENT END: restoring PostgreSQL",
flush=True,
)
docker("up", "-d", "--wait", "db")
wait_for_recovery(headers)
print(
f"Failed requests during incident: "
f"{observed_failures}/5",
flush=True,
)
if observed_failures == 0:
raise RuntimeError(
"The database incident did not affect requests"
)
print(
"PASS: database failure observed and recovered",
flush=True,
)
if __name__ == "__main__":
main()
+77
View File
@@ -0,0 +1,77 @@
import base64
import os
import sys
import urllib.error
import urllib.request
import uuid
BASE_URL = os.getenv("BASE_URL", "https://localhost:8443").rstrip("/")
CA_FILE = os.getenv("CA_FILE")
if not CA_FILE:
sys.exit("ERROR: CA_FILE must point to a trusted CA certificate")
import ssl
SSL_CONTEXT = ssl.create_default_context(cafile=CA_FILE)
username = "rl_" + uuid.uuid4().hex[:16]
password = "Wrong-Password-For-Rate-Limit-2026"
def login():
credentials = base64.b64encode(
f"{username}:{password}".encode()
).decode()
request = urllib.request.Request(
BASE_URL + "/api/v1/auth/sessions",
data=b"",
method="POST",
headers={"Authorization": "Basic " + credentials},
)
try:
with urllib.request.urlopen(
request,
context=SSL_CONTEXT,
timeout=10,
) as response:
return response.status, response.headers
except urllib.error.HTTPError as exc:
return exc.code, exc.headers
print("Testing rate limit with username:", username)
statuses = []
for attempt in range(1, 7):
status, headers = login()
statuses.append(status)
print(
f"Attempt {attempt}: HTTP {status}, "
f"Retry-After={headers.get('Retry-After')}"
)
if attempt <= 5:
assert status == 401, (
f"Expected HTTP 401 for attempt {attempt}, got {status}"
)
else:
assert status == 429, (
f"Expected HTTP 429 for attempt {attempt}, got {status}"
)
retry_after = headers.get("Retry-After")
assert retry_after and retry_after.isdigit(), (
"Missing or invalid Retry-After"
)
assert int(retry_after) > 0
print("PASS: shared login rate limit and Retry-After")
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
set -euo pipefail
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
NETWORK="${COMPOSE_PROJECT_NAME:-mtusi2026lab7}_default"
for name in api1 api2; do
echo
echo "=== Testing $name mTLS ==="
run_curl() {
docker run --rm \
--network "$NETWORK" \
--user "$(id -u):$(id -g)" \
-v "$PKI_DIR:/pki:ro" \
curlimages/curl:8.16.0 \
--silent --show-error \
--max-time 10 \
--cacert /pki/ca.crt \
--resolve "$name:8443:$(docker inspect \
-f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \
"mtusi2026lab7-$name-1")" \
"$@" \
"https://$name:8443/health/ready"
}
echo "[1] Authorized LB certificate"
response="$(run_curl \
--cert /pki/lb-client.crt \
--key /pki/lb-client.key)"
echo "$response"
[[ "$response" == *'"status":"ok"'* ]] || exit 1
echo "[2] No client certificate"
if run_curl > /dev/null 2>&1; then
echo "FAIL: connection accepted without client certificate"
exit 1
fi
echo "PASS: no certificate rejected"
echo "[3] Untrusted CA certificate"
if run_curl \
--cert /pki/rogue-client.crt \
--key /pki/rogue-client.key \
> /dev/null 2>&1; then
echo "FAIL: rogue certificate accepted"
exit 1
fi
echo "PASS: rogue CA rejected"
echo "[4] Trusted CA, forbidden SAN"
code="$(run_curl \
--cert /pki/unauthorized-client.crt \
--key /pki/unauthorized-client.key \
-o /dev/null -w '%{http_code}')"
echo "HTTP $code"
[[ "$code" == "403" ]] || {
echo "FAIL: expected HTTP 403"
exit 1
}
echo "PASS: $name mTLS identity enforcement"
done
echo
echo "PASS: all mTLS tests passed"
+251
View File
@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""OpenBao AppRole and KV v2 ACL tests for lab7."""
import json
import ssl
import stat
import uuid
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
INIT_FILE = BASE / "operator/openbao-init.json"
URL = "https://localhost:8200/v1"
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise SystemExit("FAIL: operator secret file permissions")
with INIT_FILE.open(encoding="utf-8") as file:
ROOT_TOKEN = json.load(file)["root_token"]
TLS = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
TEST_ID = uuid.uuid4().hex
PATHS = {
"api": f"api/acl-test-{TEST_ID}",
"worker": f"worker/acl-test-{TEST_ID}",
}
TOKENS = []
def request(method, path, token=None, payload=None):
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers = {}
if token is not None:
headers["X-Vault-Token"] = token
if body is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=TLS,
timeout=15,
) as response:
raw = response.read()
return (
response.status,
json.loads(raw) if raw else {},
)
def passed(message):
print("PASS:", message)
def must_deny(method, path, token, payload=None):
try:
request(method, path, token, payload)
except urllib.error.HTTPError as exc:
if exc.code == 403:
return
raise AssertionError(
f"Expected HTTP 403, received {exc.code}"
) from None
raise AssertionError("Forbidden operation unexpectedly allowed")
def login(role):
name = f"messenger-{role}"
_, role_data = request(
"GET",
f"/auth/approle/role/{name}/role-id",
ROOT_TOKEN,
)
role_id = role_data["data"]["role_id"]
_, secret_data = request(
"POST",
f"/auth/approle/role/{name}/secret-id",
ROOT_TOKEN,
{},
)
secret_id = secret_data["data"]["secret_id"]
credentials = {
"role_id": role_id,
"secret_id": secret_id,
}
_, login_data = request(
"POST",
"/auth/approle/login",
payload=credentials,
)
auth = login_data["auth"]
token = auth["client_token"]
TOKENS.append(token)
assert 0 < auth["lease_duration"] <= 1200
assert name in auth["policies"]
assert "root" not in auth["policies"]
passed(f"{role}: scoped token issued with limited TTL")
# SecretID may only be used once.
try:
request(
"POST",
"/auth/approle/login",
payload=credentials,
)
except urllib.error.HTTPError as exc:
if exc.code not in (400, 403):
raise
passed(f"{role}: SecretID reuse denied")
else:
raise AssertionError("SecretID reused successfully")
return token
def main():
print("OpenBao HTTPS:", URL)
print("TLS verification: enabled")
# Create unique synthetic secrets using operator identity.
for role, path in PATHS.items():
request(
"POST",
"/lab7/data/" + path,
ROOT_TOKEN,
{"data": {"test_role": role}},
)
passed("temporary KV v2 secrets prepared")
api_token = login("api")
worker_token = login("worker")
# Allowed: each role reads its own path.
for role, token in (
("api", api_token),
("worker", worker_token),
):
_, result = request(
"GET",
"/lab7/data/" + PATHS[role],
token,
)
assert result["data"]["data"]["test_role"] == role
passed(f"{role}: own secret read allowed")
# Denied: cross-role reads.
must_deny(
"GET",
"/lab7/data/" + PATHS["worker"],
api_token,
)
passed("API cannot read worker secrets")
must_deny(
"GET",
"/lab7/data/" + PATHS["api"],
worker_token,
)
passed("worker cannot read API secrets")
# Denied: updates, even within own path.
for role, token in (
("api", api_token),
("worker", worker_token),
):
must_deny(
"POST",
"/lab7/data/" + PATHS[role],
token,
{"data": {"test_role": "modified"}},
)
passed(f"{role}: secret modification denied")
# Denied: management of ACL policies.
for role, token in (
("api", api_token),
("worker", worker_token),
):
must_deny(
"GET",
"/sys/policies/acl/messenger-api",
token,
)
passed(f"{role}: policy administration denied")
print("PASS: all OpenBao AppRole ACL tests passed")
try:
main()
finally:
# Revoke only tokens created by this test.
for token in TOKENS:
try:
request(
"POST",
"/auth/token/revoke",
ROOT_TOKEN,
{"token": token},
)
except Exception as exc:
print(
"WARNING: token cleanup:",
type(exc).__name__,
)
# Remove only the unique test secrets.
for path in PATHS.values():
try:
request(
"DELETE",
"/lab7/metadata/" + path,
ROOT_TOKEN,
)
except Exception as exc:
print(
"WARNING: KV cleanup:",
type(exc).__name__,
)
print("OpenBao test cleanup attempted")
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""Verify OpenBao certificate auth and least-privilege ACLs."""
import json
import ssl
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7/pki"
URL = "https://localhost:8200/v1"
SERVICES = {
"api1": {
"policy": "messenger-api",
"own": "api",
"other": "worker",
},
"api2": {
"policy": "messenger-api",
"own": "api",
"other": "worker",
},
"worker": {
"policy": "messenger-worker",
"own": "worker",
"other": "api",
},
}
def request(method, path, tls, token=None, payload=None):
headers = {}
body = None
if token is not None:
headers["X-Vault-Token"] = token
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
URL + path,
headers=headers,
data=body,
method=method,
)
try:
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
raw = response.read()
result = json.loads(raw) if raw else {}
return response.status, result
except urllib.error.HTTPError as exc:
# Do not print HTTP response bodies: they may contain
# security-sensitive information.
return exc.code, {}
def verify_service(name, config):
cert = BASE / "openbao-clients" / f"{name}.crt"
key = BASE / "openbao-clients" / f"{name}.key"
tls = ssl.create_default_context(
cafile=str(BASE / "ca.crt")
)
tls.load_cert_chain(
certfile=str(cert),
keyfile=str(key),
)
print(f"=== {name} ===", flush=True)
status, result = request(
"POST",
"/auth/cert/login",
tls,
payload={"name": f"lab7-{name}"},
)
if status != 200:
raise RuntimeError(
f"{name}: certificate login HTTP {status}"
)
auth = result["auth"]
token = auth["client_token"]
print("PASS: certificate authentication successful")
try:
policies = set(auth.get("policies", []))
expected = {config["policy"]}
if policies != expected:
raise RuntimeError(
f"{name}: unexpected token policies"
)
print("PASS: only scoped service policy assigned")
own_path = (
f"/lab7/data/{config['own']}/runtime"
)
other_path = (
f"/lab7/data/{config['other']}/runtime"
)
status, result = request(
"GET",
own_path,
tls,
token=token,
)
if status != 200:
raise RuntimeError(
f"{name}: own secret read HTTP {status}"
)
secret = result.get("data", {}).get("data", {})
if not isinstance(secret, dict) or not secret:
raise RuntimeError(
f"{name}: own secret data missing"
)
print("PASS: own KV v2 secret readable")
status, _ = request(
"GET",
other_path,
tls,
token=token,
)
if status != 403:
raise RuntimeError(
f"{name}: cross-service read HTTP {status}"
)
print("PASS: cross-service KV read denied")
status, _ = request(
"POST",
own_path,
tls,
token=token,
payload={
"data": {
"acl_probe": "should-not-be-written"
}
},
)
if status != 403:
raise RuntimeError(
f"{name}: unauthorized write HTTP {status}"
)
print("PASS: KV modification denied")
finally:
status, _ = request(
"POST",
"/auth/token/revoke-self",
tls,
token=token,
payload={},
)
if status not in (200, 204):
raise RuntimeError(
f"{name}: token revocation HTTP {status}"
)
print("PASS: temporary token revoked")
def main():
for name, config in SERVICES.items():
verify_service(name, config)
print("PASS: three certificate identities verified")
print("PASS: scoped OpenBao certificate ACL tests completed")
print("PASS: no secret values or tokens printed")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: certificate ACL test:",
type(exc).__name__,
str(exc) if isinstance(exc, RuntimeError) else "",
file=sys.stderr,
)
raise SystemExit(1)
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Test certificate-based OpenBao bootstrap in isolated containers."""
import json
import subprocess
import sys
from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
BASE = Path.home() / ".local/share/mtusi2026lab7/pki"
SERVICES = {
"api1": {
"path": "lab7/data/api/runtime",
"fields": 3,
},
"api2": {
"path": "lab7/data/api/runtime",
"fields": 3,
},
"worker": {
"path": "lab7/data/worker/runtime",
"fields": 5,
},
}
def get_network():
container = subprocess.check_output(
["docker", "compose", "ps", "-q", "openbao"],
cwd=PROJECT,
text=True,
).strip()
if not container:
raise RuntimeError("OpenBao container not running")
data = json.loads(
subprocess.check_output(
["docker", "inspect", container],
text=True,
)
)[0]
networks = data["NetworkSettings"]["Networks"]
for name in networks:
if name.endswith("_default"):
return name
raise RuntimeError("Project Docker network not found")
def test_service(service, config, network):
print(f"=== {service} ===", flush=True)
cert = BASE / "openbao-clients" / f"{service}.crt"
key = BASE / "openbao-clients" / f"{service}.key"
ca = BASE / "ca.crt"
client_module = PROJECT / "src/openbao_cert_client.py"
for path in (cert, key, ca, client_module):
if not path.is_file():
raise RuntimeError(
f"Required file missing: {path.name}"
)
test_code = (
"from src.openbao_cert_client import read_runtime_secrets\n"
"import os\n"
"secrets = read_runtime_secrets()\n"
"assert len(secrets) == int(os.environ['EXPECTED_FIELDS'])\n"
"assert all(isinstance(v, str) and v for v in secrets.values())\n"
"print('PASS: certificate authentication and KV retrieval')\n"
"print('PASS: expected number of secret fields received')\n"
"print('PASS: no secret values printed')\n"
)
command = [
"docker", "run",
"--rm",
"--network", network,
"--mount",
(
f"type=bind,source={ca},"
"target=/etc/ssl/lab7/ca.crt,readonly"
),
"--mount",
(
f"type=bind,source={cert},"
"target=/run/lab7/bao/client.crt,readonly"
),
"--mount",
(
f"type=bind,source={key},"
"target=/run/lab7/bao/client.key,readonly"
),
"--mount",
(
f"type=bind,source={client_module},"
"target=/app/src/openbao_cert_client.py,readonly"
),
"-e", "BAO_ADDR=https://openbao:8200",
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
"-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt",
"-e", "BAO_KEY_FILE=/run/lab7/bao/client.key",
"-e", f"BAO_CERT_NAME=lab7-{service}",
"-e", f"BAO_SECRET_PATH={config['path']}",
"-e", f"EXPECTED_FIELDS={config['fields']}",
"--entrypoint", "python",
f"mtusi2026lab7-{service}",
"-c", test_code,
]
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=90,
)
if result.returncode != 0:
print(
f"FAIL: {service} container test "
f"exit code {result.returncode}",
file=sys.stderr,
)
raise RuntimeError("Container certificate test failed")
expected_lines = (
"PASS: certificate authentication and KV retrieval",
"PASS: expected number of secret fields received",
"PASS: no secret values printed",
)
for line in expected_lines:
if line not in result.stdout:
raise RuntimeError(
f"{service}: expected test result missing"
)
print(line, flush=True)
print(
f"PASS: {service} certificate bootstrap verified",
flush=True,
)
def main():
network = get_network()
for service, config in SERVICES.items():
test_service(service, config, network)
print("PASS: three certificate bootstrap tests completed")
print("PASS: running application containers unchanged")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: certificate bootstrap test:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env python3
"""Test certificate-based OpenBao entrypoint in Docker."""
import json
import subprocess
import sys
from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PKI = Path.home() / ".local/share/mtusi2026lab7/pki"
SERVICES = {
"api1": (
"lab7/data/api/runtime",
("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"),
),
"api2": (
"lab7/data/api/runtime",
("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"),
),
"worker": (
"lab7/data/worker/runtime",
(
"DATABASE_URL",
"RABBITMQ_USER",
"RABBITMQ_PASSWORD",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
),
}
def project_network():
container_id = subprocess.check_output(
["docker", "compose", "ps", "-q", "openbao"],
cwd=PROJECT,
text=True,
).strip()
if not container_id:
raise RuntimeError("OpenBao is not running")
details = json.loads(
subprocess.check_output(
["docker", "inspect", container_id],
text=True,
)
)[0]
for name in details["NetworkSettings"]["Networks"]:
if name.endswith("_default"):
return name
raise RuntimeError("Project Docker network not found")
def mount(source, target):
if not source.is_file():
raise RuntimeError(
"Required file missing: " + source.name
)
return (
f"type=bind,source={source},"
f"target={target},readonly"
)
def verify(service, secret_path, required, network):
print(f"=== {service} ===", flush=True)
cert = PKI / "openbao-clients" / f"{service}.crt"
key = PKI / "openbao-clients" / f"{service}.key"
child_code = (
"import os\n"
f"required = {required!r}\n"
"assert all("
"isinstance(os.environ.get(k), str) "
"and os.environ[k] for k in required"
")\n"
"print('PASS: child process received runtime credentials')\n"
)
command = [
"docker", "run", "--rm",
"--network", network,
"--mount", mount(
PKI / "ca.crt",
"/etc/ssl/lab7/ca.crt",
),
"--mount", mount(
cert,
"/run/lab7/bao/client.crt",
),
"--mount", mount(
key,
"/run/lab7/bao/client.key",
),
"--mount", mount(
PROJECT / "src/openbao_cert_client.py",
"/app/src/openbao_cert_client.py",
),
"--mount", mount(
PROJECT / "src/openbao_entrypoint.py",
"/app/src/openbao_entrypoint.py",
),
"-e", "BAO_ADDR=https://openbao:8200",
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
"-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt",
"-e", "BAO_KEY_FILE=/run/lab7/bao/client.key",
"-e", f"BAO_CERT_NAME=lab7-{service}",
"-e", f"BAO_SECRET_PATH={secret_path}",
"--entrypoint", "python",
f"mtusi2026lab7-{service}",
"-m", "src.openbao_entrypoint",
"--",
"python", "-c", child_code,
]
result = subprocess.run(
command,
capture_output=True,
text=True,
timeout=90,
)
if result.returncode != 0:
raise RuntimeError(
f"{service}: container exit code {result.returncode}"
)
expected = (
"PASS: runtime credentials loaded from OpenBao",
"PASS: child process received runtime credentials",
)
for line in expected:
if line not in result.stdout:
raise RuntimeError(
f"{service}: expected result missing"
)
print(line, flush=True)
print(
f"PASS: {service} certificate entrypoint verified",
flush=True,
)
def main():
network = project_network()
for service, (secret_path, required) in SERVICES.items():
verify(service, secret_path, required, network)
print("PASS: three certificate entrypoint tests completed")
print("PASS: running containers unchanged")
print("PASS: no secret values or tokens printed")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: certificate entrypoint test:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Verify OpenBao rejects mismatched certificate identities."""
import json
import ssl
import sys
import urllib.error
import urllib.request
from pathlib import Path
PKI = Path.home() / ".local/share/mtusi2026lab7/pki"
URL = "https://localhost:8200/v1"
CASES = (
("api1", "lab7-worker"),
("api2", "lab7-api1"),
("worker", "lab7-api2"),
)
def verify(source, claimed_identity):
tls = ssl.create_default_context(
cafile=str(PKI / "ca.crt")
)
tls.load_cert_chain(
certfile=str(
PKI / "openbao-clients" / f"{source}.crt"
),
keyfile=str(
PKI / "openbao-clients" / f"{source}.key"
),
)
body = json.dumps({
"name": claimed_identity,
}).encode("utf-8")
req = urllib.request.Request(
URL + "/auth/cert/login",
data=body,
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
data = json.load(response)
except urllib.error.HTTPError as exc:
if exc.code in (400, 403):
print(
f"PASS: {source} cannot authenticate "
f"as {claimed_identity}"
)
return
raise RuntimeError(
f"Unexpected authentication HTTP {exc.code}"
) from None
# Defensive cleanup if an unexpected login succeeded.
token = data.get("auth", {}).get("client_token")
if token:
revoke = urllib.request.Request(
URL + "/auth/token/revoke-self",
data=b"{}",
headers={
"Content-Type": "application/json",
"X-Vault-Token": token,
},
method="POST",
)
try:
with urllib.request.urlopen(
revoke,
context=tls,
timeout=15,
):
pass
except Exception:
print(
"WARNING: unexpected token revocation failed",
file=sys.stderr,
)
raise RuntimeError(
f"Certificate identity substitution accepted: {source}"
)
def main():
for source, claimed_identity in CASES:
verify(source, claimed_identity)
print("PASS: all certificate identity substitutions rejected")
print("PASS: no credentials or tokens printed")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: certificate identity test:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+271
View File
@@ -0,0 +1,271 @@
#!/usr/bin/env python3
"""Test OpenBao bootstrap from isolated API and worker containers."""
import json
import os
import ssl
import stat
import subprocess
import sys
import tempfile
import urllib.request
import urllib.error
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
OPERATOR = BASE / "operator"
INIT_FILE = OPERATOR / "openbao-init.json"
PROJECT = Path.cwd()
BAO_URL = "https://localhost:8200/v1"
SERVICES = {
"api1": "messenger-api",
"api2": "messenger-api",
"worker": "messenger-worker",
}
CONTAINER_TEST = """
import hmac
import os
from src.openbao_client import read_runtime_secrets
secrets = read_runtime_secrets()
role = os.environ["BAO_SECRET_PATH"].split("/")[2]
fields = (
"DATABASE_URL",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
)
if role == "worker":
fields += (
"RABBITMQ_USER",
"RABBITMQ_PASSWORD",
)
assert set(secrets) == set(fields), "Unexpected secret fields"
for field in fields:
assert hmac.compare_digest(
secrets[field],
os.environ[field],
), "Secret mismatch: " + field
print("PASS: AppRole authentication completed")
print("PASS: runtime secrets match service credentials")
print("PASS: scoped KV v2 secret loaded")
print("PASS: no secret values printed")
"""
def request(method, path, token, tls, payload=None):
body = None
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers = {"X-Vault-Token": token}
if body is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BAO_URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
data = response.read()
return json.loads(data) if data else {}
def private_file(path, value):
with path.open("x", encoding="utf-8") as file:
file.write(value + "\n")
path.chmod(0o600)
def main():
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Operator file must have mode 600")
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
module = PROJECT / "src/openbao_client.py"
if not module.is_file():
raise RuntimeError("OpenBao client module not found")
os.umask(0o077)
for service, role in SERVICES.items():
print("=== {} ===".format(service), flush=True)
role_response = request(
"GET",
"/auth/approle/role/{}/role-id".format(role),
root_token,
tls,
)
role_id = role_response["data"]["role_id"]
secret_response = request(
"POST",
"/auth/approle/role/{}/secret-id".format(role),
root_token,
tls,
{},
)
secret_data = secret_response["data"]
secret_id = secret_data["secret_id"]
accessor = secret_data["secret_id_accessor"]
try:
with tempfile.TemporaryDirectory(
prefix=".openbao-test-",
dir=OPERATOR,
) as temporary:
directory = Path(temporary)
private_file(directory / "role-id", role_id)
private_file(directory / "secret-id", secret_id)
command = [
"docker", "compose",
"run", "--rm", "-T", "--no-deps",
"-v",
"{}:/run/lab7/approle:ro".format(
directory
),
"-v",
"{}:/app/src/openbao_client.py:ro".format(
module
),
"-e", "BAO_ADDR=https://openbao:8200",
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
"-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id",
"-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id",
"-e",
"BAO_SECRET_PATH=lab7/data/{}/runtime".format(
"worker" if service == "worker" else "api"
),
"--entrypoint", "python",
service, "-",
]
result = subprocess.run(
command,
input=CONTAINER_TEST,
text=True,
capture_output=True,
check=False,
)
if result.returncode != 0:
print(
"FAIL: temporary container test failed",
file=sys.stderr,
)
print(
"INFO: container exit code:",
result.returncode,
file=sys.stderr,
)
raise RuntimeError(
"{} bootstrap test failed".format(service)
)
for line in result.stdout.splitlines():
if line.startswith("PASS:"):
print(line)
print(
"PASS: {} bootstrap verified".format(service),
flush=True,
)
finally:
# A single-use SecretID is normally removed
# automatically after successful authentication.
accessor_path = (
"/auth/approle/role/{}/secret-id-accessor".format(
role
)
)
try:
request(
"POST",
accessor_path + "/lookup",
root_token,
tls,
{"secret_id_accessor": accessor},
)
except urllib.error.HTTPError as exc:
if exc.code == 404:
print(
"PASS: consumed SecretID already absent",
flush=True,
)
else:
print(
"WARNING: SecretID lookup HTTP {}".format(
exc.code
),
file=sys.stderr,
)
else:
# Destroy only if the SecretID still exists.
try:
request(
"POST",
accessor_path + "/destroy",
root_token,
tls,
{"secret_id_accessor": accessor},
)
print(
"PASS: unused SecretID revoked",
flush=True,
)
except urllib.error.HTTPError as exc:
print(
"WARNING: SecretID cleanup HTTP {}".format(
exc.code
),
file=sys.stderr,
)
print("PASS: three independent bootstrap tests completed")
print("PASS: temporary credential files removed")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: OpenBao bootstrap:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+241
View File
@@ -0,0 +1,241 @@
#!/usr/bin/env python3
"""Test OpenBao entrypoint in an isolated API container."""
import json
import os
import ssl
import stat
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
OPERATOR = BASE / "operator"
INIT_FILE = OPERATOR / "openbao-init.json"
URL = "https://localhost:8200/v1"
if len(sys.argv) != 2 or sys.argv[1] not in ("api1", "api2", "worker"):
raise SystemExit(
"Usage: python3 scripts/test-openbao-entrypoint.py "
"{api1,api2,worker}"
)
SERVICE = sys.argv[1]
ROLE = (
"messenger-worker"
if SERVICE == "worker"
else "messenger-api"
)
SECRET_PATH = (
"lab7/data/worker/runtime"
if SERVICE == "worker"
else "lab7/data/api/runtime"
)
def request(method, path, token, tls, payload=None):
body = (
json.dumps(payload).encode("utf-8")
if payload is not None else None
)
headers = {"X-Vault-Token": token}
if body is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=tls,
timeout=15,
) as response:
raw = response.read()
return json.loads(raw) if raw else {}
def private_file(path, value):
with path.open("x", encoding="utf-8") as file:
file.write(value + "\n")
path.chmod(0o600)
def main():
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Invalid operator file permissions")
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
tls = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
container_id = subprocess.check_output(
["docker", "compose", "ps", "-q", "openbao"],
text=True,
).strip()
if not container_id:
raise RuntimeError("OpenBao container not running")
inspect = json.loads(subprocess.check_output(
["docker", "inspect", container_id],
text=True,
))[0]
networks = inspect["NetworkSettings"]["Networks"]
network = next(
(name for name in networks if name.endswith("_default")),
None,
)
if not network:
raise RuntimeError("Project Docker network not found")
role_result = request(
"GET",
f"/auth/approle/role/{ROLE}/role-id",
root_token,
tls,
)
role_id = role_result["data"]["role_id"]
secret_result = request(
"POST",
f"/auth/approle/role/{ROLE}/secret-id",
root_token,
tls,
{},
)
secret_data = secret_result["data"]
secret_id = secret_data["secret_id"]
accessor = secret_data["secret_id_accessor"]
print(
f"PASS: temporary {SERVICE} SecretID issued",
flush=True,
)
try:
os.umask(0o077)
with tempfile.TemporaryDirectory(
prefix=".openbao-entrypoint-",
dir=OPERATOR,
) as temporary:
directory = Path(temporary)
private_file(directory / "role-id", role_id)
private_file(directory / "secret-id", secret_id)
project = Path.cwd().resolve()
command = [
"docker", "run", "--rm",
"--network", network,
"--mount",
f"type=bind,source={directory},target=/run/lab7/approle,readonly",
"--mount",
f"type=bind,source={BASE / 'pki/ca.crt'},target=/etc/ssl/lab7/ca.crt,readonly",
"--mount",
f"type=bind,source={project / 'src/openbao_client.py'},target=/app/src/openbao_client.py,readonly",
"--mount",
f"type=bind,source={project / 'src/openbao_entrypoint.py'},target=/app/src/openbao_entrypoint.py,readonly",
"-e", "BAO_ADDR=https://openbao:8200",
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
"-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id",
"-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id",
"-e", f"BAO_SECRET_PATH={SECRET_PATH}",
"--entrypoint", "python",
f"mtusi2026lab7-{SERVICE}",
"-m", "src.openbao_entrypoint",
"--",
"python", "-c",
(
"import os; "
"required=('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY'); "
"required += ('RABBITMQ_USER','RABBITMQ_PASSWORD') "
"if os.environ.get('BAO_SECRET_PATH') == "
"'lab7/data/worker/runtime' else (); "
"assert all(os.environ.get(k) for k in required); "
"print('PASS: child process received OpenBao secrets')"
),
]
result = subprocess.run(
command,
text=True,
capture_output=True,
)
if result.returncode != 0:
print(
"FAIL: isolated entrypoint test, exit code",
result.returncode,
)
raise RuntimeError("Entrypoint test failed")
for line in result.stdout.splitlines():
if line.startswith("PASS:"):
print(line)
print(f"PASS: {SERVICE} OpenBao entrypoint verified")
finally:
# An already consumed single-use SecretID is absent.
# Revoke only if the SecretID still exists.
path = f"/auth/approle/role/{ROLE}/secret-id-accessor"
try:
request(
"POST",
path + "/lookup",
root_token,
tls,
{"secret_id_accessor": accessor},
)
except urllib.error.HTTPError as exc:
if exc.code == 404:
print("PASS: consumed SecretID already absent")
else:
print("WARNING: SecretID lookup HTTP", exc.code)
else:
try:
request(
"POST",
path + "/destroy",
root_token,
tls,
{"secret_id_accessor": accessor},
)
print("PASS: unused SecretID revoked")
except urllib.error.HTTPError as exc:
print("WARNING: SecretID cleanup HTTP", exc.code)
print("PASS: temporary bootstrap files removed")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print(
"FAIL: OpenBao entrypoint test:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python3
"""Verify real runtime secrets using scoped OpenBao AppRole."""
import hmac
import json
import ssl
import stat
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path
BASE = Path.home() / ".local/share/mtusi2026lab7"
BAO_URL = "https://localhost:8200/v1"
INIT_FILE = BASE / "operator/openbao-init.json"
FIELDS = {
"api": (
"DATABASE_URL",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
"worker": (
"DATABASE_URL",
"RABBITMQ_USER",
"RABBITMQ_PASSWORD",
"S3_ACCESS_KEY",
"S3_SECRET_KEY",
),
}
TOKENS = []
TLS = ssl.create_default_context(
cafile=str(BASE / "pki/ca.crt")
)
def check(condition, message):
if not condition:
raise RuntimeError(message)
print("PASS:", message)
def request(method, path, token=None, payload=None):
body = None
headers = {}
if token is not None:
headers["X-Vault-Token"] = token
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(
BAO_URL + path,
data=body,
headers=headers,
method=method,
)
with urllib.request.urlopen(
req,
context=TLS,
timeout=15,
) as response:
raw = response.read()
return (
response.status,
json.loads(raw) if raw else {},
)
def same_secrets(actual, expected):
if set(actual) != set(expected):
return False
return all(
isinstance(actual[key], str)
and hmac.compare_digest(
actual[key],
expected[key],
)
for key in expected
)
def get_service_token(role, root_token):
name = "messenger-" + role
_, role_response = request(
"GET",
f"/auth/approle/role/{name}/role-id",
root_token,
)
role_id = role_response["data"]["role_id"]
_, secret_response = request(
"POST",
f"/auth/approle/role/{name}/secret-id",
root_token,
{},
)
secret_id = secret_response["data"]["secret_id"]
_, login_response = request(
"POST",
"/auth/approle/login",
payload={
"role_id": role_id,
"secret_id": secret_id,
},
)
auth = login_response["auth"]
token = auth["client_token"]
TOKENS.append(token)
check(
name in auth["policies"]
and "root" not in auth["policies"],
f"{role}: correct scoped policy",
)
check(
0 < auth["lease_duration"] <= 1200,
f"{role}: limited token TTL",
)
return token
def must_deny(token, path, label):
try:
request("GET", path, token)
except urllib.error.HTTPError as exc:
check(
exc.code == 403,
label + " (HTTP 403)",
)
else:
raise RuntimeError(
label + ": forbidden read unexpectedly allowed"
)
def main(root_token):
print("OpenBao endpoint:", BAO_URL)
print("TLS verification: enabled")
result = subprocess.run(
["docker", "compose", "config", "--format", "json"],
check=True,
capture_output=True,
text=True,
)
services = json.loads(result.stdout)["services"]
expected = {
"api": {
key: services["api1"]["environment"][key]
for key in FIELDS["api"]
},
"worker": {
key: services["worker"]["environment"][key]
for key in FIELDS["worker"]
},
}
check(
all(
services["api1"]["environment"][key]
== services["api2"]["environment"][key]
for key in FIELDS["api"]
),
"API replicas use matching credentials",
)
api_token = get_service_token("api", root_token)
worker_token = get_service_token("worker", root_token)
for role, token in (
("api", api_token),
("worker", worker_token),
):
status, response = request(
"GET",
f"/lab7/data/{role}/runtime",
token,
)
actual = response["data"]["data"]
check(
status == 200
and same_secrets(actual, expected[role]),
f"{role}: runtime secrets match Compose",
)
must_deny(
api_token,
"/lab7/data/worker/runtime",
"API cannot read worker runtime secrets",
)
must_deny(
worker_token,
"/lab7/data/api/runtime",
"Worker cannot read API runtime secrets",
)
must_deny(
api_token,
"/sys/policies/acl/messenger-api",
"API cannot read policy configuration",
)
must_deny(
worker_token,
"/sys/policies/acl/messenger-worker",
"Worker cannot read policy configuration",
)
print("PASS: all OpenBao runtime access tests passed")
print("PASS: no credential values printed")
try:
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
raise RuntimeError("Operator file permissions must be 600")
with INIT_FILE.open(encoding="utf-8") as file:
root_token = json.load(file)["root_token"]
try:
main(root_token)
finally:
for token in TOKENS:
try:
request(
"POST",
"/auth/token/revoke",
root_token,
{"token": token},
)
print("PASS: temporary service token revoked")
except Exception:
print("WARNING: service token revocation failed")
except Exception as exc:
print(
"FAIL: OpenBao runtime test:",
type(exc).__name__,
file=sys.stderr,
)
raise SystemExit(1)
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Negative RabbitMQ ACL tests over authenticated TLS."""
import os
import sys
import uuid
import pika
from src.queue import RABBITMQ_QUEUE, connect
def test_publisher_cannot_consume(channel):
try:
method, properties, body = channel.basic_get(
queue=RABBITMQ_QUEUE,
auto_ack=False,
)
# Safety: if permissions are unexpectedly too broad,
# immediately return any received message to the queue.
if method is not None:
channel.basic_nack(
delivery_tag=method.delivery_tag,
requeue=True,
)
print("FAIL: publisher was allowed to read queue")
return False
except pika.exceptions.ChannelClosedByBroker as exc:
if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text:
print("PASS: publisher cannot consume image_jobs")
return True
print(
"FAIL: unexpected broker response:",
exc.reply_code,
exc.reply_text,
)
return False
def test_consumer_cannot_publish(channel):
# A unique nonexistent routing key ensures that even if
# publishing is unexpectedly permitted, no existing queue
# receives a test message.
routing_key = "lab7_acl_unroutable_" + uuid.uuid4().hex
try:
channel.basic_publish(
exchange="",
routing_key=routing_key,
body=b'{"acl_test":true}',
mandatory=False,
)
# Flush asynchronous broker responses.
channel.queue_declare(
queue=RABBITMQ_QUEUE,
passive=True,
)
print("FAIL: consumer was allowed to publish")
return False
except pika.exceptions.ChannelClosedByBroker as exc:
if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text:
print("PASS: consumer cannot publish")
return True
print(
"FAIL: unexpected broker response:",
exc.reply_code,
exc.reply_text,
)
return False
def main():
role = os.environ.get("RABBITMQ_USER")
connection = connect()
try:
print("RabbitMQ role:", role)
print("TLS connection: authenticated")
channel = connection.channel()
if role == "messenger_publisher":
passed = test_publisher_cannot_consume(channel)
elif role == "messenger_consumer":
passed = test_consumer_cannot_publish(channel)
else:
print("FAIL: unexpected RabbitMQ role")
sys.exit(1)
if not passed:
sys.exit(1)
print("PASS: RabbitMQ ACL tests for", role)
finally:
if connection.is_open:
connection.close()
if __name__ == "__main__":
main()
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
sql() {
docker compose exec -T db \
psql -U messenger -d messenger -At -c "$1"
}
echo "Finding completed image job..."
JOB_ID=$(sql "
SELECT j.id
FROM attachment_jobs j
JOIN attachment_variants v
ON v.attachment_id = j.attachment_id
WHERE j.status = 'ready'
AND v.variant_name = 'thumbnail'
ORDER BY j.created_at DESC
LIMIT 1;
")
if [[ -z "$JOB_ID" ]]; then
echo "FAIL: no completed image job found"
exit 1
fi
echo "Job: $JOB_ID"
STATE_QUERY="
SELECT
j.status || '|' ||
j.attempts || '|' ||
v.sha256 || '|' ||
(
SELECT COUNT(*)
FROM attachment_variants
WHERE attachment_id = j.attachment_id
)
FROM attachment_jobs j
JOIN attachment_variants v
ON v.attachment_id = j.attachment_id
WHERE j.id = '$JOB_ID'
AND v.variant_name = 'thumbnail';
"
BEFORE=$(sql "$STATE_QUERY")
echo "Before: $BEFORE"
echo "Publishing the same job twice..."
docker compose run --rm --no-deps api1 \
python -c '
import sys
from src.queue import publish_job
job_id = sys.argv[1]
publish_job(job_id)
publish_job(job_id)
print("Two duplicate messages published")
' "$JOB_ID"
sleep 5
AFTER=$(sql "$STATE_QUERY")
echo "After: $AFTER"
if [[ "$BEFORE" != "$AFTER" ]]; then
echo "FAIL: completed job changed after redelivery"
exit 1
fi
echo "PASS: duplicate delivery did not change completed job"
echo "PASS: thumbnail checksum and variant count preserved"
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""Positive and negative RustFS IAM tests over verified HTTPS."""
import os
import uuid
from pathlib import Path
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
BUCKET = os.environ["S3_BUCKET"]
ENDPOINT = os.environ["S3_ENDPOINT"]
CA_FILE = os.environ["AWS_CA_BUNDLE"]
assert ENDPOINT == "https://minio:9000"
assert Path(CA_FILE).is_file()
values = {}
for line in Path("/run/lab7/local.env").read_text(
encoding="utf-8"
).splitlines():
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
name, value = line.split("=", 1)
values[name.strip()] = value.strip().strip('"').strip("'")
def client(access_key, secret_key):
return boto3.client(
"s3",
endpoint_url=ENDPOINT,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name="us-east-1",
verify=CA_FILE,
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=5,
read_timeout=10,
retries={"max_attempts": 1},
),
)
admin = client(
os.environ["S3_ACCESS_KEY"],
os.environ["S3_SECRET_KEY"],
)
api = client(
values["S3_API_ACCESS_KEY"],
values["S3_API_SECRET_KEY"],
)
worker = client(
values["S3_WORKER_ACCESS_KEY"],
values["S3_WORKER_SECRET_KEY"],
)
suffix = uuid.uuid4().hex
keys = {
"staging": f"staging/acl-test-{suffix}",
"original": f"originals/acl-test-{suffix}",
"thumbnail": f"thumbnails/acl-test-{suffix}.jpg",
}
payload = b"lab7-rustfs-iam-test"
def put(s3, key):
s3.put_object(
Bucket=BUCKET,
Key=key,
Body=payload,
)
def get(s3, key):
response = s3.get_object(
Bucket=BUCKET,
Key=key,
)
try:
return response["Body"].read()
finally:
response["Body"].close()
def delete(s3, key):
s3.delete_object(
Bucket=BUCKET,
Key=key,
)
def allowed(label, operation):
operation()
print(f"PASS: {label}")
def denied(label, operation):
try:
operation()
except ClientError as exc:
error = exc.response.get("Error", {})
status = exc.response.get(
"ResponseMetadata", {}
).get("HTTPStatusCode")
code = str(error.get("Code", ""))
if status == 403 or code in (
"AccessDenied",
"AllAccessDisabled",
):
print(f"PASS: {label} denied")
return
raise AssertionError(
f"{label}: unexpected S3 error "
f"{code}, HTTP {status}"
) from exc
raise AssertionError(
f"{label}: forbidden operation was allowed"
)
def main():
print("RustFS endpoint:", ENDPOINT)
print("Bucket:", BUCKET)
print("TLS verification: enabled")
try:
# Prepare existing objects so read-denial tests
# cannot be confused with missing-object errors.
for key in keys.values():
put(admin, key)
print("PASS: temporary test objects prepared")
# API: staging upload/delete and processed-object reads.
allowed(
"API can upload staging",
lambda: put(api, keys["staging"]),
)
allowed(
"API can read original",
lambda: get(api, keys["original"]),
)
allowed(
"API can read thumbnail",
lambda: get(api, keys["thumbnail"]),
)
allowed(
"API can delete staging",
lambda: delete(api, keys["staging"]),
)
# Restore staging for the worker tests.
put(admin, keys["staging"])
# Worker: read staging, write processed objects.
allowed(
"worker can read staging",
lambda: get(worker, keys["staging"]),
)
allowed(
"worker can write original",
lambda: put(worker, keys["original"]),
)
allowed(
"worker can write thumbnail",
lambda: put(worker, keys["thumbnail"]),
)
# Negative API tests.
denied(
"API staging read",
lambda: get(api, keys["staging"]),
)
denied(
"API original write",
lambda: put(api, keys["original"]),
)
denied(
"API thumbnail write",
lambda: put(api, keys["thumbnail"]),
)
denied(
"API original delete",
lambda: delete(api, keys["original"]),
)
# Negative worker tests.
denied(
"worker original read",
lambda: get(worker, keys["original"]),
)
denied(
"worker thumbnail read",
lambda: get(worker, keys["thumbnail"]),
)
denied(
"worker staging write",
lambda: put(worker, keys["staging"]),
)
denied(
"worker staging delete",
lambda: delete(worker, keys["staging"]),
)
print("PASS: all RustFS IAM ACL tests passed")
finally:
# Root credentials are used only for test cleanup.
for key in keys.values():
try:
delete(admin, key)
except Exception:
print("WARNING: cleanup failed for", key)
print("RustFS ACL test cleanup attempted")
if __name__ == "__main__":
main()
+154
View File
@@ -0,0 +1,154 @@
import json
import re
import time
import urllib.parse
import urllib.request
LOKI = "http://loki:3100"
TEMPO = "http://tempo:3200"
TRACE_PATTERN = re.compile(r"^[0-9a-f]{32}$")
SPAN_PATTERN = re.compile(r"^[0-9a-f]{16}$")
def get_json(url):
with urllib.request.urlopen(url, timeout=15) as response:
return json.load(response)
def find_log(service, event):
params = urllib.parse.urlencode({
"query": f'{{service_name="{service}"}}',
"start": str(time.time_ns() - 6 * 3600 * 10**9),
"end": str(time.time_ns()),
"limit": 500,
"direction": "BACKWARD",
})
payload = get_json(
f"{LOKI}/loki/api/v1/query_range?{params}"
)
streams = payload.get("data", {}).get("result", [])
for stream in streams:
labels = stream.get("stream", {})
for entry in stream.get("values", []):
if len(entry) < 2:
continue
message = entry[1]
metadata = entry[2] if len(entry) >= 3 else {}
if event not in message and (
metadata.get("event") != event
):
continue
trace_id = (
metadata.get("trace_id")
or labels.get("trace_id")
)
span_id = (
metadata.get("span_id")
or labels.get("span_id")
)
if not trace_id or not TRACE_PATTERN.fullmatch(
trace_id
):
continue
if not span_id or not SPAN_PATTERN.fullmatch(
span_id
):
continue
return {
"service": service,
"event": event,
"message": message,
"trace_id": trace_id,
"span_id": span_id,
}
return None
def verify_trace(log, expected_kind):
trace_id = log["trace_id"]
payload = get_json(
f"{TEMPO}/api/traces/{trace_id}"
)
batches = payload.get("batches", [])
spans = []
for batch in batches:
for scope in batch.get("scopeSpans", []):
spans.extend(scope.get("spans", []))
if not spans:
raise AssertionError(
f"No spans found for {trace_id}"
)
kinds = [str(span.get("kind", "")) for span in spans]
if not any(expected_kind in kind for kind in kinds):
raise AssertionError(
f"Expected span kind {expected_kind}; got {kinds}"
)
print(f"Service: {log['service']}")
print(f"Event: {log['event']}")
print(f"Trace ID: {trace_id}")
print(f"Span ID: {log['span_id']}")
print(f"Tempo spans: {len(spans)}")
for span in spans:
print(
" Span:",
span.get("name"),
"kind:",
span.get("kind"),
)
print("PASS: Loki log linked to Tempo trace")
print()
def main():
cases = [
(
"messenger-api",
"HTTP request completed",
"SERVER",
),
(
"messenger-worker",
"Image job handled",
"CONSUMER",
),
]
for service, event, kind in cases:
log = find_log(service, event)
if log is None:
raise AssertionError(
f"No correlated log found for {service}"
)
verify_trace(log, kind)
print("PASS: API and worker trace correlation")
if __name__ == "__main__":
main()
+256
View File
@@ -0,0 +1,256 @@
import os
import base64
import hashlib
import json
import subprocess
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
import zlib
import struct
BASE = "http://127.0.0.1:8080"
def docker(*args):
subprocess.run(
["docker", "compose", *args],
check=True,
)
def api(method, path, token=None, body=None, headers=None):
request_headers = dict(headers or {})
if token:
request_headers["Authorization"] = f"Bearer {token}"
if isinstance(body, dict):
body = json.dumps(body).encode("utf-8")
request_headers["Content-Type"] = "application/json"
request = urllib.request.Request(
BASE + path,
data=body,
headers=request_headers,
method=method,
)
with urllib.request.urlopen(request, timeout=10) as response:
data = response.read()
return (
response.status,
json.loads(data) if data and
"application/json" in response.headers.get(
"Content-Type", ""
) else data,
)
def png_chunk(name, data):
value = name + data
return (
struct.pack(">I", len(data))
+ value
+ struct.pack(">I", zlib.crc32(value) & 0xFFFFFFFF)
)
def make_png():
width, height = 320, 200
scanline = b"\x00" + bytes([220, 80, 40]) * width
return (
b"\x89PNG\r\n\x1a\n"
+ png_chunk(
b"IHDR",
struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0),
)
+ png_chunk(
b"IDAT", zlib.compress(scanline * height)
)
+ png_chunk(b"IEND", b"")
)
def wait_ready():
for _ in range(90):
try:
status, data = api("GET", "/health/ready")
if status == 200 and data.get("status") == "ok":
return
except Exception:
pass
time.sleep(1)
raise RuntimeError("API did not become ready")
def main():
suffix = uuid.uuid4().hex[:12]
username = "lab5_" + suffix
password = "Lab5TestPassword_" + suffix
print("Stopping worker...", flush=True)
docker("stop", "worker")
wait_ready()
status, user = api(
"POST",
"/api/v1/users",
body={
"username": username,
"display_name": "Lab5 recovery test",
"password": password,
},
)
assert status == 201
credentials = base64.b64encode(
f"{username}:{password}".encode()
).decode()
status, session = api(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": f"Basic {credentials}"},
body=b"",
)
assert status == 201
token = session["token"]
status, chat = api(
"POST",
"/api/v1/chats",
token,
{
"title": "Worker recovery",
"member_ids": [user["id"]],
},
)
assert status == 201
original = make_png()
path = (
f"/api/v1/chats/{chat['id']}/attachments"
"?filename=recovery.png"
)
status, attachment = api(
"POST",
path,
token,
original,
{"Content-Type": "image/png"},
)
assert status == 202, f"Expected 202, got {status}"
assert attachment["status"] == "queued"
attachment_id = attachment["id"]
print("Upload: 202 queued", flush=True)
status, message = api(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
token,
{"text": "", "attachment_ids": [attachment_id]},
{"Idempotency-Key": "recovery-" + suffix},
)
assert status == 201
assert attachment_id in message["attachment_ids"]
print("Message created while worker is stopped", flush=True)
status, metadata = api(
"GET", f"/api/v1/attachments/{attachment_id}", token
)
assert status == 200 and metadata["status"] == "queued"
print("Restarting RabbitMQ and API...", flush=True)
docker("restart", "rabbitmq")
docker("up", "-d", "--wait", "rabbitmq")
docker("restart", "api1", "api2")
wait_ready()
status, metadata = api(
"GET", f"/api/v1/attachments/{attachment_id}", token
)
assert metadata["status"] == "queued"
print("Queued attachment survived restart", flush=True)
pause_seconds = int(
os.getenv("LAB6_WORKER_PAUSE_SECONDS", "60")
)
print(
f"INCIDENT: worker stopped for {pause_seconds} seconds",
flush=True,
)
time.sleep(pause_seconds)
print("Starting worker...", flush=True)
docker("up", "-d", "worker")
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
status, metadata = api(
"GET", f"/api/v1/attachments/{attachment_id}", token
)
if metadata["status"] == "ready":
break
if metadata["status"] == "failed":
raise RuntimeError(
f"Processing failed: {metadata.get('error_code')}"
)
time.sleep(1)
else:
raise RuntimeError("Attachment did not become ready")
status, downloaded = api(
"GET",
f"/api/v1/attachments/{attachment_id}/content",
token,
)
assert status == 200
assert downloaded == original
assert hashlib.sha256(downloaded).hexdigest() == (
hashlib.sha256(original).hexdigest()
)
status, thumbnail = api(
"GET",
f"/api/v1/attachments/{attachment_id}/content"
"?variant=thumbnail",
token,
)
assert status == 200
assert thumbnail.startswith(b"\xff\xd8")
assert thumbnail.endswith(b"\xff\xd9")
variants = metadata["variants"]
assert any(
v["name"] == "thumbnail"
and v["width"] == 256
and v["height"] == 160
for v in variants
)
print("Attachment: ready", flush=True)
print("Original: SHA-256 verified", flush=True)
print("Thumbnail: JPEG 256x160 verified", flush=True)
print("PASS: durable worker recovery", flush=True)
if __name__ == "__main__":
try:
main()
finally:
# Restore the worker even when the test fails.
docker("up", "-d", "worker")