Files
wekan/tests/rulesApiTriggerNormalize.test.cjs
T
Lauri Ojansivu b46eecf58b Fix the 20 node suites the && chain had been hiding.
The new runner ran all 260 suites for the first time: 20 failed. Four were real
defects in the app, the rest were guards pinning a spelling or a design that had
since changed - each of them written when it was true, and none of them run
since, because npm stopped the chain at the first failure.

The app fixes:

  * models/lib/themeAccents.js: accentOf('constructor') returned Object's
    constructor - a FUNCTION - because a plain lookup answers from
    Object.prototype. A board colour named after any prototype member would have
    written a function into a stylesheet. Only the map's own keys are themes now.
  * RTL: the dependency overlay and its connect handle each set a physical
    left/right AFTER the logical property, so the physical one won and both were
    pinned to the LTR side in an Arabic or Hebrew layout. The skip link, the
    avatar's account badge, the stats value column and the theme-category label
    were physical too. All logical now (inset-inline-*, text-align: start/end).

The guards, each corrected to what the code actually does now, with the reason:

  * addBoardTileHeight, publicationArgumentGuard: a fixed-size slice
    (jade + 3000, source + 1400) that a grown comment pushed the subject out of.
    Both now take the whole block they are about.
  * adminCheckboxStyle: the Grey Icons feature is gone; asserts its REMOVAL.
  * boardsVisibilitySettings: the separator count was pinned at 3; the site-theme
    picker group made it 4. Asserts the shape - one Save per section, none for
    the picker that applies immediately.
  * changelogFormat: "# Upcoming WeKan ® release" is a legitimate heading.
  * dbConformanceWiring: the log directory honours WEKAN_LOGDIR now.
  * domainTablePage: the default page is the app-wide 10, not 25.
  * ferretdbOplogGating: the exec runs under the CPU launcher.
  * leftMenu: peopleMenu takes the user (multitenancy option D).
  * loginEmailPanesMoved: the board-member restriction is two checkboxes in
    Organizations and Teams now; asserted there.
  * mobileAllBoardsFit: the bell and the avatar are two rules with variants.
  * narrowWindowLayout: the hamburger is the last button in the flow, not pinned.
  * rulesApiTriggerNormalize: #6491 made a missing matching field mean "any
    value", so the #2674 "can never match" case now matches - and removeMember
    iterates assignees, not members.
  * securityLog: the new-problems selector moved to models/lib/eventLogProblems.
  * tablePage: the Cards report renders the page the SERVER named.
  * tenantWiring: the site colour is read in two places; the autorun is the one.
  * themeAccents: see above - the guard was right, the code was not.
  * translationPane: the "no hand-written table" regex matched the +tablePage
    include it also requires.
  * uiDensity: admin table cells wrap in one td+th rule now.
  * rtl: the dir attribute comes from a helper, `!important` is not part of a
    value, and the scanner read CSS COMMENTS as declarations - the comment
    explaining why `left: 50%` needs no RTL variant was reported as a violation.

Thanks to xet7 !
2026-07-28 04:28:36 +03:00

370 lines
15 KiB
JavaScript

'use strict';
// Plain-Node regression guard (no Meteor) for issue #2674
// ("Rule: remove USER from card when move").
// Run: ELECTRON_RUN_AS_NODE=1 <node> tests/rulesApiTriggerNormalize.test.cjs
//
// The reported symptom: a rule "add user to card when it is moved TO list X"
// fires, but the companion rule "remove user from card when it is moved AWAY
// FROM list X" never does. Two silent causes remained in the REST API path
// (the rule-action errors are swallowed by the activity hook, so nothing is
// logged):
//
// 1. The rule matcher (server/rulesHelper.js buildMatchingFieldsMap) queries
// EVERY matching field of the trigger's activityType with
// {$in: [<activity value>, '*']}. A Mongo $in never matches a document
// that LACKS the field, so a trigger created over
// POST /api/boards/:boardId/rules without e.g. userId / listName /
// swimlaneName could never match any activity — the rule silently never
// fired. The UI wizard (sanitizeObject) and the rules JSON import
// (normalizeTrigger) both default missing fields to '*'; the API now does
// the same via normalizeTriggerDoc().
//
// 2. The addMember/removeMember actions crashed on `undefined._id` whenever
// the stored username no longer resolved (user renamed/deleted, or a typo
// in an API-created rule) — and the removeMember '*' branch crashed on a
// card without a members array. They now warn and skip instead, and the
// card writes are awaited.
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const repoRoot = path.resolve(__dirname, '..');
const read = rel => fs.readFileSync(path.join(repoRoot, rel), 'utf8');
const rulesApiSrc = read('server/models/rules.js');
const rulesHelperSrc = read('server/rulesHelper.js');
const apiPySrc = read('api.py');
const rulesDocSrc = read('docs/API/Rules.md');
const restApiDocSrc = read('docs/API/REST-API.md');
// --- extract the REAL implementation pieces ----------------------------------
// TriggersDef (server/triggersDef.js is an ES module; strip `export`).
const triggersDefSrc = read('server/triggersDef.js').replace(/^export /m, '');
// eslint-disable-next-line no-new-func
const TriggersDef = new Function(`${triggersDefSrc}\nreturn TriggersDef;`)();
// normalizeTriggerDoc from the rules REST API.
const normSrc = rulesApiSrc.match(/function normalizeTriggerDoc\(trigger\) \{[\s\S]*?\n\}/);
assert.ok(normSrc, 'normalizeTriggerDoc found in server/models/rules.js');
// eslint-disable-next-line no-new-func
const normalizeTriggerDoc = new Function(
'TriggersDef',
`${normSrc[0]}\nreturn normalizeTriggerDoc;`,
)(TriggersDef);
// buildMatchingFieldsMap from the rule engine (an object-literal method).
const bmfSrc = rulesHelperSrc.match(
/async buildMatchingFieldsMap\(activity, matchingFields\) \{[\s\S]*?\n \},/,
);
assert.ok(bmfSrc, 'buildMatchingFieldsMap found in server/rulesHelper.js');
const { cardTitleMatchList } = require(path.join(
repoRoot,
'models/lib/ruleCardTitleFilter.js',
));
function makeMatcherEngine(reactiveCacheStub) {
// eslint-disable-next-line no-new-func
return new Function(
'ReactiveCache',
'cardTitleMatchList',
`return { ${bmfSrc[0].replace(/,\s*$/, '')} };`,
)(reactiveCacheStub, cardTitleMatchList);
}
// Minimal Mongo find() semantics for {field: {$in: [...]}} selectors: a $in
// only matches a document MISSING the field when the $in list contains null
// (Meteor stores/queries `undefined` as null).
function mongoDocMatches(doc, selector) {
return Object.entries(selector).every(([field, cond]) => {
if (cond && typeof cond === 'object' && Array.isArray(cond.$in)) {
const inList = cond.$in.map(v => (v === undefined ? null : v));
const present =
Object.prototype.hasOwnProperty.call(doc, field) && doc[field] !== undefined;
if (!present) return inList.includes(null);
return inList.includes(doc[field] === null ? null : doc[field]);
}
return doc[field] === cond;
});
}
let passed = 0;
const tests = [];
function test(name, fn) {
tests.push([name, fn]);
}
// --- the #2674 board -----------------------------------------------------------
const LISTS = {
L0: { _id: 'L0', title: 'List 0' },
L1: { _id: 'L1', title: 'List 1' },
};
const reactiveCacheStub = {
async getList(id) {
return LISTS[id];
},
async getSwimlane() {
return undefined;
},
async getCard() {
return { _id: 'C1', title: 'Test card' };
},
};
// Activity recorded when the card is moved AWAY FROM "List 1" (into "List 0").
const movedFromList1Activity = {
activityType: 'moveCard',
boardId: 'B1',
cardId: 'C1',
cardTitle: 'Test card',
listName: 'List 0',
listId: 'L0',
oldListId: 'L1',
swimlaneName: 'Default',
userId: 'U1',
};
// Activity recorded when the card is moved TO "List 1" (from "List 0").
const movedToList1Activity = {
...movedFromList1Activity,
listName: 'List 1',
listId: 'L1',
oldListId: 'L0',
};
async function matcherFor(activity) {
const engine = makeMatcherEngine(reactiveCacheStub);
return engine.buildMatchingFieldsMap(
activity,
TriggersDef[activity.activityType].matchingFields,
);
}
// --- normalizeTriggerDoc unit behavior ----------------------------------------
test('missing moveCard matching fields default to the * wildcard', () => {
const out = normalizeTriggerDoc({ activityType: 'moveCard', oldListName: 'List 1' });
assert.strictEqual(out.oldListName, 'List 1', 'explicit value kept');
assert.strictEqual(out.listName, '*');
assert.strictEqual(out.userId, '*');
assert.strictEqual(out.swimlaneName, '*');
assert.strictEqual(out.cardTitle, '*');
assert.strictEqual(out.boardId, '*'); // strip() removed it; route re-adds the real one
});
test('empty-string and null values become the wildcard too', () => {
const out = normalizeTriggerDoc({
activityType: 'moveCard',
listName: '',
userId: null,
oldListName: 'List 1',
});
assert.strictEqual(out.listName, '*');
assert.strictEqual(out.userId, '*');
assert.strictEqual(out.oldListName, 'List 1');
});
test('explicit values are never overwritten', () => {
const out = normalizeTriggerDoc({
activityType: 'createCard',
listName: 'Doing',
userId: 'someUser',
cardTitle: 'Part A',
});
assert.strictEqual(out.listName, 'Doing');
assert.strictEqual(out.userId, 'someUser');
assert.strictEqual(out.cardTitle, 'Part A');
assert.strictEqual(out.swimlaneName, '*', 'only the missing field is defaulted');
});
test('negative: non-activity triggers (scheduledTrigger/button) are untouched', () => {
const sched = {
activityType: 'scheduledTrigger',
scheduleKind: 'aging',
listName: 'Completed',
days: 90,
};
assert.deepStrictEqual(normalizeTriggerDoc(sched), sched);
const button = { activityType: 'button', buttonKind: 'card' };
assert.deepStrictEqual(normalizeTriggerDoc(button), button);
});
// --- the #2674 end-to-end matching scenario ------------------------------------
test('#2674: UI-style "moved AWAY FROM List 1 -> removeMember" trigger matches', async () => {
const selector = await matcherFor(movedFromList1Activity);
const uiTrigger = {
activityType: 'moveCard',
boardId: 'B1',
listName: '*',
oldListName: 'List 1',
swimlaneName: '*',
cardTitle: '*',
userId: '*',
};
assert.strictEqual(mongoDocMatches(uiTrigger, selector), true);
});
test('#6491: a trigger that OMITS a field means "any value" for it', async () => {
const selector = await matcherFor(movedFromList1Activity);
// What POST /api/boards/:boardId/rules used to store: only the fields the
// caller supplied. userId/listName/swimlaneName are missing entirely.
//
// This was #2674's second half - such a trigger could never satisfy the $in
// query, so a rule created over REST silently never fired. The engine now puts
// `null` in every matching list (#6491), and a $in containing null matches a
// document that is MISSING the field, so an unrestricted field is treated as
// unrestricted rather than as impossible. Normalization below still matters:
// it makes the wildcard EXPLICIT, which is what the rules list shows and what
// a later edit round-trips.
const apiTriggerWithoutNormalization = {
activityType: 'moveCard',
boardId: 'B1',
oldListName: 'List 1',
};
assert.strictEqual(
mongoDocMatches(apiTriggerWithoutNormalization, selector),
true,
'a missing matching field is "any value", not "never matches"',
);
// ...but a field that IS restricted still has to agree.
assert.strictEqual(
mongoDocMatches({ ...apiTriggerWithoutNormalization, oldListName: 'List 0' }, selector),
false,
'an explicit value that does not match the activity still excludes the trigger',
);
});
test('#2674 fix: after normalizeTriggerDoc the API trigger matches the move-away activity', async () => {
const selector = await matcherFor(movedFromList1Activity);
const apiTrigger = {
...normalizeTriggerDoc({ activityType: 'moveCard', oldListName: 'List 1' }),
boardId: 'B1', // the route sets the real boardId after normalization
};
assert.strictEqual(mongoDocMatches(apiTrigger, selector), true);
});
test('negative: the remove-rule does NOT fire when the card moves INTO List 1', async () => {
const selector = await matcherFor(movedToList1Activity);
const removeTrigger = {
...normalizeTriggerDoc({ activityType: 'moveCard', oldListName: 'List 1' }),
boardId: 'B1',
};
assert.strictEqual(mongoDocMatches(removeTrigger, selector), false);
});
test('companion add-rule ("moved TO List 1") matches only the move-in activity', async () => {
const addTrigger = {
...normalizeTriggerDoc({ activityType: 'moveCard', listName: 'List 1' }),
boardId: 'B1',
};
assert.strictEqual(
mongoDocMatches(addTrigger, await matcherFor(movedToList1Activity)),
true,
);
assert.strictEqual(
mongoDocMatches(addTrigger, await matcherFor(movedFromList1Activity)),
false,
);
});
// --- the REST routes actually use the normalization ---------------------------
test('POST /api/boards/:boardId/rules normalizes the trigger and validates types', () => {
assert.ok(/Triggers\.insertAsync\(\{\s*\n\s*\.\.\.normalizeTriggerDoc\(strip\(trigger\)\)/.test(rulesApiSrc));
assert.ok(rulesApiSrc.includes("'trigger.activityType is required'"));
assert.ok(rulesApiSrc.includes("'action.actionType is required'"));
});
test('PUT /api/boards/:boardId/rules/:ruleId normalizes a replaced trigger', () => {
assert.ok(/\$set: \{ \.\.\.normalizeTriggerDoc\(strip\(req\.body\.trigger\)\), boardId: paramBoardId \}/.test(rulesApiSrc));
});
test('negative: no raw un-normalized trigger insert remains in the rules API', () => {
assert.ok(!/Triggers\.insertAsync\(\{ \.\.\.strip\(trigger\)/.test(rulesApiSrc));
});
// --- the removeMember/addMember actions no longer crash silently ---------------
test('removeMember "*" iterates the assignees, and tolerates a card with none', () => {
// It used to read `card.members`, which is not what addMember writes
// (card.assignMember -> assignees), so "remove every member" removed nobody.
// The guard used to pin the old `card.members || []` line; what matters is
// that the list it iterates is the ASSIGNEES and that a card with none is
// still an empty array rather than undefined.
const block = rulesHelperSrc.slice(rulesHelperSrc.indexOf("actionType === 'removeMember'"));
assert.ok(/card\.getAssignees\(\) : card\.assignees\) \|\| \[\]/.test(block),
'the assignees are read defensively - a card with none is an empty array');
assert.ok(/await card\.unassignMember\(assignees\[i\]\);/.test(block),
'and every one of them is unassigned, the way addMember assigned them');
// Comments stripped first: the comment above the fix NAMES card.members to say
// what was wrong, and a guard that reads comments as code fails on its own
// explanation.
const code = block.slice(0, block.indexOf('checkAll')).replace(/\/\/[^\n]*/g, '');
assert.ok(!/card\.members/.test(code),
'the members array it used to read is not consulted here any more');
});
test('member actions resolve the user defensively and await the card writes', () => {
assert.ok(/if \(action\.actionType === 'addMember'\) \{\s*\n\s*const member = await ReactiveCache\.getUser\(\{ username: action\.username \}\);\s*\n\s*if \(member\) \{\s*\n\s*await card\.assignMember\(member\._id\);/.test(rulesHelperSrc));
assert.ok(/await card\.unassignMember\(member\._id\);/.test(rulesHelperSrc));
assert.ok(rulesHelperSrc.includes('not found; skipping.'));
});
test('negative: the crashing `(await getUser(...))._id` pattern is gone', () => {
assert.ok(!/\(await ReactiveCache\.getUser\(\{ username: action\.username \}\)\)\._id/.test(rulesHelperSrc));
});
// --- the capability is documented (api.py + API docs) --------------------------
test('api.py help text lists the Rules API commands', () => {
const syntaxBlock = apiPySrc.slice(0, apiPySrc.indexOf('if arguments == 0'));
assert.ok(syntaxBlock.includes('Board Automation Rules API (IFTTT, Issue #2674):'));
for (const cmd of ['listrules', 'getrule', 'addrule', 'editrule', 'removerule']) {
assert.ok(syntaxBlock.includes(`api.py ${cmd} BOARDID`), `help lists ${cmd}`);
}
assert.ok(syntaxBlock.includes('"actionType":"removeMember"'), 'help shows the #2674 example');
});
test('api.py implements the rule commands it documents', () => {
for (const cmd of ['listrules', 'getrule', 'addrule', 'editrule', 'removerule']) {
assert.ok(apiPySrc.includes(`sys.argv[1] == '${cmd}'`), `api.py implements ${cmd}`);
}
});
test('docs/API/Rules.md documents all five endpoints and the #2674 workflow', () => {
assert.ok(rulesDocSrc.includes('`GET` | `/api/boards/:boardId/rules`'));
assert.ok(rulesDocSrc.includes('`GET` | `/api/boards/:boardId/rules/:ruleId`'));
assert.ok(rulesDocSrc.includes('`POST` | `/api/boards/:boardId/rules`'));
assert.ok(rulesDocSrc.includes('`PUT` | `/api/boards/:boardId/rules/:ruleId`'));
assert.ok(rulesDocSrc.includes('`DELETE` | `/api/boards/:boardId/rules/:ruleId`'));
assert.ok(rulesDocSrc.includes('"actionType": "removeMember"'));
assert.ok(rulesDocSrc.includes('oldListName'));
assert.ok(/issues\/2674/.test(rulesDocSrc));
});
test('docs/API/REST-API.md summary links to the Rules API page', () => {
assert.ok(restApiDocSrc.includes('### Rules (Board Automation / IFTTT)'));
assert.ok(restApiDocSrc.includes('Rules.md#add-a-rule'));
});
// --- runner --------------------------------------------------------------------
(async () => {
for (const [name, fn] of tests) {
try {
await fn();
passed += 1;
console.log(' ok -', name);
} catch (e) {
console.error(' FAIL -', name);
console.error(e && e.stack ? e.stack : e);
process.exitCode = 1;
}
}
console.log(`\n${passed}/${tests.length} tests passed`);
if (passed !== tests.length) process.exit(1);
})();