Modul server/fork/auth (Config, Session-Cookie, OIDC-Flow, Kontozuordnung), Einhängen in server/app.js, Client-Helfer für Login/Logout, PUT /api/user/rename für OIDC-Sessions gesperrt (A01). Tests gegen Mock-IdP. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
391 lines
17 KiB
JavaScript
391 lines
17 KiB
JavaScript
import http from 'http';
|
|
import express from 'express';
|
|
import cookieParser from 'cookie-parser';
|
|
import jwt from 'jsonwebtoken';
|
|
import { startIdp, loginAtIdp, CLIENT } from './testIdp.js';
|
|
import { createMemoryUsers } from './testUsers.js';
|
|
import { readAuthConfig, accountMiddleware, createAuthRouter } from './index.js';
|
|
import { openTx, sealTx, SESSION_COOKIE, TX_COOKIE } from './session.js';
|
|
|
|
const SECRET = 's'.repeat(40);
|
|
const ACCOUNTS = {
|
|
alice : { preferred_username: 'alice', email: 'alice@example.test', email_verified: true, name: 'Alice A.' },
|
|
bob : { preferred_username: 'bob', email: 'bob@example.test', email_verified: false }
|
|
};
|
|
|
|
let appServer; let idp; let appUrl; let delegate; let users; let authors; let renameCalled;
|
|
|
|
const buildApp = (envOverrides = {}, depsOverrides = {})=>{
|
|
const config = readAuthConfig({
|
|
HB_PUBLIC_URL : appUrl, HB_OIDC_ISSUER : idp.issuer, HB_OIDC_CLIENT_ID : CLIENT.client_id,
|
|
HB_OIDC_CLIENT_SECRET : CLIENT.client_secret, HB_SESSION_SECRET : SECRET, ...envOverrides
|
|
});
|
|
const app = express();
|
|
app.use(cookieParser());
|
|
// Stand-in für die Upstream-Account-Middleware: nc_session-Cookie == Benutzername
|
|
app.use((req, res, next)=>{ if(req.cookies.nc_session) req.account = { username: req.cookies.nc_session }; next(); });
|
|
app.use(accountMiddleware(config));
|
|
app.use(createAuthRouter(config, { getUsers: ()=>users, brewAuthorExists: async (n)=>authors.has(n), ...depsOverrides }));
|
|
app.get('/whoami', (req, res)=>res.json(req.account ?? null));
|
|
app.put('/api/user/rename', (req, res)=>{ renameCalled = true; res.json({ upstream: true }); });
|
|
app.post('/local/login', (req, res)=>res.json('upstream-token'));
|
|
app.get('/', (req, res)=>res.send('home'));
|
|
delegate = app;
|
|
return config;
|
|
};
|
|
|
|
// Mini-Browser mit Cookie-Jar
|
|
const browser = ()=>{
|
|
const jar = {};
|
|
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); const value = kv.slice(i + 1);
|
|
if(!value || attrs.some((a)=>/expires=Thu, 01 Jan 1970/i.test(a))) delete jar[name]; else jar[name] = value;
|
|
}
|
|
};
|
|
const req = async (path, init = {})=>{
|
|
const res = await fetch(path.startsWith('http') ? path : `${appUrl}${path}`, {
|
|
redirect : 'manual', ...init,
|
|
headers : { cookie: Object.entries(jar).map(([k, v])=>`${k}=${v}`).join('; '), ...(init.headers || {}) }
|
|
});
|
|
store(res);
|
|
return res;
|
|
};
|
|
return { jar, req };
|
|
};
|
|
|
|
// Vollständiger Login; gibt { b, res (Callback-Antwort), authUrl }
|
|
const login = async (sub, redirect = '/brews', b = browser())=>{
|
|
const start = await b.req(`/auth/oidc/login?redirect=${encodeURIComponent(redirect)}`);
|
|
const authUrl = start.headers.get('location');
|
|
const { callbackUrl } = await loginAtIdp(authUrl, { login: sub });
|
|
const res = await b.req(callbackUrl);
|
|
return { b, res, authUrl, callbackUrl };
|
|
};
|
|
|
|
beforeAll(async ()=>{
|
|
jest.spyOn(console, 'warn').mockImplementation(()=>{});
|
|
jest.spyOn(console, 'error').mockImplementation(()=>{});
|
|
appServer = http.createServer((req, res)=>delegate(req, res));
|
|
await new Promise((r)=>appServer.listen(0, '127.0.0.1', r));
|
|
appUrl = `http://127.0.0.1:${appServer.address().port}`;
|
|
idp = await startIdp({ accounts: ACCOUNTS, redirectUri: `${appUrl}/auth/oidc/callback` });
|
|
});
|
|
afterAll(async ()=>{
|
|
await idp.close();
|
|
await new Promise((r)=>{ appServer.closeAllConnections?.(); appServer.close(r); });
|
|
jest.restoreAllMocks();
|
|
});
|
|
beforeEach(()=>{
|
|
users = createMemoryUsers(); authors = new Set(); renameCalled = false;
|
|
buildApp();
|
|
});
|
|
|
|
describe('OIDC-Login (Authorization Code + PKCE) gegen Mock-IdP', ()=>{
|
|
test('Login-Redirect enthält PKCE S256, state, nonce, Scopes und setzt das Tx-Cookie', async ()=>{
|
|
const b = browser();
|
|
const res = await b.req('/auth/oidc/login');
|
|
expect(res.status).toBe(302);
|
|
const u = new URL(res.headers.get('location'));
|
|
expect(u.origin).toBe(idp.issuer);
|
|
expect(u.searchParams.get('code_challenge_method')).toBe('S256');
|
|
expect(u.searchParams.get('code_challenge')).toMatch(/^[\w-]{43}$/);
|
|
expect(u.searchParams.get('state')).toHaveLength(43);
|
|
expect(u.searchParams.get('nonce')).toHaveLength(43);
|
|
expect(u.searchParams.get('scope')).toBe('openid profile email');
|
|
expect(u.searchParams.get('redirect_uri')).toBe(`${appUrl}/auth/oidc/callback`);
|
|
const setCookie = res.headers.getSetCookie().find((c)=>c.startsWith(TX_COOKIE));
|
|
expect(setCookie).toMatch(/HttpOnly/i);
|
|
expect(setCookie).toMatch(/SameSite=Lax/i);
|
|
expect(setCookie).toMatch(/Path=\/auth\/oidc/);
|
|
expect(setCookie).toMatch(/Max-Age=600/);
|
|
expect(setCookie).not.toMatch(/Secure/i); // http-Testumgebung
|
|
});
|
|
|
|
test('Erfolg: Konto angelegt, Session-Cookie, Weiterleitung, req.account gesetzt', async ()=>{
|
|
const { b, res } = await login('alice', '/edit/xyz?a=1');
|
|
expect(res.status).toBe(302);
|
|
expect(res.headers.get('location')).toBe('/edit/xyz?a=1');
|
|
const sessionCookie = res.headers.getSetCookie().find((c)=>c.startsWith(SESSION_COOKIE));
|
|
expect(sessionCookie).toMatch(/HttpOnly/i);
|
|
expect(sessionCookie).toMatch(/Path=\//);
|
|
expect(b.jar[TX_COOKIE]).toBeUndefined(); // Transaktion verbraucht
|
|
|
|
expect(users.rows).toHaveLength(1);
|
|
expect(users.rows[0]).toMatchObject({ username: 'alice', oidcIssuer: idp.issuer, oidcSub: 'alice', email: 'alice@example.test', emailVerified: true, displayName: 'Alice A.' });
|
|
|
|
const who = await (await b.req('/whoami')).json();
|
|
expect(who).toEqual({ username: 'alice', uid: users.rows[0].id, provider: 'oidc' });
|
|
|
|
const claims = jwt.verify(b.jar[SESSION_COOKIE], SECRET, { algorithms: ['HS256'] });
|
|
expect(claims).toMatchObject({ v: 1, username: 'alice', iss: idp.issuer, sub: 'alice' });
|
|
expect(claims.exp - claims.iat).toBe(7 * 24 * 3600);
|
|
});
|
|
|
|
test('erneuter Login erzeugt kein zweites Konto', async ()=>{
|
|
await login('alice');
|
|
await login('alice');
|
|
expect(users.rows).toHaveLength(1);
|
|
expect(users.rows[0].lastLoginAt).toBeInstanceOf(Date);
|
|
});
|
|
|
|
test('Namenskollision mit Brew-Autor: neues Konto bekommt Suffix', async ()=>{
|
|
authors.add('alice');
|
|
await login('alice');
|
|
expect(users.rows[0].username).toBe('alice-2');
|
|
});
|
|
|
|
test('E-Mail-Verknüpfung nur bei HB_OIDC_LINK_BY_EMAIL=true und verifizierter E-Mail', async ()=>{
|
|
const pre = await users.create({ username: 'legacy-alice', email: 'alice@example.test' });
|
|
await login('alice');
|
|
expect(users.rows.map((r)=>r.username).sort()).toEqual(['alice', 'legacy-alice']);
|
|
|
|
users = createMemoryUsers();
|
|
const pre2 = await users.create({ username: 'legacy-alice', email: 'alice@example.test' });
|
|
buildApp({ HB_OIDC_LINK_BY_EMAIL: 'true' });
|
|
await login('alice');
|
|
expect(users.rows).toHaveLength(1);
|
|
expect(users.rows[0]).toMatchObject({ id: pre2.id, username: 'legacy-alice', oidcSub: 'alice' });
|
|
expect(pre.id).not.toBe(pre2.id);
|
|
|
|
users = createMemoryUsers();
|
|
await users.create({ username: 'legacy-bob', email: 'bob@example.test' });
|
|
await login('bob'); // E-Mail nicht verifiziert
|
|
expect(users.rows.find((r)=>r.username === 'legacy-bob').oidcSub).toBeNull();
|
|
});
|
|
|
|
test('eigener Anzeigename und Scopes über Umgebung', async ()=>{
|
|
buildApp({ HB_OIDC_SCOPES: 'openid email', HB_OIDC_USERNAME_CLAIM: 'email' });
|
|
const res = await browser().req('/auth/oidc/login');
|
|
expect(new URL(res.headers.get('location')).searchParams.get('scope')).toBe('openid email');
|
|
});
|
|
|
|
describe('Fehlerfälle im Callback', ()=>{
|
|
const expectErrorPage = async (res, status)=>{
|
|
expect(res.status).toBe(status);
|
|
expect(res.headers.get('content-type')).toMatch(/html/);
|
|
expect(await res.text()).toMatch(/Erneut anmelden/);
|
|
};
|
|
|
|
test('ohne Transaktion → 400', async ()=>{
|
|
const res = await browser().req('/auth/oidc/callback?code=abc&state=xyz');
|
|
await expectErrorPage(res, 400);
|
|
});
|
|
|
|
test('falscher state → 400, kein Konto, keine Session', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
const u = new URL(callbackUrl);
|
|
u.searchParams.set('state', 'manipuliert');
|
|
const res = await b.req(u.href);
|
|
await expectErrorPage(res, 400);
|
|
expect(users.rows).toHaveLength(0);
|
|
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
|
expect(b.jar[TX_COOKIE]).toBeUndefined();
|
|
});
|
|
|
|
test('Transaktion nur einmal verwendbar (Replay)', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
const txCookie = b.jar[TX_COOKIE];
|
|
expect((await b.req(callbackUrl)).status).toBe(302);
|
|
b.jar[TX_COOKIE] = txCookie; // Angreifer spielt Cookie + Code erneut ein
|
|
const res = await b.req(callbackUrl);
|
|
await expectErrorPage(res, 400); // Code ist beim IdP verbraucht
|
|
expect(users.rows).toHaveLength(1);
|
|
});
|
|
|
|
test('abgelaufene Transaktion → 400', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET });
|
|
const tx = openTx(config, b.jar[TX_COOKIE]);
|
|
b.jar[TX_COOKIE] = sealTx(config, { ...tx, createdAt: Date.now() - 11 * 60 * 1000 });
|
|
await expectErrorPage(await b.req(callbackUrl), 400);
|
|
expect(users.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('manipuliertes Tx-Cookie → 400', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
b.jar[TX_COOKIE] = `${b.jar[TX_COOKIE].slice(0, -3)}AAA`;
|
|
await expectErrorPage(await b.req(callbackUrl), 400);
|
|
});
|
|
|
|
test('falscher nonce (ID-Token passt nicht zur Transaktion) → 400', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET });
|
|
const tx = openTx(config, b.jar[TX_COOKIE]);
|
|
b.jar[TX_COOKIE] = sealTx(config, { ...tx, nonce: 'anderer-nonce' });
|
|
await expectErrorPage(await b.req(callbackUrl), 400);
|
|
expect(users.rows).toHaveLength(0);
|
|
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
|
});
|
|
|
|
test('falscher PKCE-Verifier → 400', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const { callbackUrl } = await loginAtIdp(start.headers.get('location'), { login: 'alice' });
|
|
const config = readAuthConfig({ HB_PUBLIC_URL: appUrl, HB_OIDC_ISSUER: idp.issuer, HB_OIDC_CLIENT_ID: 'x', HB_OIDC_CLIENT_SECRET: 'x', HB_SESSION_SECRET: SECRET });
|
|
const tx = openTx(config, b.jar[TX_COOKIE]);
|
|
b.jar[TX_COOKIE] = sealTx(config, { ...tx, codeVerifier: 'A'.repeat(43) });
|
|
await expectErrorPage(await b.req(callbackUrl), 400);
|
|
expect(users.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('IdP meldet error=access_denied → 400 mit Hinweis', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const state = new URL(start.headers.get('location')).searchParams.get('state');
|
|
const res = await b.req(`/auth/oidc/callback?error=access_denied&state=${state}&iss=${encodeURIComponent(idp.issuer)}`);
|
|
await expectErrorPage(res, 400);
|
|
expect(users.rows).toHaveLength(0);
|
|
});
|
|
|
|
test('Code ungültig → 400', async ()=>{
|
|
const b = browser();
|
|
const start = await b.req('/auth/oidc/login');
|
|
const state = new URL(start.headers.get('location')).searchParams.get('state');
|
|
const res = await b.req(`/auth/oidc/callback?code=falsch&state=${state}&iss=${encodeURIComponent(idp.issuer)}`);
|
|
await expectErrorPage(res, 400);
|
|
});
|
|
|
|
test('Fehler im Konto-Mapping → 500 ohne Session', async ()=>{
|
|
buildApp({}, { getUsers: ()=>({ findByOidc: async ()=>{ throw new Error('db down'); } }) });
|
|
const { b, res } = await login('alice');
|
|
await expectErrorPage(res, 500);
|
|
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
|
});
|
|
|
|
test('IdP nicht erreichbar → 502, späterer Versuch klappt (Discovery nicht dauerhaft gecacht)', async ()=>{
|
|
buildApp({ HB_OIDC_ISSUER: 'http://127.0.0.1:9' });
|
|
const res = await browser().req('/auth/oidc/login');
|
|
await expectErrorPage(res, 502);
|
|
// anderer Router mit funktionierendem IdP
|
|
buildApp();
|
|
expect((await browser().req('/auth/oidc/login')).status).toBe(302);
|
|
});
|
|
});
|
|
|
|
describe('offene Weiterleitung', ()=>{
|
|
test.each(['//evil.example', 'https://evil.example/x', '/\\evil.example', 'javascript:alert(1)'])('redirect=%s → /', async (redirect)=>{
|
|
const { res } = await login('alice', redirect);
|
|
expect(res.headers.get('location')).toBe('/');
|
|
});
|
|
});
|
|
|
|
describe('Logout', ()=>{
|
|
test('löscht das Session-Cookie und leitet auf / um', async ()=>{
|
|
const { b } = await login('alice');
|
|
const res = await b.req('/auth/logout');
|
|
expect(res.status).toBe(302);
|
|
expect(res.headers.get('location')).toBe('/');
|
|
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
|
expect(await (await b.req('/whoami')).json()).toBeNull();
|
|
});
|
|
|
|
test('mit HB_OIDC_END_SESSION=true Redirect zum end_session_endpoint des IdP', async ()=>{
|
|
buildApp({ HB_OIDC_END_SESSION: 'true' });
|
|
const { b } = await login('alice');
|
|
const res = await b.req('/auth/logout');
|
|
const loc = new URL(res.headers.get('location'));
|
|
expect(loc.origin).toBe(idp.issuer);
|
|
expect(loc.pathname).toBe('/session/end');
|
|
expect(loc.searchParams.get('client_id')).toBe(CLIENT.client_id);
|
|
expect(loc.searchParams.get('post_logout_redirect_uri')).toBe(`${appUrl}/`);
|
|
expect(b.jar[SESSION_COOKIE]).toBeUndefined();
|
|
});
|
|
});
|
|
});
|
|
|
|
describe('Session-Gültigkeit', ()=>{
|
|
test('abgelaufene und fremd signierte Sessions liefern kein Konto', async ()=>{
|
|
const b = browser();
|
|
const claims = { v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' };
|
|
b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: -5 });
|
|
expect(await (await b.req('/whoami')).json()).toBeNull();
|
|
b.jar[SESSION_COOKIE] = jwt.sign(claims, 'x'.repeat(40), { expiresIn: 60 });
|
|
expect(await (await b.req('/whoami')).json()).toBeNull();
|
|
b.jar[SESSION_COOKIE] = jwt.sign(claims, SECRET, { expiresIn: 60 });
|
|
expect((await (await b.req('/whoami')).json()).username).toBe('mallory');
|
|
});
|
|
});
|
|
|
|
describe('PUT /api/user/rename', ()=>{
|
|
test('OIDC-Session → 403 A01, Upstream-Route wird nicht erreicht', async ()=>{
|
|
const { b } = await login('alice');
|
|
const res = await b.req('/api/user/rename', {
|
|
method : 'PUT', headers : { 'content-type': 'application/json' },
|
|
body : JSON.stringify({ username: 'victim', newUsername: 'alice' })
|
|
});
|
|
expect(res.status).toBe(403);
|
|
expect(await res.json()).toMatchObject({ HBErrorCode: 'A01' });
|
|
expect(renameCalled).toBe(false);
|
|
});
|
|
|
|
test('naturalcrit-Session → Upstream-Verhalten', async ()=>{
|
|
const b = browser();
|
|
b.jar.nc_session = 'carol';
|
|
const res = await b.req('/api/user/rename', { method: 'PUT' });
|
|
expect(await res.json()).toEqual({ upstream: true });
|
|
expect(renameCalled).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('Alt-Logins abschaltbar (HB_AUTH_PROVIDERS)', ()=>{
|
|
test('beide aktiv: nc_session gilt (mit provider), Auswahlseite, /local/login erreichbar', async ()=>{
|
|
buildApp({ HB_AUTH_PROVIDERS: 'oidc,naturalcrit' });
|
|
const b = browser();
|
|
b.jar.nc_session = 'carol';
|
|
expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' });
|
|
const chooser = await b.req('/auth/login?redirect=%2Fbrews');
|
|
const html = await chooser.text();
|
|
expect(html).toMatch(/\/auth\/oidc\/login\?redirect=%2Fbrews/);
|
|
expect(html).toMatch(/naturalcrit\.com\/login/);
|
|
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200);
|
|
});
|
|
|
|
test('nur oidc: nc_session wird ignoriert, /local/login 404, /auth/login leitet direkt zum IdP-Login', async ()=>{
|
|
buildApp({ HB_AUTH_PROVIDERS: 'oidc' });
|
|
const b = browser();
|
|
b.jar.nc_session = 'carol';
|
|
expect(await (await b.req('/whoami')).json()).toBeNull();
|
|
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(404);
|
|
const res = await b.req('/auth/login?redirect=%2Fx');
|
|
expect(res.status).toBe(302);
|
|
expect(res.headers.get('location')).toBe('/auth/oidc/login?redirect=%2Fx');
|
|
// OIDC-Login funktioniert weiter
|
|
const { b: b2 } = await login('alice');
|
|
expect((await (await b2.req('/whoami')).json()).provider).toBe('oidc');
|
|
});
|
|
|
|
test('nur naturalcrit: OIDC-Endpunkte gesperrt, hb_session wird ignoriert', async ()=>{
|
|
buildApp({ HB_AUTH_PROVIDERS: 'naturalcrit' });
|
|
const b = browser();
|
|
expect((await b.req('/auth/oidc/login')).status).toBe(404);
|
|
expect((await b.req('/auth/oidc/callback?code=x&state=y')).status).toBe(404);
|
|
expect((await b.req('/auth/login')).status).toBe(404);
|
|
b.jar[SESSION_COOKIE] = jwt.sign({ v: 1, uid: 'u', username: 'mallory', iss: 'i', sub: 's' }, SECRET, { expiresIn: 60 });
|
|
b.jar.nc_session = 'carol';
|
|
expect(await (await b.req('/whoami')).json()).toEqual({ username: 'carol', provider: 'naturalcrit' });
|
|
expect((await b.req('/local/login', { method: 'POST' })).status).toBe(200);
|
|
});
|
|
|
|
test('nur oidc: PUT /api/user/rename ohne OIDC-Session erreicht die Upstream-Route (dort greift die Kontoprüfung)', async ()=>{
|
|
buildApp({ HB_AUTH_PROVIDERS: 'oidc' });
|
|
const b = browser();
|
|
b.jar.nc_session = 'carol';
|
|
const res = await b.req('/api/user/rename', { method: 'PUT' });
|
|
expect(renameCalled).toBe(true);
|
|
expect(res.status).toBe(200);
|
|
});
|
|
});
|