const { allowedWhileImpersonating, impersonationBlocker } = require('../src/utils/impersonation'); describe('allowedWhileImpersonating', () => { test('reads are allowed', () => { expect(allowedWhileImpersonating('GET', '/api/registrations/myregistrations')).toBe(true); // Ending (and logging) a viewing-as session works on v2 too; other v2 writes stay blocked. expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end')).toBe(true); expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/log')).toBe(true); expect(allowedWhileImpersonating('POST', '/api/v2/payments')).toBe(false); expect(allowedWhileImpersonating('HEAD', '/api/events')).toBe(true); expect(allowedWhileImpersonating('OPTIONS', '/api/payments')).toBe(true); }); test('every write is refused', () => { for (const m of ['POST', 'PUT', 'PATCH', 'DELETE']) { expect(allowedWhileImpersonating(m, '/api/registrations')).toBe(false); expect(allowedWhileImpersonating(m, '/api/payments/yoco-checkout')).toBe(false); expect(allowedWhileImpersonating(m, '/api/users/profile')).toBe(false); } }); test('except ending the session and logging page views', () => { expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end')).toBe(true); expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/log?x=1')).toBe(true); expect(allowedWhileImpersonating('DELETE', '/api/v2/me/impersonation/end')).toBe(false); expect(allowedWhileImpersonating('POST', '/api/v2/me/impersonation/end/../../users')).toBe(false); }); }); describe('impersonationBlocker', () => { const admin = { id: 'a', role: 'admin', twoFactorEnabled: true }; const user = { id: 'u', role: 'user', isActive: true }; test('an admin with 2FA can view a user', () => { expect(impersonationBlocker(admin, user)).toBeNull(); expect(impersonationBlocker(admin, { ...user, role: 'supervisor' })).toBeNull(); }); test('refusals', () => { expect(impersonationBlocker({ ...admin, role: 'supervisor' }, user)).toMatch(/Only admins/); expect(impersonationBlocker({ ...admin, twoFactorEnabled: false }, user)).toMatch(/two-factor/); expect(impersonationBlocker(admin, { ...user, role: 'admin' })).toMatch(/Admins can't/); expect(impersonationBlocker(admin, { ...admin })).toMatch(/yourself/); expect(impersonationBlocker(admin, { ...user, isActive: false })).toMatch(/deactivated/); expect(impersonationBlocker(admin, null)).toMatch(/not found/); }); });