forked from mtusi2026/mtusi2026lab7
Защитить мессенджер TLS и OpenBao и проверить отзыв прав worker
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-only init, unseal, service policies and scoped secrets."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from bootstrap import ROLES, SECRETS
|
||||
|
||||
ADDRESS = f"https://localhost:{int(os.getenv('BAO_HOST_PORT', '8207'))}/v1/"
|
||||
CA = SECRETS / "tls/trust/ca.crt"
|
||||
RECEIPT = SECRETS / "operator/bao.json"
|
||||
|
||||
|
||||
def call(path, data=None, *, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = Request(
|
||||
ADDRESS + path,
|
||||
json.dumps(data).encode() if data is not None else None,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urlopen(req, context=ssl.create_default_context(cafile=CA), timeout=30) as response:
|
||||
body = response.read()
|
||||
return json.loads(body) if body else {}
|
||||
|
||||
|
||||
def secret(name):
|
||||
return (SECRETS / name).read_text().strip()
|
||||
|
||||
|
||||
def config(role):
|
||||
ca = "/run/tls/trust/ca.crt"
|
||||
db = (
|
||||
f"postgresql://{role}:{secret(f'db_{role}_password')}@postgres:5432/messenger"
|
||||
f"?sslmode=verify-full&sslrootcert={ca}"
|
||||
)
|
||||
cache = (
|
||||
f"rediss://{role}:{secret(f'cache_{role}_password')}@valkey:6379/0"
|
||||
f"?ssl_ca_certs={ca}&ssl_check_hostname=True"
|
||||
if role == "api"
|
||||
else ""
|
||||
)
|
||||
broker = (
|
||||
f"rediss://{role}:{secret(f'broker_{role}_password')}@broker:6380/0"
|
||||
f"?ssl_ca_certs={ca}&ssl_check_hostname=True&ssl_certfile=/run/tls/client/service.crt"
|
||||
"&ssl_keyfile=/run/tls/client/service.key"
|
||||
if role in ("api", "worker", "relay")
|
||||
else ""
|
||||
)
|
||||
return {
|
||||
"database_url": db,
|
||||
"cache_url": cache,
|
||||
"broker_url": broker,
|
||||
"s3_access_key": secret(f"s3_{role}_access_key_id") if role != "relay" else "",
|
||||
"s3_secret_key": secret(f"s3_{role}_secret_access_key") if role != "relay" else "",
|
||||
}
|
||||
|
||||
|
||||
def setup():
|
||||
os.umask(0o077)
|
||||
for attempt in range(20):
|
||||
try:
|
||||
state = call("sys/init")
|
||||
break
|
||||
except URLError:
|
||||
if attempt == 19:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
if not state["initialized"]:
|
||||
result = call("sys/init", {"secret_shares": 1, "secret_threshold": 1}, method="PUT")
|
||||
RECEIPT.write_text(
|
||||
json.dumps({"root_token": result["root_token"], "unseal_key": result["keys_base64"][0]})
|
||||
)
|
||||
if not RECEIPT.exists():
|
||||
raise SystemExit("This OpenBao volume requires its original operator receipt")
|
||||
receipt = json.loads(RECEIPT.read_text())
|
||||
if call("sys/seal-status")["sealed"]:
|
||||
call("sys/unseal", {"key": receipt["unseal_key"]}, method="PUT")
|
||||
for attempt in range(30):
|
||||
try:
|
||||
call("sys/health")
|
||||
break
|
||||
except HTTPError as exc:
|
||||
if exc.code not in (429, 503) or attempt == 29:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
token = receipt["root_token"]
|
||||
if "cert/" not in call("sys/auth", token=token):
|
||||
call("sys/auth/cert", {"type": "cert"}, token=token)
|
||||
if "services/" not in call("sys/mounts", token=token):
|
||||
call("sys/mounts/services", {"type": "kv", "options": {"version": "2"}}, token=token)
|
||||
for role in ROLES:
|
||||
policy = (
|
||||
f'path "services/data/{role}" {{ capabilities = ["read"] }}\n'
|
||||
'path "auth/token/revoke-self" { capabilities = ["update"] }\n'
|
||||
)
|
||||
call("sys/policies/acl/" + role, {"policy": policy}, token=token, method="PUT")
|
||||
cert = secret(f"tls/{role}-client/service.crt")
|
||||
call(
|
||||
f"auth/cert/certs/{role}",
|
||||
{
|
||||
"certificate": cert,
|
||||
"allowed_uri_sans": f"urn:mtusi:lab7:{role}-client",
|
||||
"token_policies": [role],
|
||||
"token_ttl": "90s",
|
||||
"token_max_ttl": "120s",
|
||||
"token_no_default_policy": True,
|
||||
},
|
||||
token=token,
|
||||
)
|
||||
call(f"services/data/{role}", {"data": config(role)}, token=token)
|
||||
print("OpenBao initialized and unsealed; four scoped identities configured.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--revoke", choices=ROLES)
|
||||
parser.add_argument("--seal", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
if args.revoke or args.seal:
|
||||
token = json.loads(RECEIPT.read_text())["root_token"]
|
||||
if args.revoke:
|
||||
call(f"auth/cert/certs/{args.revoke}", token=token, method="DELETE")
|
||||
print(f"Certificate role {args.revoke} revoked.")
|
||||
else:
|
||||
call("sys/seal", {}, token=token, method="PUT")
|
||||
print("OpenBao sealed.")
|
||||
else:
|
||||
setup()
|
||||
except HTTPError as exc:
|
||||
raise SystemExit(f"OpenBao operator action failed (HTTP {exc.code})") from None
|
||||
except (URLError, TimeoutError):
|
||||
raise SystemExit("OpenBao unavailable over verified TLS") from None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user