1380 lines
50 KiB
Python
Executable File
1380 lines
50 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""bao-secret-drop: Minimal local webapp for dropping secrets into OpenBao via Zitadel Device Code."""
|
|
|
|
import argparse
|
|
import base64
|
|
import html
|
|
import http.cookies
|
|
import json
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from http import HTTPStatus
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
DEFAULT_BAO_ADDR = os.environ.get("BAO_ADDR") or os.environ.get("VAULT_ADDR") or "https://bao.site.latha.org"
|
|
DEFAULT_AUTH_MOUNT = os.environ.get("BAO_AUTH_MOUNT") or os.environ.get("BAO_JWT_MOUNT") or "jwt"
|
|
DEFAULT_ROLE = os.environ.get("BAO_OIDC_ROLE") or os.environ.get("BAO_JWT_ROLE") or "admin"
|
|
DEFAULT_MOUNT = os.environ.get("BAO_KV_MOUNT") or "secret"
|
|
DEFAULT_OIDC_ISSUER = os.environ.get("ZITADEL_ISSUER") or os.environ.get("OIDC_ISSUER") or "https://auth.site.latha.org"
|
|
DEFAULT_CLIENT_ID = os.environ.get("ZITADEL_CLIENT_ID") or os.environ.get("OIDC_CLIENT_ID") or "400222693598691513"
|
|
DEFAULT_CLIENT_SECRET = os.environ.get("ZITADEL_CLIENT_SECRET") or os.environ.get("OIDC_CLIENT_SECRET") or ""
|
|
DEFAULT_OIDC_SCOPE = os.environ.get("ZITADEL_SCOPE") or os.environ.get("OIDC_SCOPE") or "openid profile email"
|
|
|
|
SESSIONS_LOCK = threading.Lock()
|
|
SESSIONS: dict[str, dict] = {}
|
|
SESSION_TTL_SECONDS = 8 * 3600
|
|
|
|
DEVICE_FLOWS_LOCK = threading.Lock()
|
|
PENDING_DEVICE_FLOWS: dict[str, dict] = {}
|
|
|
|
OIDC_DISCOVERY_LOCK = threading.Lock()
|
|
OIDC_DISCOVERY_CACHE: dict[str, tuple[float, dict]] = {}
|
|
OIDC_DISCOVERY_TTL_SECONDS = 3600
|
|
|
|
|
|
def cleanup_sessions() -> None:
|
|
now = time.time()
|
|
with SESSIONS_LOCK:
|
|
expired = [sid for sid, s in SESSIONS.items() if s.get("expires_at", 0) < now]
|
|
for sid in expired:
|
|
del SESSIONS[sid]
|
|
|
|
|
|
def cleanup_device_flows() -> None:
|
|
now = time.time()
|
|
with DEVICE_FLOWS_LOCK:
|
|
expired = [fid for fid, data in PENDING_DEVICE_FLOWS.items() if data.get("expires_at", 0) < now]
|
|
for fid in expired:
|
|
del PENDING_DEVICE_FLOWS[fid]
|
|
|
|
|
|
def b64url_decode(segment: str) -> bytes:
|
|
pad = "=" * (-len(segment) % 4)
|
|
return base64.urlsafe_b64decode(segment + pad)
|
|
|
|
|
|
def decode_jwt_claims(token: str) -> dict:
|
|
parts = token.split(".")
|
|
if len(parts) != 3:
|
|
return {}
|
|
try:
|
|
return json.loads(b64url_decode(parts[1]).decode("utf-8"))
|
|
except Exception:
|
|
return {}
|
|
|
|
|
|
def http_json_request(
|
|
url: str,
|
|
method: str = "GET",
|
|
headers: dict[str, str] | None = None,
|
|
data: bytes | None = None,
|
|
) -> tuple[int, dict]:
|
|
req_headers = {"Accept": "application/json"}
|
|
if headers:
|
|
req_headers.update(headers)
|
|
req = urllib.request.Request(url, data=data, headers=req_headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
raw = resp.read().decode("utf-8")
|
|
return resp.status, json.loads(raw) if raw else {}
|
|
except urllib.error.HTTPError as e:
|
|
raw = e.read().decode("utf-8", errors="replace")
|
|
try:
|
|
body = json.loads(raw) if raw else {}
|
|
except json.JSONDecodeError:
|
|
body = {"error": raw or str(e)}
|
|
return e.code, body
|
|
except urllib.error.URLError as e:
|
|
return 502, {"error": f"Upstream connection error: {e.reason}"}
|
|
|
|
|
|
def discover_oidc_metadata(issuer: str) -> tuple[dict | None, str | None]:
|
|
issuer_clean = issuer.rstrip("/")
|
|
now = time.time()
|
|
with OIDC_DISCOVERY_LOCK:
|
|
cached = OIDC_DISCOVERY_CACHE.get(issuer_clean)
|
|
if cached and cached[0] > now:
|
|
return cached[1], None
|
|
|
|
status, body = http_json_request(f"{issuer_clean}/.well-known/openid-configuration", method="GET")
|
|
if status != 200 or not isinstance(body, dict):
|
|
err = (body.get("error_description") or body.get("error") if isinstance(body, dict) else None) or f"HTTP {status}"
|
|
return None, f"Failed to fetch OIDC discovery from {issuer_clean}: {err}"
|
|
|
|
body.setdefault("device_authorization_endpoint", f"{issuer_clean}/oauth/v2/device_authorization")
|
|
body.setdefault("token_endpoint", f"{issuer_clean}/oauth/v2/token")
|
|
with OIDC_DISCOVERY_LOCK:
|
|
OIDC_DISCOVERY_CACHE[issuer_clean] = (now + OIDC_DISCOVERY_TTL_SECONDS, body)
|
|
return body, None
|
|
|
|
|
|
def bao_request(
|
|
bao_addr: str,
|
|
path: str,
|
|
method: str = "GET",
|
|
token: str | None = None,
|
|
payload: dict | None = None,
|
|
) -> tuple[int, dict]:
|
|
url = bao_addr.rstrip("/") + path
|
|
headers = {"Accept": "application/json"}
|
|
data = None
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
if payload is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
data = json.dumps(payload).encode("utf-8")
|
|
|
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=15) as resp:
|
|
raw = resp.read().decode("utf-8")
|
|
return resp.status, json.loads(raw) if raw else {}
|
|
except urllib.error.HTTPError as e:
|
|
raw = e.read().decode("utf-8", errors="replace")
|
|
try:
|
|
body = json.loads(raw) if raw else {}
|
|
except json.JSONDecodeError:
|
|
body = {"errors": [raw or str(e)]}
|
|
return e.code, body
|
|
except urllib.error.URLError as e:
|
|
return 502, {"errors": [f"Upstream OpenBao connection error: {e.reason}"]}
|
|
|
|
|
|
def normalize_secret_path(raw_path: str, mount: str) -> str:
|
|
p = raw_path.strip().strip("/")
|
|
mount_clean = mount.strip().strip("/")
|
|
if p.startswith(mount_clean + "/data/"):
|
|
p = p[len(mount_clean) + len("/data/") :]
|
|
elif p.startswith(mount_clean + "/"):
|
|
p = p[len(mount_clean) + 1 :]
|
|
return p.strip("/")
|
|
|
|
|
|
HTML_PAGE = r"""<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
<title>OpenBao Secret Drop</title>
|
|
<style>
|
|
:root {
|
|
--bg: #0d1117;
|
|
--surface: #161b22;
|
|
--surface-2: #1f2630;
|
|
--border: #30363d;
|
|
--text: #e6edf3;
|
|
--muted: #8b949e;
|
|
--accent: #2f81f7;
|
|
--accent-hover: #388bfd;
|
|
--ok-bg: rgba(46, 160, 67, 0.14);
|
|
--ok-border: #2ea043;
|
|
--ok-text: #56d364;
|
|
--err-bg: rgba(248, 81, 73, 0.14);
|
|
--err-border: #f85149;
|
|
--err-text: #ff7b72;
|
|
--warn-bg: rgba(210, 153, 34, 0.14);
|
|
--warn-border: #d29922;
|
|
--warn-text: #e3b341;
|
|
--radius: 10px;
|
|
}
|
|
* { box-sizing: border-box; }
|
|
body {
|
|
margin: 0;
|
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, sans-serif;
|
|
background: var(--bg);
|
|
color: var(--text);
|
|
line-height: 1.5;
|
|
padding: 24px 16px 48px;
|
|
}
|
|
.container {
|
|
max-width: 760px;
|
|
margin: 0 auto;
|
|
}
|
|
.header {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
gap: 12px;
|
|
margin-bottom: 20px;
|
|
}
|
|
.brand h1 {
|
|
margin: 0;
|
|
font-size: 1.35rem;
|
|
font-weight: 650;
|
|
letter-spacing: -0.01em;
|
|
}
|
|
.brand .sub {
|
|
font-size: 0.85rem;
|
|
color: var(--muted);
|
|
word-break: break-all;
|
|
}
|
|
.card {
|
|
background: var(--surface);
|
|
border: 1px solid var(--border);
|
|
border-radius: var(--radius);
|
|
padding: 20px;
|
|
margin-bottom: 16px;
|
|
}
|
|
.auth-bar {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
align-items: center;
|
|
justify-content: space-between;
|
|
gap: 12px;
|
|
}
|
|
.identity {
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 4px;
|
|
}
|
|
.badge {
|
|
display: inline-flex;
|
|
align-items: center;
|
|
gap: 6px;
|
|
font-size: 0.8rem;
|
|
font-weight: 600;
|
|
padding: 3px 10px;
|
|
border-radius: 999px;
|
|
width: fit-content;
|
|
}
|
|
.badge.ok { background: var(--ok-bg); color: var(--ok-text); border: 1px solid var(--ok-border); }
|
|
.badge.warn { background: var(--warn-bg); color: var(--warn-text); border: 1px solid var(--warn-border); }
|
|
.meta {
|
|
font-size: 0.83rem;
|
|
color: var(--muted);
|
|
}
|
|
button, .btn {
|
|
appearance: none;
|
|
border: 1px solid var(--border);
|
|
background: var(--surface-2);
|
|
color: var(--text);
|
|
padding: 9px 14px;
|
|
border-radius: 8px;
|
|
font-size: 0.9rem;
|
|
font-weight: 550;
|
|
cursor: pointer;
|
|
transition: background 0.15s, border-color 0.15s;
|
|
text-decoration: none;
|
|
display: inline-flex;
|
|
align-items: center;
|
|
gap: 6px;
|
|
}
|
|
button:hover:not(:disabled), .btn:hover { background: #29323f; border-color: #485260; }
|
|
button:disabled { opacity: 0.5; cursor: not-allowed; }
|
|
.btn-primary {
|
|
background: var(--accent);
|
|
border-color: var(--accent);
|
|
color: #fff;
|
|
}
|
|
.btn-primary:hover:not(:disabled) {
|
|
background: var(--accent-hover);
|
|
border-color: var(--accent-hover);
|
|
}
|
|
.btn-sm { padding: 5px 10px; font-size: 0.8rem; }
|
|
.btn-danger { color: var(--err-text); }
|
|
label {
|
|
display: block;
|
|
font-size: 0.85rem;
|
|
font-weight: 600;
|
|
margin-bottom: 6px;
|
|
color: var(--text);
|
|
}
|
|
input[type="text"], input[type="password"] {
|
|
width: 100%;
|
|
background: var(--bg);
|
|
border: 1px solid var(--border);
|
|
color: var(--text);
|
|
border-radius: 8px;
|
|
padding: 9px 12px;
|
|
font-size: 0.92rem;
|
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
}
|
|
input:focus {
|
|
outline: none;
|
|
border-color: var(--accent);
|
|
box-shadow: 0 0 0 2px rgba(47, 129, 247, 0.25);
|
|
}
|
|
.presets {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
gap: 8px;
|
|
margin-top: 8px;
|
|
margin-bottom: 16px;
|
|
}
|
|
.existing-keys {
|
|
font-size: 0.82rem;
|
|
color: var(--muted);
|
|
margin-top: 6px;
|
|
min-height: 1.2em;
|
|
}
|
|
.rows {
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 10px;
|
|
margin: 12px 0 14px;
|
|
}
|
|
.row {
|
|
display: grid;
|
|
grid-template-columns: minmax(150px, 1fr) minmax(200px, 1.5fr) auto auto;
|
|
gap: 8px;
|
|
align-items: center;
|
|
}
|
|
@media (max-width: 600px) {
|
|
.row {
|
|
grid-template-columns: 1fr;
|
|
}
|
|
}
|
|
.checkbox-row {
|
|
display: flex;
|
|
align-items: center;
|
|
gap: 8px;
|
|
margin: 14px 0 18px;
|
|
font-size: 0.88rem;
|
|
color: var(--muted);
|
|
}
|
|
.checkbox-row input { width: auto; }
|
|
.actions {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
justify-content: space-between;
|
|
align-items: center;
|
|
gap: 12px;
|
|
}
|
|
.alert {
|
|
border-radius: 8px;
|
|
padding: 12px 14px;
|
|
font-size: 0.88rem;
|
|
margin-top: 14px;
|
|
display: none;
|
|
white-space: pre-wrap;
|
|
overflow-wrap: anywhere;
|
|
}
|
|
.alert.ok { display: block; background: var(--ok-bg); border: 1px solid var(--ok-border); color: var(--ok-text); }
|
|
.alert.err { display: block; background: var(--err-bg); border: 1px solid var(--err-border); color: var(--err-text); }
|
|
.auth-card {
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 14px;
|
|
}
|
|
.oidc-panel {
|
|
border-top: 1px solid var(--border);
|
|
padding-top: 14px;
|
|
display: flex;
|
|
flex-direction: column;
|
|
gap: 12px;
|
|
}
|
|
.oidc-link-box {
|
|
background: var(--bg);
|
|
border: 1px solid var(--border);
|
|
border-radius: 8px;
|
|
padding: 10px 12px;
|
|
display: none;
|
|
flex-direction: column;
|
|
gap: 8px;
|
|
}
|
|
.oidc-link-box.visible { display: flex; }
|
|
.oidc-link-actions {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
align-items: center;
|
|
gap: 8px;
|
|
}
|
|
.callback-row {
|
|
display: flex;
|
|
flex-wrap: wrap;
|
|
gap: 8px;
|
|
align-items: center;
|
|
}
|
|
.callback-row input {
|
|
flex: 1 1 280px;
|
|
}
|
|
code {
|
|
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
font-size: 0.85em;
|
|
background: rgba(110, 118, 129, 0.18);
|
|
padding: 2px 5px;
|
|
border-radius: 4px;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container">
|
|
<div class="header">
|
|
<div class="brand">
|
|
<h1>OpenBao Secret Drop</h1>
|
|
<div class="sub" id="baoAddr">Target: loading...</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="card auth-card">
|
|
<div class="auth-bar">
|
|
<div class="identity">
|
|
<span class="badge warn" id="authBadge">Checking session...</span>
|
|
<div class="meta" id="authMeta">Sign in via Zitadel Device Code to write secrets to OpenBao KV v2.</div>
|
|
</div>
|
|
<div id="authActions">
|
|
<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startDeviceLogin()">Sign in with Zitadel</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="oidc-panel" id="oidcPanel" style="display: none;">
|
|
<div class="oidc-link-box" id="oidcLinkBox">
|
|
<div class="meta" id="oidcStatusText">Authorize this device in Zitadel (no redirect URL required).</div>
|
|
<div style="display:flex; flex-wrap:wrap; align-items:center; gap:10px;">
|
|
<code id="deviceUserCode" style="font-size:1.15rem; font-weight:700; letter-spacing:0.08em; padding:6px 10px;">----</code>
|
|
<button type="button" class="btn-sm" id="copyCodeBtn" onclick="copyText(currentUserCode, 'copyCodeBtn', 'Copy Code')">Copy Code</button>
|
|
</div>
|
|
<div class="oidc-link-actions">
|
|
<a class="btn btn-primary btn-sm" id="oidcAuthLink" href="#" target="_blank" rel="noopener noreferrer">Open Zitadel Device Login</a>
|
|
<button type="button" class="btn-sm" id="copyOidcUrlBtn" onclick="copyText(currentAuthUrl, 'copyOidcUrlBtn', 'Copy URL')">Copy URL</button>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="alert" id="authAlert" style="margin-top: 0;"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="card">
|
|
<form id="secretForm" autocomplete="off">
|
|
<div>
|
|
<label for="secretPath">KV v2 Secret Path (under <code id="mountLabel">secret/</code>)</label>
|
|
<input id="secretPath" type="text" list="pathSuggestions" placeholder="e.g. depot or gitea-mcp" value="depot" required />
|
|
<datalist id="pathSuggestions"></datalist>
|
|
<div class="existing-keys" id="existingKeys"></div>
|
|
</div>
|
|
|
|
<div class="presets">
|
|
<button type="button" class="btn-sm" onclick="applyPreset('depot', ['DEPOT_TOKEN', 'DEPOT_PROJECT_ID'])">Preset: Depot</button>
|
|
<button type="button" class="btn-sm" onclick="applyPreset('gitea-mcp', ['GITEA_TOKEN'])">Preset: Gitea</button>
|
|
<button type="button" class="btn-sm" onclick="applyPreset('cloudflare', ['CLOUDFLARE_API_TOKEN'])">Preset: Cloudflare</button>
|
|
<button type="button" class="btn-sm" onclick="addRow('', '')">+ Add Field</button>
|
|
</div>
|
|
|
|
<label>Token / Secret Fields</label>
|
|
<div class="rows" id="rows"></div>
|
|
|
|
<label class="checkbox-row">
|
|
<input type="checkbox" id="mergeExisting" checked />
|
|
Merge with existing keys at this path (uncheck to replace all keys at this path)
|
|
</label>
|
|
|
|
<div class="actions">
|
|
<button type="button" onclick="addRow('', '')">+ Add Field</button>
|
|
<button type="submit" class="btn-primary" id="submitBtn" disabled>Save to OpenBao</button>
|
|
</div>
|
|
|
|
<div class="alert" id="resultAlert"></div>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
let isAuthenticated = false;
|
|
let currentAuthUrl = '';
|
|
let currentUserCode = '';
|
|
let currentFlowId = '';
|
|
let pollTimer = null;
|
|
|
|
function stopPolling() {
|
|
if (pollTimer !== null) {
|
|
clearTimeout(pollTimer);
|
|
pollTimer = null;
|
|
}
|
|
}
|
|
|
|
function scheduleDevicePoll(delayMs) {
|
|
stopPolling();
|
|
if (!currentFlowId) return;
|
|
pollTimer = setTimeout(pollDeviceFlow, delayMs);
|
|
}
|
|
|
|
async function pollDeviceFlow() {
|
|
if (!currentFlowId) return;
|
|
try {
|
|
const res = await fetch('/api/auth/device/poll', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ flow_id: currentFlowId }),
|
|
});
|
|
const data = await res.json();
|
|
if (data.status === 'complete') {
|
|
currentFlowId = '';
|
|
stopPolling();
|
|
await loadMe();
|
|
return;
|
|
}
|
|
if (data.status === 'pending') {
|
|
const secs = Number(data.interval || 5);
|
|
document.getElementById('oidcStatusText').textContent =
|
|
`Confirm code ${currentUserCode} in Zitadel (polling every ${secs}s)...`;
|
|
scheduleDevicePoll(secs * 1000);
|
|
return;
|
|
}
|
|
currentFlowId = '';
|
|
stopPolling();
|
|
showAuthAlert('err', data.error || 'Device login failed.');
|
|
} catch (err) {
|
|
scheduleDevicePoll(5000);
|
|
}
|
|
}
|
|
|
|
function showAuthAlert(kind, msg) {
|
|
const box = document.getElementById('authAlert');
|
|
if (!msg) {
|
|
box.className = 'alert';
|
|
box.textContent = '';
|
|
return;
|
|
}
|
|
document.getElementById('oidcPanel').style.display = 'flex';
|
|
box.className = 'alert ' + kind;
|
|
box.textContent = msg;
|
|
}
|
|
|
|
async function startDeviceLogin() {
|
|
showAuthAlert('', '');
|
|
stopPolling();
|
|
const btn = document.getElementById('oidcSignInBtn');
|
|
if (btn) {
|
|
btn.disabled = true;
|
|
btn.textContent = 'Starting...';
|
|
}
|
|
try {
|
|
const res = await fetch('/api/auth/device/start', { method: 'POST' });
|
|
const data = await res.json();
|
|
if (!res.ok || !data.flow_id) {
|
|
showAuthAlert('err', data.error || 'Failed to start Zitadel device login.');
|
|
return;
|
|
}
|
|
currentFlowId = data.flow_id;
|
|
currentUserCode = data.user_code || '';
|
|
currentAuthUrl = data.verification_uri_complete || data.verification_uri || '';
|
|
|
|
document.getElementById('deviceUserCode').textContent = currentUserCode;
|
|
document.getElementById('oidcAuthLink').href = currentAuthUrl;
|
|
document.getElementById('oidcPanel').style.display = 'flex';
|
|
document.getElementById('oidcLinkBox').classList.add('visible');
|
|
|
|
let popup = null;
|
|
try {
|
|
popup = window.open(currentAuthUrl, '_blank');
|
|
} catch (_) {
|
|
popup = null;
|
|
}
|
|
const secs = Number(data.interval || 5);
|
|
document.getElementById('oidcStatusText').textContent = popup
|
|
? `Opened Zitadel in a new tab. Confirm code ${currentUserCode} (polling every ${secs}s)...`
|
|
: `Click "Open Zitadel Device Login" and confirm code ${currentUserCode} (polling every ${secs}s)...`;
|
|
scheduleDevicePoll(secs * 1000);
|
|
} catch (err) {
|
|
showAuthAlert('err', 'Failed to start device login: ' + err.message);
|
|
} finally {
|
|
if (btn) {
|
|
btn.disabled = false;
|
|
btn.textContent = 'Sign in with Zitadel';
|
|
}
|
|
}
|
|
}
|
|
|
|
async function retryBaoLogin() {
|
|
showAuthAlert('', '');
|
|
const btn = document.getElementById('retryBaoBtn');
|
|
if (btn) {
|
|
btn.disabled = true;
|
|
btn.textContent = 'Connecting...';
|
|
}
|
|
try {
|
|
const res = await fetch('/api/bao/login', { method: 'POST' });
|
|
const data = await res.json();
|
|
await loadMe();
|
|
if (!res.ok || !data.bao_authenticated) {
|
|
showAuthAlert('err', data.error || 'Failed to authenticate with OpenBao.');
|
|
}
|
|
} catch (err) {
|
|
showAuthAlert('err', 'OpenBao login failed: ' + err.message);
|
|
} finally {
|
|
if (btn) {
|
|
btn.disabled = false;
|
|
btn.textContent = 'Retry OpenBao Login';
|
|
}
|
|
}
|
|
}
|
|
|
|
async function copyText(text, btnId, defaultLabel) {
|
|
if (!text) return;
|
|
const btn = document.getElementById(btnId);
|
|
try {
|
|
await navigator.clipboard.writeText(text);
|
|
btn.textContent = 'Copied!';
|
|
setTimeout(() => { btn.textContent = defaultLabel; }, 1500);
|
|
} catch (_) {
|
|
const ta = document.createElement('textarea');
|
|
ta.value = text;
|
|
ta.style.position = 'fixed';
|
|
ta.style.opacity = '0';
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
try {
|
|
document.execCommand('copy');
|
|
btn.textContent = 'Copied!';
|
|
setTimeout(() => { btn.textContent = defaultLabel; }, 1500);
|
|
} catch (err) {
|
|
showAuthAlert('err', 'Could not copy automatically.');
|
|
} finally {
|
|
ta.remove();
|
|
}
|
|
}
|
|
}
|
|
|
|
function addRow(key = '', value = '') {
|
|
const rows = document.getElementById('rows');
|
|
const row = document.createElement('div');
|
|
row.className = 'row';
|
|
|
|
const keyInput = document.createElement('input');
|
|
keyInput.type = 'text';
|
|
keyInput.placeholder = 'KEY_NAME';
|
|
keyInput.value = key;
|
|
keyInput.autocomplete = 'off';
|
|
keyInput.spellcheck = false;
|
|
|
|
const valInput = document.createElement('input');
|
|
valInput.type = 'password';
|
|
valInput.placeholder = 'Secret value';
|
|
valInput.value = value;
|
|
valInput.autocomplete = 'new-password';
|
|
valInput.spellcheck = false;
|
|
|
|
const toggleBtn = document.createElement('button');
|
|
toggleBtn.type = 'button';
|
|
toggleBtn.className = 'btn-sm';
|
|
toggleBtn.textContent = 'Show';
|
|
toggleBtn.onclick = () => {
|
|
const show = valInput.type === 'password';
|
|
valInput.type = show ? 'text' : 'password';
|
|
toggleBtn.textContent = show ? 'Hide' : 'Show';
|
|
};
|
|
|
|
const removeBtn = document.createElement('button');
|
|
removeBtn.type = 'button';
|
|
removeBtn.className = 'btn-sm btn-danger';
|
|
removeBtn.textContent = 'Remove';
|
|
removeBtn.onclick = () => {
|
|
if (document.querySelectorAll('#rows .row').length > 1) {
|
|
row.remove();
|
|
} else {
|
|
keyInput.value = '';
|
|
valInput.value = '';
|
|
}
|
|
};
|
|
|
|
row.append(keyInput, valInput, toggleBtn, removeBtn);
|
|
rows.appendChild(row);
|
|
}
|
|
|
|
function applyPreset(path, keys) {
|
|
document.getElementById('secretPath').value = path;
|
|
const rows = document.getElementById('rows');
|
|
rows.innerHTML = '';
|
|
keys.forEach((k) => addRow(k, ''));
|
|
loadExistingKeys();
|
|
}
|
|
|
|
async function loadMe() {
|
|
const res = await fetch('/api/me');
|
|
const data = await res.json();
|
|
document.getElementById('baoAddr').textContent =
|
|
`Zitadel: ${data.oidc_issuer} -> OpenBao: ${data.bao_addr} (auth/${data.auth_mount}, role: ${data.role})`;
|
|
document.getElementById('mountLabel').textContent = `${data.mount}/`;
|
|
|
|
const badge = document.getElementById('authBadge');
|
|
const meta = document.getElementById('authMeta');
|
|
const actions = document.getElementById('authActions');
|
|
const panel = document.getElementById('oidcPanel');
|
|
const submitBtn = document.getElementById('submitBtn');
|
|
|
|
isAuthenticated = !!data.bao_authenticated;
|
|
submitBtn.disabled = !isAuthenticated;
|
|
|
|
if (data.authenticated) {
|
|
stopPolling();
|
|
panel.style.display = 'none';
|
|
document.getElementById('oidcLinkBox').classList.remove('visible');
|
|
if (data.bao_authenticated) {
|
|
badge.className = 'badge ok';
|
|
badge.textContent = `Authenticated: ${data.display_name || 'Zitadel user'}`;
|
|
meta.textContent = `OpenBao policies: ${(data.policies || []).join(', ') || 'default'}`;
|
|
actions.innerHTML = '<button type="button" onclick="logout()">Sign out</button>';
|
|
showAuthAlert('', '');
|
|
loadPaths();
|
|
loadExistingKeys();
|
|
} else {
|
|
badge.className = 'badge warn';
|
|
badge.textContent = `Zitadel: ${data.display_name || 'signed in'} (OpenBao pending)`;
|
|
meta.textContent = data.bao_error
|
|
? `OpenBao auth error: ${data.bao_error}`
|
|
: 'OpenBao session is not active yet.';
|
|
actions.innerHTML =
|
|
'<button type="button" class="btn-primary" id="retryBaoBtn" onclick="retryBaoLogin()">Retry OpenBao Login</button>' +
|
|
'<button type="button" onclick="logout()">Sign out</button>';
|
|
}
|
|
} else {
|
|
badge.className = 'badge warn';
|
|
badge.textContent = 'Not signed in';
|
|
meta.textContent = data.client_id
|
|
? 'Sign in via Zitadel Device Code to write secrets to OpenBao KV v2.'
|
|
: 'Missing Zitadel client_id: start with --client-id <ID> or ZITADEL_CLIENT_ID.';
|
|
actions.innerHTML = `<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startDeviceLogin()"${data.client_id ? '' : ' disabled'}>Sign in with Zitadel</button>`;
|
|
if (!currentFlowId && !document.getElementById('authAlert').textContent) {
|
|
panel.style.display = 'none';
|
|
}
|
|
}
|
|
}
|
|
|
|
async function loadPaths() {
|
|
if (!isAuthenticated) return;
|
|
try {
|
|
const res = await fetch('/api/paths');
|
|
if (!res.ok) return;
|
|
const data = await res.json();
|
|
const dl = document.getElementById('pathSuggestions');
|
|
dl.innerHTML = '';
|
|
(data.paths || []).forEach((p) => {
|
|
const opt = document.createElement('option');
|
|
opt.value = p;
|
|
dl.appendChild(opt);
|
|
});
|
|
} catch (_) {}
|
|
}
|
|
|
|
async function loadExistingKeys() {
|
|
const el = document.getElementById('existingKeys');
|
|
const path = document.getElementById('secretPath').value.trim();
|
|
if (!isAuthenticated || !path) {
|
|
el.textContent = '';
|
|
return;
|
|
}
|
|
try {
|
|
const res = await fetch('/api/keys?path=' + encodeURIComponent(path));
|
|
if (!res.ok) {
|
|
el.textContent = '';
|
|
return;
|
|
}
|
|
const data = await res.json();
|
|
if (data.keys && data.keys.length) {
|
|
el.textContent = `Existing keys at this path: ${data.keys.join(', ')}`;
|
|
} else {
|
|
el.textContent = 'New secret path (no existing keys yet).';
|
|
}
|
|
} catch (_) {
|
|
el.textContent = '';
|
|
}
|
|
}
|
|
|
|
async function logout() {
|
|
stopPolling();
|
|
await fetch('/auth/logout', { method: 'POST' });
|
|
location.reload();
|
|
}
|
|
|
|
document.getElementById('secretPath').addEventListener('change', loadExistingKeys);
|
|
|
|
document.getElementById('secretForm').addEventListener('submit', async (e) => {
|
|
e.preventDefault();
|
|
const alertBox = document.getElementById('resultAlert');
|
|
alertBox.className = 'alert';
|
|
alertBox.textContent = '';
|
|
|
|
const path = document.getElementById('secretPath').value.trim();
|
|
const merge = document.getElementById('mergeExisting').checked;
|
|
const entries = [];
|
|
document.querySelectorAll('#rows .row').forEach((row) => {
|
|
const inputs = row.querySelectorAll('input');
|
|
const k = inputs[0].value.trim();
|
|
const v = inputs[1].value;
|
|
if (k) entries.push({ key: k, value: v });
|
|
});
|
|
|
|
if (!path || entries.length === 0) {
|
|
alertBox.className = 'alert err';
|
|
alertBox.textContent = 'Provide a secret path and at least one key/value field.';
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('submitBtn');
|
|
btn.disabled = true;
|
|
btn.textContent = 'Saving...';
|
|
|
|
try {
|
|
const res = await fetch('/api/secrets', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ path, merge, entries }),
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) {
|
|
alertBox.className = 'alert err';
|
|
alertBox.textContent = data.error || 'Failed to save secret.';
|
|
} else {
|
|
alertBox.className = 'alert ok';
|
|
alertBox.textContent =
|
|
`Saved to ${data.mount}/${data.path} (version ${data.version ?? '?'}).\n` +
|
|
`Updated keys: ${data.keys_written.join(', ')}\n` +
|
|
`All keys at path: ${data.total_keys.join(', ')}`;
|
|
document.querySelectorAll('#rows .row input[type="password"], #rows .row input[type="text"]').forEach((inp, idx) => {
|
|
if (idx % 2 === 1) inp.value = '';
|
|
});
|
|
loadPaths();
|
|
loadExistingKeys();
|
|
}
|
|
} catch (err) {
|
|
alertBox.className = 'alert err';
|
|
alertBox.textContent = 'Request failed: ' + err.message;
|
|
} finally {
|
|
btn.disabled = !isAuthenticated;
|
|
btn.textContent = 'Save to OpenBao';
|
|
}
|
|
});
|
|
|
|
// Initialize with Depot preset rows
|
|
applyPreset('depot', ['DEPOT_TOKEN', 'DEPOT_PROJECT_ID']);
|
|
loadMe();
|
|
</script>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
|
|
class SecretDropHandler(BaseHTTPRequestHandler):
|
|
server_version = "bao-secret-drop/1.0"
|
|
|
|
def log_message(self, format: str, *args) -> None:
|
|
sys.stderr.write(f"[bao-secret-drop] {self.address_string()} - {format % args}\n")
|
|
|
|
def _get_session_id(self) -> str | None:
|
|
raw_cookie = self.headers.get("Cookie", "")
|
|
if not raw_cookie:
|
|
return None
|
|
cookie = http.cookies.SimpleCookie()
|
|
cookie.load(raw_cookie)
|
|
morsel = cookie.get("bao_drop_sid")
|
|
return morsel.value if morsel else None
|
|
|
|
def _get_session(self) -> dict | None:
|
|
cleanup_sessions()
|
|
sid = self._get_session_id()
|
|
if not sid:
|
|
return None
|
|
with SESSIONS_LOCK:
|
|
return SESSIONS.get(sid)
|
|
|
|
def _send_json(self, status: int, data: dict, extra_headers: list[tuple[str, str]] | None = None) -> None:
|
|
body = json.dumps(data).encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
if extra_headers:
|
|
for k, v in extra_headers:
|
|
self.send_header(k, v)
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def _send_html(self, status: int, body_str: str, extra_headers: list[tuple[str, str]] | None = None) -> None:
|
|
body = body_str.encode("utf-8")
|
|
self.send_response(status)
|
|
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
self.send_header("Cache-Control", "no-store")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
if extra_headers:
|
|
for k, v in extra_headers:
|
|
self.send_header(k, v)
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def _read_json_body(self) -> dict | None:
|
|
length = int(self.headers.get("Content-Length", "0") or "0")
|
|
if length <= 0 or length > 1024 * 1024:
|
|
return None
|
|
raw = self.rfile.read(length).decode("utf-8")
|
|
return json.loads(raw)
|
|
|
|
def _require_bao_session(self) -> dict | None:
|
|
sess = self._get_session()
|
|
if not sess:
|
|
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated. Please sign in with Zitadel."})
|
|
return None
|
|
if not sess.get("bao_token"):
|
|
err = sess.get("bao_error") or "OpenBao session is not active. Retry OpenBao login."
|
|
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": err})
|
|
return None
|
|
return sess
|
|
|
|
def _start_device_flow(self, cfg: dict) -> tuple[int, dict]:
|
|
if not cfg["client_id"]:
|
|
return 400, {"error": "Zitadel client_id is not configured. Pass --client-id or set ZITADEL_CLIENT_ID."}
|
|
|
|
meta, err = discover_oidc_metadata(cfg["oidc_issuer"])
|
|
if err or not meta:
|
|
return 502, {"error": err or "Failed to load OIDC discovery metadata"}
|
|
|
|
form = {"client_id": cfg["client_id"], "scope": cfg["oidc_scope"]}
|
|
if cfg["client_secret"]:
|
|
form["client_secret"] = cfg["client_secret"]
|
|
|
|
d_status, d_body = http_json_request(
|
|
meta["device_authorization_endpoint"],
|
|
method="POST",
|
|
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
data=urllib.parse.urlencode(form).encode("utf-8"),
|
|
)
|
|
device_code = d_body.get("device_code") or ""
|
|
if d_status != 200 or not device_code or d_body.get("error"):
|
|
d_err = d_body.get("error_description") or d_body.get("error") or f"HTTP {d_status}"
|
|
return 502, {"error": f"Zitadel device authorization failed: {d_err}"}
|
|
|
|
expires_in = int(d_body.get("expires_in") or 300)
|
|
interval = max(1, int(d_body.get("interval") or 5))
|
|
cleanup_device_flows()
|
|
flow_id = secrets.token_urlsafe(24)
|
|
with DEVICE_FLOWS_LOCK:
|
|
PENDING_DEVICE_FLOWS[flow_id] = {
|
|
"device_code": device_code,
|
|
"user_code": d_body.get("user_code") or "",
|
|
"verification_uri": d_body.get("verification_uri") or "",
|
|
"verification_uri_complete": d_body.get("verification_uri_complete") or d_body.get("verification_uri") or "",
|
|
"interval": interval,
|
|
"expires_at": time.time() + expires_in,
|
|
}
|
|
|
|
return 200, {
|
|
"flow_id": flow_id,
|
|
"user_code": d_body.get("user_code") or "",
|
|
"verification_uri": d_body.get("verification_uri") or "",
|
|
"verification_uri_complete": d_body.get("verification_uri_complete") or d_body.get("verification_uri") or "",
|
|
"expires_in": expires_in,
|
|
"interval": interval,
|
|
}
|
|
|
|
def _login_bao_with_jwt(self, cfg: dict, jwt_token: str) -> tuple[bool, dict]:
|
|
auth_mount = cfg["auth_mount"].strip("/")
|
|
status, body = bao_request(
|
|
cfg["bao_addr"],
|
|
f"/v1/auth/{auth_mount}/login",
|
|
method="POST",
|
|
payload={"role": cfg["role"], "jwt": jwt_token},
|
|
)
|
|
auth = body.get("auth") or {}
|
|
client_token = auth.get("client_token")
|
|
if status != 200 or not client_token:
|
|
err = "; ".join(body.get("errors", [])) or f"OpenBao returned HTTP {status}"
|
|
return False, {"error": err, "status": status}
|
|
|
|
lookup_status, lookup_body = bao_request(
|
|
cfg["bao_addr"],
|
|
"/v1/auth/token/lookup-self",
|
|
method="GET",
|
|
token=client_token,
|
|
)
|
|
ldata = lookup_body.get("data", {}) if lookup_status == 200 else {}
|
|
policies = ldata.get("policies") or auth.get("policies") or []
|
|
return True, {
|
|
"bao_token": client_token,
|
|
"policies": policies,
|
|
"bao_display_name": ldata.get("display_name") or "",
|
|
}
|
|
|
|
def _poll_device_flow(self, cfg: dict, flow_id: str) -> tuple[int, dict, str | None]:
|
|
cleanup_device_flows()
|
|
with DEVICE_FLOWS_LOCK:
|
|
flow = PENDING_DEVICE_FLOWS.get(flow_id)
|
|
if not flow or flow.get("expires_at", 0) < time.time():
|
|
PENDING_DEVICE_FLOWS.pop(flow_id, None)
|
|
return 400, {"status": "expired", "error": "Device code expired. Click Sign in with Zitadel to try again."}, None
|
|
device_code = flow["device_code"]
|
|
interval = int(flow["interval"])
|
|
|
|
meta, err = discover_oidc_metadata(cfg["oidc_issuer"])
|
|
if err or not meta:
|
|
return 502, {"status": "error", "error": err or "Failed to load OIDC discovery metadata"}, None
|
|
|
|
token_form = {
|
|
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
|
"device_code": device_code,
|
|
"client_id": cfg["client_id"],
|
|
}
|
|
if cfg["client_secret"]:
|
|
token_form["client_secret"] = cfg["client_secret"]
|
|
|
|
t_status, t_body = http_json_request(
|
|
meta["token_endpoint"],
|
|
method="POST",
|
|
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
|
data=urllib.parse.urlencode(token_form).encode("utf-8"),
|
|
)
|
|
t_err = t_body.get("error") or ""
|
|
if t_err == "authorization_pending":
|
|
return 200, {"status": "pending", "interval": interval}, None
|
|
if t_err == "slow_down":
|
|
with DEVICE_FLOWS_LOCK:
|
|
if flow_id in PENDING_DEVICE_FLOWS:
|
|
PENDING_DEVICE_FLOWS[flow_id]["interval"] = min(interval + 5, 30)
|
|
interval = PENDING_DEVICE_FLOWS[flow_id]["interval"]
|
|
return 200, {"status": "pending", "interval": interval}, None
|
|
if t_status != 200 or t_err:
|
|
with DEVICE_FLOWS_LOCK:
|
|
PENDING_DEVICE_FLOWS.pop(flow_id, None)
|
|
msg = t_body.get("error_description") or t_err or f"HTTP {t_status}"
|
|
return 400, {"status": "error", "error": f"Zitadel device login failed: {msg}"}, None
|
|
|
|
with DEVICE_FLOWS_LOCK:
|
|
PENDING_DEVICE_FLOWS.pop(flow_id, None)
|
|
|
|
id_token = t_body.get("id_token") or ""
|
|
access_token = t_body.get("access_token") or ""
|
|
jwt_for_bao = id_token or access_token
|
|
if not jwt_for_bao:
|
|
return 401, {"status": "error", "error": "Zitadel token response did not include an id_token or access_token"}, None
|
|
|
|
claims = decode_jwt_claims(id_token) if id_token else {}
|
|
if claims:
|
|
expected_iss = (meta.get("issuer") or cfg["oidc_issuer"]).rstrip("/")
|
|
token_iss = str(claims.get("iss") or "").rstrip("/")
|
|
if token_iss and token_iss != expected_iss:
|
|
return 401, {"status": "error", "error": f"Unexpected token issuer: {token_iss}"}, None
|
|
aud = claims.get("aud")
|
|
aud_list = aud if isinstance(aud, list) else ([aud] if aud else [])
|
|
if aud_list and cfg["client_id"] not in aud_list:
|
|
return 401, {"status": "error", "error": "Token audience does not match configured client_id"}, None
|
|
|
|
userinfo = {}
|
|
if access_token and meta.get("userinfo_endpoint"):
|
|
u_status, u_body = http_json_request(
|
|
meta["userinfo_endpoint"],
|
|
method="GET",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
if u_status == 200 and isinstance(u_body, dict):
|
|
userinfo = u_body
|
|
|
|
display_name = (
|
|
userinfo.get("preferred_username")
|
|
or userinfo.get("email")
|
|
or userinfo.get("name")
|
|
or claims.get("preferred_username")
|
|
or claims.get("email")
|
|
or claims.get("name")
|
|
or claims.get("sub")
|
|
or "zitadel-user"
|
|
)
|
|
|
|
bao_ok, bao_res = self._login_bao_with_jwt(cfg, jwt_for_bao)
|
|
sid = secrets.token_urlsafe(32)
|
|
with SESSIONS_LOCK:
|
|
SESSIONS[sid] = {
|
|
"id_token": jwt_for_bao,
|
|
"access_token": access_token,
|
|
"display_name": display_name,
|
|
"bao_token": bao_res.get("bao_token") if bao_ok else None,
|
|
"policies": bao_res.get("policies", []) if bao_ok else [],
|
|
"bao_error": None if bao_ok else bao_res.get("error"),
|
|
"expires_at": time.time() + SESSION_TTL_SECONDS,
|
|
}
|
|
|
|
return (
|
|
200,
|
|
{
|
|
"status": "complete",
|
|
"ok": True,
|
|
"display_name": display_name,
|
|
"bao_authenticated": bao_ok,
|
|
"policies": bao_res.get("policies", []) if bao_ok else [],
|
|
"bao_error": None if bao_ok else bao_res.get("error"),
|
|
},
|
|
sid,
|
|
)
|
|
|
|
def _refresh_bao_session(self, cfg: dict, sess: dict) -> tuple[bool, dict]:
|
|
bao_ok, bao_res = self._login_bao_with_jwt(cfg, sess["id_token"])
|
|
with SESSIONS_LOCK:
|
|
if bao_ok:
|
|
sess["bao_token"] = bao_res["bao_token"]
|
|
sess["policies"] = bao_res.get("policies", [])
|
|
sess["bao_error"] = None
|
|
else:
|
|
sess["bao_token"] = None
|
|
sess["policies"] = []
|
|
sess["bao_error"] = bao_res.get("error")
|
|
return bao_ok, bao_res
|
|
|
|
def do_GET(self) -> None:
|
|
parsed = urllib.parse.urlparse(self.path)
|
|
cfg = self.server.config # type: ignore[attr-defined]
|
|
|
|
if parsed.path == "/":
|
|
self._send_html(HTTPStatus.OK, HTML_PAGE)
|
|
return
|
|
|
|
if parsed.path == "/healthz":
|
|
self._send_json(HTTPStatus.OK, {"ok": True})
|
|
return
|
|
|
|
if parsed.path == "/api/me":
|
|
sess = self._get_session()
|
|
base_info = {
|
|
"bao_addr": cfg["bao_addr"],
|
|
"auth_mount": cfg["auth_mount"],
|
|
"role": cfg["role"],
|
|
"mount": cfg["mount"],
|
|
"oidc_issuer": cfg["oidc_issuer"],
|
|
"client_id": bool(cfg["client_id"]),
|
|
}
|
|
if not sess:
|
|
self._send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
**base_info,
|
|
"authenticated": False,
|
|
"bao_authenticated": False,
|
|
},
|
|
)
|
|
return
|
|
self._send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
**base_info,
|
|
"authenticated": True,
|
|
"bao_authenticated": bool(sess.get("bao_token")),
|
|
"bao_error": sess.get("bao_error"),
|
|
"display_name": sess["display_name"],
|
|
"policies": sess["policies"],
|
|
},
|
|
)
|
|
return
|
|
|
|
if parsed.path == "/api/paths":
|
|
sess = self._require_bao_session()
|
|
if not sess:
|
|
return
|
|
mount = cfg["mount"].strip("/")
|
|
status, body = bao_request(
|
|
cfg["bao_addr"],
|
|
f"/v1/{mount}/metadata?list=true",
|
|
method="GET",
|
|
token=sess["bao_token"],
|
|
)
|
|
if status != 200:
|
|
self._send_json(HTTPStatus.OK, {"paths": []})
|
|
return
|
|
keys = body.get("data", {}).get("keys", [])
|
|
self._send_json(HTTPStatus.OK, {"paths": keys})
|
|
return
|
|
|
|
if parsed.path == "/api/keys":
|
|
sess = self._require_bao_session()
|
|
if not sess:
|
|
return
|
|
qs = urllib.parse.parse_qs(parsed.query)
|
|
raw_path = (qs.get("path") or [""])[0]
|
|
secret_path = normalize_secret_path(raw_path, cfg["mount"])
|
|
if not secret_path:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Invalid path"})
|
|
return
|
|
mount = cfg["mount"].strip("/")
|
|
status, body = bao_request(
|
|
cfg["bao_addr"],
|
|
f"/v1/{mount}/data/{urllib.parse.quote(secret_path, safe='/')}",
|
|
method="GET",
|
|
token=sess["bao_token"],
|
|
)
|
|
if status == 404:
|
|
self._send_json(HTTPStatus.OK, {"keys": []})
|
|
return
|
|
if status != 200:
|
|
self._send_json(status, {"error": "; ".join(body.get("errors", [])) or "Failed to read path"})
|
|
return
|
|
secret_data = (body.get("data") or {}).get("data") or {}
|
|
self._send_json(HTTPStatus.OK, {"keys": sorted(secret_data.keys())})
|
|
return
|
|
|
|
self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found"})
|
|
|
|
def do_POST(self) -> None:
|
|
parsed = urllib.parse.urlparse(self.path)
|
|
cfg = self.server.config # type: ignore[attr-defined]
|
|
|
|
if parsed.path == "/auth/logout":
|
|
sid = self._get_session_id()
|
|
if sid:
|
|
with SESSIONS_LOCK:
|
|
SESSIONS.pop(sid, None)
|
|
self.send_response(HTTPStatus.OK)
|
|
self.send_header("Set-Cookie", "bao_drop_sid=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0")
|
|
self.send_header("Content-Type", "application/json")
|
|
self.end_headers()
|
|
self.wfile.write(b'{"ok":true}')
|
|
return
|
|
|
|
if parsed.path == "/api/bao/login":
|
|
sess = self._get_session()
|
|
if not sess:
|
|
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not signed in to Zitadel."})
|
|
return
|
|
bao_ok, bao_res = self._refresh_bao_session(cfg, sess)
|
|
if not bao_ok:
|
|
self._send_json(
|
|
bao_res.get("status") or 502,
|
|
{"bao_authenticated": False, "error": bao_res.get("error")},
|
|
)
|
|
return
|
|
self._send_json(
|
|
HTTPStatus.OK,
|
|
{"bao_authenticated": True, "policies": sess["policies"]},
|
|
)
|
|
return
|
|
|
|
if parsed.path == "/api/auth/device/start":
|
|
status, result = self._start_device_flow(cfg)
|
|
self._send_json(status, result)
|
|
return
|
|
|
|
if parsed.path == "/api/auth/device/poll":
|
|
try:
|
|
req_body = self._read_json_body()
|
|
except json.JSONDecodeError:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Invalid JSON body"})
|
|
return
|
|
flow_id = str((req_body or {}).get("flow_id") or "").strip()
|
|
if not flow_id:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "flow_id is required"})
|
|
return
|
|
|
|
status, result, sid = self._poll_device_flow(cfg, flow_id)
|
|
headers = [("Set-Cookie", f"bao_drop_sid={sid}; HttpOnly; SameSite=Lax; Path=/")] if sid else None
|
|
self._send_json(status, result, extra_headers=headers)
|
|
return
|
|
|
|
if parsed.path == "/api/secrets":
|
|
sess = self._require_bao_session()
|
|
if not sess:
|
|
return
|
|
try:
|
|
req_body = self._read_json_body()
|
|
except json.JSONDecodeError:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Invalid JSON body"})
|
|
return
|
|
if not req_body:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Empty request body"})
|
|
return
|
|
|
|
secret_path = normalize_secret_path(str(req_body.get("path", "")), cfg["mount"])
|
|
if not secret_path:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Secret path is required"})
|
|
return
|
|
|
|
entries = req_body.get("entries") or []
|
|
new_data: dict[str, str] = {}
|
|
for item in entries:
|
|
if isinstance(item, dict):
|
|
k = str(item.get("key", "")).strip()
|
|
v = str(item.get("value", ""))
|
|
if k:
|
|
new_data[k] = v
|
|
if not new_data:
|
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "At least one non-empty key is required"})
|
|
return
|
|
|
|
mount = cfg["mount"].strip("/")
|
|
encoded_path = urllib.parse.quote(secret_path, safe="/")
|
|
final_data: dict[str, str] = {}
|
|
|
|
if req_body.get("merge", True):
|
|
g_status, g_body = bao_request(
|
|
cfg["bao_addr"],
|
|
f"/v1/{mount}/data/{encoded_path}",
|
|
method="GET",
|
|
token=sess["bao_token"],
|
|
)
|
|
if g_status == 200:
|
|
existing = (g_body.get("data") or {}).get("data") or {}
|
|
if isinstance(existing, dict):
|
|
final_data.update(existing)
|
|
|
|
final_data.update(new_data)
|
|
|
|
w_status, w_body = bao_request(
|
|
cfg["bao_addr"],
|
|
f"/v1/{mount}/data/{encoded_path}",
|
|
method="POST",
|
|
token=sess["bao_token"],
|
|
payload={"data": final_data},
|
|
)
|
|
if w_status not in (200, 204):
|
|
err = "; ".join(w_body.get("errors", [])) or f"OpenBao returned HTTP {w_status}"
|
|
self._send_json(w_status, {"error": err})
|
|
return
|
|
|
|
version = (w_body.get("data") or {}).get("version")
|
|
self._send_json(
|
|
HTTPStatus.OK,
|
|
{
|
|
"ok": True,
|
|
"mount": mount,
|
|
"path": secret_path,
|
|
"version": version,
|
|
"keys_written": list(new_data.keys()),
|
|
"total_keys": sorted(final_data.keys()),
|
|
},
|
|
)
|
|
return
|
|
|
|
self._send_json(HTTPStatus.NOT_FOUND, {"error": "Not found"})
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description="Serve a local Zitadel Device Code OpenBao secret entry webapp.")
|
|
parser.add_argument("--host", default="127.0.0.1", help="Bind host (default: 127.0.0.1)")
|
|
parser.add_argument("--port", type=int, default=8250, help="Bind port (default: 8250)")
|
|
parser.add_argument("--bao-addr", default=DEFAULT_BAO_ADDR, help=f"OpenBao URL (default: {DEFAULT_BAO_ADDR})")
|
|
parser.add_argument("--auth-mount", default=DEFAULT_AUTH_MOUNT, help=f"OpenBao JWT/OIDC auth mount (default: {DEFAULT_AUTH_MOUNT})")
|
|
parser.add_argument("--role", default=DEFAULT_ROLE, help=f"OpenBao JWT/OIDC role (default: {DEFAULT_ROLE})")
|
|
parser.add_argument("--mount", default=DEFAULT_MOUNT, help=f"KV v2 mount (default: {DEFAULT_MOUNT})")
|
|
parser.add_argument("--oidc-issuer", default=DEFAULT_OIDC_ISSUER, help=f"Zitadel/OIDC issuer URL (default: {DEFAULT_OIDC_ISSUER})")
|
|
parser.add_argument("--client-id", default=DEFAULT_CLIENT_ID, help=f"Zitadel OAuth2 client ID (default: {DEFAULT_CLIENT_ID})")
|
|
parser.add_argument("--client-secret", default=DEFAULT_CLIENT_SECRET, help="Optional OAuth2 client secret (or ZITADEL_CLIENT_SECRET)")
|
|
parser.add_argument("--oidc-scope", default=DEFAULT_OIDC_SCOPE, help=f"OIDC scopes (default: {DEFAULT_OIDC_SCOPE!r})")
|
|
args = parser.parse_args()
|
|
|
|
server = ThreadingHTTPServer((args.host, args.port), SecretDropHandler)
|
|
server.config = { # type: ignore[attr-defined]
|
|
"bao_addr": args.bao_addr.rstrip("/"),
|
|
"auth_mount": args.auth_mount.strip("/"),
|
|
"role": args.role,
|
|
"mount": args.mount.strip("/"),
|
|
"oidc_issuer": args.oidc_issuer.rstrip("/"),
|
|
"client_id": args.client_id.strip(),
|
|
"client_secret": args.client_secret,
|
|
"oidc_scope": args.oidc_scope,
|
|
}
|
|
print(
|
|
f"bao-secret-drop listening on http://{args.host}:{args.port}/ "
|
|
f"(issuer={server.config['oidc_issuer']}, client_id={server.config['client_id']})",
|
|
flush=True,
|
|
)
|
|
try:
|
|
server.serve_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
server.server_close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|