Fix OIDC login for iframe previews with new-tab flow and callback URL paste

This commit is contained in:
nandi committed 2026-11-17 19:05:26 +00:00
1 parent d5368940e1
commit aaa61ae958
1 file changed
+344 -56
+344 -56
View File
@@ -277,6 +277,43 @@ HTML_PAGE = r"""<!DOCTYPE html>
}
.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;
@@ -295,13 +332,36 @@ HTML_PAGE = r"""<!DOCTYPE html>
</div>
</div>
<div class="card 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 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 id="authActions">
<a class="btn btn-primary" href="/auth/login">Sign in with OIDC</a>
<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>
@@ -341,6 +401,161 @@ HTML_PAGE = r"""<!DOCTYPE html>
<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');
@@ -405,23 +620,29 @@ HTML_PAGE = r"""<!DOCTYPE html>
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 = '<a class="btn btn-primary" href="/auth/login">Sign in with OIDC</a>';
actions.innerHTML = '<button type="button" class="btn-primary" id="oidcSignInBtn" onclick="startOidcLogin()">Sign in with OpenBao OIDC</button>';
panel.style.display = 'flex';
}
}
@@ -466,6 +687,7 @@ HTML_PAGE = r"""<!DOCTYPE html>
}
async function logout() {
stopPolling();
await fetch('/auth/logout', { method: 'POST' });
location.reload();
}
@@ -561,12 +783,15 @@ class SecretDropHandler(BaseHTTPRequestHandler):
with SESSIONS_LOCK:
return SESSIONS.get(sid)
def _send_json(self, status: int, data: dict) -> None:
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)
@@ -589,6 +814,62 @@ class SecretDropHandler(BaseHTTPRequestHandler):
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]
@@ -601,17 +882,26 @@ class SecretDropHandler(BaseHTTPRequestHandler):
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":
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 = html.escape("; ".join(body.get("errors", [])) or f"HTTP {status}")
self._send_html(502, f"<h1>OIDC Init Failed</h1><p>{err}</p><p><a href='/'>Back</a></p>")
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)
@@ -619,45 +909,11 @@ class SecretDropHandler(BaseHTTPRequestHandler):
return
if parsed.path == "/oidc/callback":
params = urllib.parse.parse_qs(parsed.query)
if "error" in params:
err = html.escape(params.get("error_description", params["error"])[0])
self._send_html(400, f"<h1>OIDC Error</h1><p>{err}</p><p><a href='/'>Back</a></p>")
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
if not parsed.query:
self._send_html(400, "<h1>Missing OIDC callback parameters</h1><p><a href='/'>Back</a></p>")
return
status, body = bao_request(
cfg["bao_addr"],
f"/v1/auth/oidc/oidc/callback?{parsed.query}",
method="GET",
)
auth = body.get("auth") or {}
client_token = auth.get("client_token")
if status != 200 or not client_token:
err = html.escape("; ".join(body.get("errors", [])) or f"HTTP {status}")
self._send_html(401, f"<h1>OIDC Callback Failed</h1><p>{err}</p><p><a href='/'>Back</a></p>")
return
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,
}
self.send_response(HTTPStatus.FOUND)
self.send_header("Set-Cookie", f"bao_drop_sid={sid}; HttpOnly; SameSite=Lax; Path=/")
@@ -756,6 +1012,38 @@ class SecretDropHandler(BaseHTTPRequestHandler):
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: