Merge pull request 'Safer workflow conditions; Pulse is admin-only' (#60) from safe-conditions into main
CI / UI screenshots (before/after) (push) Skipped
CI / Lint (eslint) (push) Successful in 27s
CI / Security (npm audit) (push) Successful in 24s
CI / Integration (api) (push) Successful in 2m30s
CI / Scan (secrets, workflows, shell) (push) Successful in 1m26s
CI / UI (playwright) (push) Successful in 1m41s
CI / Test (jest) (push) Successful in 17m6s
CI / Deploy (push) Successful in 17s
CI / Deploy worker (push) Successful in 10s
CI / Notify (push) Successful in 5s
CI / UI screenshots (before/after) (push) Skipped
CI / Lint (eslint) (push) Successful in 27s
CI / Security (npm audit) (push) Successful in 24s
CI / Integration (api) (push) Successful in 2m30s
CI / Scan (secrets, workflows, shell) (push) Successful in 1m26s
CI / UI (playwright) (push) Successful in 1m41s
CI / Test (jest) (push) Successful in 17m6s
CI / Deploy (push) Successful in 17s
CI / Deploy worker (push) Successful in 10s
CI / Notify (push) Successful in 5s
This commit was merged in pull request #60.
This commit is contained in:
commit
e6dbb2869b
10 files changed
+453
-20
No files matched your search
@@ -452,7 +452,7 @@ startup. Invalid entries are logged and skipped. Worker and Gandalf API-key rout
|
|||||||
### WebSocket authentication
|
### WebSocket authentication
|
||||||
|
|
||||||
Every WebSocket upgrade is authenticated. A browser connection must come through a trusted proxy
|
Every WebSocket upgrade is authenticated. A browser connection must come through a trusted proxy
|
||||||
(see above) with an Authelia identity in the `admin` or `employee` group, and only those
|
(see above) with an Authelia identity in the `admin` group (Pulse is admin-only), and only those
|
||||||
connections receive the live event feed. A worker authenticates with
|
connections receive the live event feed. A worker authenticates with
|
||||||
`Authorization: Bearer <WORKER_API_KEY>` at the handshake, and also sends the key in its
|
`Authorization: Bearer <WORKER_API_KEY>` at the handshake, and also sends the key in its
|
||||||
`worker_connect` message. A wrong key is always refused. Only a connection that identified as a
|
`worker_connect` message. A wrong key is always refused. Only a connection that identified as a
|
||||||
|
|||||||
@@ -0,0 +1,245 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// Safe evaluator for workflow conditions (step.condition and route `if`).
|
||||||
|
//
|
||||||
|
// Conditions are written in a small JavaScript-like expression language:
|
||||||
|
// (state.carrier||'1') === '0' && parseInt(state.crc_errors||'0') > 10
|
||||||
|
// params.switch_ip && params.switch_ip.trim() !== ''
|
||||||
|
// They are parsed into a tree and interpreted here; nothing is ever handed to a
|
||||||
|
// JavaScript engine, so a condition can only read the workflow's own data. It can't
|
||||||
|
// reach globals, prototypes or the server process.
|
||||||
|
//
|
||||||
|
// Supported: string, number, boolean, null and undefined literals; the names state,
|
||||||
|
// params and promptResponse; member access by name (own data properties of plain
|
||||||
|
// objects only, never __proto__, constructor or prototype); the calls parseInt,
|
||||||
|
// parseFloat, Number, String and Boolean; the string methods trim, toLowerCase,
|
||||||
|
// toUpperCase, includes, startsWith and endsWith; and the operators
|
||||||
|
// || && ! === !== == != < <= > >= + - * / % with JavaScript semantics, plus parentheses.
|
||||||
|
|
||||||
|
const FUNCTIONS = {
|
||||||
|
parseInt: (v, radix) => parseInt(v, radix),
|
||||||
|
parseFloat: v => parseFloat(v),
|
||||||
|
Number: v => Number(v),
|
||||||
|
String: v => String(v),
|
||||||
|
Boolean: v => Boolean(v),
|
||||||
|
};
|
||||||
|
const STRING_METHODS = new Set(['trim', 'toLowerCase', 'toUpperCase', 'includes', 'startsWith', 'endsWith']);
|
||||||
|
const FORBIDDEN_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
|
||||||
|
const MAX_LENGTH = 2000;
|
||||||
|
const MAX_DEPTH = 50;
|
||||||
|
|
||||||
|
class ConditionError extends Error {}
|
||||||
|
|
||||||
|
function tokenize(src) {
|
||||||
|
const tokens = [];
|
||||||
|
let i = 0;
|
||||||
|
const two = ['===', '!==', '==', '!=', '<=', '>=', '&&', '||'];
|
||||||
|
while (i < src.length) {
|
||||||
|
const c = src[i];
|
||||||
|
if (/\s/.test(c)) { i++; continue; }
|
||||||
|
if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(src[i + 1] || ''))) {
|
||||||
|
const m = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(src.slice(i));
|
||||||
|
tokens.push({ t: 'num', v: Number(m[0]) });
|
||||||
|
i += m[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c === '\'' || c === '"') {
|
||||||
|
let j = i + 1;
|
||||||
|
let s = '';
|
||||||
|
while (j < src.length && src[j] !== c) {
|
||||||
|
if (src[j] === '\\') {
|
||||||
|
const n = src[j + 1];
|
||||||
|
s += n === 'n' ? '\n' : n === 't' ? '\t' : n;
|
||||||
|
j += 2;
|
||||||
|
} else {
|
||||||
|
s += src[j++];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (j >= src.length) throw new ConditionError('unterminated string');
|
||||||
|
tokens.push({ t: 'str', v: s });
|
||||||
|
i = j + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (/[A-Za-z_$]/.test(c)) {
|
||||||
|
const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(src.slice(i));
|
||||||
|
tokens.push({ t: 'id', v: m[0] });
|
||||||
|
i += m[0].length;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const op = [...two].sort((a, b) => b.length - a.length).find(o => src.startsWith(o, i));
|
||||||
|
if (op) { tokens.push({ t: 'op', v: op }); i += op.length; continue; }
|
||||||
|
if ('!<>+-*/%().,'.includes(c)) { tokens.push({ t: 'op', v: c }); i++; continue; }
|
||||||
|
throw new ConditionError(`unexpected character ${JSON.stringify(c)}`);
|
||||||
|
}
|
||||||
|
tokens.push({ t: 'end' });
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Precedence climbing, lowest first.
|
||||||
|
const BINARY = [
|
||||||
|
['||'], ['&&'], ['===', '!==', '==', '!='], ['<', '<=', '>', '>='], ['+', '-'], ['*', '/', '%'],
|
||||||
|
];
|
||||||
|
|
||||||
|
function parse(src) {
|
||||||
|
if (typeof src !== 'string') throw new ConditionError('condition must be a string');
|
||||||
|
if (src.length > MAX_LENGTH) throw new ConditionError('condition is too long');
|
||||||
|
const tokens = tokenize(src);
|
||||||
|
let pos = 0;
|
||||||
|
const peek = () => tokens[pos];
|
||||||
|
const isOp = v => peek().t === 'op' && peek().v === v;
|
||||||
|
const expect = v => {
|
||||||
|
if (!isOp(v)) throw new ConditionError(`expected ${v}`);
|
||||||
|
pos++;
|
||||||
|
};
|
||||||
|
|
||||||
|
function binary(level, depth) {
|
||||||
|
if (depth > MAX_DEPTH) throw new ConditionError('condition is nested too deeply');
|
||||||
|
if (level === BINARY.length) return unary(depth);
|
||||||
|
let left = binary(level + 1, depth + 1);
|
||||||
|
while (peek().t === 'op' && BINARY[level].includes(peek().v)) {
|
||||||
|
const op = tokens[pos++].v;
|
||||||
|
left = { k: 'bin', op, left, right: binary(level + 1, depth + 1) };
|
||||||
|
}
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
function unary(depth) {
|
||||||
|
if (depth > MAX_DEPTH) throw new ConditionError('condition is nested too deeply');
|
||||||
|
if (isOp('!') || isOp('-') || isOp('+')) {
|
||||||
|
const op = tokens[pos++].v;
|
||||||
|
return { k: 'un', op, arg: unary(depth + 1) };
|
||||||
|
}
|
||||||
|
return postfix(depth);
|
||||||
|
}
|
||||||
|
|
||||||
|
function args(depth) {
|
||||||
|
expect('(');
|
||||||
|
const list = [];
|
||||||
|
if (!isOp(')')) {
|
||||||
|
list.push(binary(0, depth + 1));
|
||||||
|
while (isOp(',')) { pos++; list.push(binary(0, depth + 1)); }
|
||||||
|
}
|
||||||
|
expect(')');
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
function postfix(depth) {
|
||||||
|
let node = primary(depth);
|
||||||
|
for (;;) {
|
||||||
|
if (isOp('.')) {
|
||||||
|
pos++;
|
||||||
|
const name = peek();
|
||||||
|
if (name.t !== 'id') throw new ConditionError('expected a property name after "."');
|
||||||
|
pos++;
|
||||||
|
if (FORBIDDEN_NAMES.has(name.v)) throw new ConditionError(`"${name.v}" is not allowed`);
|
||||||
|
if (isOp('(')) {
|
||||||
|
if (!STRING_METHODS.has(name.v)) throw new ConditionError(`method "${name.v}" is not allowed`);
|
||||||
|
node = { k: 'method', obj: node, name: name.v, args: args(depth) };
|
||||||
|
} else {
|
||||||
|
node = { k: 'member', obj: node, name: name.v };
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function primary(depth) {
|
||||||
|
const tok = peek();
|
||||||
|
if (tok.t === 'num' || tok.t === 'str') { pos++; return { k: 'lit', v: tok.v }; }
|
||||||
|
if (tok.t === 'op' && tok.v === '(') {
|
||||||
|
pos++;
|
||||||
|
const inner = binary(0, depth + 1);
|
||||||
|
expect(')');
|
||||||
|
return inner;
|
||||||
|
}
|
||||||
|
if (tok.t === 'id') {
|
||||||
|
pos++;
|
||||||
|
switch (tok.v) {
|
||||||
|
case 'true': return { k: 'lit', v: true };
|
||||||
|
case 'false': return { k: 'lit', v: false };
|
||||||
|
case 'null': return { k: 'lit', v: null };
|
||||||
|
case 'undefined': return { k: 'lit', v: undefined };
|
||||||
|
case 'state': case 'params': case 'promptResponse':
|
||||||
|
return { k: 'var', name: tok.v };
|
||||||
|
}
|
||||||
|
if (Object.prototype.hasOwnProperty.call(FUNCTIONS, tok.v) && isOp('(')) {
|
||||||
|
return { k: 'call', name: tok.v, args: args(depth) };
|
||||||
|
}
|
||||||
|
throw new ConditionError(`unknown name "${tok.v}"`);
|
||||||
|
}
|
||||||
|
throw new ConditionError(tok.t === 'end' ? 'unexpected end of condition' : `unexpected "${tok.v}"`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const tree = binary(0, 0);
|
||||||
|
if (peek().t !== 'end') throw new ConditionError(`unexpected "${peek().v}"`);
|
||||||
|
return tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPlainObject(v) {
|
||||||
|
if (v === null || typeof v !== 'object') return false;
|
||||||
|
const proto = Object.getPrototypeOf(v);
|
||||||
|
return proto === Object.prototype || proto === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function evaluate(node, scope) {
|
||||||
|
switch (node.k) {
|
||||||
|
case 'lit': return node.v;
|
||||||
|
case 'var': return scope[node.name];
|
||||||
|
case 'member': {
|
||||||
|
const obj = evaluate(node.obj, scope);
|
||||||
|
// Only data the workflow put there: own properties of plain objects.
|
||||||
|
if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, node.name)) return obj[node.name];
|
||||||
|
if (typeof obj === 'string' && node.name === 'length') return obj.length;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
case 'method': {
|
||||||
|
const obj = evaluate(node.obj, scope);
|
||||||
|
if (typeof obj !== 'string') throw new ConditionError(`.${node.name}() needs a string`);
|
||||||
|
const a = node.args.map(x => evaluate(x, scope));
|
||||||
|
return String.prototype[node.name].apply(obj, a);
|
||||||
|
}
|
||||||
|
case 'call': return FUNCTIONS[node.name](...node.args.map(x => evaluate(x, scope)));
|
||||||
|
case 'un': {
|
||||||
|
const v = evaluate(node.arg, scope);
|
||||||
|
return node.op === '!' ? !v : node.op === '-' ? -v : +v;
|
||||||
|
}
|
||||||
|
case 'bin': {
|
||||||
|
if (node.op === '||') return evaluate(node.left, scope) || evaluate(node.right, scope);
|
||||||
|
if (node.op === '&&') return evaluate(node.left, scope) && evaluate(node.right, scope);
|
||||||
|
const l = evaluate(node.left, scope);
|
||||||
|
const r = evaluate(node.right, scope);
|
||||||
|
switch (node.op) {
|
||||||
|
case '===': return l === r;
|
||||||
|
case '!==': return l !== r;
|
||||||
|
case '==': return l == r; // eslint-disable-line eqeqeq -- the language supports loose equality
|
||||||
|
case '!=': return l != r; // eslint-disable-line eqeqeq
|
||||||
|
case '<': return l < r;
|
||||||
|
case '<=': return l <= r;
|
||||||
|
case '>': return l > r;
|
||||||
|
case '>=': return l >= r;
|
||||||
|
case '+': return l + r;
|
||||||
|
case '-': return l - r;
|
||||||
|
case '*': return l * r;
|
||||||
|
case '/': return l / r;
|
||||||
|
case '%': return l % r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new ConditionError('invalid condition');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Throws ConditionError when the condition can't be parsed (used to validate on save).
|
||||||
|
function checkCondition(src) {
|
||||||
|
parse(src);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluates a condition to a boolean. Values in state and params are the workflow's
|
||||||
|
// own data; anything that isn't a plain object is treated as empty.
|
||||||
|
function evaluateCondition(src, state, params) {
|
||||||
|
const s = isPlainObject(state) ? state : {};
|
||||||
|
const p = isPlainObject(params) ? params : {};
|
||||||
|
return !!evaluate(parse(src), { state: s, params: p, promptResponse: s.promptResponse });
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { evaluateCondition, checkCondition, ConditionError };
|
||||||
+3
-2
@@ -5,7 +5,8 @@ const crypto = require('crypto');
|
|||||||
const net = require('net');
|
const net = require('net');
|
||||||
const { renderError } = require('./render');
|
const { renderError } = require('./render');
|
||||||
|
|
||||||
const ALLOWED_GROUPS = ['admin', 'employee'];
|
// 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'];
|
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
|
// Parse TRUSTED_PROXIES ("a.b.c.d, a.b.c.0/24, ...") into a BlockList of the
|
||||||
@@ -113,7 +114,7 @@ function makeAuthenticatePage(pool) {
|
|||||||
|
|
||||||
if (!hasAccess) {
|
if (!hasAccess) {
|
||||||
return renderError(req, res, 403, 'Access denied',
|
return renderError(req, res, 403, 'Access denied',
|
||||||
'You must be in the admin or employee group to use this service.');
|
'Pulse is limited to the admin group.');
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
+31
-6
@@ -1,4 +1,5 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
const { evaluateCondition, checkCondition } = require('./condition');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate a webhook URL.
|
* Validate a webhook URL.
|
||||||
@@ -43,20 +44,44 @@ function applyParams(command, params) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Evaluate a condition expression safely using vm.runInNewContext.
|
* Evaluate a workflow condition with the safe interpreter in lib/condition.js (no vm,
|
||||||
* Returns boolean (false on error).
|
* no JavaScript engine). Returns a boolean; a condition that can't be parsed or
|
||||||
|
* evaluated counts as false.
|
||||||
*/
|
*/
|
||||||
function evalCondition(condition, state, params) {
|
function evalCondition(condition, state, params) {
|
||||||
const vm = require('vm');
|
|
||||||
try {
|
try {
|
||||||
const context = vm.createContext({ state, params, promptResponse: state.promptResponse });
|
return evaluateCondition(condition, state, params);
|
||||||
return !!vm.runInNewContext(condition, context, { timeout: 100 });
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} (condition: ${condition})`);
|
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} (condition: ${condition})`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every condition in a workflow definition that doesn't parse, as
|
||||||
|
* [{ step, condition, error }]. Used to reject bad definitions when they are saved.
|
||||||
|
*/
|
||||||
|
function conditionErrors(definition) {
|
||||||
|
const problems = [];
|
||||||
|
let def = definition;
|
||||||
|
if (typeof def === 'string') {
|
||||||
|
try { def = JSON.parse(def); } catch { return problems; } // JSON errors are reported elsewhere
|
||||||
|
}
|
||||||
|
const steps = (def && Array.isArray(def.steps)) ? def.steps : [];
|
||||||
|
steps.forEach((step, i) => {
|
||||||
|
const label = (step && (step.id || step.name)) || `step ${i + 1}`;
|
||||||
|
const exprs = [];
|
||||||
|
if (step && step.condition) exprs.push(step.condition);
|
||||||
|
for (const c of (step && Array.isArray(step.conditions) ? step.conditions : [])) {
|
||||||
|
if (c && !c.default && c.if) exprs.push(c.if);
|
||||||
|
}
|
||||||
|
for (const expr of exprs) {
|
||||||
|
try { checkCondition(expr); } catch (e) { problems.push({ step: label, condition: expr, error: e.message }); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return problems;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Calculate the next run date for a scheduled command.
|
* Calculate the next run date for a scheduled command.
|
||||||
*/
|
*/
|
||||||
@@ -87,4 +112,4 @@ function calculateNextRun(scheduleType, scheduleValue) {
|
|||||||
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { validateWebhookUrl, applyParams, evalCondition, calculateNextRun };
|
module.exports = { validateWebhookUrl, applyParams, evalCondition, conditionErrors, calculateNextRun };
|
||||||
@@ -8,10 +8,10 @@ const path = require('path');
|
|||||||
const fs = require('fs');
|
const fs = require('fs');
|
||||||
const helmet = require('helmet');
|
const helmet = require('helmet');
|
||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
const { validateWebhookUrl, applyParams, evalCondition, calculateNextRun } = require('./lib/utils');
|
const { validateWebhookUrl, applyParams, evalCondition, conditionErrors, calculateNextRun } = require('./lib/utils');
|
||||||
const { PAGES } = require('./lib/nav');
|
const { PAGES } = require('./lib/nav');
|
||||||
const { renderPage, renderError } = require('./lib/render');
|
const { renderPage, renderError } = require('./lib/render');
|
||||||
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies } = require('./lib/pageauth');
|
const { upsertUser, makeAuthenticatePage, ssoIdentity, trustedProxies, ALLOWED_GROUPS } = require('./lib/pageauth');
|
||||||
const { safeEqual, checkWorkerKey, workerAuthEnforced, classifyUpgrade, allowWorkerConnect } = require('./lib/wsauth');
|
const { safeEqual, checkWorkerKey, workerAuthEnforced, classifyUpgrade, allowWorkerConnect } = require('./lib/wsauth');
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -869,14 +869,13 @@ async function authenticateSSO(req, res, next) {
|
|||||||
|
|
||||||
const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity;
|
const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity;
|
||||||
|
|
||||||
// Check if user is in allowed groups (admin or employee)
|
// Only the groups in ALLOWED_GROUPS (lib/pageauth.js): admins.
|
||||||
const allowedGroups = ['admin', 'employee'];
|
const hasAccess = groups.some(g => ALLOWED_GROUPS.includes(g));
|
||||||
const hasAccess = groups.some(g => allowedGroups.includes(g));
|
|
||||||
|
|
||||||
if (!hasAccess) {
|
if (!hasAccess) {
|
||||||
return res.status(403).json({
|
return res.status(403).json({
|
||||||
error: 'Access denied',
|
error: 'Access denied',
|
||||||
message: 'You must be in admin or employee group'
|
message: 'Pulse is limited to the admin group'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1426,8 +1425,11 @@ app.get('/api/workflows/:id', authenticateSSO, async (req, res) => {
|
|||||||
|
|
||||||
app.post('/api/workflows', authenticateSSO, requireJSON, async (req, res) => {
|
app.post('/api/workflows', authenticateSSO, requireJSON, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
|
if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin only' });
|
||||||
const { name, description, definition, webhook_url } = req.body;
|
const { name, description, definition, webhook_url } = req.body;
|
||||||
if (!name || !definition) return res.status(400).json({ error: 'name and definition are required' });
|
if (!name || !definition) return res.status(400).json({ error: 'name and definition are required' });
|
||||||
|
const badConditions = conditionErrors(definition);
|
||||||
|
if (badConditions.length) return res.status(400).json({ error: 'Invalid condition', problems: badConditions });
|
||||||
|
|
||||||
const webhookCheck = validateWebhookUrl(webhook_url);
|
const webhookCheck = validateWebhookUrl(webhook_url);
|
||||||
if (!webhookCheck.ok) return res.status(400).json({ error: webhookCheck.reason });
|
if (!webhookCheck.ok) return res.status(400).json({ error: webhookCheck.reason });
|
||||||
@@ -1750,6 +1752,8 @@ app.put('/api/workflows/:id', authenticateSSO, requireJSON, async (req, res) =>
|
|||||||
} catch {
|
} catch {
|
||||||
return res.status(400).json({ error: 'Invalid JSON in definition' });
|
return res.status(400).json({ error: 'Invalid JSON in definition' });
|
||||||
}
|
}
|
||||||
|
const badConditions = conditionErrors(defObj);
|
||||||
|
if (badConditions.length) return res.status(400).json({ error: 'Invalid condition', problems: badConditions });
|
||||||
|
|
||||||
const [result] = await pool.query(
|
const [result] = await pool.query(
|
||||||
'UPDATE workflows SET name=?, description=?, definition=?, webhook_url=?, updated_at=NOW() WHERE id=?',
|
'UPDATE workflows SET name=?, description=?, definition=?, webhook_url=?, updated_at=NOW() WHERE id=?',
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const vm = require('vm');
|
||||||
|
const { evaluateCondition, checkCondition } = require('../lib/condition');
|
||||||
|
const { evalCondition, conditionErrors } = require('../lib/utils');
|
||||||
|
|
||||||
|
// Every condition used by the production workflows (2026-11-22).
|
||||||
|
const PRODUCTION = [
|
||||||
|
"params.switch_ip && params.switch_ip.trim() !== ''",
|
||||||
|
"(state.carrier||'x') === 'error'",
|
||||||
|
"(state.carrier||'1') === '0' && (state.has_dom||'no') === 'yes'",
|
||||||
|
"(state.carrier||'1') === '0'",
|
||||||
|
"parseInt(state.carrier_changes||'0') > 100 && (state.has_dom||'no') === 'yes'",
|
||||||
|
"parseInt(state.carrier_changes||'0') > 100",
|
||||||
|
"parseInt(state.carrier_changes||'0') > 20 && (state.has_dom||'no') === 'yes'",
|
||||||
|
"parseInt(state.carrier_changes||'0') > 20",
|
||||||
|
"(state.duplex||'full') === 'half'",
|
||||||
|
"parseInt(state.crc_errors||'0') > 10 || parseInt(state.frame_errors||'0') > 10",
|
||||||
|
"(state.has_dom||'no') === 'no'",
|
||||||
|
"state.sfp_rx_dbm === 'no_dom' || parseFloat(state.sfp_rx_dbm||'0') < -26",
|
||||||
|
"parseFloat(state.sfp_rx_dbm||'0') < -18",
|
||||||
|
"parseFloat(state.sfp_tx_dbm||'0') < -10",
|
||||||
|
"(state.carrier||'0') === '1' && (state.operstate||'down') === 'up'",
|
||||||
|
"state.sfp_rx_dbm && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -25",
|
||||||
|
"state.sfp_rx_dbm && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -18",
|
||||||
|
"(state.carrier||'0') === '0'",
|
||||||
|
"(state.duplex||'half') === 'full' && parseInt(state.crc_errors||'0') < 10",
|
||||||
|
"(state.duplex||'half') === 'full'",
|
||||||
|
"(state.has_dom||'no') === 'yes' && state.sfp_rx_dbm !== 'no_dom' && parseFloat(state.sfp_rx_dbm||'0') < -18",
|
||||||
|
"(state.has_dom||'no') === 'yes'",
|
||||||
|
"state.ring_rx_cur && state.ring_rx_max && state.ring_rx_cur !== 'unknown' && state.ring_rx_max !== 'unknown' && parseInt(state.ring_rx_cur||'0') < parseInt(state.ring_rx_max||'0') && parseInt(state.rx_dropped||'0') + parseInt(state.rx_missed||'0') > 0",
|
||||||
|
"parseInt(state.rx_dropped||'0') + parseInt(state.rx_missed||'0') > 100",
|
||||||
|
"(state.flowctl_rx||'on') === 'on' || (state.flowctl_tx||'on') === 'on'",
|
||||||
|
"state.speed && state.speed !== '-1' && parseInt(state.speed||'0') > 0 && (state.duplex||'full') === 'full'",
|
||||||
|
];
|
||||||
|
const VALUES = [undefined, '', '0', '1', '-1', '5', '11', '25', '150', '1000', '-12', '-20', '-27', 'error', 'yes', 'no',
|
||||||
|
'no_dom', 'full', 'half', 'on', 'off', 'up', 'down', 'unknown', ' 10.0.0.1 '];
|
||||||
|
|
||||||
|
// Small deterministic PRNG so failures are reproducible.
|
||||||
|
function rng(seed) { return () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648; }
|
||||||
|
|
||||||
|
describe('production conditions behave exactly as plain JavaScript did', () => {
|
||||||
|
for (const cond of PRODUCTION) {
|
||||||
|
test(cond, () => {
|
||||||
|
expect(() => checkCondition(cond)).not.toThrow();
|
||||||
|
const keys = [...new Set([...cond.matchAll(/(?:state|params)\.([a-z_]+)/g)].map(m => m[1]))];
|
||||||
|
const rand = rng(cond.length);
|
||||||
|
for (let i = 0; i < 150; i++) {
|
||||||
|
const state = {}; const params = {};
|
||||||
|
for (const k of keys) {
|
||||||
|
const v = VALUES[Math.floor(rand() * VALUES.length)];
|
||||||
|
if (v !== undefined) { state[k] = v; params[k] = v; }
|
||||||
|
}
|
||||||
|
// Reference: the old behaviour (vm), on trusted test input only.
|
||||||
|
const expected = !!vm.runInNewContext(cond, { state, params, parseInt, parseFloat });
|
||||||
|
expect(evaluateCondition(cond, state, params)).toBe(expected);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the language', () => {
|
||||||
|
const ev = (c, state = {}, params = {}) => evaluateCondition(c, state, params);
|
||||||
|
test('operators, precedence and literals', () => {
|
||||||
|
expect(ev('1 + 2 * 3 === 7')).toBe(true);
|
||||||
|
expect(ev('(1 + 2) * 3 === 9')).toBe(true);
|
||||||
|
expect(ev('!false && (null || "x") === "x"')).toBe(true);
|
||||||
|
expect(ev('-5 < -4 && 10 % 3 === 1 && 7 / 2 === 3.5')).toBe(true);
|
||||||
|
expect(ev("'a' + 1 === 'a1'")).toBe(true);
|
||||||
|
expect(ev('1 == "1" && 1 != 2')).toBe(true);
|
||||||
|
expect(ev("state.x === undefined", {})).toBe(true);
|
||||||
|
expect(ev("'it\\'s' === \"it's\"")).toBe(true);
|
||||||
|
});
|
||||||
|
test('functions and string methods', () => {
|
||||||
|
expect(ev("parseInt('42px') === 42 && parseFloat('-3.5') === -3.5")).toBe(true);
|
||||||
|
expect(ev("Number('7') === 7 && String(7) === '7' && Boolean('')=== false")).toBe(true);
|
||||||
|
expect(ev("state.h.toLowerCase().startsWith('web') && state.h.includes('01')", { h: 'WEB-01' })).toBe(true);
|
||||||
|
expect(ev("state.h.length === 6", { h: 'WEB-01' })).toBe(true);
|
||||||
|
expect(ev('promptResponse === "Yes"', { promptResponse: 'Yes' })).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('a condition can only read the workflow data', () => {
|
||||||
|
const rejected = [
|
||||||
|
'this',
|
||||||
|
'state.constructor',
|
||||||
|
'state.__proto__',
|
||||||
|
'params.prototype',
|
||||||
|
"state['x']",
|
||||||
|
'globalThis',
|
||||||
|
'process',
|
||||||
|
'require',
|
||||||
|
'Function',
|
||||||
|
'eval("1")',
|
||||||
|
'state.x = 1',
|
||||||
|
'(() => 1)()',
|
||||||
|
'`template`',
|
||||||
|
'1; 2',
|
||||||
|
"state.x.toString()",
|
||||||
|
"'a'.constructor",
|
||||||
|
"parseInt.call(null, '1')",
|
||||||
|
];
|
||||||
|
test.each(rejected)('%s is refused', cond => {
|
||||||
|
expect(() => checkCondition(cond)).toThrow();
|
||||||
|
expect(evalCondition(cond, {}, {})).toBe(false); // and the engine treats it as false
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inherited properties are invisible', () => {
|
||||||
|
expect(evaluateCondition('state.toString === undefined && state.hasOwnProperty === undefined', {}, {})).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('string methods only work on strings', () => {
|
||||||
|
expect(evalCondition('state.n.trim() === "1"', { n: 1 }, {})).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('huge or deeply nested input is refused', () => {
|
||||||
|
expect(() => checkCondition('1+'.repeat(2000) + '1')).toThrow();
|
||||||
|
expect(() => checkCondition('('.repeat(200) + '1' + ')'.repeat(200))).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('conditionErrors', () => {
|
||||||
|
test('lists every condition that does not parse, by step', () => {
|
||||||
|
const problems = conditionErrors({ steps: [
|
||||||
|
{ id: 'ok', type: 'execute', condition: "params.env === 'prod'" },
|
||||||
|
{ id: 'bad', type: 'execute', condition: 'state.constructor' },
|
||||||
|
{ id: 'route', type: 'route', conditions: [{ if: 'state.x ===' }, { default: true, goto: 'end' }] },
|
||||||
|
] });
|
||||||
|
expect(problems.map(p => p.step)).toEqual(['bad', 'route']);
|
||||||
|
});
|
||||||
|
test('accepts a JSON string definition and ignores malformed JSON', () => {
|
||||||
|
expect(conditionErrors(JSON.stringify({ steps: [{ condition: 'process' }] }))).toHaveLength(1);
|
||||||
|
expect(conditionErrors('{not json')).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -15,6 +15,13 @@ describe('HTTP', () => {
|
|||||||
expect((await api('GET', '/api/user', { headers: { ...SSO, 'Remote-Groups': 'guests' } })).status).toBe(403);
|
expect((await api('GET', '/api/user', { headers: { ...SSO, 'Remote-Groups': 'guests' } })).status).toBe(403);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Pulse is admin-only: employees are refused on the API and the pages', async () => {
|
||||||
|
const employee = { ...SSO, 'Remote-Groups': 'employee' };
|
||||||
|
expect((await api('GET', '/api/user', { headers: employee })).status).toBe(403);
|
||||||
|
expect((await api('GET', '/api/workers', { headers: employee })).status).toBe(403);
|
||||||
|
expect((await api('GET', '/', { headers: employee })).status).toBe(403);
|
||||||
|
});
|
||||||
|
|
||||||
test('worker heartbeats need the worker key', async () => {
|
test('worker heartbeats need the worker key', async () => {
|
||||||
const r = await api('POST', '/api/workers/heartbeat', {
|
const r = await api('POST', '/api/workers/heartbeat', {
|
||||||
headers: { 'X-API-Key': 'wrong' }, body: { worker_id: 'x', name: 'x' },
|
headers: { 'X-API-Key': 'wrong' }, body: { worker_id: 'x', name: 'x' },
|
||||||
|
|||||||
@@ -155,3 +155,17 @@ test.failing('a goto to a missing step fails the execution (#20)', async () => {
|
|||||||
const ex = await waitForExecution(id);
|
const ex = await waitForExecution(id);
|
||||||
expect(ex.status).toBe('failed');
|
expect(ex.status).toBe('failed');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a workflow whose condition does not parse is refused on save', async () => {
|
||||||
|
const create = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps: [
|
||||||
|
{ id: 'a', type: 'execute', command: 'true', targets: ['node-01'], condition: 'state.constructor' },
|
||||||
|
] } });
|
||||||
|
expect(create.status).toBe(400);
|
||||||
|
expect(create.json.problems[0]).toMatchObject({ step: 'a', condition: 'state.constructor' });
|
||||||
|
|
||||||
|
const id = await createWorkflow([{ id: 'ok', type: 'execute', command: 'true', targets: ['node-01'] }]);
|
||||||
|
const update = await sso('PUT', `/api/workflows/${id}`, { name: 'x', definition: { steps: [
|
||||||
|
{ id: 'r', type: 'route', conditions: [{ if: 'process', goto: 'end' }] },
|
||||||
|
] } });
|
||||||
|
expect(update.status).toBe(400);
|
||||||
|
});
|
||||||
@@ -52,14 +52,14 @@ test('multi-worker mode sends the command to every selected worker', async ({ pa
|
|||||||
test('Executions updates live when a command starts elsewhere', async ({ page, request }) => {
|
test('Executions updates live when a command starts elsewhere', async ({ page, request }) => {
|
||||||
await page.goto('/executions');
|
await page.goto('/executions');
|
||||||
await page.waitForLoadState('networkidle');
|
await page.waitForLoadState('networkidle');
|
||||||
const rows = page.locator('#ex-list-manual .ex-row');
|
|
||||||
const before = await rows.count();
|
|
||||||
|
|
||||||
// Start a command through the API, not this page: only the WebSocket can tell it.
|
// Start a command through the API, not this page: only the WebSocket can tell it.
|
||||||
const workers = await (await request.get('/api/workers')).json();
|
const workers = await (await request.get('/api/workers')).json();
|
||||||
const node3 = workers.find(w => w.name === 'node-03');
|
const node3 = workers.find(w => w.name === 'node-03');
|
||||||
const res = await request.post(`/api/workers/${node3.id}/command`, { data: { command: `echo ${token()}` } });
|
const res = await request.post(`/api/workers/${node3.id}/command`, { data: { command: `echo ${token()}` } });
|
||||||
expect(res.ok()).toBeTruthy();
|
expect(res.ok()).toBeTruthy();
|
||||||
|
const { execution_id: id } = await res.json();
|
||||||
|
|
||||||
await expect(rows).toHaveCount(before + 1);
|
// Its own row appears without a reload (by id, so it works however full the list is).
|
||||||
|
await expect(page.locator(`#ex-list-manual .ex-row[data-execution-id="${id}"]`)).toBeVisible();
|
||||||
});
|
});
|
||||||
@@ -47,7 +47,9 @@ describe('classifyUpgrade', () => {
|
|||||||
const opts = (enforce) => ({ trusted, workerKey: KEY, enforce });
|
const opts = (enforce) => ({ trusted, workerKey: KEY, enforce });
|
||||||
|
|
||||||
test('trusted proxy with an allowed group is a browser', () => {
|
test('trusted proxy with an allowed group is a browser', () => {
|
||||||
expect(classifyUpgrade(req(PROXY, sso('employee')), opts(true))).toBe('browser');
|
expect(classifyUpgrade(req(PROXY, sso('admin')), opts(true))).toBe('browser');
|
||||||
|
// Pulse is admin-only: employees are not browsers either.
|
||||||
|
expect(classifyUpgrade(req(PROXY, sso('employee')), opts(true))).toBe('reject');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('trusted proxy with a wrong group is not a browser', () => {
|
test('trusted proxy with a wrong group is not a browser', () => {
|
||||||
|
|||||||
Reference in new issue
Block a user