forked from mtusi2026/mtusi2026lab7
116 lines
4.7 KiB
Python
116 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Действия оператора. Root token и unseal shares остаются на хосте."""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import ssl
|
|
import sys
|
|
import time
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
from bootstrap_security import OPERATOR, ROOT, write
|
|
|
|
ROLES = {"api": "messenger_api", "worker": "messenger_worker", "janitor": "messenger_janitor"}
|
|
|
|
|
|
class OpenBao:
|
|
def __init__(self, address):
|
|
self.address = address.rstrip("/")
|
|
ca_file = ROOT / "certs/ca.crt"
|
|
if not ca_file.is_file():
|
|
raise RuntimeError("Отсутствует certs/ca.crt. Сначала выполните make init.")
|
|
self.context = ssl.create_default_context(cafile=str(ca_file))
|
|
|
|
def request(self, method, path, body=None, token=None):
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
req = Request(self.address + "/v1/" + path, method=method,
|
|
data=json.dumps(body).encode() if body is not None else None,
|
|
headers=headers)
|
|
with urlopen(req, context=self.context, timeout=4) as res:
|
|
return json.load(res) if res.status != 204 else {}
|
|
|
|
def wait(self):
|
|
for _ in range(30):
|
|
try:
|
|
return self.request("GET", "sys/init")
|
|
except (URLError, TimeoutError):
|
|
time.sleep(1)
|
|
raise RuntimeError("OpenBao не ответил на HTTPS")
|
|
|
|
|
|
def store_secrets(bao, token, roles):
|
|
for role in roles:
|
|
data = json.loads((OPERATOR / f"s3-{role}.json").read_text())
|
|
if role == "api":
|
|
data["valkey"] = json.loads((OPERATOR / "valkey.json").read_text())["password"]
|
|
bao.request("POST", "messenger/data/" + role, {"data": data}, token)
|
|
|
|
|
|
def unseal(bao, state):
|
|
if not bao.request("GET", "sys/seal-status")["sealed"]:
|
|
return
|
|
for share in state["keys_base64"][:2]:
|
|
result = bao.request("PUT", "sys/unseal", {"key": share})
|
|
if result["sealed"]:
|
|
raise RuntimeError("Не удалось выполнить unseal")
|
|
|
|
|
|
def provision(bao, token):
|
|
if "cert/" not in bao.request("GET", "sys/auth", token=token):
|
|
bao.request("POST", "sys/auth/cert", {"type": "cert"}, token)
|
|
if "messenger/" not in bao.request("GET", "sys/mounts", token=token):
|
|
bao.request("POST", "sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token)
|
|
ca = (ROOT / "certs/ca.crt").read_text()
|
|
for role, identity in ROLES.items():
|
|
policy = (ROOT / "infra/openbao/policies" / f"{role}.hcl").read_text()
|
|
bao.request("PUT", "sys/policies/acl/" + role, {"policy": policy}, token)
|
|
bao.request("POST", "auth/cert/certs/" + role, {
|
|
"certificate": ca, "allowed_dns_sans": [identity], "token_policies": [role],
|
|
"token_no_default_policy": True, "token_ttl": 30, "token_max_ttl": 30,
|
|
"token_explicit_max_ttl": 30,
|
|
}, token)
|
|
store_secrets(bao, token, ROLES)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=("bootstrap", "unseal", "seal", "sync-secret"))
|
|
parser.add_argument("--address", default=os.environ.get("BAO_OPERATOR_ADDR", "https://localhost:8200"))
|
|
parser.add_argument("--role", choices=ROLES)
|
|
args = parser.parse_args()
|
|
os.umask(0o077)
|
|
state_file = OPERATOR / "bao-init.json"
|
|
bao = OpenBao(args.address)
|
|
initialized = bao.wait()["initialized"]
|
|
if not initialized:
|
|
if args.action != "bootstrap" or state_file.exists():
|
|
raise RuntimeError("OpenBao ещё не инициализирован или данные тома не совпадают с ключами")
|
|
state = bao.request("PUT", "sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
|
write(state_file, json.dumps(state) + "\n", 0o600)
|
|
state = json.loads(state_file.read_text())
|
|
token = state["root_token"]
|
|
if args.action == "seal":
|
|
bao.request("PUT", "sys/seal", token=token)
|
|
else:
|
|
unseal(bao, state)
|
|
if args.action == "bootstrap":
|
|
provision(bao, token)
|
|
elif args.action == "sync-secret":
|
|
if args.role is None:
|
|
parser.error("--role требуется для sync-secret")
|
|
store_secrets(bao, token, [args.role])
|
|
print(f"OpenBao: {args.action} выполнено")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except HTTPError as error:
|
|
sys.exit(f"OpenBao: HTTP {error.code} ({error.url.rsplit('/', 1)[-1]})")
|
|
except (OSError, RuntimeError) as error:
|
|
sys.exit(str(error))
|