80 lines
3.9 KiB
Python
80 lines
3.9 KiB
Python
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import ssl
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
LOCAL = ROOT / "secrets"
|
|
|
|
|
|
def api(opener, base, path, body=None, token=None, method=None):
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
try:
|
|
with opener.open(Request(base + "/v1/" + path, data=data, headers=headers, method=method),
|
|
timeout=5) as response:
|
|
payload = response.read()
|
|
return json.loads(payload) if payload else None
|
|
except HTTPError as error:
|
|
raise RuntimeError(f"OpenBao {path}: HTTP {error.code}") from None
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Initialize and provision the local OpenBao as the operator.")
|
|
parser.add_argument("action", choices=("configure", "unseal"))
|
|
parser.add_argument("--url", default="https://localhost:18207")
|
|
parser.add_argument("--operator-file", type=Path, default=LOCAL / "operator" / "openbao.json")
|
|
args = parser.parse_args()
|
|
context = ssl.create_default_context(cafile=str(LOCAL / "pki/ca.crt"))
|
|
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context))
|
|
for _ in range(30):
|
|
try:
|
|
state = api(opener, args.url, "sys/init")
|
|
break
|
|
except (URLError, TimeoutError):
|
|
time.sleep(1)
|
|
else:
|
|
raise RuntimeError("OpenBao is unavailable")
|
|
if not state["initialized"]:
|
|
if args.action != "configure" or args.operator_file.exists():
|
|
raise RuntimeError("Initialization requires configure and a new operator file")
|
|
args.operator_file.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
with os.fdopen(os.open(args.operator_file, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600),
|
|
"w", encoding="ascii") as output:
|
|
result = api(opener, args.url, "sys/init", {"secret_shares": 1, "secret_threshold": 1})
|
|
json.dump({"unseal": result["keys_base64"][0], "root": result["root_token"]}, output)
|
|
secrets = json.loads(args.operator_file.read_text(encoding="ascii"))
|
|
if api(opener, args.url, "sys/seal-status")["sealed"]:
|
|
result = api(opener, args.url, "sys/unseal", {"key": secrets["unseal"]})
|
|
if result["sealed"]:
|
|
raise RuntimeError("OpenBao is still sealed")
|
|
if args.action == "configure":
|
|
root = secrets["root"]
|
|
if "messenger/" not in api(opener, args.url, "sys/mounts", token=root):
|
|
api(opener, args.url, "sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, root)
|
|
if "cert/" not in api(opener, args.url, "sys/auth", token=root):
|
|
api(opener, args.url, "sys/auth/cert", {"type": "cert"}, root)
|
|
template = (ROOT / "infra/openbao/service-policy.hcl").read_text(encoding="ascii")
|
|
for role in ("api", "worker", "dispatch"):
|
|
api(opener, args.url, f"sys/policies/acl/{role}", {"policy": template.replace("ROLE", role)}, root)
|
|
certificate = (LOCAL / f"pki/{role}-bao.crt").read_text(encoding="ascii")
|
|
api(opener, args.url, f"auth/cert/certs/{role}", {
|
|
"certificate": certificate, "allowed_dns_sans": [f"{role}-bao"],
|
|
"token_policies": [role], "token_ttl": 300, "token_max_ttl": 600,
|
|
"token_no_default_policy": True,
|
|
}, root)
|
|
values = json.loads((LOCAL / f"bao_{role}.json").read_text(encoding="ascii"))
|
|
api(opener, args.url, f"messenger/data/{role}", {"data": values}, root)
|
|
print("OpenBao доступен. Ключ распечатывания и root token находятся только у оператора.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|