#!/usr/bin/env bash
# Silent owner command for the governed openbao-platform-admin-login lane.
# Warden rejects any child output and self-revokes the attended session after
# this command exits. The role payload contains no secret values.

set -euo pipefail

ROLE_PATH="auth/netkingdom/role/platform-admin"
CALLBACK_URI="http://127.0.0.1:18200/ui/vault/auth/netkingdom/oidc/callback"
PAYLOAD="$(mktemp "${TMPDIR:-/tmp}/openbao-platform-admin-role.XXXXXX.json")"
READBACK="$(mktemp "${TMPDIR:-/tmp}/openbao-platform-admin-readback.XXXXXX.json")"

cleanup() {
  rm -f "$PAYLOAD" "$READBACK"
}
trap cleanup EXIT INT TERM
chmod 0600 "$PAYLOAD" "$READBACK"

command -v bao >/dev/null 2>&1
command -v python3 >/dev/null 2>&1

cat >"$PAYLOAD" <<'ROLE_JSON'
{
  "role_type": "oidc",
  "user_claim": "sub",
  "groups_claim": "groups",
  "oidc_scopes": ["openid", "profile", "email", "groups"],
  "allowed_redirect_uris": [
    "http://localhost:8250/oidc/callback",
    "http://127.0.0.1:8250/oidc/callback",
    "http://127.0.0.1:18200/ui/vault/auth/netkingdom/oidc/callback",
    "https://bao.coulomb.social/ui/vault/auth/netkingdom/oidc/callback",
    "https://bao.coulomb.social/ui/vault/auth/keycape/oidc/callback"
  ],
  "bound_claims": {
    "groups": ["net-kingdom-admins"]
  },
  "claim_mappings": {
    "email": "email",
    "preferred_username": "username"
  },
  "policies": ["platform-admin"],
  "ttl": "1h"
}
ROLE_JSON

bao write "$ROLE_PATH" @"$PAYLOAD" >/dev/null 2>&1
bao read -format=json "$ROLE_PATH" >"$READBACK" 2>/dev/null
python3 - "$READBACK" "$CALLBACK_URI" <<'PY' >/dev/null 2>&1
import json
import sys

path, callback = sys.argv[1:]
with open(path, encoding="utf-8") as handle:
    role = json.load(handle).get("data") or {}

if callback not in role.get("allowed_redirect_uris", []):
    raise SystemExit(1)
if role.get("role_type") != "oidc":
    raise SystemExit(1)
if "platform-admin" not in role.get("token_policies", role.get("policies", [])):
    raise SystemExit(1)
PY
