Files
wekan/tests/commentCardBoundary.test.cjs
T
Lauri Ojansivu 988b177e59 Email to card: board addresses, IMAP mailboxes, provider webhooks and Sandstorm grain email.
An email to a member's personal board address, board+<token>@<domain>,
becomes a card on that board, as Trello's email-to-board does (#794,
#3948). The subject is the title; the body (quoted replies stripped, HTML
as text) is the description, with a From line; attachments are attached
(no SVG, as for uploads). The author is the address's member, never the
From address, and they must still have write access when the email
arrives. A reply whose In-Reply-To/References matches a card's thread
becomes a comment on it.

Notification Settings, at three levels: the Admin Panel turns it on and
holds the domain, the provider webhook secret and the IMAP mailboxes with
their passwords (never published, never sent back to a browser); a board
admin turns the board on and picks the list and swimlane; board and
member choose which parts of an email are used. The member sees and
replaces their own address.

It arrives by POST /api/inbound-email (Mailgun, SendGrid, Postmark, JSON,
forms, multipart with attachments, raw MIME), by IMAP polling with
imapflow and mailparser under a database lease so one replica polls, or
on Sandstorm through the grain's own address: the bridge's Maildir is
read, a member's board token in the subject routes it, and WeKan's
outgoing email goes through HackSessionContext.send, since a grain has no
network. The email and hack-session capnp schemas are generated with the
other Sandstorm bindings.

Unknown addresses, wrong webhook secrets and over-limit addresses are
logged under authn.inbound-email. Rate limit per address, size limits,
Message-ID deduplication. The new strings are translated in every locale.

Thanks to xet7 !
2026-10-13 16:47:16 +03:00

73 lines
5.2 KiB
JavaScript

'use strict';
// Hall of Fame regression coverage: CommentBoundaryBleed.
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { commentCardMatchesBoard, recordCommentBoundaryDenial } = require('../models/lib/commentCardBoundary');
const { hasPrivateCommentWrite } = require('../models/lib/commentPrivateFields');
const root = path.join(__dirname, '..');
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
test('comment boundary accepts the real card board and rejects foreign or missing cards', () => {
const card = { _id: 'cardB', boardId: 'B' };
assert.equal(commentCardMatchesBoard(card, 'cardB', 'B'), true);
for (const args of [[card, 'cardB', 'A'], [card, 'other', 'B'], [null, 'cardB', 'A'], [card, {}, 'B']]) {
assert.equal(commentCardMatchesBoard(...args), false);
}
assert.doesNotThrow(() => recordCommentBoundaryDenial('test'), 'missing logger cannot break denial');
});
test('REST attack returns 404 before any insert, while legitimate comments still reach validation', async () => {
const source = read('server/models/cardComments.js');
const at = source.indexOf("WebApp.handlers.post('/api/boards/:boardId/cards/:cardId/comments'");
const start = source.indexOf(' const paramBoardId', at);
const end = source.indexOf(' // Validate the required', start);
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const run = new AsyncFunction('req', 'res', 'Authentication', 'ReactiveCache', 'allowIsBoardMemberCommentOnly', 'commentCardMatchesBoard', 'recordCommentBoundaryDenial', 'sendJsonResult', source.slice(start, end) + '\nreturn "validated-boundary";');
for (const foreign of [false, true]) {
const logs = [], responses = [];
const result = await run({ params: { boardId: 'A', cardId: 'card' }, userId: 'u' }, {},
{ checkLoggedIn() {}, checkBoardExists() {}, async checkAdminOrCondition() {} },
{ getBoard: async () => ({}), getCard: async query => ({ _id: query._id, boardId: foreign ? 'B' : query.boardId }) },
() => true, commentCardMatchesBoard, source => logs.push(source), (res, data) => responses.push(data));
assert.equal(result, foreign ? undefined : 'validated-boundary');
assert.equal(logs.length, foreign ? 1 : 0);
if (foreign) assert.equal(responses[0].code, 404);
}
});
test('DDP insertion and rebinding cannot bypass the boundary', async () => {
const source = read('server/permissions/cardComments.js');
const at = source.indexOf('CardComments.deny({');
let deny;
new Function('CardComments', 'Cards', 'commentCardMatchesBoard', 'recordCommentBoundaryDenial', 'hasPrivateCommentWrite', 'recordCommentPrivateDenial', source.slice(at, source.indexOf('CardComments.allow({', at)))(
{ deny: value => { deny = value; } }, { findOneAsync: async id => ({ _id: id, boardId: 'B' }) }, commentCardMatchesBoard, () => {}, hasPrivateCommentWrite, () => {});
assert.equal(await deny.insert('u', { cardId: 'c', boardId: 'A' }), true);
assert.equal(await deny.insert('u', { cardId: 'c', boardId: 'B' }), false);
assert.equal(deny.update('u', {}, ['cardId']), true);
assert.equal(deny.update('u', {}, ['boardId']), true);
assert.equal(deny.update('u', {}, ['text']), false);
assert.equal(await deny.insert('u', { cardId: 'c', boardId: 'B', webhookResponseRevision: 'forged' }), true);
assert.equal(deny.update('u', {}, ['text'], { $rename: { text: 'webhookResponseRevision' } }), true);
});
test('negative: every externally supplied REST comment insert is preceded by the card boundary', () => {
const walk = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
const file = path.join(dir, entry.name);
return entry.isDirectory() ? walk(file) : file.endsWith('.js') ? [file] : [];
});
const paths = walk(path.join(root, 'server')).filter(file => /CardComments\.(?:direct\.)?insertAsync\(/.test(fs.readFileSync(file, 'utf8')));
assert.deepEqual(paths.map(file => path.relative(root, file)).sort(),
['server/emailToCard.js', 'server/models/cardComments.js', 'server/routes/inboundEmail.js']);
// #794: an emailed reply is a comment on a card found ON the board of the
// address it was sent to, by a member with write access there - the card is
// never named by the sender.
const emailToCard = read('server/emailToCard.js');
assert.match(emailToCard, /Cards\.findOneAsync\(\{ boardId: board\._id, archived: false, 'email\.threadIds'/);
assert.match(emailToCard, /allowIsBoardMemberWithWriteAccess\(user\._id, board\)/);
assert.match(read('server/emailView.js'), /ReactiveCache\.getCard\(\{ _id: input\.cardId, boardId: board\._id \}\)/);
const source = read('server/models/cardComments.js');
const at = source.indexOf("WebApp.handlers.post('/api/boards/:boardId/cards/:cardId/comments'");
assert.ok(source.indexOf('commentCardMatchesBoard(card, paramCardId, paramBoardId)', at) < source.indexOf('CardComments.direct.insertAsync(', at));
// Inbound email derives boardId from the authenticated/authorized card,
// rather than accepting an independent board id from an HTTP parameter.
assert.match(read('server/routes/inboundEmail.js'), /boardId:\s*card\.boardId/);
});