ЛР 7: TLS/mTLS, Argon2id, OpenBao и negative tests (оценка 3)
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Яковлев Матвей Дмитриевич
2026-11-28 12:29:50 +01:00
parent 20afc2c790
commit 8c75b7266f
53 changed files with 3114 additions and 89 deletions
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""One-time operator bootstrap for the lab7 OpenBao instance.
Creates init keys (saved outside Git), unseals, enables KV-v2, writes a scoped
policy and an AppRole, stores role_id/secret_id outside Git, and writes the
application secrets. Root token and unseal keys are never given to the app.
"""
import json
import os
import ssl
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PRIVATE = ROOT / "certs" / "private"
CA = ROOT / "certs" / "ca.crt"
ADDR = "https://localhost:8200"
CTX = ssl.create_default_context(cafile=str(CA))
def call(method, path, body=None, token=None, allow_codes=()):
data = json.dumps(body).encode() if body is not None else None
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
req = urllib.request.Request(ADDR + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, context=CTX, timeout=10) as response:
raw = response.read()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as exc:
if exc.code in allow_codes:
return json.loads(exc.read())
raise RuntimeError("%s %s -> %s: %s" % (method, path, exc.code, exc.read()[:300])) from None
def load_dotenv():
env_file = ROOT / ".env"
if env_file.exists():
for line in env_file.read_text().splitlines():
if "=" in line and not line.lstrip().startswith("#"):
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip())
def main():
load_dotenv()
init_file = PRIVATE / "bao-init.json"
if init_file.exists():
initial = json.loads(init_file.read_text())
else:
if call("GET", "/v1/sys/init").get("initialized"):
raise SystemExit("OpenBao is already initialized but local init file is missing")
initial = call("POST", "/v1/sys/init", {"secret_shares": 5, "secret_threshold": 3})
init_file.write_text(json.dumps(initial, indent=2))
os.chmod(init_file, 0o600)
root = initial["root_token"]
health = call("GET", "/v1/sys/health", allow_codes=(503, 472, 473))
if health.get("sealed"):
for key in initial["keys"][:3]:
call("POST", "/v1/sys/unseal", {"key": key}, token=root)
print("OpenBao unsealed with operator-held keys")
configured = (PRIVATE / "bao-approle.json").exists()
if not configured:
call("POST", "/v1/sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token=root)
policy = (ROOT / "security" / "app-policy.hcl").read_text()
call("POST", "/v1/sys/policies/acl/messenger-app", {"policy": policy}, token=root)
call("POST", "/v1/sys/auth/approle", {"type": "approle"}, token=root)
call("POST", "/v1/auth/approle/role/messenger-app", {
"token_policies": "messenger-app", "token_ttl": "1h", "token_max_ttl": "4h",
}, token=root)
role_id = call("GET", "/v1/auth/approle/role/messenger-app/role-id", token=root)["data"]["role_id"]
secret_id = call("POST", "/v1/auth/approle/role/messenger-app/secret-id", token=root)["data"]["secret_id"]
approle_file = PRIVATE / "bao-approle.json"
approle_file.write_text(json.dumps({"role_id": role_id, "secret_id": secret_id}, indent=2))
os.chmod(approle_file, 0o600)
secret = {
"DATABASE_URL": os.environ.get("DATABASE_URL",
"postgresql://messenger:messenger@db:5432/messenger"),
"S3_ACCESS_KEY": os.environ.get("S3_ACCESS_KEY", "messenger"),
"S3_SECRET_KEY": os.environ.get("S3_SECRET_KEY", "local-only-synthetic-s3-secret"),
"REDIS_PASSWORD": os.environ.get("REDIS_PASSWORD", "local-only-synthetic-redis"),
}
call("POST", "/v1/secret/data/messenger/app", {"data": secret}, token=root)
print("OpenBao bootstrapped: unsealed, KV-v2 + scoped AppRole, secret path secret/messenger/app")
if __name__ == "__main__":
main()