Files
wekan/tests/importExportBoundary.test.cjs
T
Lauri Ojansivu 567f99227b A failed import or export disables an account only when it was an attempt.
secureTransfer recorded every throw as a high "blocked" event naming the
user, and that disables the account. sanitize-html 2.18.0 threw
RangeError on nested <iframe>, so a card planted with the payload locked
out the next member who exported the board; any library fault would do
the same. The transfer boundary now marks its own refusals
(TransferBoundaryError: a cycle, a non-plain object, a size limit), and
models/lib/transferFailure.cjs records only those as blocked - high, and
medium for a size limit as before. Anything else is ImportExportFailure:
detected, still naming whose import or export it was, and never blocking
an account.

tests/transferFailure.test.cjs drives real boundary refusals and a
sanitizer that throws through blockOnSecurityEvent's own decision; with
the old secureTransfer it fails. It also fails if the boundary throws a
plain Error or anything but secureTransfer calls it.

Thanks to xet7 !
2026-10-22 04:56:40 +03:00

143 lines
6.7 KiB
JavaScript

'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const root = path.join(__dirname, '..');
const source = fs.readFileSync(path.join(root, 'models/lib/importExportBoundary.js'), 'utf8');
const boundary = {};
new Function('exports', source
.replace(/export \{ sanitizeTransferValue, neutralizeSpreadsheetFormula, BLOCKED_KEYS \};/,
'exports.sanitizeTransferValue = sanitizeTransferValue;\nexports.neutralizeSpreadsheetFormula = neutralizeSpreadsheetFormula;\nexports.BLOCKED_KEYS = BLOCKED_KEYS;'))(boundary);
let passed = 0;
function test(name, fn) {
fn();
passed += 1;
console.log(' ok -', name);
}
console.log('importExportBoundary:');
test('removes prototype keys without polluting Object.prototype', () => {
const input = JSON.parse('{"safe":1,"__proto__":{"polluted":true},"nested":{"constructor":{"x":1}}}');
const result = boundary.sanitizeTransferValue(input);
assert.deepStrictEqual(result.value, { safe: 1, nested: {} });
assert.strictEqual({}.polluted, undefined);
assert.strictEqual(result.warnings.length, 2);
});
test('never invokes accessors', () => {
let invoked = false;
const input = { safe: 'yes' };
Object.defineProperty(input, 'trap', { enumerable: true, get() { invoked = true; return 'bad'; } });
const result = boundary.sanitizeTransferValue(input);
assert.strictEqual(invoked, false);
assert.deepStrictEqual(result.value, { safe: 'yes' });
});
test('uses the established sanitizer for active strings', () => {
const seen = [];
const result = boundary.sanitizeTransferValue({
html: '<img src=x onerror=alert(1)>hello',
scheme: 'javascript:alert(1)',
vbScheme: 'vbscript:msgbox(1)',
dataScheme: 'data:text/html,<script>alert(1)</script>',
base64: 'YWJjZGVmZw==',
}, {
// This is an observation stub, not an example sanitizer. The production
// callback is server/lib/inputSanitizer.js (sanitize-html). Return fixed clean
// fixtures so a regex that incompletely strips schemes or multi-character
// HTML can never creep into security regression code.
sanitizeHtml(value) {
seen.push(value);
return `clean-${seen.length}`;
},
});
assert.deepStrictEqual(result.value, {
html: 'clean-1',
scheme: 'clean-2',
vbScheme: 'clean-3',
dataScheme: 'clean-4',
base64: 'YWJjZGVmZw==',
});
assert.strictEqual(seen.length, 4);
});
test('rejects cycles, excessive nesting and giant arrays', () => {
const cycle = {}; cycle.self = cycle;
assert.throws(() => boundary.sanitizeTransferValue(cycle), /cycle/);
assert.throws(() => boundary.sanitizeTransferValue({ a: { b: 1 } }, { maxDepth: 1 }), /nesting/);
assert.throws(() => boundary.sanitizeTransferValue([1, 2], { maxArray: 1 }), /array limit/);
});
test('normalizes invalid scalar values and strips export secrets', () => {
const result = boundary.sanitizeTransferValue({
ok: 2, bad: Infinity, date: new Date('invalid'), apiToken: 'do-not-export',
}, { direction: 'export' });
assert.deepStrictEqual(result.value, { ok: 2, bad: null, date: null });
});
test('neutralizes every spreadsheet formula prefix', () => {
for (const value of ['=1+1', '+cmd', '-2+3', '@SUM(A1)', '\t=1', '\r=1', '\n=1']) {
assert.strictEqual(boundary.neutralizeSpreadsheetFormula(value), `'${value}`);
}
assert.strictEqual(boundary.neutralizeSpreadsheetFormula('ordinary'), 'ordinary');
});
test('all import transports and export adapters use the common boundary', () => {
for (const file of [
'models/import.js', 'models/importZip.js', 'server/trelloApiImport.js',
'models/exporter.js', 'models/lib/externalExporters.js',
]) {
const contents = fs.readFileSync(path.join(root, file), 'utf8');
assert.ok(contents.includes('secureTransfer'), `${file} bypasses common boundary`);
}
const wrapper = fs.readFileSync(path.join(root, 'server/lib/secureTransfer.js'), 'utf8');
assert.ok(wrapper.includes('sanitizeTransferValue'));
// A refusal is recorded as blocked through the shared decision, which keeps
// a fault of the code from being recorded as the user's attempt.
assert.ok(wrapper.includes('transferFailureEvent(error, context)'));
assert.ok(fs.readFileSync(path.join(root, 'models/lib/transferFailure.cjs'), 'utf8').includes("action: 'blocked'"));
assert.ok(wrapper.includes("action: 'sanitized'"));
const exporter = fs.readFileSync(path.join(root, 'models/exporter.js'), 'utf8');
assert.match(exporter, /secureExportDoc\(doc, `export:wekan-stream:\$\{key\}`\)/);
const rest = fs.readFileSync(path.join(root, 'server/models/boards.js'), 'utf8');
assert.match(rest, /Meteor\.callAsync\('importBoard'/);
});
test('a text export is made from sanitized values, not sanitized as HTML afterwards', () => {
// OPML keeps a card's title in <outline text="...">. Sanitizing the finished
// document as HTML removed those tags with the titles in them, so the OPML
// export held only the board's name.
// A stand-in sanitizer, stripping to a fixed point (tests/tagStrippingFixedPoint.test.cjs).
const stripTags = value => {
let text = String(value);
let previous;
do {
previous = text;
text = text.replace(/<[^>]*>/g, '');
} while (text !== previous);
return text;
};
const opml = '<opml version="2.0"><head><title>Board</title></head><body><outline text="Alpha Card"/></body></opml>';
const whole = boundary.sanitizeTransferValue(opml, { direction: 'export', sanitizeHtml: stripTags }).value;
assert.doesNotMatch(whole, /Alpha Card/, 'negative: the old order lost the card');
const values = boundary.sanitizeTransferValue({ items: [{ title: 'Alpha Card', description: '<img src=x onerror=1>' }] },
{ direction: 'export', sanitizeHtml: stripTags }).value;
assert.equal(values.items[0].title, 'Alpha Card');
assert.equal(values.items[0].description, '', 'a value with markup is still sanitized');
const exporters = fs.readFileSync(path.join(root, 'models/lib/externalExporters.js'), 'utf8');
const build = exporters.slice(exporters.indexOf('export async function buildExternalExport'));
assert.match(build, /if \(typeof formatted !== 'string'\) return secureTransfer\(formatted, context\);/);
assert.match(build, /items: secureTransfer\(collected\.items, context\) \}\);/);
// The board, lists and swimlanes keep their prototype: the boundary refuses
// a non-plain object, and passing the collected documents whole made every
// external export answer 500.
assert.match(build, /Object\.assign\(Object\.create\(Object\.getPrototypeOf\(doc\)\), doc, \{ title: secureTransfer\(doc\.title, context\) \}\)/);
assert.doesNotMatch(build, /secureTransfer\(await collect\(/, 'negative: never the collected documents whole');
});
console.log(`\nimportExportBoundary: ${passed} tests passed`);