Files
bao-secret-drop/bao_secret_drop.py
T

1154 lines
40 KiB
Python
Executable File

#!/usr/bin/env python3
"""bao-secret-drop: Minimal local webapp for dropping secrets into OpenBao via OIDC."""
import argparse
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_ROLE = os.environ.get("BAO_OIDC_ROLE") or "admin"
DEFAULT_MOUNT = os.environ.get("BAO_KV_MOUNT") or "secret"
SESSIONS_LOCK = threading.Lock()
SESSIONS: dict[str, dict] = {}
SESSION_TTL_SECONDS = 8 * 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 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 OIDC to write secrets to OpenBao KV v2.</div>
</div>
<div id="authActions">
<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startOidcLogin()">Sign in with OpenBao OIDC</button>
</div>
</div>
<div class="oidc-panel" id="oidcPanel" style="display: none;">
<div class="oidc-link-box" id="oidcLinkBox">
<div class="meta" id="oidcStatusText">OIDC login URL ready. Complete sign-in in the new tab (polling session every 1.5s)...</div>
<div class="oidc-link-actions">
<a class="btn btn-primary btn-sm" id="oidcAuthLink" href="#" target="_blank" rel="noopener noreferrer">Open OIDC Login in New Tab</a>
<button type="button" class="btn-sm" id="copyOidcUrlBtn" onclick="copyOidcUrl()">Copy URL</button>
</div>
</div>
<div>
<label for="callbackUrlInput">Paste redirected callback URL</label>
<div class="callback-row">
<input id="callbackUrlInput" type="text" placeholder="http://localhost:8250/oidc/callback?code=...&state=..." autocomplete="off" spellcheck="false" />
<button type="button" class="btn-primary" id="completeLoginBtn" onclick="completeManualLogin()">Complete Login</button>
</div>
<div class="meta" style="margin-top: 6px;">If the redirected <code>localhost</code> tab cannot reach this VM, copy the full URL (or query string) from your browser's address bar and paste it here.</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 pollTimer = null;
function stopPolling() {
if (pollTimer !== null) {
clearInterval(pollTimer);
pollTimer = null;
}
}
function startPolling() {
if (pollTimer !== null) return;
pollTimer = setInterval(async () => {
try {
const res = await fetch('/api/me');
if (!res.ok) return;
const data = await res.json();
if (data.authenticated) {
stopPolling();
await loadMe();
}
} catch (_) {}
}, 1500);
}
function showAuthAlert(kind, msg) {
const box = document.getElementById('authAlert');
if (!msg) {
box.className = 'alert';
box.textContent = '';
return;
}
box.className = 'alert ' + kind;
box.textContent = msg;
}
async function startOidcLogin() {
showAuthAlert('', '');
const btn = document.getElementById('oidcSignInBtn');
if (btn) {
btn.disabled = true;
btn.textContent = 'Starting OIDC...';
}
try {
const res = await fetch('/api/auth/url');
const data = await res.json();
if (!res.ok || !data.auth_url) {
showAuthAlert('err', data.error || 'Failed to initialize OIDC login.');
return;
}
currentAuthUrl = data.auth_url;
const link = document.getElementById('oidcAuthLink');
link.href = currentAuthUrl;
document.getElementById('oidcLinkBox').classList.add('visible');
let popup = null;
try {
popup = window.open(currentAuthUrl, '_blank');
} catch (_) {
popup = null;
}
const statusEl = document.getElementById('oidcStatusText');
if (!popup) {
statusEl.textContent = 'Popup may be blocked in this iframe. Click "Open OIDC Login in New Tab" or "Copy URL" below (polling every 1.5s)...';
} else {
statusEl.textContent = 'Opened OIDC login in a new tab. Waiting for completion (polling every 1.5s)...';
}
startPolling();
} catch (err) {
showAuthAlert('err', 'Failed to fetch OIDC URL: ' + err.message);
} finally {
if (btn) {
btn.disabled = false;
btn.textContent = 'Sign in with OpenBao OIDC';
}
}
}
async function copyOidcUrl() {
if (!currentAuthUrl) return;
const btn = document.getElementById('copyOidcUrlBtn');
try {
await navigator.clipboard.writeText(currentAuthUrl);
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy URL'; }, 1500);
} catch (_) {
const ta = document.createElement('textarea');
ta.value = currentAuthUrl;
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
try {
document.execCommand('copy');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy URL'; }, 1500);
} catch (err) {
showAuthAlert('err', 'Could not copy automatically. Right-click "Open OIDC Login in New Tab" to copy the link.');
} finally {
ta.remove();
}
}
}
function extractCallbackQuery(rawInput) {
const trimmed = (rawInput || '').trim();
if (!trimmed) return '';
let query = '';
if (trimmed.includes('?')) {
query = trimmed.split('?', 2)[1];
} else {
query = trimmed.replace(/^\?/, '');
}
if (query.includes('#')) {
query = query.split('#', 2)[0];
}
return query;
}
async function completeManualLogin() {
showAuthAlert('', '');
const raw = document.getElementById('callbackUrlInput').value;
const query = extractCallbackQuery(raw);
const params = new URLSearchParams(query);
const code = params.get('code');
const state = params.get('state');
if (!code || !state) {
showAuthAlert('err', 'Please paste a valid callback URL or query string containing both code and state parameters.');
return;
}
const btn = document.getElementById('completeLoginBtn');
btn.disabled = true;
btn.textContent = 'Completing...';
try {
const res = await fetch('/api/auth/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ callback_url: raw.trim() }),
});
const data = await res.json();
if (!res.ok || !data.ok) {
showAuthAlert('err', data.error || 'Failed to complete OIDC login.');
return;
}
document.getElementById('callbackUrlInput').value = '';
stopPolling();
await loadMe();
} catch (err) {
showAuthAlert('err', 'Request failed: ' + err.message);
} finally {
btn.disabled = false;
btn.textContent = 'Complete Login';
}
}
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 = `Target: ${data.bao_addr} (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.authenticated;
submitBtn.disabled = !isAuthenticated;
if (isAuthenticated) {
stopPolling();
badge.className = 'badge ok';
badge.textContent = `Authenticated: ${data.display_name || 'OIDC user'}`;
meta.textContent = `Policies: ${(data.policies || []).join(', ') || 'default'}`;
actions.innerHTML = '<button type="button" onclick="logout()">Sign out</button>';
panel.style.display = 'none';
document.getElementById('oidcLinkBox').classList.remove('visible');
showAuthAlert('', '');
loadPaths();
loadExistingKeys();
} else {
badge.className = 'badge warn';
badge.textContent = 'Not signed in';
meta.textContent = 'Sign in via OIDC to write secrets to OpenBao KV v2.';
actions.innerHTML = '<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startOidcLogin()">Sign in with OpenBao OIDC</button>';
panel.style.display = 'flex';
}
}
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 _init_oidc_auth_url(self, cfg: dict) -> tuple[str | None, str | None]:
status, body = bao_request(
cfg["bao_addr"],
"/v1/auth/oidc/oidc/auth_url",
method="POST",
payload={"role": cfg["role"], "redirect_uri": cfg["redirect_uri"]},
)
auth_url = body.get("data", {}).get("auth_url")
if status != 200 or not auth_url:
err = "; ".join(body.get("errors", [])) or f"HTTP {status}"
return None, err
return auth_url, None
def _complete_oidc_callback(self, cfg: dict, raw_query: str) -> tuple[int, dict, str | None]:
query = raw_query.lstrip("?").split("#", 1)[0].strip()
if not query:
return 400, {"error": "Missing OIDC callback parameters"}, None
params = urllib.parse.parse_qs(query)
if "error" in params:
err = params.get("error_description", params["error"])[0]
return 400, {"error": err}, None
if not params.get("code") or not params.get("state"):
return 400, {"error": "Missing code or state parameter in OIDC callback"}, None
status, body = bao_request(
cfg["bao_addr"],
f"/v1/auth/oidc/oidc/callback?{query}",
method="GET",
)
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"HTTP {status}"
return 401, {"error": err}, None
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 {}
display_name = ldata.get("display_name") or auth.get("metadata", {}).get("role") or "oidc-user"
policies = ldata.get("policies") or auth.get("policies") or []
sid = secrets.token_urlsafe(32)
with SESSIONS_LOCK:
SESSIONS[sid] = {
"token": client_token,
"display_name": display_name,
"policies": policies,
"expires_at": time.time() + SESSION_TTL_SECONDS,
}
return 200, {"ok": True, "display_name": display_name, "policies": policies}, sid
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/auth/url":
auth_url, err = self._init_oidc_auth_url(cfg)
if err or not auth_url:
self._send_json(502, {"error": err or "Failed to initialize OIDC"})
return
self._send_json(HTTPStatus.OK, {"auth_url": auth_url})
return
if parsed.path == "/auth/login":
qs = urllib.parse.parse_qs(parsed.query)
mode = (qs.get("mode") or [""])[0]
auth_url, err = self._init_oidc_auth_url(cfg)
if err or not auth_url:
if mode == "json":
self._send_json(502, {"error": err or "Failed to initialize OIDC"})
else:
self._send_html(502, f"<h1>OIDC Init Failed</h1><p>{html.escape(err or 'Unknown error')}</p><p><a href='/'>Back</a></p>")
return
if mode == "json":
self._send_json(HTTPStatus.OK, {"auth_url": auth_url})
return
self.send_response(HTTPStatus.FOUND)
self.send_header("Location", auth_url)
self.end_headers()
return
if parsed.path == "/oidc/callback":
status, result, sid = self._complete_oidc_callback(cfg, parsed.query)
if status != 200 or not sid:
err = html.escape(result.get("error", "OIDC callback failed"))
self._send_html(status, f"<h1>OIDC Callback Failed</h1><p>{err}</p><p><a href='/'>Back</a></p>")
return
self.send_response(HTTPStatus.FOUND)
self.send_header("Set-Cookie", f"bao_drop_sid={sid}; HttpOnly; SameSite=Lax; Path=/")
self.send_header("Location", "/")
self.end_headers()
return
if parsed.path == "/api/me":
sess = self._get_session()
if not sess:
self._send_json(
HTTPStatus.OK,
{
"authenticated": False,
"bao_addr": cfg["bao_addr"],
"role": cfg["role"],
"mount": cfg["mount"],
},
)
return
self._send_json(
HTTPStatus.OK,
{
"authenticated": True,
"display_name": sess["display_name"],
"policies": sess["policies"],
"bao_addr": cfg["bao_addr"],
"role": cfg["role"],
"mount": cfg["mount"],
},
)
return
if parsed.path == "/api/paths":
sess = self._get_session()
if not sess:
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated"})
return
mount = cfg["mount"].strip("/")
status, body = bao_request(
cfg["bao_addr"],
f"/v1/{mount}/metadata?list=true",
method="GET",
token=sess["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._get_session()
if not sess:
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated"})
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["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/auth/complete":
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
raw_cb = str(req_body.get("callback_url") or req_body.get("url") or req_body.get("query") or "").strip()
if not raw_cb:
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "callback_url is required"})
return
if "?" in raw_cb:
raw_query = raw_cb.split("?", 1)[1]
else:
raw_query = raw_cb
status, result, sid = self._complete_oidc_callback(cfg, raw_query)
if status != 200 or not sid:
self._send_json(status, result)
return
self._send_json(
HTTPStatus.OK,
result,
extra_headers=[("Set-Cookie", f"bao_drop_sid={sid}; HttpOnly; SameSite=Lax; Path=/")],
)
return
if parsed.path == "/api/secrets":
sess = self._get_session()
if not sess:
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated. Please sign in with OIDC."})
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["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["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 OIDC-authenticated 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("--role", default=DEFAULT_ROLE, help=f"OpenBao OIDC role (default: {DEFAULT_ROLE})")
parser.add_argument("--mount", default=DEFAULT_MOUNT, help=f"KV v2 mount (default: {DEFAULT_MOUNT})")
parser.add_argument("--redirect-uri", default=None, help="OIDC redirect URI (default: http://localhost:<port>/oidc/callback)")
args = parser.parse_args()
redirect_uri = args.redirect_uri or f"http://localhost:{args.port}/oidc/callback"
server = ThreadingHTTPServer((args.host, args.port), SecretDropHandler)
server.config = { # type: ignore[attr-defined]
"bao_addr": args.bao_addr.rstrip("/"),
"role": args.role,
"mount": args.mount.strip("/"),
"redirect_uri": redirect_uri,
}
print(f"bao-secret-drop listening on http://{args.host}:{args.port}/ (redirect_uri={redirect_uri})", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()