Safer workflow conditions; Pulse is admin-only
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
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
- 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>
This commit is contained in:
1 parent
f5a4333a8e
commit
040ad028c0
10 files changed
+453
-20
No files matched your search
@@ -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 { 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'];
|
||||
|
||||
// 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) {
|
||||
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 {
|
||||
|
||||
+31
-6
@@ -1,4 +1,5 @@
|
||||
'use strict';
|
||||
const { evaluateCondition, checkCondition } = require('./condition');
|
||||
|
||||
/**
|
||||
* Validate a webhook URL.
|
||||
@@ -43,20 +44,44 @@ function applyParams(command, params) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluate a condition expression safely using vm.runInNewContext.
|
||||
* Returns boolean (false on error).
|
||||
* Evaluate a workflow condition with the safe interpreter in lib/condition.js (no vm,
|
||||
* no JavaScript engine). Returns a boolean; a condition that can't be parsed or
|
||||
* evaluated counts as false.
|
||||
*/
|
||||
function evalCondition(condition, state, params) {
|
||||
const vm = require('vm');
|
||||
try {
|
||||
const context = vm.createContext({ state, params, promptResponse: state.promptResponse });
|
||||
return !!vm.runInNewContext(condition, context, { timeout: 100 });
|
||||
return evaluateCondition(condition, state, params);
|
||||
} catch (e) {
|
||||
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} (condition: ${condition})`);
|
||||
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.
|
||||
*/
|
||||
@@ -87,4 +112,4 @@ function calculateNextRun(scheduleType, scheduleValue) {
|
||||
throw new Error(`Unknown schedule type: ${scheduleType}`);
|
||||
}
|
||||
|
||||
module.exports = { validateWebhookUrl, applyParams, evalCondition, calculateNextRun };
|
||||
module.exports = { validateWebhookUrl, applyParams, evalCondition, conditionErrors, calculateNextRun };
|
||||
Reference in new issue
Block a user