Files
wekan/tests/activityPayloadValues.test.cjs
T
Lauri Ojansivu d2b40f64df Turn off all webhooks: the server sends none and refuses to add or change one.
Admin Panel / Settings / Features gets one switch, stored as
webhooksDisabled on the Settings document and saved by the site-admin
method saveWebhooksDisabled (audited). While it is on:

- nothing is sent: board and global webhooks, two-way webhooks,
  Mattermost direct messages, the grouped and scheduled queue, durable
  Sync webhooks, the login and registration webhook and bot dispatches
  all ask webhooksOff() first (models/lib/webhooksSwitch.js SENDERS);
- adding or changing a webhook is refused: the Integrations deny rules,
  the REST POST/PUT and activities routes (403 webhooks-disabled), a
  webhook's own delivery settings and saveAccountWebhook. Each refusal
  is recorded in Admin Panel / Problems as "Webhooks turned off"
  (authz.webhooks-disabled, blocksAccount: false); a silent non-send is
  never recorded;
- nothing is deleted, so turning it off brings every webhook back.
  Removing a webhook stays allowed.

Also the site-admin method webhooksReportPage for the coming Admin Panel
/ Problems report: every integration with its board and owner, the
token reduced to whether one is set, secrets masked in the URL.

Tests: tests/webhooksSwitch.test.cjs (the queue sends nothing and keeps
what waits; every webhookFetch caller is a sender that asks or is listed
as not a webhook; every write path refuses and records; report rows
carry no token), a server mocha test, and the existing vm-driven suites
supplied with the switch, with a negative case that nothing is sent.

Thanks to xet7 !
2026-11-22 20:34:47 +02:00

115 lines
7.1 KiB
JavaScript

'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
function fixture() {
const hooks = [], deliveries = [], notifications = [], pendingDeliveries = [];
const source = fs.readFileSync(require.resolve('../server/models/activities.js'), 'utf8').replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
const context = { Meteor: { startup() {}, call() { throw new Error('#6782: no method call delivers a webhook'); } },
// #6782: the activity hook delivers through this function, not a method.
deliverActivityWebhook: async (integration, description, params) => { deliveries.push(structuredClone(params)); },
// Since 54c3130ce/4c762f407 the model captures a notification intent in a
// before.insert hook and the after.insert hook no longer calls
// Notifications.notify directly: it hands the prepared context to
// deliverStoredActivityNotifications, which freezes one plan row per
// recipient from context.params. The fixture therefore registers the
// before hook separately (it is not under test here) and records the
// params each recipient's stored delivery is built from, so every value
// assertion below still checks what a notification actually receives.
Activities: { before: { insert: () => {} }, after: { insert: fn => hooks.push(fn) }, _transform: doc => doc },
deliverStoredActivityNotifications: (activity, userId, buildContext) => {
const delivery = (async () => {
const context = await buildContext();
for (let n = 0; n < context.users.length; n += 1) notifications.push(structuredClone(context.params));
})();
pendingDeliveries.push(delivery);
return delivery;
},
RulesHelper: { executeRules: async () => {} }, getFeatureFlags: () => ({}),
ACTIVITY_NOTIFICATION_TITLE: {}, Integrations: { Const: { GLOBAL_WEBHOOK_ID: 'global' } },
ReactiveCache: { getIntegrations: async () => [{ _id: 'integration' }] },
Notifications: { getUsers: async () => [{ _id: 'watcher' }], notify: (user, title, description, params) => notifications.push(structuredClone(params)) },
safeDeliver: async fn => fn(), require: id => require(`..${id}`), process: { env: {} }, console,
// Admin Panel / Settings / Features / Turn off all webhooks: on here.
webhooksOff: async () => false,
};
vm.runInNewContext(source, context);
const doc = value => ({ _id: 'activity', activityType: 'setCustomField',
customFieldId: 'field', customField: async () => ({ name: 'Estimate' }), ...value });
return { deliveries, notifications, run: async value => {
await hooks[1]('author', doc(value));
await Promise.all(pendingDeliveries);
},
prepare: value => context.prepareActivityNotification('author', doc(value)) };
}
test('actual activity hook forwards zero, false, empty and null to notifications and webhooks', async () => {
for (const value of [0, false, '', null, 'text', 12]) {
const f = fixture(); await f.run({ value, oldValue: value, timeValue: value, timeOldValue: value });
assert.equal(f.deliveries.length, 1); assert.equal(f.notifications.length, 1);
for (const payload of [f.deliveries[0], f.notifications[0]]) {
for (const key of ['value', 'oldValue', 'customFieldValue', 'timeValue', 'timeOldValue']) {
assert.equal(Object.hasOwn(payload, key), true, `${key} must not vanish`);
assert.equal(payload[key], value);
}
}
}
});
test('absent and undefined values remain absent rather than being invented as empty strings', async () => {
for (const values of [{}, { value: undefined, oldValue: undefined, timeValue: undefined, timeOldValue: undefined }]) {
const f = fixture(); await f.run(values);
for (const payload of [f.deliveries[0], f.notifications[0]]) {
for (const key of ['value', 'oldValue', 'customFieldValue', 'timeValue', 'timeOldValue']) assert.equal(Object.hasOwn(payload, key), false);
assert.equal(payload.customField, 'Estimate');
}
}
});
async function outgoingPayload(params, type = 'outgoing', attributes) {
const source = fs.readFileSync(require.resolve('../server/notifications/outgoing.js'), 'utf8').replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
let method, payload;
const integration = { boardId: 'board', url: 'https://example.test/hook', type };
const context = { structuredClone, Meteor: { methods: methods => { method = methods.outgoingWebhooks; } },
// HookBleed: the request is built from the stored integration - here the
// one the call names, as in ordinary use.
check() {}, ReactiveCache: { getUser: async () => ({ getLanguage: () => 'en' }),
getIntegration: async () => structuredClone(integration), getBoard: async () => ({ hasMember: () => true }),
getCurrentSetting: async () => ({}) },
// #3695: the payload builder outgoing.js imports (stripped above).
...require('../models/lib/webhookPayload'), ...require('../models/lib/notificationDelivery'),
TAPi18n: { ensureLanguageLoaded: async () => {}, __: () => 'changed' },
Integrations: { Const: { TWOWAY: 'two-way' } },
// The senders call webhookFetch: fetchSafe off Sandstorm (server/sandstormEgress.js).
webhookFetch: async (url, request) => { payload = JSON.parse(request.body); return { status: 200 }; },
process: { env: attributes ? { WEBHOOKS_ATTRIBUTES: attributes } : {} },
webhooksOff: async () => false,
};
vm.runInNewContext(source, context);
assert.equal(typeof method, 'function', 'the client method is still registered');
await context.deliverActivityWebhook(integration, 'act-setCustomField', params, 'author');
return payload;
}
test('outgoing HTTP payload preserves falsy configured attributes without widening the attribute list', async () => {
for (const value of [0, false, '', null]) {
const f = fixture(); await f.run({ value, oldValue: value });
const defaultPayload = await outgoingPayload(f.deliveries[0]);
assert.equal(defaultPayload.customFieldValue, value);
assert.equal(Object.hasOwn(defaultPayload, 'value'), false, 'default attribute selection is retained');
const configured = await outgoingPayload(f.deliveries[0], 'outgoing', 'value,oldValue');
assert.equal(configured.value, value); assert.equal(configured.oldValue, value);
assert.equal(Object.hasOwn(configured, 'customFieldValue'), false);
const bidirectional = await outgoingPayload(f.deliveries[0], 'two-way');
assert.equal(bidirectional.value, value); assert.equal(bidirectional.oldValue, value);
}
const absent = await outgoingPayload({ value: undefined }, 'outgoing', 'value,oldValue');
assert.equal(Object.hasOwn(absent, 'value'), false); assert.equal(Object.hasOwn(absent, 'oldValue'), false);
});
test('shared activity preparation selects the same payload and recipients without notification or webhook writes', async () => {
const f=fixture(),prepared=await f.prepare({value:0,oldValue:false});
assert.equal(f.deliveries.length,0);assert.equal(f.notifications.length,0);
assert.deepEqual(Array.from(prepared.users,user=>user._id),['watcher']);
await f.run({value:0,oldValue:false});
assert.deepEqual(structuredClone(prepared.params),f.notifications[0]);
});