Add justfile and switch auth to Zitadel Device Code flow
This commit is contained in:
1 parent
aaa61ae958
commit
177c65f18e
3 files changed
+470
-235
No files matched your search
@@ -1,11 +1,17 @@
|
|||||||
# bao-secret-drop
|
# bao-secret-drop
|
||||||
|
|
||||||
Minimal, zero-dependency Python 3 webapp for signing in to OpenBao via OIDC and submitting tokens/secrets into KV v2.
|
Minimal, zero-dependency Python 3 webapp for signing in via Zitadel Device Code (no redirect URI needed) and dropping tokens/secrets into OpenBao KV v2.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bao-secret-drop --host 127.0.0.1 --port 8250
|
just run
|
||||||
```
|
```
|
||||||
|
|
||||||
Then open `http://localhost:8250/` in your browser, click **Sign in with OIDC**, enter your KV v2 secret path and key/value pairs, and submit.
|
Or override defaults (`--client-id 400222693598691513`, `--oidc-issuer https://auth.site.latha.org`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
just run --client-id <your-zitadel-client-id> --oidc-issuer https://auth.site.latha.org --bao-addr https://bao.site.latha.org --auth-mount jwt --role admin
|
||||||
|
```
|
||||||
|
|
||||||
|
Then open `http://localhost:8250/` in your browser, click **Sign in with Zitadel**, approve the displayed device code in Zitadel, enter your KV v2 secret path and key/value pairs, and submit.
|
||||||
+458
-232
@@ -1,7 +1,8 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""bao-secret-drop: Minimal local webapp for dropping secrets into OpenBao via OIDC."""
|
"""bao-secret-drop: Minimal local webapp for dropping secrets into OpenBao via Zitadel Device Code."""
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
import base64
|
||||||
import html
|
import html
|
||||||
import http.cookies
|
import http.cookies
|
||||||
import json
|
import json
|
||||||
@@ -17,13 +18,25 @@ from http import HTTPStatus
|
|||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
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_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_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_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_LOCK = threading.Lock()
|
||||||
SESSIONS: dict[str, dict] = {}
|
SESSIONS: dict[str, dict] = {}
|
||||||
SESSION_TTL_SECONDS = 8 * 3600
|
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:
|
def cleanup_sessions() -> None:
|
||||||
now = time.time()
|
now = time.time()
|
||||||
@@ -33,6 +46,74 @@ def cleanup_sessions() -> None:
|
|||||||
del SESSIONS[sid]
|
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(
|
def bao_request(
|
||||||
bao_addr: str,
|
bao_addr: str,
|
||||||
path: str,
|
path: str,
|
||||||
@@ -336,31 +417,26 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
<div class="auth-bar">
|
<div class="auth-bar">
|
||||||
<div class="identity">
|
<div class="identity">
|
||||||
<span class="badge warn" id="authBadge">Checking session...</span>
|
<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 class="meta" id="authMeta">Sign in via Zitadel Device Code to write secrets to OpenBao KV v2.</div>
|
||||||
</div>
|
</div>
|
||||||
<div id="authActions">
|
<div id="authActions">
|
||||||
<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startOidcLogin()">Sign in with OpenBao OIDC</button>
|
<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startDeviceLogin()">Sign in with Zitadel</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="oidc-panel" id="oidcPanel" style="display: none;">
|
<div class="oidc-panel" id="oidcPanel" style="display: none;">
|
||||||
<div class="oidc-link-box" id="oidcLinkBox">
|
<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="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">
|
<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>
|
<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="copyOidcUrl()">Copy URL</button>
|
<button type="button" class="btn-sm" id="copyOidcUrlBtn" onclick="copyText(currentAuthUrl, 'copyOidcUrlBtn', 'Copy URL')">Copy URL</button>
|
||||||
</div>
|
</div>
|
||||||
</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 class="alert" id="authAlert" style="margin-top: 0;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -402,28 +478,51 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
<script>
|
<script>
|
||||||
let isAuthenticated = false;
|
let isAuthenticated = false;
|
||||||
let currentAuthUrl = '';
|
let currentAuthUrl = '';
|
||||||
|
let currentUserCode = '';
|
||||||
|
let currentFlowId = '';
|
||||||
let pollTimer = null;
|
let pollTimer = null;
|
||||||
|
|
||||||
function stopPolling() {
|
function stopPolling() {
|
||||||
if (pollTimer !== null) {
|
if (pollTimer !== null) {
|
||||||
clearInterval(pollTimer);
|
clearTimeout(pollTimer);
|
||||||
pollTimer = null;
|
pollTimer = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function startPolling() {
|
function scheduleDevicePoll(delayMs) {
|
||||||
if (pollTimer !== null) return;
|
stopPolling();
|
||||||
pollTimer = setInterval(async () => {
|
if (!currentFlowId) return;
|
||||||
try {
|
pollTimer = setTimeout(pollDeviceFlow, delayMs);
|
||||||
const res = await fetch('/api/me');
|
}
|
||||||
if (!res.ok) return;
|
|
||||||
const data = await res.json();
|
async function pollDeviceFlow() {
|
||||||
if (data.authenticated) {
|
if (!currentFlowId) return;
|
||||||
stopPolling();
|
try {
|
||||||
await loadMe();
|
const res = await fetch('/api/auth/device/poll', {
|
||||||
}
|
method: 'POST',
|
||||||
} catch (_) {}
|
headers: { 'Content-Type': 'application/json' },
|
||||||
}, 1500);
|
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) {
|
function showAuthAlert(kind, msg) {
|
||||||
@@ -433,27 +532,33 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
box.textContent = '';
|
box.textContent = '';
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
document.getElementById('oidcPanel').style.display = 'flex';
|
||||||
box.className = 'alert ' + kind;
|
box.className = 'alert ' + kind;
|
||||||
box.textContent = msg;
|
box.textContent = msg;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function startOidcLogin() {
|
async function startDeviceLogin() {
|
||||||
showAuthAlert('', '');
|
showAuthAlert('', '');
|
||||||
|
stopPolling();
|
||||||
const btn = document.getElementById('oidcSignInBtn');
|
const btn = document.getElementById('oidcSignInBtn');
|
||||||
if (btn) {
|
if (btn) {
|
||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
btn.textContent = 'Starting OIDC...';
|
btn.textContent = 'Starting...';
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/auth/url');
|
const res = await fetch('/api/auth/device/start', { method: 'POST' });
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok || !data.auth_url) {
|
if (!res.ok || !data.flow_id) {
|
||||||
showAuthAlert('err', data.error || 'Failed to initialize OIDC login.');
|
showAuthAlert('err', data.error || 'Failed to start Zitadel device login.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
currentAuthUrl = data.auth_url;
|
currentFlowId = data.flow_id;
|
||||||
const link = document.getElementById('oidcAuthLink');
|
currentUserCode = data.user_code || '';
|
||||||
link.href = currentAuthUrl;
|
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');
|
document.getElementById('oidcLinkBox').classList.add('visible');
|
||||||
|
|
||||||
let popup = null;
|
let popup = null;
|
||||||
@@ -462,33 +567,55 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
} catch (_) {
|
} catch (_) {
|
||||||
popup = null;
|
popup = null;
|
||||||
}
|
}
|
||||||
const statusEl = document.getElementById('oidcStatusText');
|
const secs = Number(data.interval || 5);
|
||||||
if (!popup) {
|
document.getElementById('oidcStatusText').textContent = 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)...';
|
? `Opened Zitadel in a new tab. Confirm code ${currentUserCode} (polling every ${secs}s)...`
|
||||||
} else {
|
: `Click "Open Zitadel Device Login" and confirm code ${currentUserCode} (polling every ${secs}s)...`;
|
||||||
statusEl.textContent = 'Opened OIDC login in a new tab. Waiting for completion (polling every 1.5s)...';
|
scheduleDevicePoll(secs * 1000);
|
||||||
}
|
|
||||||
startPolling();
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showAuthAlert('err', 'Failed to fetch OIDC URL: ' + err.message);
|
showAuthAlert('err', 'Failed to start device login: ' + err.message);
|
||||||
} finally {
|
} finally {
|
||||||
if (btn) {
|
if (btn) {
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
btn.textContent = 'Sign in with OpenBao OIDC';
|
btn.textContent = 'Sign in with Zitadel';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function copyOidcUrl() {
|
async function retryBaoLogin() {
|
||||||
if (!currentAuthUrl) return;
|
showAuthAlert('', '');
|
||||||
const btn = document.getElementById('copyOidcUrlBtn');
|
const btn = document.getElementById('retryBaoBtn');
|
||||||
|
if (btn) {
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = 'Connecting...';
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(currentAuthUrl);
|
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!';
|
btn.textContent = 'Copied!';
|
||||||
setTimeout(() => { btn.textContent = 'Copy URL'; }, 1500);
|
setTimeout(() => { btn.textContent = defaultLabel; }, 1500);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
const ta = document.createElement('textarea');
|
const ta = document.createElement('textarea');
|
||||||
ta.value = currentAuthUrl;
|
ta.value = text;
|
||||||
ta.style.position = 'fixed';
|
ta.style.position = 'fixed';
|
||||||
ta.style.opacity = '0';
|
ta.style.opacity = '0';
|
||||||
document.body.appendChild(ta);
|
document.body.appendChild(ta);
|
||||||
@@ -496,67 +623,15 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
try {
|
try {
|
||||||
document.execCommand('copy');
|
document.execCommand('copy');
|
||||||
btn.textContent = 'Copied!';
|
btn.textContent = 'Copied!';
|
||||||
setTimeout(() => { btn.textContent = 'Copy URL'; }, 1500);
|
setTimeout(() => { btn.textContent = defaultLabel; }, 1500);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
showAuthAlert('err', 'Could not copy automatically. Right-click "Open OIDC Login in New Tab" to copy the link.');
|
showAuthAlert('err', 'Could not copy automatically.');
|
||||||
} finally {
|
} finally {
|
||||||
ta.remove();
|
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 = '') {
|
function addRow(key = '', value = '') {
|
||||||
const rows = document.getElementById('rows');
|
const rows = document.getElementById('rows');
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
@@ -614,7 +689,8 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
async function loadMe() {
|
async function loadMe() {
|
||||||
const res = await fetch('/api/me');
|
const res = await fetch('/api/me');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
document.getElementById('baoAddr').textContent = `Target: ${data.bao_addr} (role: ${data.role})`;
|
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}/`;
|
document.getElementById('mountLabel').textContent = `${data.mount}/`;
|
||||||
|
|
||||||
const badge = document.getElementById('authBadge');
|
const badge = document.getElementById('authBadge');
|
||||||
@@ -623,26 +699,41 @@ HTML_PAGE = r"""<!DOCTYPE html>
|
|||||||
const panel = document.getElementById('oidcPanel');
|
const panel = document.getElementById('oidcPanel');
|
||||||
const submitBtn = document.getElementById('submitBtn');
|
const submitBtn = document.getElementById('submitBtn');
|
||||||
|
|
||||||
isAuthenticated = !!data.authenticated;
|
isAuthenticated = !!data.bao_authenticated;
|
||||||
submitBtn.disabled = !isAuthenticated;
|
submitBtn.disabled = !isAuthenticated;
|
||||||
|
|
||||||
if (isAuthenticated) {
|
if (data.authenticated) {
|
||||||
stopPolling();
|
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';
|
panel.style.display = 'none';
|
||||||
document.getElementById('oidcLinkBox').classList.remove('visible');
|
document.getElementById('oidcLinkBox').classList.remove('visible');
|
||||||
showAuthAlert('', '');
|
if (data.bao_authenticated) {
|
||||||
loadPaths();
|
badge.className = 'badge ok';
|
||||||
loadExistingKeys();
|
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 {
|
} else {
|
||||||
badge.className = 'badge warn';
|
badge.className = 'badge warn';
|
||||||
badge.textContent = 'Not signed in';
|
badge.textContent = 'Not signed in';
|
||||||
meta.textContent = 'Sign in via OIDC to write secrets to OpenBao KV v2.';
|
meta.textContent = data.client_id
|
||||||
actions.innerHTML = '<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startOidcLogin()">Sign in with OpenBao OIDC</button>';
|
? 'Sign in via Zitadel Device Code to write secrets to OpenBao KV v2.'
|
||||||
panel.style.display = 'flex';
|
: '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';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -814,40 +905,76 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
raw = self.rfile.read(length).decode("utf-8")
|
raw = self.rfile.read(length).decode("utf-8")
|
||||||
return json.loads(raw)
|
return json.loads(raw)
|
||||||
|
|
||||||
def _init_oidc_auth_url(self, cfg: dict) -> tuple[str | None, str | None]:
|
def _require_bao_session(self) -> dict | None:
|
||||||
status, body = bao_request(
|
sess = self._get_session()
|
||||||
cfg["bao_addr"],
|
if not sess:
|
||||||
"/v1/auth/oidc/oidc/auth_url",
|
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",
|
method="POST",
|
||||||
payload={"role": cfg["role"], "redirect_uri": cfg["redirect_uri"]},
|
headers={"Content-Type": "application/x-www-form-urlencoded"},
|
||||||
|
data=urllib.parse.urlencode(form).encode("utf-8"),
|
||||||
)
|
)
|
||||||
auth_url = body.get("data", {}).get("auth_url")
|
device_code = d_body.get("device_code") or ""
|
||||||
if status != 200 or not auth_url:
|
if d_status != 200 or not device_code or d_body.get("error"):
|
||||||
err = "; ".join(body.get("errors", [])) or f"HTTP {status}"
|
d_err = d_body.get("error_description") or d_body.get("error") or f"HTTP {d_status}"
|
||||||
return None, err
|
return 502, {"error": f"Zitadel device authorization failed: {d_err}"}
|
||||||
return auth_url, None
|
|
||||||
|
|
||||||
def _complete_oidc_callback(self, cfg: dict, raw_query: str) -> tuple[int, dict, str | None]:
|
expires_in = int(d_body.get("expires_in") or 300)
|
||||||
query = raw_query.lstrip("?").split("#", 1)[0].strip()
|
interval = max(1, int(d_body.get("interval") or 5))
|
||||||
if not query:
|
cleanup_device_flows()
|
||||||
return 400, {"error": "Missing OIDC callback parameters"}, None
|
flow_id = secrets.token_urlsafe(24)
|
||||||
params = urllib.parse.parse_qs(query)
|
with DEVICE_FLOWS_LOCK:
|
||||||
if "error" in params:
|
PENDING_DEVICE_FLOWS[flow_id] = {
|
||||||
err = params.get("error_description", params["error"])[0]
|
"device_code": device_code,
|
||||||
return 400, {"error": err}, None
|
"user_code": d_body.get("user_code") or "",
|
||||||
if not params.get("code") or not params.get("state"):
|
"verification_uri": d_body.get("verification_uri") or "",
|
||||||
return 400, {"error": "Missing code or state parameter in OIDC callback"}, None
|
"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(
|
status, body = bao_request(
|
||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
f"/v1/auth/oidc/oidc/callback?{query}",
|
f"/v1/auth/{auth_mount}/login",
|
||||||
method="GET",
|
method="POST",
|
||||||
|
payload={"role": cfg["role"], "jwt": jwt_token},
|
||||||
)
|
)
|
||||||
auth = body.get("auth") or {}
|
auth = body.get("auth") or {}
|
||||||
client_token = auth.get("client_token")
|
client_token = auth.get("client_token")
|
||||||
if status != 200 or not client_token:
|
if status != 200 or not client_token:
|
||||||
err = "; ".join(body.get("errors", [])) or f"HTTP {status}"
|
err = "; ".join(body.get("errors", [])) or f"OpenBao returned HTTP {status}"
|
||||||
return 401, {"error": err}, None
|
return False, {"error": err, "status": status}
|
||||||
|
|
||||||
lookup_status, lookup_body = bao_request(
|
lookup_status, lookup_body = bao_request(
|
||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
@@ -856,19 +983,135 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
token=client_token,
|
token=client_token,
|
||||||
)
|
)
|
||||||
ldata = lookup_body.get("data", {}) if lookup_status == 200 else {}
|
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 []
|
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)
|
sid = secrets.token_urlsafe(32)
|
||||||
with SESSIONS_LOCK:
|
with SESSIONS_LOCK:
|
||||||
SESSIONS[sid] = {
|
SESSIONS[sid] = {
|
||||||
"token": client_token,
|
"id_token": jwt_for_bao,
|
||||||
|
"access_token": access_token,
|
||||||
"display_name": display_name,
|
"display_name": display_name,
|
||||||
"policies": policies,
|
"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,
|
"expires_at": time.time() + SESSION_TTL_SECONDS,
|
||||||
}
|
}
|
||||||
|
|
||||||
return 200, {"ok": True, "display_name": display_name, "policies": policies}, sid
|
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:
|
def do_GET(self) -> None:
|
||||||
parsed = urllib.parse.urlparse(self.path)
|
parsed = urllib.parse.urlparse(self.path)
|
||||||
@@ -882,82 +1125,49 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
self._send_json(HTTPStatus.OK, {"ok": True})
|
self._send_json(HTTPStatus.OK, {"ok": True})
|
||||||
return
|
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":
|
if parsed.path == "/api/me":
|
||||||
sess = self._get_session()
|
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:
|
if not sess:
|
||||||
self._send_json(
|
self._send_json(
|
||||||
HTTPStatus.OK,
|
HTTPStatus.OK,
|
||||||
{
|
{
|
||||||
|
**base_info,
|
||||||
"authenticated": False,
|
"authenticated": False,
|
||||||
"bao_addr": cfg["bao_addr"],
|
"bao_authenticated": False,
|
||||||
"role": cfg["role"],
|
|
||||||
"mount": cfg["mount"],
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
self._send_json(
|
self._send_json(
|
||||||
HTTPStatus.OK,
|
HTTPStatus.OK,
|
||||||
{
|
{
|
||||||
|
**base_info,
|
||||||
"authenticated": True,
|
"authenticated": True,
|
||||||
|
"bao_authenticated": bool(sess.get("bao_token")),
|
||||||
|
"bao_error": sess.get("bao_error"),
|
||||||
"display_name": sess["display_name"],
|
"display_name": sess["display_name"],
|
||||||
"policies": sess["policies"],
|
"policies": sess["policies"],
|
||||||
"bao_addr": cfg["bao_addr"],
|
|
||||||
"role": cfg["role"],
|
|
||||||
"mount": cfg["mount"],
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if parsed.path == "/api/paths":
|
if parsed.path == "/api/paths":
|
||||||
sess = self._get_session()
|
sess = self._require_bao_session()
|
||||||
if not sess:
|
if not sess:
|
||||||
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated"})
|
|
||||||
return
|
return
|
||||||
mount = cfg["mount"].strip("/")
|
mount = cfg["mount"].strip("/")
|
||||||
status, body = bao_request(
|
status, body = bao_request(
|
||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
f"/v1/{mount}/metadata?list=true",
|
f"/v1/{mount}/metadata?list=true",
|
||||||
method="GET",
|
method="GET",
|
||||||
token=sess["token"],
|
token=sess["bao_token"],
|
||||||
)
|
)
|
||||||
if status != 200:
|
if status != 200:
|
||||||
self._send_json(HTTPStatus.OK, {"paths": []})
|
self._send_json(HTTPStatus.OK, {"paths": []})
|
||||||
@@ -967,9 +1177,8 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
return
|
return
|
||||||
|
|
||||||
if parsed.path == "/api/keys":
|
if parsed.path == "/api/keys":
|
||||||
sess = self._get_session()
|
sess = self._require_bao_session()
|
||||||
if not sess:
|
if not sess:
|
||||||
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated"})
|
|
||||||
return
|
return
|
||||||
qs = urllib.parse.parse_qs(parsed.query)
|
qs = urllib.parse.parse_qs(parsed.query)
|
||||||
raw_path = (qs.get("path") or [""])[0]
|
raw_path = (qs.get("path") or [""])[0]
|
||||||
@@ -982,7 +1191,7 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
f"/v1/{mount}/data/{urllib.parse.quote(secret_path, safe='/')}",
|
f"/v1/{mount}/data/{urllib.parse.quote(secret_path, safe='/')}",
|
||||||
method="GET",
|
method="GET",
|
||||||
token=sess["token"],
|
token=sess["bao_token"],
|
||||||
)
|
)
|
||||||
if status == 404:
|
if status == 404:
|
||||||
self._send_json(HTTPStatus.OK, {"keys": []})
|
self._send_json(HTTPStatus.OK, {"keys": []})
|
||||||
@@ -1012,42 +1221,48 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
self.wfile.write(b'{"ok":true}')
|
self.wfile.write(b'{"ok":true}')
|
||||||
return
|
return
|
||||||
|
|
||||||
if parsed.path == "/api/auth/complete":
|
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:
|
try:
|
||||||
req_body = self._read_json_body()
|
req_body = self._read_json_body()
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Invalid JSON body"})
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Invalid JSON body"})
|
||||||
return
|
return
|
||||||
if not req_body:
|
flow_id = str((req_body or {}).get("flow_id") or "").strip()
|
||||||
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "Empty request body"})
|
if not flow_id:
|
||||||
|
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "flow_id is required"})
|
||||||
return
|
return
|
||||||
|
|
||||||
raw_cb = str(req_body.get("callback_url") or req_body.get("url") or req_body.get("query") or "").strip()
|
status, result, sid = self._poll_device_flow(cfg, flow_id)
|
||||||
if not raw_cb:
|
headers = [("Set-Cookie", f"bao_drop_sid={sid}; HttpOnly; SameSite=Lax; Path=/")] if sid else None
|
||||||
self._send_json(HTTPStatus.BAD_REQUEST, {"error": "callback_url is required"})
|
self._send_json(status, result, extra_headers=headers)
|
||||||
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
|
return
|
||||||
|
|
||||||
if parsed.path == "/api/secrets":
|
if parsed.path == "/api/secrets":
|
||||||
sess = self._get_session()
|
sess = self._require_bao_session()
|
||||||
if not sess:
|
if not sess:
|
||||||
self._send_json(HTTPStatus.UNAUTHORIZED, {"error": "Not authenticated. Please sign in with OIDC."})
|
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
req_body = self._read_json_body()
|
req_body = self._read_json_body()
|
||||||
@@ -1084,7 +1299,7 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
f"/v1/{mount}/data/{encoded_path}",
|
f"/v1/{mount}/data/{encoded_path}",
|
||||||
method="GET",
|
method="GET",
|
||||||
token=sess["token"],
|
token=sess["bao_token"],
|
||||||
)
|
)
|
||||||
if g_status == 200:
|
if g_status == 200:
|
||||||
existing = (g_body.get("data") or {}).get("data") or {}
|
existing = (g_body.get("data") or {}).get("data") or {}
|
||||||
@@ -1097,7 +1312,7 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
cfg["bao_addr"],
|
cfg["bao_addr"],
|
||||||
f"/v1/{mount}/data/{encoded_path}",
|
f"/v1/{mount}/data/{encoded_path}",
|
||||||
method="POST",
|
method="POST",
|
||||||
token=sess["token"],
|
token=sess["bao_token"],
|
||||||
payload={"data": final_data},
|
payload={"data": final_data},
|
||||||
)
|
)
|
||||||
if w_status not in (200, 204):
|
if w_status not in (200, 204):
|
||||||
@@ -1123,24 +1338,35 @@ class SecretDropHandler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
parser = argparse.ArgumentParser(description="Serve a local OIDC-authenticated OpenBao secret entry webapp.")
|
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("--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("--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("--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("--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("--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)")
|
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()
|
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 = ThreadingHTTPServer((args.host, args.port), SecretDropHandler)
|
||||||
server.config = { # type: ignore[attr-defined]
|
server.config = { # type: ignore[attr-defined]
|
||||||
"bao_addr": args.bao_addr.rstrip("/"),
|
"bao_addr": args.bao_addr.rstrip("/"),
|
||||||
|
"auth_mount": args.auth_mount.strip("/"),
|
||||||
"role": args.role,
|
"role": args.role,
|
||||||
"mount": args.mount.strip("/"),
|
"mount": args.mount.strip("/"),
|
||||||
"redirect_uri": redirect_uri,
|
"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}/ (redirect_uri={redirect_uri})", flush=True)
|
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:
|
try:
|
||||||
server.serve_forever()
|
server.serve_forever()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
Reference in new issue
Block a user