#!/usr/bin/env node // E2E-Smoketest des OIDC-Logins gegen eine laufende App und einen echten IdP (Keycloak oder Authentik // aus dem Compose-Setup). Fährt den Flow wie ein Browser (Cookie-Jar), ohne Browser-Abhängigkeit. // // Aufruf: node scripts/oidc-e2e.mjs --idp keycloak|authentik [--base http://localhost:8000] // [--user testuser] [--password testuser-dev] [--expect testuser] [--forwarded-proto https] // Exit-Code 0 = alle Prüfungen bestanden. const arg = (name, def)=>{ const i = process.argv.indexOf(`--${name}`); return i > -1 ? process.argv[i + 1] : def; }; const idpKind = arg('idp'); const base = arg('base', 'http://localhost:8000').replace(/\/$/, ''); const user = arg('user', 'testuser'); const password = arg('password', 'testuser-dev'); const expectName = arg('expect', user); const forwardedProto = arg('forwarded-proto'); // nur nötig, wenn die App mit NODE_ENV=production hinter http läuft if(!['keycloak', 'authentik'].includes(idpKind)) { console.error('--idp keycloak|authentik angeben'); process.exit(2); } const jar = new Map(); const store = (res)=>{ for(const c of res.headers.getSetCookie()) { const [kv, ...attrs] = c.split(';'); const i = kv.indexOf('='); const name = kv.slice(0, i).trim(); const value = kv.slice(i + 1); const key = `${new URL(res.url).hostname}|${name}`; if(!value || attrs.some((a)=>/expires=Thu, 01 Jan 1970/i.test(a) || /max-age=0/i.test(a))) jar.delete(key); else jar.set(key, { name, value }); } }; const cookieFor = (url)=>[...jar.entries()].filter(([k])=>k.startsWith(`${new URL(url).hostname}|`)).map(([, c])=>`${c.name}=${c.value}`).join('; '); const http = async (url, init = {})=>{ const headers = { cookie: cookieFor(url), ...(forwardedProto && url.startsWith(base) ? { 'x-forwarded-proto': forwardedProto } : {}), ...(init.headers || {}) }; const res = await fetch(url, { redirect: 'manual', ...init, headers }); store(res); return res; }; const follow = async (url, init)=>{ // folgt Redirects, solange sie beim IdP bleiben; stoppt beim Wechsel zur App let res = await http(url, init); for(let i = 0; i < 20; i++) { const loc = res.headers.get('location'); if(!loc) return { res, url }; const next = new URL(loc, url).href; if(next.startsWith(base)) return { res, url, callback: next }; url = next; res = await http(url); } throw new Error('Zu viele Redirects'); }; let failed = 0; const check = (name, ok, detail = '')=>{ console.log(`${ok ? 'OK ' : 'FAIL'} ${name}${detail ? ` (${detail})` : ''}`); if(!ok) failed++; }; const hidden = (html, name)=>new RegExp(`name="${name}"[^>]*value="([^"]*)"`).exec(html)?.[1]; const loginKeycloak = async (authUrl)=>{ const { res, url } = await follow(authUrl); const html = await res.text(); const action = /]*id="kc-form-login"[^>]*action="([^"]+)"/.exec(html)?.[1]?.replaceAll('&', '&'); if(!action) throw new Error(`Keycloak-Loginformular nicht gefunden (Status ${res.status})`); const post = await follow(new URL(action, url).href, { method : 'POST', headers : { 'content-type': 'application/x-www-form-urlencoded' }, body : new URLSearchParams({ username: user, password, credentialId: hidden(html, 'credentialId') ?? '' }) }); return post.callback; }; const loginAuthentik = async (authUrl)=>{ const origin = new URL(authUrl).origin; const first = await http(authUrl); const loc = new URL(first.headers.get('location'), origin); // /if/flow//?next= const slug = loc.pathname.split('/').filter(Boolean)[2]; let exec = `${origin}/api/v3/flows/executor/${slug}/?query=${encodeURIComponent(loc.search.slice(1))}`; const jsonHeaders = { 'content-type': 'application/json', accept: 'application/json' }; const send = async (body)=>{ let res = await http(exec, body ? { method: 'POST', headers: jsonHeaders, body: JSON.stringify(body) } : { headers: jsonHeaders }); // authentik normalisiert die Query per Redirect; neue URL merken und erneut senden for(let i = 0; i < 3 && [301, 302, 303, 307, 308].includes(res.status); i++) { exec = new URL(res.headers.get('location'), origin).href; res = await http(exec, body ? { method: 'POST', headers: jsonHeaders, body: JSON.stringify(body) } : { headers: jsonHeaders }); } const text = await res.text(); try { return JSON.parse(text); } catch { throw new Error(`Authentik-Executor: Status ${res.status}, Antwort kein JSON: ${text.slice(0, 200)}`); } }; let ch = await send(); for(let i = 0; i < 8; i++) { if(ch.component === 'ak-stage-identification') ch = await send({ uid_field: user }); else if(ch.component === 'ak-stage-password') ch = await send({ password }); else if(ch.component === 'xak-flow-redirect') break; else if(ch.component === 'ak-stage-authenticator-validate' && !ch.device_challenges?.length) ch = await send(); // kein MFA-Gerät: Stage neu laden (wird übersprungen) else if(ch.component === 'ak-stage-consent') ch = await send({}); else throw new Error(`Unerwartete Authentik-Stage: ${ch.component} ${JSON.stringify({ ...ch, flow_info: undefined, pending_user_avatar: undefined }).slice(0, 900)}`); } if(ch.component !== 'xak-flow-redirect') throw new Error('Authentik-Flow endete nicht im Redirect'); const { callback } = await follow(new URL(ch.to, origin).href); return callback; }; const accountFromPage = async (path)=>{ const html = await (await http(`${base}${path}`)).text(); const m = /window\.__INITIAL_PROPS__ = (\{.*?\})<\/script>/s.exec(html); return m ? JSON.parse(m[1]) : null; }; try { const start = await http(`${base}/auth/oidc/login?redirect=${encodeURIComponent('/account')}`); const authUrl = start.headers.get('location'); check('Login leitet zum IdP weiter', start.status === 302 && !!authUrl, authUrl?.split('?')[0]); const q = new URL(authUrl).searchParams; check('PKCE S256, state und nonce gesetzt', q.get('code_challenge_method') === 'S256' && !!q.get('state') && !!q.get('nonce')); const callback = await (idpKind === 'keycloak' ? loginKeycloak : loginAuthentik)(authUrl); check('IdP leitet auf den Callback der App zurück', !!callback, callback?.split('?')[0]); const cb = await http(callback); check('Callback stellt Session aus und leitet auf die Zielseite', cb.status === 302 && cb.headers.get('location') === '/account', `${cb.status} ${cb.headers.get('location')}`); check('Session-Cookie hb_session gesetzt', cb.headers.getSetCookie().some((c)=>c.startsWith('hb_session=') && /httponly/i.test(c))); const props = await accountFromPage('/account'); check(`Angemeldet als "${expectName}" (provider oidc)`, props?.account?.username === expectName && props.account.provider === 'oidc', JSON.stringify(props?.account)); check('Client-Konfiguration enthält Auth-Provider', props?.config?.auth?.providers?.includes('oidc'), JSON.stringify(props?.config?.auth)); // Zweiter Login desselben Benutzers: gleiches Konto const out = await http(`${base}/auth/logout`); check('Logout leitet weiter und löscht die Session', out.status === 302 && !jar.has(`${new URL(base).hostname}|hb_session`), out.headers.get('location')?.split('?')[0]); const after = await accountFromPage('/account'); check('Nach Logout kein Konto', !after?.account); // Fehlerfall: Callback ohne Transaktion const bad = await http(`${base}/auth/oidc/callback?code=x&state=y`); check('Callback ohne Transaktion → 400', bad.status === 400); } catch(err) { console.error('FEHLER:', err.message); failed++; } console.log(failed ? `\n${failed} Prüfung(en) fehlgeschlagen` : '\nAlle Prüfungen bestanden'); process.exit(failed ? 1 : 0);