'use strict'; jest.mock('../lib/render', () => ({ renderError: jest.fn((_req, response, status) => response.status(status).send('error page')) })); const { parseTrustedProxies, requestSource, isTrustedProxy, ssoIdentity } = require('../lib/pageauth'); const PROXY = '192.0.2.10'; const IDENTITY = { 'remote-user': 'alice', 'remote-name': 'Alice', 'remote-email': 'alice@example.com', 'remote-groups': 'admin, ops' }; function req(remoteAddress, headers = IDENTITY) { return { headers: { ...headers }, socket: { remoteAddress } }; } function res() { const r = { statusCode: 200 }; r.status = jest.fn(code => { r.statusCode = code; return r; }); r.send = jest.fn(() => r); return r; } let warn; let error; beforeEach(() => { warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); error = jest.spyOn(console, 'error').mockImplementation(() => {}); }); afterEach(() => jest.restoreAllMocks()); describe('parseTrustedProxies', () => { test('unset or empty trusts nobody', () => { expect(parseTrustedProxies(undefined).count).toBe(0); expect(parseTrustedProxies(' , ').count).toBe(0); }); test('accepts addresses, CIDR ranges and IPv6', () => { const t = parseTrustedProxies(`${PROXY}, 198.51.100.0/24, 2001:db8::1`); expect(t.count).toBe(3); expect(t.list.check('198.51.100.77', 'ipv4')).toBe(true); expect(t.list.check('2001:db8::1', 'ipv6')).toBe(true); }); test('invalid entries are skipped and logged, never widened', () => { const t = parseTrustedProxies('not-an-ip, 192.0.2.1/, 192.0.2.1/33, 192.0.2.1/x'); expect(t.count).toBe(0); expect(t.list.check('203.0.113.5', 'ipv4')).toBe(false); expect(error).toHaveBeenCalledTimes(4); }); }); describe('requestSource', () => { test('strips the IPv4-mapped IPv6 prefix', () => { expect(requestSource(req(`::ffff:${PROXY}`))).toBe(PROXY); expect(requestSource(req('2001:db8::1'))).toBe('2001:db8::1'); expect(requestSource({ headers: {}, socket: {} })).toBe(''); }); }); describe('ssoIdentity', () => { const trusted = parseTrustedProxies(PROXY); test('proxy identity is accepted', () => { expect(ssoIdentity(req(PROXY), trusted)).toEqual({ username: 'alice', name: 'Alice', email: 'alice@example.com', groups: ['admin', 'ops'] }); expect(ssoIdentity(req(`::ffff:${PROXY}`), trusted).username).toBe('alice'); }); test('a LAN host cannot claim an identity, and the attempt is logged', () => { expect(ssoIdentity(req('192.0.2.99'), trusted)).toBeNull(); expect(warn.mock.calls[0][0]).toContain('"192.0.2.99"'); }); test('forwarding headers cannot borrow the proxy address', () => { const headers = { ...IDENTITY, 'x-real-ip': PROXY, 'x-forwarded-for': PROXY }; expect(ssoIdentity(req('192.0.2.99', headers), trusted)).toBeNull(); }); test('fails closed with no trusted proxies', () => { expect(ssoIdentity(req(PROXY), parseTrustedProxies(''))).toBeNull(); }); test('a request without identity headers is unauthenticated but not logged', () => { expect(ssoIdentity(req('192.0.2.99', {}), trusted)).toBeNull(); expect(ssoIdentity(req(PROXY, {}), trusted)).toBeNull(); expect(warn).not.toHaveBeenCalled(); }); test('isTrustedProxy rejects a missing or garbage peer', () => { expect(isTrustedProxy({ headers: {}, socket: {} }, trusted)).toBe(false); expect(isTrustedProxy(req('garbage'), trusted)).toBe(false); }); }); describe('makeAuthenticatePage', () => { const OLD_ENV = process.env.TRUSTED_PROXIES; afterAll(() => { process.env.TRUSTED_PROXIES = OLD_ENV; }); // The page middleware reads TRUSTED_PROXIES itself (parsed once, on first use). function load() { let mod; jest.isolateModules(() => { mod = require('../lib/pageauth'); }); return mod; } test('untrusted source gets 401 and never reaches the users table', async () => { process.env.TRUSTED_PROXIES = PROXY; const pool = { query: jest.fn() }; const next = jest.fn(); const r = res(); await load().makeAuthenticatePage(pool)(req('192.0.2.99'), r, next); expect(r.statusCode).toBe(401); expect(next).not.toHaveBeenCalled(); expect(pool.query).not.toHaveBeenCalled(); }); test('trusted proxy with an allowed group passes', async () => { process.env.TRUSTED_PROXIES = PROXY; const pool = { query: jest.fn().mockResolvedValue([]) }; const next = jest.fn(); const request = req(PROXY); await load().makeAuthenticatePage(pool)(request, res(), next); expect(next).toHaveBeenCalled(); expect(request.user).toMatchObject({ username: 'alice', isAdmin: true }); }); test('trusted proxy without an allowed group gets 403', async () => { process.env.TRUSTED_PROXIES = PROXY; const r = res(); await load().makeAuthenticatePage({ query: jest.fn() })( req(PROXY, { ...IDENTITY, 'remote-groups': 'guests' }), r, jest.fn()); expect(r.statusCode).toBe(403); }); test('page middleware fails closed when TRUSTED_PROXIES is unset', async () => { delete process.env.TRUSTED_PROXIES; const r = res(); await load().makeAuthenticatePage({ query: jest.fn() })(req(PROXY), r, jest.fn()); expect(r.statusCode).toBe(401); }); });