lab7: OpenBao 2.7.3 (не dev, raft на volume, TLS, audit), AppRole и scoped policy для api/relay/worker, секреты только из OpenBao, скрипт оператора и проверка allow/deny

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:41:57 +03:00
parent 93f4ed1013
commit 876f610847
16 changed files with 623 additions and 45 deletions
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper: runs scripts\bao_check.sh (OpenBao allow/deny, no root credential in apps) with Git Bash.
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0bao_check.sh"
exit /b %ERRORLEVEL%
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""OpenBao allow/deny check, run INSIDE a service container with that service's own credentials:
docker compose exec -T api python - < scripts/bao_check.py (wrapper: scripts/bao_check.sh)
Uses exactly what the service has: BAO_ADDR, BAO_CACERT (server verified), BAO_ROLE_ID_FILE,
BAO_SECRET_ID_FILE, BAO_SECRET_PATH. Prints status codes and key NAMES only, never values or tokens.
Expected for service S (api | relay | worker):
allow AppRole login; read messenger/data/S; token lookup-self; revoke-self
deny read messenger/data/<other services>; write/patch messenger/data/S; list metadata;
write a policy; read the policy list; create a token; enable an auth method; read sys/mounts
deny the revoked token afterwards; a login with a wrong secret_id
"""
import json
import os
import ssl
import sys
import urllib.error
import urllib.request
ADDR = os.environ["BAO_ADDR"].rstrip("/")
CTX = ssl.create_default_context(cafile=os.environ["BAO_CACERT"])
PATH = os.environ["BAO_SECRET_PATH"]
SERVICE = PATH.rsplit("/", 1)[-1]
OTHERS = [s for s in ("api", "relay", "worker") if s != SERVICE]
def call(method, path, token=None, body=None):
data = json.dumps(body).encode() if body is not None else (b"{}" if method in ("POST", "PUT") else None)
req = urllib.request.Request(f"{ADDR}/v1/{path}", data=data, method=method,
headers={"Content-Type": "application/json", **({"X-Vault-Token": token} if token else {})})
try:
with urllib.request.urlopen(req, timeout=5, context=CTX) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else {})
except urllib.error.HTTPError as exc:
return exc.code, {}
def read(name):
with open(os.environ[name], encoding="utf-8") as f:
return f.read().strip()
failures = 0
def expect(label, status, allowed):
global failures
ok = (200 <= status < 300) if allowed else status in (400, 403)
failures += not ok
print(f" {'PASS' if ok else 'FAIL'} {'allow' if allowed else 'deny '} {label:58s} -> HTTP {status}")
print(f"service {SERVICE}: OpenBao {ADDR} (TLS verified against {os.environ['BAO_CACERT']})")
status, body = call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": read("BAO_SECRET_ID_FILE")})
expect("AppRole login with the service's role_id/secret_id", status, True)
auth = body.get("auth") or {}
token = auth.get("client_token", "")
print(f" token policies={auth.get('token_policies')} ttl={auth.get('lease_duration')}s renewable={auth.get('renewable')}")
status, body = call("GET", PATH, token)
expect(f"read own path {PATH}", status, True)
print(f" keys: {sorted((body.get('data') or {}).get('data') or {})}")
status, _ = call("GET", "auth/token/lookup-self", token)
expect("token lookup-self", status, True)
for other in OTHERS:
expect(f"read other service's path messenger/data/{other}", call("GET", f"messenger/data/{other}", token)[0], False)
expect(f"write own path {PATH}", call("POST", PATH, token, {"data": {"x": "y"}})[0], False)
expect("list messenger/metadata", call("LIST", "messenger/metadata", token)[0], False)
expect(f"write policy sys/policies/acl/{SERVICE}", call("PUT", f"sys/policies/acl/{SERVICE}", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0], False)
expect("read policy list sys/policies/acl", call("LIST", "sys/policies/acl", token)[0], False)
expect("create a child token auth/token/create", call("POST", "auth/token/create", token, {"policies": ["api"]})[0], False)
expect("enable an auth method sys/auth/userpass", call("POST", "sys/auth/userpass", token, {"type": "userpass"})[0], False)
expect("read sys/mounts", call("GET", "sys/mounts", token)[0], False)
expect("revoke-self", call("POST", "auth/token/revoke-self", token)[0], True)
expect("use the token after revoke-self (lookup-self)", call("GET", "auth/token/lookup-self", token)[0], False)
expect("read own path with the revoked token", call("GET", PATH, token)[0], False)
expect("AppRole login with a wrong secret_id", call("POST", "auth/approle/login", body={"role_id": read("BAO_ROLE_ID_FILE"), "secret_id": "00000000-0000-0000-0000-000000000000"})[0], False)
print(f"{'PASS' if failures == 0 else 'FAIL'}: OpenBao policy of {SERVICE}, {failures} failure(s)")
sys.exit(1 if failures else 0)
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# OpenBao proof (README defense step 4): policy allow/deny for every service + no root credential
# in the application containers. Prints PASS/FAIL lines, never a token, share or secret value.
# sh scripts/bao_check.sh (Windows: scripts\bao_check.cmd)
set -u
cd "$(dirname "$0")/.."
export MSYS_NO_PATHCONV=1 # Git Bash: keep /run/secrets as a container path
OPERATOR_DIR="${OPERATOR_DIR:-$HOME/.mtusi-lab7-operator/${COMPOSE_PROJECT_NAME:-mtusi-lab7}}"
rc=0
for svc in api relay worker; do
echo "== $svc"
docker compose exec -T "$svc" python - < scripts/bao_check.py || rc=1
done
echo
echo "== root credential / unseal material in the application containers (values compared, never printed)"
for svc in api relay worker; do
# 1. no token-like variable in the container configuration
names="$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(docker compose ps -q "$svc" | head -1)" \
| cut -d= -f1 | grep -iE 'TOKEN|UNSEAL|ROOT' || true)"
if [ -n "$names" ]; then echo " FAIL $svc: token-like env names: $names"; rc=1; else echo " PASS $svc: no *TOKEN*/*UNSEAL*/*ROOT* environment variable"; fi
# 2. the operator's root token and unseal shares do not occur anywhere in the container's
# secrets, code, temp files or process environment (fed via stdin, compared inside)
# Positive control: the same search MUST find a value that is there (the service's own role_id),
# otherwise "absent" below would prove nothing.
found="$(docker compose exec -T "$svc" sh -c 'read -r v; grep -rlsF -- "$v" /run/secrets | head -1' < "secrets/bao/${svc}_role_id")"
if [ -n "$found" ]; then echo " PASS control: own role_id found by the same search ($found)"; else echo " FAIL control search found nothing"; rc=1; fi
for f in root-token unseal-share-1 unseal-share-2 unseal-share-3; do
if [ ! -f "$OPERATOR_DIR/$f" ]; then echo " FAIL operator file $f missing in $OPERATOR_DIR"; rc=1; continue; fi
found="$(docker compose exec -T "$svc" sh -c 'read -r v; for p in /run/secrets /app /tmp /proc/1/environ; do grep -rqsF -- "$v" "$p" && echo "$p"; done; true' < "$OPERATOR_DIR/$f")"
if [ -n "$found" ]; then echo " FAIL $svc: $f found in $found"; rc=1; else echo " PASS $svc: $f absent (/run/secrets, /app, /tmp, PID 1 environment)"; fi
done
echo " $svc /run/secrets: $(docker compose exec -T "$svc" ls /run/secrets | tr '\n' ' ')"
done
[ "$rc" = 0 ] && echo "PASS: OpenBao allow/deny and no root credential in the application" || echo "FAIL"
exit "$rc"
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""OpenBao operator actions of the lab 7 stand (docs/OPERATOR.md). Stdlib only; run on the host.
python scripts/bao_operator.py bootstrap # init (once) + unseal + configure + issue AppRole creds
python scripts/bao_operator.py unseal # after every OpenBao (re)start: it starts SEALED
python scripts/bao_operator.py status # initialized / sealed / mounts / roles (no secrets)
python scripts/bao_operator.py new-secret-id api # issue a new SecretID for one service
Who holds what:
* unseal shares (3, threshold 2) and the root token: the OPERATOR, in OPERATOR_DIR, outside the
repository (default ~/.mtusi-lab7-operator/<compose project>/, files 0600). Never in Git, never
in a container of the application, never printed. In a real team the 3 shares go to 3 people.
* role_id + secret_id of api / relay / worker: ./secrets/bao/ (git-ignored), each pair mounted as
a Docker secret ONLY into its own service - the "first secret" the service logs in with.
* the root token is used only by this script, for configuration.
Every secret travels to the OpenBao CLI over the STDIN of `docker compose exec` (never as a command
line argument or an environment variable of a process): the root token is the first stdin line,
read by `read -r BAO_TOKEN`; KV values and policies follow as JSON/HCL on stdin (`-`).
The CLI runs inside the openbao container against https://127.0.0.1:8200 with the internal CA
(BAO_ADDR/BAO_CACERT in compose.yaml): the server certificate is verified.
Idempotent: init only if not initialized; mounts/auth/policies/roles/KV are (re)written to the
state described here; an existing secret_id file is kept unless `new-secret-id` is asked.
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
POLICIES = ROOT / "infra" / "openbao" / "policies"
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")
OPERATOR_DIR = Path(os.environ.get("OPERATOR_DIR") or Path.home() / ".mtusi-lab7-operator" / PROJECT)
SHARES, THRESHOLD = 3, 2
# Token of a service: 1 h, at most 4 h with renewals; the services revoke it right after reading.
# SecretID: valid 30 days, unlimited logins (every restart of a replica logs in again).
ROLE_SETTINGS = ["token_ttl=1h", "token_max_ttl=4h", "token_type=service", "token_no_default_policy=true",
"secret_id_ttl=720h", "secret_id_num_uses=0"]
# What each service may read: KV v2 messenger/data/<service>. Values come from ./secrets.
SERVICE_SECRETS = {
"api": {"database_url": "database_url_api", "cache_url": "cache_url",
"s3_access_key_id": "s3_api_access_key_id", "s3_secret_access_key": "s3_api_secret_access_key"},
"relay": {"database_url": "database_url_relay", "broker_url": "broker_url_relay"},
"worker": {"database_url": "database_url_worker", "broker_url": "broker_url_worker",
"s3_access_key_id": "s3_worker_access_key_id", "s3_secret_access_key": "s3_worker_secret_access_key"},
}
def say(text: str) -> None:
print(f"bao-operator: {text}", flush=True)
def bao(*args: str, token: str | None = None, stdin: bytes = b"", check: bool = True) -> subprocess.CompletedProcess:
"""Run `bao <args>` inside the openbao container; the token (if any) is the first stdin line."""
script = 'read -r BAO_TOKEN; export BAO_TOKEN; exec bao "$@"' if token else 'exec bao "$@"'
data = ((token + "\n").encode() if token else b"") + stdin
result = subprocess.run(["docker", "compose", "exec", "-T", "openbao", "sh", "-c", script, "sh", *args],
input=data, capture_output=True, cwd=ROOT)
if check and result.returncode != 0:
# stderr of the CLI names the failing path/permission; it never contains our stdin data.
raise SystemExit(f"bao-operator: `bao {' '.join(args)}` failed: {result.stderr.decode(errors='replace').strip()[:400]}")
return result
def status() -> dict:
result = bao("status", "-format=json", check=False) # exit 2 = sealed, still prints JSON
if result.returncode not in (0, 2):
raise SystemExit("bao-operator: OpenBao is not reachable (is `docker compose up -d openbao` running?): "
+ result.stderr.decode(errors="replace").strip()[:300])
return json.loads(result.stdout)
def private_write(path: Path, value: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(value + "\n", encoding="utf-8", newline="\n")
os.chmod(path, 0o600)
def operator_file(name: str) -> str:
path = OPERATOR_DIR / name
if not path.exists():
raise SystemExit(f"bao-operator: {path} is missing: the operator material of this OpenBao is not here")
return path.read_text(encoding="utf-8").strip()
def init() -> None:
if status()["initialized"]:
say("already initialized")
return
if (OPERATOR_DIR / "root-token").exists():
raise SystemExit(f"bao-operator: OpenBao is NOT initialized but {OPERATOR_DIR} has material of an older "
"instance; move it away first (it does not belong to this storage)")
out = json.loads(bao("operator", "init", f"-key-shares={SHARES}", f"-key-threshold={THRESHOLD}", "-format=json").stdout)
for i, share in enumerate(out["unseal_keys_b64"], 1):
private_write(OPERATOR_DIR / f"unseal-share-{i}", share)
private_write(OPERATOR_DIR / "root-token", out["root_token"])
os.chmod(OPERATOR_DIR, 0o700)
say(f"initialized: {SHARES} unseal shares (threshold {THRESHOLD}) and the root token saved to {OPERATOR_DIR} "
"(outside the repository; not printed)")
def unseal() -> None:
state = status()
if not state["initialized"]:
raise SystemExit("bao-operator: not initialized yet: run `bootstrap`")
if not state["sealed"]:
say("already unsealed")
return
for i in range(1, THRESHOLD + 1):
bao("write", "-format=json", "sys/unseal", "key=-", stdin=operator_file(f"unseal-share-{i}").encode())
state = status()
if state["sealed"]:
raise SystemExit("bao-operator: still sealed after the threshold of shares")
say(f"unsealed with {THRESHOLD} of {SHARES} shares")
def secret(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def configure() -> None:
token = operator_file("root-token")
mounts = json.loads(bao("secrets", "list", "-format=json", token=token).stdout)
if "messenger/" not in mounts:
bao("secrets", "enable", "-path=messenger", "-version=2", "kv", token=token)
say("KV v2 mounted at messenger/")
auths = json.loads(bao("auth", "list", "-format=json", token=token).stdout)
if "approle/" not in auths:
bao("auth", "enable", "approle", token=token)
say("auth method approle enabled")
# The audit device (file -> container stdout) is declared in infra/openbao/config.hcl:
# OpenBao 2.7 refuses to enable audit devices over the API.
for service, values in SERVICE_SECRETS.items():
bao("policy", "write", service, "-", token=token, stdin=(POLICIES / f"{service}.hcl").read_bytes())
bao("write", f"auth/approle/role/{service}", f"token_policies={service}", *ROLE_SETTINGS, token=token)
data = {key: secret(source) for key, source in values.items()}
bao("kv", "put", "-mount=messenger", service, "-", token=token, stdin=json.dumps(data).encode())
role_id = json.loads(bao("read", "-format=json", f"auth/approle/role/{service}/role-id", token=token).stdout)["data"]["role_id"]
private_write(SECRETS / "bao" / f"{service}_role_id", role_id)
os.chmod(SECRETS / "bao" / f"{service}_role_id", 0o644) # readable by the container user (bind mount)
if not (SECRETS / "bao" / f"{service}_secret_id").exists():
issue_secret_id(service, token)
say(f"{service}: policy {service} (read messenger/data/{service}), AppRole, KV keys {sorted(data)}")
def issue_secret_id(service: str, token: str | None = None) -> None:
token = token or operator_file("root-token")
out = json.loads(bao("write", "-f", "-format=json", f"auth/approle/role/{service}/secret-id", token=token).stdout)
path = SECRETS / "bao" / f"{service}_secret_id"
private_write(path, out["data"]["secret_id"])
os.chmod(path, 0o644) # the service reads it through the bind mount (folder ./secrets is 0700)
say(f"{service}: new SecretID written to secrets/bao/{service}_secret_id (TTL 720h; not printed)")
def main(argv: list[str]) -> int:
command = argv[0] if argv else "status"
if command == "bootstrap":
init()
unseal()
configure()
say("done; start the stand: docker compose up -d --build --wait")
elif command == "unseal":
unseal()
elif command == "status":
state = status()
say(f"initialized={state['initialized']} sealed={state['sealed']} storage={state.get('storage_type')} "
f"version={state.get('version')} operator_dir={OPERATOR_DIR}")
elif command == "new-secret-id" and len(argv) == 2 and argv[1] in SERVICE_SECRETS:
issue_secret_id(argv[1])
say(f"restart the service to use it: docker compose up -d --force-recreate {argv[1]}")
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+13 -8
View File
@@ -1,21 +1,26 @@
#!/bin/sh
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey,
# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are
# preserved: no `down -v`, no FLUSH, no purge, no re-seed.
# Output is suppressed by the test; run it by hand to see the steps.
# S3 (SeaweedFS), the broker (RabbitMQ) and OpenBao. Volumes, schema, data, queued messages and the
# OpenBao storage are preserved: no `down -v`, no FLUSH, no purge, no re-seed.
# Lab 7: OpenBao comes back SEALED; the operator unseal step (scripts/bao_operator.py unseal, shares
# from the operator directory outside the repository) runs before the services that need secrets.
# Output is suppressed by the test; run it by hand to see the steps (no secret is printed).
set -eu
cd "$(dirname "$0")/.."
PY="${PYTHON:-python}"
# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the
# stores restart underneath.
docker compose stop lb api relay worker
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer
# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata.
docker compose restart postgres valkey s3 broker
# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy
# resolves the new replica addresses through Docker DNS by itself - no stale backend list.
# flush, RabbitMQ quorum log, OpenBao raft), then start again.
docker compose restart postgres valkey s3 broker openbao
# 3. Operator: unseal (OpenBao is sealed after every start).
"$PY" scripts/bao_operator.py unseal
# 4. API replicas (log in to OpenBao again, read their secrets), the LB, then relay and worker.
# HAProxy resolves the new replica addresses through Docker DNS by itself.
docker compose start api
docker compose start lb
docker compose start relay worker
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved"
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3, broker and openbao restarted with volumes preserved; openbao unsealed"