forked from mtusi2026/mtusi2026lab7
54 lines
2.0 KiB
Python
54 lines
2.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Prove each AppRole can read only its own KV-v2 path and cannot write it."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from pathlib import Path
|
|
|
|
import hvac
|
|
from hvac.exceptions import Forbidden
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("service", choices=("api", "worker"))
|
|
parser.add_argument("--url", default="https://127.0.0.1:8200")
|
|
args = parser.parse_args()
|
|
|
|
secret_dir = ROOT / "secrets" / f"openbao-{args.service}"
|
|
role_id = (secret_dir / "role_id").read_text(encoding="utf-8").strip()
|
|
secret_id = (secret_dir / "secret_id").read_text(encoding="utf-8").strip()
|
|
ca = ROOT / "secrets" / "ca" / "service-ca.crt"
|
|
own_path = f"messenger/{args.service}"
|
|
other_path = "messenger/worker" if args.service == "api" else "messenger/api"
|
|
client = hvac.Client(url=args.url, verify=str(ca), timeout=10)
|
|
try:
|
|
client.auth.approle.login(role_id=role_id, secret_id=secret_id)
|
|
client.secrets.kv.v2.read_secret_version(path=own_path, mount_point="secret")
|
|
print(f"PASS: {args.service} AppRole can read {own_path}")
|
|
try:
|
|
client.secrets.kv.v2.read_secret_version(path=other_path, mount_point="secret")
|
|
except Forbidden:
|
|
print(f"PASS: {args.service} AppRole cannot read {other_path}")
|
|
else:
|
|
raise SystemExit(f"FAIL: {args.service} AppRole unexpectedly read {other_path}")
|
|
try:
|
|
client.secrets.kv.v2.create_or_update_secret(
|
|
path=own_path, secret={"probe": "must-not-be-written"}, mount_point="secret"
|
|
)
|
|
except Forbidden:
|
|
print(f"PASS: {args.service} AppRole cannot write {own_path}")
|
|
else:
|
|
raise SystemExit(f"FAIL: {args.service} AppRole unexpectedly wrote {own_path}")
|
|
finally:
|
|
try:
|
|
client.logout(revoke_token=True)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|