feat(lab7): implement secure messenger infrastructure with TLS, OpenBao and observability
Skeleton contracts / contracts (pull_request) Blocked by required conditions

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
+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)