169 lines
5.8 KiB
Python
169 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Operator-only OpenBao bootstrap; this container is never used by the app."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import ssl
|
|
import sys
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
ADDRESS = os.environ.get("OPENBAO_ADDR", "https://openbao:8200").rstrip("/")
|
|
CA_FILE = os.environ.get("OPENBAO_CACERT", "/run/certs/ca.crt")
|
|
OPERATOR_FILE = Path("/run/operator/openbao-operator.json")
|
|
APPROLE_DIR = Path("/output/approle")
|
|
|
|
|
|
class BaoClient:
|
|
def __init__(self, token=None):
|
|
self.token = token
|
|
self.context = ssl.create_default_context(cafile=CA_FILE)
|
|
self.context.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
|
|
def request(self, method, path, body=None, allow_status=()):
|
|
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
headers = {"Content-Type": "application/json"}
|
|
if self.token:
|
|
headers["X-Vault-Token"] = self.token
|
|
request = Request(ADDRESS + "/v1/" + path.lstrip("/"), data=data, headers=headers, method=method)
|
|
try:
|
|
with urlopen(request, context=self.context, timeout=10) as response:
|
|
payload = response.read()
|
|
return json.loads(payload) if payload else {}
|
|
except HTTPError as exc:
|
|
if exc.code in allow_status:
|
|
return {}
|
|
raise RuntimeError(f"OpenBao API rejected {method} {path} (HTTP {exc.code})") from None
|
|
except URLError as exc:
|
|
raise RuntimeError(f"OpenBao TLS connection failed ({type(exc.reason).__name__})") from None
|
|
|
|
|
|
def wait_for_openbao(client):
|
|
for _ in range(60):
|
|
try:
|
|
client.request("GET", "sys/health", allow_status=(501, 503, 530))
|
|
return
|
|
except RuntimeError:
|
|
time.sleep(2)
|
|
raise RuntimeError("OpenBao did not become reachable over verified TLS")
|
|
|
|
|
|
def create_role(client, name, policy, secret_path, secret_values):
|
|
policy_text = f'path "{secret_path}" {{ capabilities = ["read"] }}\n'
|
|
client.request("PUT", f"sys/policies/acl/{policy}", {"policy": policy_text})
|
|
|
|
role_path = f"auth/approle/role/{name}"
|
|
client.request(
|
|
"POST",
|
|
role_path,
|
|
{
|
|
"token_policies": [policy],
|
|
"token_ttl": "1h",
|
|
"token_max_ttl": "4h",
|
|
"secret_id_ttl": "720h",
|
|
"secret_id_num_uses": 0,
|
|
"bind_secret_id": True,
|
|
},
|
|
)
|
|
role_id = client.request("GET", role_path + "/role-id")["data"]["role_id"]
|
|
secret_id = client.request("POST", role_path + "/secret-id", {})["data"]["secret_id"]
|
|
client.request(
|
|
"POST",
|
|
secret_path,
|
|
{"data": secret_values},
|
|
)
|
|
|
|
target = APPROLE_DIR / name.removeprefix("messenger-")
|
|
target.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
os.chown(target, 10001, 10001)
|
|
target.chmod(0o500)
|
|
for filename, value in (("role_id", role_id), ("secret_id", secret_id)):
|
|
file_path = target / filename
|
|
file_path.write_text(value + "\n", encoding="utf-8")
|
|
os.chown(file_path, 10001, 10001)
|
|
file_path.chmod(0o400)
|
|
|
|
|
|
def main():
|
|
if not Path(CA_FILE).is_file() or not OPERATOR_FILE.is_file():
|
|
raise RuntimeError("OpenBao CA or operator bootstrap material is missing")
|
|
material = json.loads(OPERATOR_FILE.read_text(encoding="utf-8"))
|
|
key = material["unseal_keys_b64"][0]
|
|
root_token = material["root_token"]
|
|
anonymous = BaoClient()
|
|
wait_for_openbao(anonymous)
|
|
anonymous.request("POST", "sys/unseal", {"key": key})
|
|
|
|
client = BaoClient(root_token)
|
|
health = client.request("GET", "sys/health", allow_status=(501, 503, 530))
|
|
if health.get("sealed") or not health.get("initialized"):
|
|
raise RuntimeError("OpenBao did not reach initialized, unsealed state")
|
|
|
|
mounts = client.request("GET", "sys/mounts")
|
|
if "secret/" not in mounts:
|
|
client.request(
|
|
"POST",
|
|
"sys/mounts/secret",
|
|
{"type": "kv", "options": {"version": "2"}},
|
|
)
|
|
else:
|
|
options = mounts["secret/"].get("options", {})
|
|
if options.get("version") != "2":
|
|
raise RuntimeError("OpenBao secret/ mount exists but is not KV v2")
|
|
|
|
auth = client.request("GET", "sys/auth")
|
|
if "approle/" not in auth:
|
|
client.request("POST", "sys/auth/approle", {"type": "approle"})
|
|
|
|
api_values = {
|
|
"database_url": (
|
|
"postgresql://messenger_api:"
|
|
+ os.environ["POSTGRES_API_PASSWORD"]
|
|
+ "@postgres:5432/messenger"
|
|
),
|
|
"broker_url": (
|
|
"amqps://messenger_api:"
|
|
+ os.environ["RABBITMQ_API_PASSWORD"]
|
|
+ "@rabbitmq:5671/messenger"
|
|
),
|
|
"s3_access_key": os.environ["S3_API_ACCESS_KEY"],
|
|
"s3_secret_key": os.environ["S3_API_SECRET_KEY"],
|
|
}
|
|
worker_values = {
|
|
"database_url": (
|
|
"postgresql://messenger_worker:"
|
|
+ os.environ["POSTGRES_WORKER_PASSWORD"]
|
|
+ "@postgres:5432/messenger"
|
|
),
|
|
"broker_url": (
|
|
"amqps://messenger_worker:"
|
|
+ os.environ["RABBITMQ_WORKER_PASSWORD"]
|
|
+ "@rabbitmq:5671/messenger"
|
|
),
|
|
"s3_access_key": os.environ["S3_WORKER_ACCESS_KEY"],
|
|
"s3_secret_key": os.environ["S3_WORKER_SECRET_KEY"],
|
|
}
|
|
create_role(
|
|
client,
|
|
"messenger-api",
|
|
"messenger-api",
|
|
"secret/data/messenger/api",
|
|
api_values,
|
|
)
|
|
create_role(
|
|
client,
|
|
"messenger-worker",
|
|
"messenger-worker",
|
|
"secret/data/messenger/worker",
|
|
worker_values,
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (KeyError, OSError, ValueError, RuntimeError) as exc:
|
|
print(f"ERROR: {exc}", file=sys.stderr)
|
|
raise SystemExit(1)
|