fix(auth): PUT /api/user/rename auch für naturalcrit-Sitzungen absichern (F14)
Die Upstream-Route prüft nur, ob newUsername der eigenen Sitzung gehört, nicht den alten Namen. Der Fork-Router beantwortet die Route jetzt vorher: - OIDC-Sitzung: 403 A01 (unverändert) - ohne Anmeldung: 403 - naturalcrit, HB_NATURALCRIT_RENAME=off (Standard): 403 A02 - naturalcrit, HB_NATURALCRIT_RENAME=signed: nur mit Nachweis oldSession (nc_session-Token des alten Namens, HS256 mit SECRET), sonst 403 A03 Mit signed startet die App außerhalb lokaler Umgebungen nicht, solange SECRET der Standardwert ist. server/app.js bleibt unverändert. ADR 0001: neuer Abschnitt 7, Konfiguration, Tests, Folgen, F14. Closes #21 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bbf838c5d6
commit
03455c5bf5
9 files changed
+251
-43
No files matched your search
@@ -21,13 +21,14 @@ const buildApp = (envOverrides = {}, depsOverrides = {})=>{
|
||||
HB_OIDC_CLIENT_SECRET : CLIENT.client_secret, HB_SESSION_SECRET : SECRET, ...envOverrides
|
||||
}, { upstreamSecret: 'eigenes-secret' });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
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.put('/api/user/rename', (req, res)=>{ renameCalled = req.body; res.json({ upstream: true }); });
|
||||
app.post('/local/login', (req, res)=>res.json('upstream-token'));
|
||||
app.get('/', (req, res)=>res.send('home'));
|
||||
delegate = app;
|
||||
@@ -320,23 +321,93 @@ describe('Session-Gültigkeit', ()=>{
|
||||
});
|
||||
|
||||
describe('PUT /api/user/rename', ()=>{
|
||||
const UPSTREAM_SECRET = 'eigenes-secret'; // wie in buildApp()
|
||||
const rename = (b, body)=>b.req('/api/user/rename', {
|
||||
method : 'PUT', headers : { 'content-type': 'application/json' }, body : JSON.stringify(body)
|
||||
});
|
||||
const ncBrowser = (username)=>{ const b = browser(); b.jar.nc_session = username; return b; };
|
||||
// nc_session-Token, wie naturalcrit es mit jwt-simple ausstellt (HS256, ohne exp)
|
||||
const ncToken = (username, secret = UPSTREAM_SECRET, opts = {})=>jwt.sign({ username, issued: new Date().toISOString() }, secret, { noTimestamp: true, ...opts });
|
||||
const expectDenied = async (res, code)=>{
|
||||
expect(res.status).toBe(403);
|
||||
const body = await res.json();
|
||||
if(code) expect(body.HBErrorCode).toBe(code); else expect(body.HBErrorCode).toBeUndefined();
|
||||
expect(renameCalled).toBe(false);
|
||||
};
|
||||
|
||||
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);
|
||||
await expectDenied(await rename(b, { username: 'victim', newUsername: 'alice' }), 'A01');
|
||||
});
|
||||
|
||||
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);
|
||||
test('OIDC-Session → 403 A01 auch mit HB_NATURALCRIT_RENAME=signed und gültigem Nachweis', async ()=>{
|
||||
buildApp({ HB_NATURALCRIT_RENAME: 'signed' });
|
||||
const { b } = await login('alice');
|
||||
await expectDenied(await rename(b, { username: 'old', newUsername: 'alice', oldSession: ncToken('old') }), 'A01');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['Standard (oidc,naturalcrit)', {}],
|
||||
['nur oidc', { HB_AUTH_PROVIDERS: 'oidc' }],
|
||||
['nur naturalcrit, signed', { HB_AUTH_PROVIDERS: 'naturalcrit', HB_NATURALCRIT_RENAME: 'signed' }]
|
||||
])('ohne Anmeldung → 403 (%s)', async (name, env)=>{
|
||||
buildApp(env);
|
||||
await expectDenied(await rename(browser(), { username: 'victim', newUsername: 'mallory' }));
|
||||
});
|
||||
|
||||
test('nur oidc: nc_session zählt nicht als Anmeldung → 403', async ()=>{
|
||||
buildApp({ HB_AUTH_PROVIDERS: 'oidc', HB_NATURALCRIT_RENAME: 'signed' });
|
||||
await expectDenied(await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') }));
|
||||
});
|
||||
|
||||
describe('naturalcrit, Standard HB_NATURALCRIT_RENAME=off', ()=>{
|
||||
test('fremder alter Name → 403 A02', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory' }), 'A02');
|
||||
});
|
||||
|
||||
test('auch mit gültigem Nachweis → 403 A02 (Endpunkt gesperrt)', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') }), 'A02');
|
||||
});
|
||||
});
|
||||
|
||||
describe('naturalcrit, HB_NATURALCRIT_RENAME=signed', ()=>{
|
||||
beforeEach(()=>buildApp({ HB_NATURALCRIT_RENAME: 'signed' }));
|
||||
|
||||
test('eigener Rename mit Nachweis → 200, Upstream-Route erhält den Body ohne Token', async ()=>{
|
||||
const res = await rename(ncBrowser('carol'), { username: 'carol-alt', newUsername: 'carol', oldSession: ncToken('carol-alt') });
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ upstream: true });
|
||||
expect(renameCalled).toEqual({ username: 'carol-alt', newUsername: 'carol' });
|
||||
});
|
||||
|
||||
test('fremder alter Name ohne Nachweis → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory' }), 'A03');
|
||||
});
|
||||
|
||||
test('fremder alter Name mit eigenem Token als Nachweis → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory', oldSession: ncToken('mallory') }), 'A03');
|
||||
});
|
||||
|
||||
test.each([
|
||||
['fremder Schlüssel', ()=>ncToken('victim', 'x'.repeat(40))],
|
||||
['alg HS512', ()=>ncToken('victim', UPSTREAM_SECRET, { algorithm: 'HS512' })],
|
||||
['unsigniert (alg none)', ()=>jwt.sign({ username: 'victim' }, null, { algorithm: 'none' })],
|
||||
['abgelaufen', ()=>ncToken('victim', UPSTREAM_SECRET, { expiresIn: -5 })],
|
||||
['kein String', ()=>({ username: 'victim' })],
|
||||
['Token ohne username', ()=>jwt.sign({ issued: 'x' }, UPSTREAM_SECRET)]
|
||||
])('ungültiger Nachweis (%s) → 403 A03', async (name, token)=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'victim', newUsername: 'mallory', oldSession: token() }), 'A03');
|
||||
});
|
||||
|
||||
test('newUsername gehört nicht zur Sitzung → 403 A03', async ()=>{
|
||||
await expectDenied(await rename(ncBrowser('mallory'), { username: 'mallory', newUsername: 'victim', oldSession: ncToken('mallory') }), 'A03');
|
||||
});
|
||||
|
||||
test('fehlende Felder → 400', async ()=>{
|
||||
const res = await rename(ncBrowser('carol'), { newUsername: 'carol' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(renameCalled).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -378,13 +449,4 @@ describe('Alt-Logins abschaltbar (HB_AUTH_PROVIDERS)', ()=>{
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
// Auth-Konfiguration ausschließlich aus Umgebungsvariablen (ADR 0001, "Konfiguration").
|
||||
const VALID_PROVIDERS = ['oidc', 'naturalcrit'];
|
||||
// PUT /api/user/rename für naturalcrit-Sitzungen (ADR 0001, Abschnitt 7)
|
||||
const VALID_NC_RENAME = ['off', 'signed'];
|
||||
const MIN_SECRET_BYTES = 32;
|
||||
|
||||
const bool = (v, def = false)=>{
|
||||
@@ -46,9 +48,23 @@ export const readAuthConfig = (env = process.env, { upstreamSecret, isLocal = fa
|
||||
linkByEmail : bool(env.HB_OIDC_LINK_BY_EMAIL),
|
||||
endSession : bool(env.HB_OIDC_END_SESSION),
|
||||
label : env.HB_OIDC_LABEL || 'Anmelden'
|
||||
},
|
||||
// PUT /api/user/rename für naturalcrit-Sitzungen; secret = Schlüssel der Upstream-nc_session (ADR 0001, Abschnitt 7)
|
||||
naturalcrit : {
|
||||
rename : (env.HB_NATURALCRIT_RENAME || 'off').trim().toLowerCase(),
|
||||
secret : upstreamSecret
|
||||
}
|
||||
};
|
||||
|
||||
if(!VALID_NC_RENAME.includes(config.naturalcrit.rename)) {
|
||||
throw new Error(`HB_NATURALCRIT_RENAME ungültig: "${env.HB_NATURALCRIT_RENAME}" (erlaubt: ${VALID_NC_RENAME.join(', ')})`);
|
||||
}
|
||||
// Mit dem Standard-"secret" ließe sich der Nachweis (ein signiertes nc_session-Token des alten Namens) fälschen
|
||||
if(config.naturalcrit.rename === 'signed' && providers.includes('naturalcrit') && !isLocal
|
||||
&& (!upstreamSecret || upstreamSecret === 'secret')) {
|
||||
throw new Error('HB_NATURALCRIT_RENAME=signed braucht ein eigenes Upstream-"secret" (Env SECRET), der Standardwert ist unsicher.');
|
||||
}
|
||||
|
||||
if(providers.includes('oidc')) {
|
||||
const required = {
|
||||
HB_OIDC_ISSUER : config.oidc.issuer,
|
||||
|
||||
@@ -33,6 +33,20 @@ describe('Auth-Konfiguration', ()=>{
|
||||
expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'oidc' })).toThrow(/HB_OIDC_ISSUER.*HB_OIDC_CLIENT_ID.*HB_OIDC_CLIENT_SECRET.*HB_PUBLIC_URL.*HB_SESSION_SECRET/);
|
||||
});
|
||||
|
||||
test('HB_NATURALCRIT_RENAME: Standard off, signed erlaubt, unbekannter Wert bricht ab', ()=>{
|
||||
expect(readAuthConfig({}).naturalcrit).toEqual({ rename: 'off', secret: undefined });
|
||||
expect(readAuthConfig({ HB_NATURALCRIT_RENAME: ' Signed ' }, own).naturalcrit).toEqual({ rename: 'signed', secret: 'eigenes-secret' });
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'upstream' }, own)).toThrow(/HB_NATURALCRIT_RENAME ungültig/);
|
||||
});
|
||||
|
||||
test('HB_NATURALCRIT_RENAME=signed mit Standard-secret bricht außerhalb lokaler Umgebungen ab', ()=>{
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' }, { upstreamSecret: 'secret' })).toThrow(/eigenes Upstream-"secret"/);
|
||||
expect(()=>readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' })).toThrow(/eigenes Upstream-"secret"/);
|
||||
expect(readAuthConfig({ HB_NATURALCRIT_RENAME: 'signed' }, { upstreamSecret: 'secret', isLocal: true }).naturalcrit.rename).toBe('signed');
|
||||
// ohne naturalcrit-Provider ist der Modus wirkungslos und kein Startfehler
|
||||
expect(readAuthConfig({ ...base, HB_AUTH_PROVIDERS: 'oidc', HB_NATURALCRIT_RENAME: 'signed' }).naturalcrit.rename).toBe('signed');
|
||||
});
|
||||
|
||||
test('zu kurzes Session-Secret und unbekannter Provider brechen ab', ()=>{
|
||||
expect(()=>readAuthConfig({ ...base, HB_SESSION_SECRET: 'kurz' }, own)).toThrow(/32 Byte/);
|
||||
expect(()=>readAuthConfig({ HB_AUTH_PROVIDERS: 'ldap' })).toThrow(/unbekannte/);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { readAuthConfig, hasProvider, clientConfig } from './config.js';
|
||||
import { createOidcClient, OidcCallbackError } from './oidc.js';
|
||||
import { issueSession, readSession, clearSession, setTx, takeTx, safeRedirect } from './session.js';
|
||||
import { mapAccount } from './accountMapping.js';
|
||||
import { renameGuard } from './rename.js';
|
||||
|
||||
export { readAuthConfig, clientConfig };
|
||||
|
||||
@@ -43,16 +44,8 @@ export const createAuthRouter = (config, deps = {})=>{
|
||||
const parseCookies = cookieParser();
|
||||
router.use((req, res, next)=>req.cookies ? next() : parseCookies(req, res, next));
|
||||
|
||||
// Upstream-Route sperren/umleiten, bevor sie greift
|
||||
router.put('/api/user/rename', (req, res, next)=>{
|
||||
if(req.account?.provider === 'oidc') {
|
||||
return res.status(403).json({
|
||||
error : 'Benutzernamen von OIDC-Konten sind unveränderlich.',
|
||||
HBErrorCode : 'A01'
|
||||
});
|
||||
}
|
||||
next();
|
||||
});
|
||||
// Upstream-Route absichern, bevor sie greift: OIDC gesperrt (A01), naturalcrit nur mit Nachweis (ADR 0001 §7)
|
||||
router.put('/api/user/rename', renameGuard(config));
|
||||
|
||||
if(!naturalcritEnabled) {
|
||||
router.post('/local/login', (req, res)=>res.status(404).json({ error: 'Not found' }));
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// Absicherung von PUT /api/user/rename (ADR 0001, Abschnitt 7).
|
||||
// Die Upstream-Route prüft nur, ob newUsername der eigenen Sitzung gehört, nicht aber den alten Namen.
|
||||
// Dieser Wächter läuft im Fork-Router vor der Upstream-Route und lässt nur nachgewiesene Umbenennungen durch.
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const deny = (res, error, HBErrorCode)=>res.status(403).json(HBErrorCode ? { error, HBErrorCode } : { error });
|
||||
|
||||
// Nachweis für den alten Namen: ein mit dem Upstream-"secret" signiertes nc_session-Token (HS256, wie jwt-simple)
|
||||
// mit username === alter Name. Wer es vorlegt, hatte eine Sitzung unter dem alten Namen und konnte dessen Brews
|
||||
// ohnehin bearbeiten; die Umbenennung gibt ihm also keine zusätzlichen Rechte.
|
||||
export const verifyOldNameProof = (token, oldUsername, secret)=>{
|
||||
if(typeof token !== 'string' || !token || !secret) return false;
|
||||
try {
|
||||
const payload = jwt.verify(token, secret, { algorithms: ['HS256'] });
|
||||
return typeof payload?.username === 'string' && payload.username === oldUsername;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} config Ergebnis von readAuthConfig()
|
||||
*/
|
||||
export const renameGuard = (config)=>(req, res, next)=>{
|
||||
const account = req.account;
|
||||
if(account?.provider === 'oidc') {
|
||||
return deny(res, 'Benutzernamen von OIDC-Konten sind unveränderlich.', 'A01');
|
||||
}
|
||||
if(!account?.username) {
|
||||
return deny(res, 'Must be logged in to change your username');
|
||||
}
|
||||
if(config.naturalcrit.rename !== 'signed') {
|
||||
return deny(res, 'Umbenennen ist auf dieser Instanz deaktiviert (HB_NATURALCRIT_RENAME=off).', 'A02');
|
||||
}
|
||||
|
||||
const { username, newUsername, oldSession } = req.body ?? {};
|
||||
if(typeof username !== 'string' || typeof newUsername !== 'string' || !username || !newUsername) {
|
||||
return res.status(400).json({ error: 'Username and newUsername are required.' });
|
||||
}
|
||||
if(newUsername !== account.username || !verifyOldNameProof(oldSession, username, config.naturalcrit.secret)) {
|
||||
return deny(res, 'Kein gültiger Nachweis für den alten Benutzernamen (oldSession).', 'A03');
|
||||
}
|
||||
delete req.body.oldSession; // Token nicht an die Upstream-Route und deren Logs weiterreichen
|
||||
next();
|
||||
};
|
||||
Reference in new issue
Block a user