Files
pulse/lib/pageauth.js
T
jaredandClaude Opus 5.5 040ad028c0
CI / UI screenshots (before/after) (push) Skipped
CI / Lint (eslint) (push) Successful in 25s
CI / Test (jest) (push) Successful in 25s
CI / Security (npm audit) (push) Successful in 21s
CI / Scan (secrets, workflows, shell) (push) Successful in 2m0s
CI / Integration (api) (push) Successful in 2m23s
CI / Lint (eslint) (pull_request) Successful in 24s
CI / Test (jest) (pull_request) Successful in 32s
CI / Security (npm audit) (pull_request) Successful in 39s
CI / UI (playwright) (push) Successful in 2m6s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Skipped
CI / Integration (api) (pull_request) Successful in 2m13s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 2m46s
CI / UI screenshots (before/after) (pull_request) Successful in 27s
CI / UI (playwright) (pull_request) Successful in 3m5s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
Safer workflow conditions; Pulse is admin-only
- Workflow conditions (step.condition and route `if`) are now parsed and
  interpreted by lib/condition.js instead of being run with Node's vm
  module. The language covers what workflows use: state/params lookups,
  parseInt/parseFloat/Number/String/Boolean, a few string methods, the
  usual operators with JavaScript semantics. Conditions can only read the
  workflow's own data. Every condition in the production workflows gives
  the same result as before (differential test, 150 random states each).
- Creating and updating a workflow rejects conditions that don't parse
  (400 with the step and the error).
- Creating a workflow requires admin, like editing already did.
- Only the admin group may use Pulse (pages, API and live WebSocket);
  employees get 403. Gandalf and workers use API keys and are unaffected.
- The live-update UI test finds its execution's row by id instead of
  counting rows (the list is capped at 50).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:05:42 -05:00

142 lines
5.0 KiB
JavaScript

// Authelia SSO helpers shared by the JSON API middleware (server.js authenticateSSO)
// and the HTML page middleware (authenticatePage).
const crypto = require('crypto');
const net = require('net');
const { renderError } = require('./render');
// Pulse is for admins only (it runs commands as root on every worker).
const ALLOWED_GROUPS = ['admin'];
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) {
const userId = crypto.randomUUID();
await pool.query(
`INSERT INTO users (id, username, display_name, email, groups, last_login)
VALUES (?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE
display_name=VALUES(display_name),
email=VALUES(email),
groups=VALUES(groups),
last_login=NOW()`,
[
userId,
headers['remote-user'],
headers['remote-name'],
headers['remote-email'],
headers['remote-groups']
]
);
}
// Express middleware factory for HTML page routes: same auth rules as the API,
// but failures render a themed HTML page instead of JSON.
function makeAuthenticatePage(pool) {
return async function authenticatePage(req, res, next) {
const identity = ssoIdentity(req);
if (!identity) {
return renderError(req, res, 401, 'Not authenticated',
'Not authenticated. Sign in through Authelia SSO (auth.lotusguild.org).');
}
const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity;
const hasAccess = groups.some(g => ALLOWED_GROUPS.includes(g));
if (!hasAccess) {
return renderError(req, res, 403, 'Access denied',
'Pulse is limited to the admin group.');
}
try {
await upsertUser(pool, req.headers);
} catch (error) {
console.error('Error updating user:', error);
}
req.user = {
username: remoteUser,
name: remoteName || remoteUser,
email: remoteEmail || '',
groups: groups,
isAdmin: groups.includes('admin')
};
next();
};
}
module.exports = {
upsertUser, makeAuthenticatePage, ALLOWED_GROUPS,
parseTrustedProxies, trustedProxies, requestSource, isTrustedProxy, ssoIdentity
};