Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d96028070 | ||
|
|
c890d5c078 | ||
|
|
72933df47a | ||
|
|
bf7e91cc57 | ||
|
|
0746c9cf73 | ||
|
|
db1f71aa4c | ||
|
|
e6dbb2869b | ||
|
|
040ad028c0 | ||
|
|
f5a4333a8e | ||
|
|
a34867af92 | ||
|
|
4459ce46cc | ||
|
|
783d6db160 |
No files matched your search
+14
-1
@@ -27,6 +27,7 @@ jobs:
|
|||||||
lint:
|
lint:
|
||||||
name: Lint (eslint)
|
name: Lint (eslint)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20 # a hung step fails instead of blocking main
|
||||||
container: node:20-bookworm
|
container: node:20-bookworm
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
@@ -46,6 +47,7 @@ jobs:
|
|||||||
test:
|
test:
|
||||||
name: Test (jest)
|
name: Test (jest)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
container: node:20-bookworm
|
container: node:20-bookworm
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
@@ -57,6 +59,7 @@ jobs:
|
|||||||
audit:
|
audit:
|
||||||
name: Security (npm audit)
|
name: Security (npm audit)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 10
|
||||||
container: node:20-bookworm
|
container: node:20-bookworm
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
@@ -85,6 +88,7 @@ jobs:
|
|||||||
integration:
|
integration:
|
||||||
name: Integration (api)
|
name: Integration (api)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 25
|
||||||
container: node:20-bookworm # the server and workers on production's Node
|
container: node:20-bookworm # the server and workers on production's Node
|
||||||
env:
|
env:
|
||||||
DB_HOST: 127.0.0.1
|
DB_HOST: 127.0.0.1
|
||||||
@@ -109,6 +113,7 @@ jobs:
|
|||||||
scan:
|
scan:
|
||||||
name: Scan (secrets, workflows, shell)
|
name: Scan (secrets, workflows, shell)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
container: node:20-bookworm
|
container: node:20-bookworm
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
|
||||||
@@ -139,14 +144,18 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
apt-get install -y -qq --no-install-recommends python3-venv >/dev/null
|
apt-get install -y -qq --no-install-recommends python3-venv >/dev/null
|
||||||
python3 -m venv /tmp/semgrep && /tmp/semgrep/bin/pip install -q semgrep==1.184.0
|
python3 -m venv /tmp/semgrep && /tmp/semgrep/bin/pip install -q semgrep==1.184.0
|
||||||
|
# Pulse's own rules must still catch their test cases before they're trusted.
|
||||||
|
/tmp/semgrep/bin/semgrep --metrics=off --test --config .semgrep/pulse.yml .semgrep/pulse.js
|
||||||
/tmp/semgrep/bin/semgrep scan --metrics=off --error \
|
/tmp/semgrep/bin/semgrep scan --metrics=off --error \
|
||||||
|
--config .semgrep/pulse.yml \
|
||||||
--config p/javascript --config p/nodejs --config p/expressjs \
|
--config p/javascript --config p/nodejs --config p/expressjs \
|
||||||
--config p/secrets --config p/security-audit \
|
--config p/secrets --config p/security-audit \
|
||||||
--exclude public/web_template --exclude node_modules
|
--exclude public/web_template --exclude node_modules --exclude .semgrep/pulse.js
|
||||||
|
|
||||||
ui:
|
ui:
|
||||||
name: UI (playwright)
|
name: UI (playwright)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
# Official image with Chromium and its system libraries; its version must match
|
# Official image with Chromium and its system libraries; its version must match
|
||||||
# @playwright/test in package.json.
|
# @playwright/test in package.json.
|
||||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||||
@@ -182,6 +191,7 @@ jobs:
|
|||||||
ui-screenshots:
|
ui-screenshots:
|
||||||
name: UI screenshots (before/after)
|
name: UI screenshots (before/after)
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
if: github.event_name == 'pull_request'
|
if: github.event_name == 'pull_request'
|
||||||
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
container: mcr.microsoft.com/playwright:v1.64.1-noble
|
||||||
env:
|
env:
|
||||||
@@ -231,6 +241,7 @@ jobs:
|
|||||||
deploy:
|
deploy:
|
||||||
name: Deploy
|
name: Deploy
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
needs: [lint, test, audit, scan, integration, ui]
|
needs: [lint, test, audit, scan, integration, ui]
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
# Never run two deploys at once; queue instead of cancelling a deploy mid-way.
|
# Never run two deploys at once; queue instead of cancelling a deploy mid-way.
|
||||||
@@ -290,6 +301,7 @@ jobs:
|
|||||||
deploy-worker:
|
deploy-worker:
|
||||||
name: Deploy worker
|
name: Deploy worker
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 15
|
||||||
container: node:20-bookworm
|
container: node:20-bookworm
|
||||||
needs: [deploy] # the server first: it must understand anything new the worker sends
|
needs: [deploy] # the server first: it must understand anything new the worker sends
|
||||||
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
@@ -356,6 +368,7 @@ jobs:
|
|||||||
notify:
|
notify:
|
||||||
name: Notify
|
name: Notify
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 5
|
||||||
needs: [lint, test, audit, scan, integration, ui, deploy, deploy-worker]
|
needs: [lint, test, audit, scan, integration, ui, deploy, deploy-worker]
|
||||||
# Alert on any failure on main or in the weekly audit, and on every deploy outcome.
|
# Alert on any failure on main or in the weekly audit, and on every deploy outcome.
|
||||||
if: >-
|
if: >-
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/* Test cases for .semgrep/pulse.yml (semgrep --test .semgrep). Not loaded by Pulse. */
|
||||||
|
/* eslint-disable */
|
||||||
|
|
||||||
|
function render(el, w, rows, keep) {
|
||||||
|
// ruleid: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = '<b>' + w.name + '</b>';
|
||||||
|
// ruleid: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = rows.map(r => '<td>' + r.host + '</td>').join('');
|
||||||
|
// ruleid: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML += `<i>${w.note}</i>`;
|
||||||
|
// ok: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = '<b>' + esc(w.name) + '</b>';
|
||||||
|
// ok: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = '<b>' + Pulse.esc(w.name) + '</b>';
|
||||||
|
// ok: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = '<a href="/x?id=' + encodeURIComponent(w.id) + '">x</a>';
|
||||||
|
// ok: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = '<span class="' + Pulse.fmt.status(w.status) + '">' + (w.status === 'online' ? 'on' : 'off') + '</span>';
|
||||||
|
// ok: pulse-innerhtml-unescaped
|
||||||
|
el.innerHTML = rows.map(r => (keep.has(r.id) ? 'x' : '') + esc(r.name)).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function server() {
|
||||||
|
// ruleid: pulse-no-shell-in-server
|
||||||
|
require('child_process').execSync('ls ' + dir);
|
||||||
|
// ok: pulse-no-shell-in-server
|
||||||
|
require('child_process').execFileSync('git', ['rev-parse', 'HEAD']);
|
||||||
|
// ruleid: pulse-no-vm
|
||||||
|
const vm = require('vm');
|
||||||
|
// ruleid: pulse-no-vm
|
||||||
|
return eval(input);
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Pulse's own semgrep rules, run by the Scan job. Test cases: .semgrep/pulse.js
|
||||||
|
# (semgrep --test --config .semgrep/pulse.yml .semgrep/pulse.js).
|
||||||
|
# The innerHTML rule checks member accesses (w.name, r.host); a value first copied into
|
||||||
|
# a plain variable is not caught, so keep escaping at the point of insertion.
|
||||||
|
rules:
|
||||||
|
- id: pulse-no-vm
|
||||||
|
message: >-
|
||||||
|
Node's vm module is not a sandbox: code it runs can reach the server process.
|
||||||
|
Workflow conditions go through lib/condition.js; don't evaluate user input with vm.
|
||||||
|
severity: ERROR
|
||||||
|
languages: [javascript]
|
||||||
|
paths:
|
||||||
|
exclude: [tests/]
|
||||||
|
pattern-either:
|
||||||
|
- pattern: require('vm')
|
||||||
|
- pattern: new Function(...)
|
||||||
|
- pattern: eval(...)
|
||||||
|
|
||||||
|
- id: pulse-no-shell-in-server
|
||||||
|
message: >-
|
||||||
|
The server must not run shell commands: use execFile/execFileSync with an argument
|
||||||
|
list. (Running commands is the worker's job, over the authenticated WebSocket.)
|
||||||
|
severity: ERROR
|
||||||
|
languages: [javascript]
|
||||||
|
paths:
|
||||||
|
include: [server.js, lib/]
|
||||||
|
pattern-either:
|
||||||
|
- pattern: require('child_process').exec(...)
|
||||||
|
- pattern: require('child_process').execSync(...)
|
||||||
|
- pattern: "require('child_process').spawn(..., {..., shell: true, ...})"
|
||||||
|
- pattern: |
|
||||||
|
const { ..., exec, ... } = require('child_process');
|
||||||
|
- pattern: |
|
||||||
|
const { ..., execSync, ... } = require('child_process');
|
||||||
|
|
||||||
|
- id: pulse-innerhtml-unescaped
|
||||||
|
message: >-
|
||||||
|
Value inserted into innerHTML without escaping. Wrap it in esc() / Pulse.esc(), or
|
||||||
|
build the element with textContent.
|
||||||
|
severity: ERROR
|
||||||
|
languages: [javascript]
|
||||||
|
paths:
|
||||||
|
include: [public/assets/]
|
||||||
|
patterns:
|
||||||
|
- pattern-either:
|
||||||
|
- pattern-inside: $EL.innerHTML = $RHS
|
||||||
|
- pattern-inside: $EL.innerHTML += $RHS
|
||||||
|
- pattern: $OBJ.$PROP
|
||||||
|
- pattern-not: $X.innerHTML
|
||||||
|
- pattern-not-inside: esc(...)
|
||||||
|
- pattern-not-inside: $NS.esc(...)
|
||||||
|
- pattern-not-inside: escHtml(...)
|
||||||
|
- pattern-not-inside: $NS.escHtml(...)
|
||||||
|
- pattern-not-inside: encodeURIComponent(...)
|
||||||
|
- pattern-not-inside: String(...)
|
||||||
|
# The member as a method name (rows.map(...), Pulse.fmt.status(...)): not a value.
|
||||||
|
- pattern-not-inside: $OBJ.$PROP(...)
|
||||||
|
# Inputs to helpers whose result is not the raw value: Set.has() gives a boolean,
|
||||||
|
# the Pulse.fmt formatters give class names or formatted dates.
|
||||||
|
- pattern-not-inside: $SET.has(...)
|
||||||
|
- pattern-not-inside: $NS.fmt.$FN(...)
|
||||||
|
- pattern-not-inside: fmt.$FN(...)
|
||||||
|
# Values only compared (to pick a class or a symbol) are not inserted.
|
||||||
|
- pattern-not-inside: $A === $B
|
||||||
|
- pattern-not-inside: $A !== $B
|
||||||
|
- pattern-not-inside: $A == $B
|
||||||
|
- pattern-not-inside: $A != $B
|
||||||
@@ -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
|
||||||
@@ -589,7 +589,7 @@ Everything runs from `.gitea/workflows/ci.yml`:
|
|||||||
| `Lint (eslint)` | `npm run lint` (errors on bugs-in-waiting such as `==`, shadowed or unused variables and `eval`; no warnings allowed), plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR |
|
| `Lint (eslint)` | `npm run lint` (errors on bugs-in-waiting such as `==`, shadowed or unused variables and `eval`; no warnings allowed), plus a check that fails on em or en dashes anywhere in the repo, including the vendored design system | Every push and PR |
|
||||||
| `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR |
|
| `Test (jest)` | `npm test`: unit tests for `lib/` and the worker, and the deploy-script sandbox tests. Fails if coverage drops below the floors in `package.json` (`lib/` 90% lines, `worker/` 40%) | Every push and PR |
|
||||||
| `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) |
|
| `Security (npm audit)` | `npm audit --audit-level=high`, plus a CycloneDX SBOM of production dependencies (kept 90 days as the `sbom-cyclonedx` artifact of each `main` build) | Every push and PR, and weekly (Monday 06:00) |
|
||||||
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
| `Scan (secrets, workflows, shell)` | gitleaks over the whole git history, actionlint on the workflow files (with shellcheck on their scripts), shellcheck on every `*.sh`, a check that `public/web_template` is byte-identical to upstream at the commit in its `VERSION`, and semgrep (JavaScript, Node.js, Express, secrets and security-audit rule packs, plus Pulse's own rules in `.semgrep/pulse.yml`: no `vm`/`eval`, no shell commands in the server, no unescaped values in `innerHTML`; their test cases in `.semgrep/pulse.js` run first). Suppress a reviewed false positive on its line with `nosemgrep: <rule id>` and a comment saying why | Every push and PR |
|
||||||
| `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
| `Integration (api)` | Starts the real server and three workers on Node 20 against MariaDB, then runs `tests/integration/` over HTTP and WebSocket: the Gandalf API contract, HTTP and WebSocket auth, and execution reliability (worker crash, capacity, abort) | Every push and PR |
|
||||||
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
| `UI (playwright)` | Starts the real server and three workers against a MariaDB service container, then runs the Playwright tests in `tests/ui/` (desktop and phone) | Every push and PR |
|
||||||
| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests |
|
| `UI screenshots (before/after)` | On PRs that touch `public/`, `views/` or the render/nav code: runs the base branch and the PR side by side with the same seeded data and uploads a `ui-screenshots` artifact with one before/after image per page (desktop and phone). Pages that came out identical are listed in `unchanged.txt`. Not a required check; attach the relevant images to the PR for review | Pull requests |
|
||||||
@@ -608,6 +608,11 @@ use it: Gandalf's submit-and-poll contract (`/api/internal/command`, `/api/inter
|
|||||||
SSO and worker-key auth on HTTP and on the WebSocket upgrade, forged results from a browser socket,
|
SSO and worker-key auth on HTTP and on the WebSocket upgrade, forged results from a browser socket,
|
||||||
and that executions always finish (a worker killed mid-command, a worker at capacity, an abort
|
and that executions always finish (a worker killed mid-command, a worker at capacity, an abort
|
||||||
followed by a late result). Tests that need to kill or limit a worker start their own.
|
followed by a late result). Tests that need to kill or limit a worker start their own.
|
||||||
|
The workflow engine (execute, parse, route, prompt, params, dry run, loop detection, abort) and the
|
||||||
|
scheduler are covered too; the scheduler tests make a schedule due by setting `next_run` in the
|
||||||
|
database, and the stack ticks the scheduler every second (`PULSE_SCHEDULER_TICK_MS`). Known bugs are
|
||||||
|
written as `test.failing` with their issue number: when a fix lands, the test starts failing until
|
||||||
|
the marker is removed.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scripts/ci/ui-stack.sh start
|
DB_HOST=127.0.0.1 DB_PORT=3399 DB_USER=pulse DB_PASSWORD=... DB_NAME=pulse scripts/ci/ui-stack.sh start
|
||||||
@@ -713,12 +718,19 @@ and add a hook to `/etc/webhook/hooks.json`, with the same secret as the repo's
|
|||||||
{ "source": "payload", "name": "ts" }
|
{ "source": "payload", "name": "ts" }
|
||||||
],
|
],
|
||||||
"trigger-rule": {
|
"trigger-rule": {
|
||||||
"match": { "type": "payload-hmac-sha256", "secret": "<WORKER_WEBHOOK_SECRET>",
|
"and": [
|
||||||
"parameter": { "source": "header", "name": "X-Gitea-Signature" } }
|
{ "match": { "type": "payload-hmac-sha256", "secret": "<WORKER_WEBHOOK_SECRET>",
|
||||||
|
"parameter": { "source": "header", "name": "X-Gitea-Signature" } } },
|
||||||
|
{ "match": { "type": "ip-whitelist", "ip-range": "10.10.10.70/32" } }
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Both Pulse hooks (`pulse-deploy` on CT 122 and `pulse-worker-deploy` on CT 153) only accept requests
|
||||||
|
from the CI runner, 10.10.10.70, as well as requiring the signature. If the runner's address changes,
|
||||||
|
deploys fail in CI (the verify step times out) until the `ip-range` is updated on both hosts.
|
||||||
|
|
||||||
To add a worker host, install Node 20 and the worker as above, give it a `.env` with `WORKER_NAME`,
|
To add a worker host, install Node 20 and the worker as above, give it a `.env` with `WORKER_NAME`,
|
||||||
`PULSE_SERVER`, `PULSE_WS` and `WORKER_API_KEY`, and add its hook (one hook URL per host in the
|
`PULSE_SERVER`, `PULSE_WS` and `WORKER_API_KEY`, and add its hook (one hook URL per host in the
|
||||||
`Deploy worker` job).
|
`Deploy worker` job).
|
||||||
|
|||||||
@@ -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 };
|
||||||
@@ -26,6 +26,14 @@
|
|||||||
return meta.loadavg.map(l => Number(l).toFixed(2)).join(', ');
|
return meta.loadavg.map(l => Number(l).toFixed(2)).join(', ');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The commit the worker runs (#40): a short sha linked to the commit, or "unknown".
|
||||||
|
function versionHtml(meta) {
|
||||||
|
const v = meta && meta.version;
|
||||||
|
if (typeof v !== 'string' || !/^[0-9a-f]{40}$/.test(v)) return esc('unknown');
|
||||||
|
return '<a class="wk-version" href="https://code.lotusguild.org/LotusGuild/pulse/commit/' + esc(v) +
|
||||||
|
'" target="_blank" rel="noopener" title="' + esc(v) + '">' + esc(v.slice(0, 7)) + '</a>';
|
||||||
|
}
|
||||||
|
|
||||||
/* -------------------------------------------------------------------
|
/* -------------------------------------------------------------------
|
||||||
Card construction
|
Card construction
|
||||||
------------------------------------------------------------------- */
|
------------------------------------------------------------------- */
|
||||||
@@ -66,6 +74,8 @@
|
|||||||
'<div class="lt-kv-val" data-wk-uptime>' + esc(fmt.uptime(meta && meta.uptime)) + '</div>' +
|
'<div class="lt-kv-val" data-wk-uptime>' + esc(fmt.uptime(meta && meta.uptime)) + '</div>' +
|
||||||
'<div class="lt-kv-key">Active Tasks</div>' +
|
'<div class="lt-kv-key">Active Tasks</div>' +
|
||||||
'<div class="lt-kv-val" data-wk-tasks>' + esc((meta && meta.activeTasks || 0) + ' / ' + (meta && meta.maxConcurrentTasks || 0)) + '</div>' +
|
'<div class="lt-kv-val" data-wk-tasks>' + esc((meta && meta.activeTasks || 0) + ' / ' + (meta && meta.maxConcurrentTasks || 0)) + '</div>' +
|
||||||
|
'<div class="lt-kv-key">Version</div>' +
|
||||||
|
'<div class="lt-kv-val" data-wk-version>' + versionHtml(meta) + '</div>' +
|
||||||
'</div>' +
|
'</div>' +
|
||||||
footerHtml(worker)
|
footerHtml(worker)
|
||||||
);
|
);
|
||||||
@@ -132,6 +142,9 @@
|
|||||||
const tasks = card.querySelector('[data-wk-tasks]');
|
const tasks = card.querySelector('[data-wk-tasks]');
|
||||||
if (tasks) tasks.textContent = (meta && meta.activeTasks || 0) + ' / ' + (meta && meta.maxConcurrentTasks || 0);
|
if (tasks) tasks.textContent = (meta && meta.activeTasks || 0) + ' / ' + (meta && meta.maxConcurrentTasks || 0);
|
||||||
|
|
||||||
|
const version = card.querySelector('[data-wk-version]');
|
||||||
|
if (version) version.innerHTML = versionHtml(meta);
|
||||||
|
|
||||||
// Admin footer can appear/disappear if isAdmin changes mid-session (rare,
|
// Admin footer can appear/disappear if isAdmin changes mid-session (rare,
|
||||||
// but keep it correct rather than assuming it's static).
|
// but keep it correct rather than assuming it's static).
|
||||||
const hasFooter = !!card.querySelector('.lt-card-footer');
|
const hasFooter = !!card.querySelector('.lt-card-footer');
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export WORKER_API_KEY=ui-test-worker-key WORKER_AUTH_ENFORCE=1
|
|||||||
export GANDALF_API_KEY=ui-test-gandalf-key
|
export GANDALF_API_KEY=ui-test-gandalf-key
|
||||||
export SECRET_KEY=ui-test-secret EXECUTION_RETENTION_DAYS=30
|
export SECRET_KEY=ui-test-secret EXECUTION_RETENTION_DAYS=30
|
||||||
export PULSE_API_RATE_MAX=100000 PULSE_EXEC_RATE_MAX=100000 # one test client makes many requests
|
export PULSE_API_RATE_MAX=100000 PULSE_EXEC_RATE_MAX=100000 # one test client makes many requests
|
||||||
|
export PULSE_SCHEDULER_TICK_MS=1000 # scheduler tests shouldn't wait a minute
|
||||||
|
|
||||||
stop() {
|
stop() {
|
||||||
for f in "$RUN"/*.pid; do
|
for f in "$RUN"/*.pid; do
|
||||||
|
|||||||
@@ -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();
|
||||||
@@ -381,8 +381,9 @@ async function processScheduledCommands() {
|
|||||||
|
|
||||||
|
|
||||||
if (!DEV_READONLY) {
|
if (!DEV_READONLY) {
|
||||||
// Run scheduler every minute
|
// Run scheduler every minute (tests shorten it with PULSE_SCHEDULER_TICK_MS, minimum 1 s)
|
||||||
setInterval(processScheduledCommands, 60 * 1000);
|
const tick = parseInt(process.env.PULSE_SCHEDULER_TICK_MS, 10);
|
||||||
|
setInterval(processScheduledCommands, Number.isInteger(tick) && tick >= 1000 ? tick : 60 * 1000);
|
||||||
// Initial run on startup
|
// Initial run on startup
|
||||||
setTimeout(processScheduledCommands, 5000);
|
setTimeout(processScheduledCommands, 5000);
|
||||||
} else {
|
} else {
|
||||||
@@ -868,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'
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1425,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 });
|
||||||
@@ -1749,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' },
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// The scheduler (processScheduledCommands in server.js). The test stack ticks every
|
||||||
|
// second (PULSE_SCHEDULER_TICK_MS); a schedule is made due at once by setting its
|
||||||
|
// next_run in the database, the one place these tests reach past the API.
|
||||||
|
const mysql = require('mysql2/promise');
|
||||||
|
const { api, sso, SSO, waitFor, waitForExecution, workerByName, commandResult, startWorker, sleep } = require('./helpers');
|
||||||
|
|
||||||
|
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||||
|
let db;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
db = await mysql.createConnection({
|
||||||
|
host: process.env.DB_HOST || '127.0.0.1',
|
||||||
|
port: Number(process.env.DB_PORT || 3306),
|
||||||
|
user: process.env.DB_USER || 'pulse',
|
||||||
|
password: process.env.DB_PASSWORD || 'ci-only',
|
||||||
|
database: process.env.DB_NAME || 'pulse',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
afterAll(() => db && db.end());
|
||||||
|
|
||||||
|
async function createSchedule(fields) {
|
||||||
|
const r = await sso('POST', '/api/scheduled-commands', {
|
||||||
|
name: `int ${unique()}`, schedule_type: 'interval', schedule_value: '60', ...fields,
|
||||||
|
});
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
const makeDue = id => db.query('UPDATE scheduled_commands SET next_run = NOW() - INTERVAL 1 SECOND WHERE id = ?', [id]);
|
||||||
|
async function executionsOf(name) {
|
||||||
|
const [rows] = await db.query('SELECT id, status FROM executions WHERE started_by = ? ORDER BY started_at', [`scheduler:${name}`]);
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a due schedule runs its command on its worker and moves next_run forward', async () => {
|
||||||
|
const worker = await workerByName('node-02');
|
||||||
|
const name = `int ${unique()}`;
|
||||||
|
const created = await createSchedule({ name, command: 'echo scheduled-ok', worker_ids: [worker.id] });
|
||||||
|
expect(created.status).toBe(200);
|
||||||
|
await makeDue(created.json.id);
|
||||||
|
|
||||||
|
const [run] = await waitFor(async () => { const r = await executionsOf(name); return r.length ? r : null; },
|
||||||
|
{ what: 'the scheduled execution' });
|
||||||
|
const ex = await waitForExecution(run.id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(commandResult(ex).stdout.trim()).toBe('scheduled-ok');
|
||||||
|
|
||||||
|
const [[row]] = await db.query('SELECT next_run, last_run FROM scheduled_commands WHERE id = ?', [created.json.id]);
|
||||||
|
expect(row.last_run).not.toBeNull();
|
||||||
|
expect(new Date(row.next_run).getTime()).toBeGreaterThan(Date.now() + 50 * 60_000); // about 60 min ahead
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a disabled schedule does not run', async () => {
|
||||||
|
const worker = await workerByName('node-02');
|
||||||
|
const name = `int ${unique()}`;
|
||||||
|
const created = await createSchedule({ name, command: 'echo nope', worker_ids: [worker.id] });
|
||||||
|
const toggled = await sso('PUT', `/api/scheduled-commands/${created.json.id}/toggle`);
|
||||||
|
expect(toggled.json.enabled).toBe(false);
|
||||||
|
await makeDue(created.json.id);
|
||||||
|
await sleep(3500); // several scheduler ticks
|
||||||
|
expect(await executionsOf(name)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only admins can create schedules, and bad input is refused', async () => {
|
||||||
|
const worker = await workerByName('node-01');
|
||||||
|
const asEmployee = await api('POST', '/api/scheduled-commands', {
|
||||||
|
headers: { ...SSO, 'Remote-Groups': 'employee' },
|
||||||
|
body: { name: 'x', command: 'true', worker_ids: [worker.id], schedule_type: 'interval', schedule_value: '5' },
|
||||||
|
});
|
||||||
|
expect(asEmployee.status).toBe(403);
|
||||||
|
expect((await createSchedule({ command: 'true' })).status).toBe(400); // no workers
|
||||||
|
expect((await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_value: '-5' })).status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Known bug: calculateNextRun throws on a bad cron expression, and the route answers 500.
|
||||||
|
test.failing('an invalid cron expression is a 400, not a server error', async () => {
|
||||||
|
const worker = await workerByName('node-01');
|
||||||
|
const r = await createSchedule({ command: 'true', worker_ids: [worker.id], schedule_type: 'cron', schedule_value: 'not a cron' });
|
||||||
|
expect(r.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Known bug #9: a schedule whose worker is offline is skipped silently, leaving no trace.
|
||||||
|
test.failing('a schedule whose worker is offline records a failed run (#9)', async () => {
|
||||||
|
const workerName = `int-sched-${unique()}`;
|
||||||
|
const w = await startWorker(workerName);
|
||||||
|
const name = `int ${unique()}`;
|
||||||
|
try {
|
||||||
|
const created = await createSchedule({ name, command: 'echo unreachable', worker_ids: [w.id] });
|
||||||
|
w.child.kill('SIGKILL');
|
||||||
|
await waitFor(async () => (await workerByName(workerName))?.status === 'offline', { what: 'the worker to go offline' });
|
||||||
|
await makeDue(created.json.id);
|
||||||
|
await sleep(3500);
|
||||||
|
const runs = await executionsOf(name);
|
||||||
|
expect(runs).toHaveLength(1);
|
||||||
|
expect(runs[0].status).toBe('failed');
|
||||||
|
} finally { await w.stop(); }
|
||||||
|
});
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
// The workflow engine (executeWorkflowSteps in server.js), driven through the API
|
||||||
|
// with real workers. Known bugs are written as test.failing: they document today's
|
||||||
|
// behaviour and start failing (so the marker must be removed) once the bug is fixed.
|
||||||
|
const { sso, waitFor, waitForExecution, sleep } = require('./helpers');
|
||||||
|
|
||||||
|
const unique = () => `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
||||||
|
|
||||||
|
async function createWorkflow(steps, extra = {}) {
|
||||||
|
const r = await sso('POST', '/api/workflows', { name: `int ${unique()}`, definition: { steps, ...extra } });
|
||||||
|
expect(r.status).toBe(200);
|
||||||
|
return r.json.id;
|
||||||
|
}
|
||||||
|
async function start(workflowId, body = {}) {
|
||||||
|
const r = await sso('POST', '/api/executions', { workflow_id: workflowId, ...body });
|
||||||
|
expect(r.status).toBe(200);
|
||||||
|
return r.json.id;
|
||||||
|
}
|
||||||
|
const logs = (ex, action) => (ex.logs || []).filter(l => l.action === action);
|
||||||
|
const outputs = ex => logs(ex, 'command_result').map(l => (l.stdout || '').trim());
|
||||||
|
|
||||||
|
test('an execute step on all workers runs everywhere and completes', async () => {
|
||||||
|
const marker = `all-${unique()}`;
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'hello', name: 'Hello', type: 'execute', command: `echo ${marker}`, targets: ['all'] },
|
||||||
|
]));
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(outputs(ex).filter(o => o === marker)).toHaveLength(3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failing step fails the execution and stops the workflow', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'bad', type: 'execute', command: 'exit 3', targets: ['node-01'] },
|
||||||
|
{ id: 'never', type: 'execute', command: 'echo should-not-run', targets: ['node-01'] },
|
||||||
|
]));
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('failed');
|
||||||
|
expect(outputs(ex)).not.toContain('should-not-run');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parse reads KEY=VALUE output and route jumps on it', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'probe', type: 'execute', command: 'echo STATUS=degraded', targets: ['node-01'] },
|
||||||
|
{ id: 'parse', type: 'parse' },
|
||||||
|
{ id: 'decide', type: 'route', conditions: [
|
||||||
|
{ if: "state.status === 'degraded'", goto: 'fix', label: 'needs fixing' },
|
||||||
|
{ default: true, goto: 'end' },
|
||||||
|
] },
|
||||||
|
{ id: 'skipped', type: 'execute', command: 'echo not-me', targets: ['node-01'] },
|
||||||
|
{ id: 'fix', type: 'execute', command: 'echo fixed', targets: ['node-01'] },
|
||||||
|
]));
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(logs(ex, 'parse_complete')[0].parsed).toEqual({ status: 'degraded' });
|
||||||
|
expect(logs(ex, 'route_taken')[0]).toMatchObject({ goto: 'fix', label: 'needs fixing' });
|
||||||
|
expect(outputs(ex)).toContain('fixed');
|
||||||
|
expect(outputs(ex)).not.toContain('not-me');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a false condition skips the step', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'prod-only', type: 'execute', command: 'echo prod', targets: ['node-01'], condition: "params.env === 'prod'" },
|
||||||
|
{ id: 'always', type: 'execute', command: 'echo always', targets: ['node-01'] },
|
||||||
|
], { params: [{ name: 'env' }] }), { params: { env: 'staging' } });
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(logs(ex, 'step_skipped')).toHaveLength(1);
|
||||||
|
expect(outputs(ex)).toEqual(['always']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a prompt waits for an answer, rejects invalid options, and routes on the answer', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'ask', type: 'prompt', message: 'Restart?', options: ['Yes', 'No'], key: 'answer', routes: { No: 'end' } },
|
||||||
|
{ id: 'restart', type: 'execute', command: 'echo restarted', targets: ['node-02'] },
|
||||||
|
]));
|
||||||
|
await waitFor(async () => logs((await sso('GET', `/api/executions/${id}`)).json || {}, 'prompt').length > 0,
|
||||||
|
{ what: 'the prompt to be asked' });
|
||||||
|
|
||||||
|
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Maybe' })).status).toBe(400);
|
||||||
|
expect((await sso('POST', `/api/executions/${id}/respond`, { response: 'Yes' })).status).toBe(200);
|
||||||
|
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(logs(ex, 'prompt_response')[0]).toMatchObject({ response: 'Yes', responded_by: 'int.tester' });
|
||||||
|
expect(outputs(ex)).toEqual(['restarted']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('parameters are substituted, and unsafe values are refused', async () => {
|
||||||
|
const wf = await createWorkflow([
|
||||||
|
{ id: 'greet', type: 'execute', command: 'echo host={{host}}', targets: ['node-03'] },
|
||||||
|
], { params: [{ name: 'host', required: true }] });
|
||||||
|
|
||||||
|
expect((await sso('POST', '/api/executions', { workflow_id: wf })).status).toBe(400); // required
|
||||||
|
|
||||||
|
const ok = await waitForExecution(await start(wf, { params: { host: 'db-01.lan' } }));
|
||||||
|
expect(ok.status).toBe('completed');
|
||||||
|
expect(outputs(ok)).toEqual(['host=db-01.lan']);
|
||||||
|
|
||||||
|
const bad = await waitForExecution(await start(wf, { params: { host: 'x; reboot' } }));
|
||||||
|
expect(bad.status).toBe('failed');
|
||||||
|
expect(outputs(bad)).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a dry run logs the commands without running them', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'danger', type: 'execute', command: 'echo would-run', targets: ['all'] },
|
||||||
|
]), { dry_run: true });
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
expect(ex.status).toBe('completed');
|
||||||
|
expect(logs(ex, 'dry_run_skipped')).toHaveLength(1);
|
||||||
|
expect(logs(ex, 'command_result')).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an endless goto loop is detected and fails the execution', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'loop', type: 'route', conditions: [{ default: true, goto: 'loop' }] },
|
||||||
|
]));
|
||||||
|
const ex = await waitForExecution(id, { timeout: 60_000 });
|
||||||
|
expect(ex.status).toBe('failed');
|
||||||
|
expect(logs(ex, 'workflow_error')[0].error).toMatch(/Infinite loop/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an aborted execution stays failed', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'pause', type: 'wait', duration: 2 },
|
||||||
|
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||||
|
]));
|
||||||
|
await sleep(500);
|
||||||
|
expect((await sso('POST', `/api/executions/${id}/abort`)).status).toBe(200);
|
||||||
|
await sleep(4000);
|
||||||
|
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||||
|
expect(ex.status).toBe('failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Known bug #8: abort marks the execution failed but the engine keeps going.
|
||||||
|
test.failing('abort stops the workflow before its next step (#8)', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'pause', type: 'wait', duration: 2 },
|
||||||
|
{ id: 'after', type: 'execute', command: 'echo after-abort', targets: ['node-01'] },
|
||||||
|
]));
|
||||||
|
await sleep(500);
|
||||||
|
await sso('POST', `/api/executions/${id}/abort`);
|
||||||
|
await sleep(5000);
|
||||||
|
const ex = (await sso('GET', `/api/executions/${id}`)).json;
|
||||||
|
expect(logs(ex, 'step_started').map(l => l.step)).toEqual([1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Known bug #20: a goto to a step that doesn't exist ends as 'completed'.
|
||||||
|
test.failing('a goto to a missing step fails the execution (#20)', async () => {
|
||||||
|
const id = await start(await createWorkflow([
|
||||||
|
{ id: 'jump', type: 'route', conditions: [{ default: true, goto: 'no-such-step' }] },
|
||||||
|
]));
|
||||||
|
const ex = await waitForExecution(id);
|
||||||
|
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);
|
||||||
|
});
|
||||||
@@ -39,6 +39,17 @@ test('workers page lists each worker as online', async ({ page }) => {
|
|||||||
await expect(grid.getByText(/^online$/i)).toHaveCount(3);
|
await expect(grid.getByText(/^online$/i)).toHaveCount(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('workers page shows the commit each worker runs (#40)', async ({ page }) => {
|
||||||
|
const head = require('child_process').execFileSync('git', ['rev-parse', 'HEAD']).toString().trim();
|
||||||
|
await page.goto('/workers');
|
||||||
|
const versions = page.locator('#wk-grid [data-wk-version] a.wk-version');
|
||||||
|
await expect(versions).toHaveCount(3);
|
||||||
|
for (const v of await versions.all()) {
|
||||||
|
await expect(v).toHaveText(head.slice(0, 7));
|
||||||
|
await expect(v).toHaveAttribute('href', `https://code.lotusguild.org/LotusGuild/pulse/commit/${head}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test('quick command offers every online worker', async ({ page }) => {
|
test('quick command offers every online worker', async ({ page }) => {
|
||||||
await page.goto('/quick');
|
await page.goto('/quick');
|
||||||
await expect(page.locator('#qc-worker option', { hasText: 'online' })).toHaveCount(3);
|
await expect(page.locator('#qc-worker option', { hasText: 'online' })).toHaveCount(3);
|
||||||
|
|||||||
@@ -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