diff --git a/README.md b/README.md index 9d858f8..fec9da0 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,9 @@ DB_PASSWORD=your-db-password # Worker API Key (for worker authentication) WORKER_API_KEY=your-worker-api-key +# Reverse proxy that runs Authelia forward auth (required for SSO logins) +TRUSTED_PROXIES=192.0.2.10 + # Auto-cleanup configuration (optional) EXECUTION_RETENTION_DAYS=30 EOF @@ -393,7 +396,7 @@ The **Workers** tab displays real-time metrics for each worker: - Load More button for large execution lists ### Security -- Authelia SSO integration for user authentication +- Authelia SSO integration for user authentication, with identity headers only accepted from `TRUSTED_PROXIES` - API key authentication for workers - User session management - Admin-only operations (worker deletion, workflow management) @@ -420,6 +423,7 @@ DB_NAME=pulse # Database name DB_USER=pulse_user # Database user DB_PASSWORD= # Database password WORKER_API_KEY= # Worker authentication key +TRUSTED_PROXIES=[,] # Proxies allowed to send Authelia identity headers (required, see below) EXECUTION_RETENTION_DAYS=30 # Auto-cleanup retention (default: 30) # Web UI (all optional) @@ -430,6 +434,20 @@ PULSE_DEV_READONLY=1 # Local dev guard: disable all background wr DISABLE_BACKGROUND_JOBS=1 # Alias for PULSE_DEV_READONLY ``` +### Trusted proxies + +Authelia's forward auth passes the user to Pulse in the `Remote-User`, `Remote-Name`, +`Remote-Email` and `Remote-Groups` headers. Those headers are only trustworthy when the reverse +proxy sent the request, because the proxy overwrites them. Pulse listens on every interface, so +any other host that can reach the port could set them itself and log in as anyone. + +`TRUSTED_PROXIES` is a comma-separated list of addresses or CIDR ranges (IPv4 or IPv6). Pulse +only accepts identity headers from a connection whose peer address is on the list. It uses the +TCP peer, not `X-Forwarded-For` or `X-Real-IP`, which a client could forge. Requests from +anywhere else are treated as not logged in, and are logged with their source address. It fails +closed: if `TRUSTED_PROXIES` is unset, no SSO login succeeds and a warning is printed at +startup. Invalid entries are logged and skipped. Worker and Gandalf API-key routes don't use it. + ### Local development against a real database Running a local instance against the production MariaDB is safe only with the read-only guard on: diff --git a/lib/pageauth.js b/lib/pageauth.js index 324c377..45da1b3 100644 --- a/lib/pageauth.js +++ b/lib/pageauth.js @@ -2,9 +2,79 @@ // and the HTML page middleware (authenticatePage). const crypto = require('crypto'); +const net = require('net'); const { renderError } = require('./render'); const ALLOWED_GROUPS = ['admin', 'employee']; +const IDENTITY_HEADERS = ['remote-user', 'remote-name', 'remote-email', 'remote-groups']; + +// Parse TRUSTED_PROXIES ("a.b.c.d, a.b.c.0/24, ...") into a BlockList of the +// addresses allowed to send Authelia identity headers. Invalid entries are logged +// and skipped, never widened: "10.0.0.1/" must not become a /0 that trusts everyone. +function parseTrustedProxies(value) { + const list = new net.BlockList(); + let count = 0; + for (const raw of String(value || '').split(',')) { + const entry = raw.trim(); + if (!entry) continue; + const slash = entry.indexOf('/'); + const addr = slash === -1 ? entry : entry.slice(0, slash); + const bits = slash === -1 ? null : entry.slice(slash + 1); + const type = net.isIPv4(addr) ? 'ipv4' : (net.isIPv6(addr) ? 'ipv6' : null); + const maxBits = type === 'ipv4' ? 32 : 128; + if (!type || (bits !== null && !(/^\d{1,3}$/.test(bits) && Number(bits) <= maxBits))) { + console.error(`[Auth] Ignoring invalid TRUSTED_PROXIES entry ${JSON.stringify(entry)}`); + continue; + } + if (bits === null) list.addAddress(addr, type); + else list.addSubnet(addr, Number(bits), type); + count++; + } + return { list, count }; +} + +let _trusted = null; +// Parsed on first use, after server.js has loaded .env. +function trustedProxies() { + if (!_trusted) _trusted = parseTrustedProxies(process.env.TRUSTED_PROXIES); + return _trusted; +} + +// The TCP peer that sent the request. Pulse is reached directly (no local +// reverse proxy), so this is NPM for SSO traffic, and can't be forged by a header. +function requestSource(req) { + let addr = (req.socket && req.socket.remoteAddress) || ''; + if (addr.startsWith('::ffff:') && net.isIPv4(addr.slice(7))) addr = addr.slice(7); + return addr; +} + +function isTrustedProxy(req, trusted = trustedProxies()) { + const addr = requestSource(req); + const type = net.isIPv4(addr) ? 'ipv4' : (net.isIPv6(addr) ? 'ipv6' : null); + return type !== null && trusted.list.check(addr, type); +} + +// The Remote-* identity headers are only real when NPM sent the request, because +// Authelia's forward auth overwrites them; any other LAN host could set them itself. +// Returns null when the request carries no trusted identity. Fails closed: with +// TRUSTED_PROXIES unset, nobody is trusted. +function ssoIdentity(req, trusted = trustedProxies()) { + const h = req.headers; + if (!isTrustedProxy(req, trusted)) { + if (IDENTITY_HEADERS.some(name => h[name])) { + console.warn(`[Auth] Ignored identity headers from untrusted source ${JSON.stringify(requestSource(req))}; ` + + 'only TRUSTED_PROXIES may send them'); + } + return null; + } + if (!h['remote-user']) return null; + return { + username: h['remote-user'], + name: h['remote-name'], + email: h['remote-email'], + groups: h['remote-groups'] ? h['remote-groups'].split(',').map(g => g.trim()) : [] + }; +} // Upsert the SSO user into the `users` table. Extracted verbatim from authenticateSSO. async function upsertUser(pool, headers) { @@ -31,17 +101,14 @@ async function upsertUser(pool, headers) { // but failures render a themed HTML page instead of JSON. function makeAuthenticatePage(pool) { return async function authenticatePage(req, res, next) { - const remoteUser = req.headers['remote-user']; - const remoteName = req.headers['remote-name']; - const remoteEmail = req.headers['remote-email']; - const remoteGroups = req.headers['remote-groups']; + const identity = ssoIdentity(req); - if (!remoteUser) { + if (!identity) { return renderError(req, res, 401, 'Not authenticated', 'Not authenticated — access via Authelia SSO (auth.lotusguild.org).'); } - const groups = remoteGroups ? remoteGroups.split(',').map(g => g.trim()) : []; + const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity; const hasAccess = groups.some(g => ALLOWED_GROUPS.includes(g)); if (!hasAccess) { @@ -67,4 +134,7 @@ function makeAuthenticatePage(pool) { }; } -module.exports = { upsertUser, makeAuthenticatePage, ALLOWED_GROUPS }; +module.exports = { + upsertUser, makeAuthenticatePage, ALLOWED_GROUPS, + parseTrustedProxies, trustedProxies, requestSource, isTrustedProxy, ssoIdentity +}; diff --git a/server.js b/server.js index 39d2f2c..16ac001 100644 --- a/server.js +++ b/server.js @@ -13,7 +13,7 @@ require('dotenv').config(); const { validateWebhookUrl, applyParams, evalCondition, calculateNextRun } = require('./lib/utils'); const { PAGES } = require('./lib/nav'); const { renderPage, renderError } = require('./lib/render'); -const { upsertUser, makeAuthenticatePage } = require('./lib/pageauth'); +const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies } = require('./lib/pageauth'); const app = express(); const server = http.createServer(app); @@ -676,21 +676,19 @@ async function fireWebhook(executionId, status) { // Authelia SSO Middleware async function authenticateSSO(req, res, next) { - // Check for Authelia headers - const remoteUser = req.headers['remote-user']; - const remoteName = req.headers['remote-name']; - const remoteEmail = req.headers['remote-email']; - const remoteGroups = req.headers['remote-groups']; + // Authelia headers, only honoured from TRUSTED_PROXIES (see lib/pageauth.js) + const identity = ssoIdentity(req); - if (!remoteUser) { - return res.status(401).json({ + if (!identity) { + return res.status(401).json({ error: 'Not authenticated', message: 'Please access this service through auth.lotusguild.org' }); } + const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity; + // Check if user is in allowed groups (admin or employee) - const groups = remoteGroups ? remoteGroups.split(',').map(g => g.trim()) : []; const allowedGroups = ['admin', 'employee']; const hasAccess = groups.some(g => allowedGroups.includes(g)); @@ -1843,6 +1841,13 @@ initDatabase().then(() => { console.log(`PULSE Server running on http://${HOST}:${PORT}`); console.log(`Connected to MariaDB at ${process.env.DB_HOST}`); console.log(`Authentication: Authelia SSO`); + const trustedCount = trustedProxies().count; + if (trustedCount) { + console.log(`Trusted proxies for SSO headers: ${trustedCount}`); + } else { + console.warn('WARNING: TRUSTED_PROXIES is not set, so no SSO login can succeed. ' + + 'Set it to the reverse proxy address(es) that run Authelia forward auth.'); + } console.log(`Worker API Key configured: ${process.env.WORKER_API_KEY ? 'Yes' : 'No'}`); if (DEV_READONLY) { console.warn('************************************************************'); diff --git a/tests/pageauth.test.js b/tests/pageauth.test.js new file mode 100644 index 0000000..00ebe58 --- /dev/null +++ b/tests/pageauth.test.js @@ -0,0 +1,146 @@ +'use strict'; + +jest.mock('../lib/render', () => ({ + renderError: jest.fn((req, res, status) => res.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); + }); +});