Files
wekan/tests/fixedVulnerabilityClasses.test.cjs
T
Lauri Ojansivu eb47e04657 Tests: ask whether a fixed mistake is anywhere ELSE, and close two gaps it found.
Every entry in https://wekan.fi/hall-of-fame/ has a suite pinning the place it was
found. None of them could answer the other half of the question: is the same
MISTAKE somewhere else - in WeKan, or in the FerretDB fork WeKan ships as its
default database? A per-site regression test knows one file, and the next
occurrence is written months later by somebody who never read the advisory.

tests/fixedVulnerabilityClasses.test.cjs asks it as a CLASS, over the whole tree
and over .tools/FerretDB when the clone is there (and saying it skipped those
checks when it is not, rather than passing quietly):

  ZipBleed      an archive entry naming its own destination path, without a
                containment check - and only for real archive readers, since a
                readdir entry name is one component and can escape nothing
  WhereBleed    a client-supplied selector carrying operators that execute
                JavaScript
  TransitBleed  rejectUnauthorized: false, NODE_TLS_REJECT_UNAUTHORIZED, and Go's
                InsecureSkipVerify in the FerretDB fork
  SourceBleed   eval() / new Function() on the server
  MimeBleed     an SVG served inline by a route that neither sanitizes it nor
                forces a download
  RandomBleed   a secret from Math.random(), and random bytes folded onto an
                alphabet with a bare % - CWE-1204 modulo bias

Comments and string literals are stripped before matching, or the advisory notes
explaining a fix would trip the check enforcing it. Allowed occurrences are listed
with the reason they are allowed. Each check was confirmed to FAIL on the mistake
by writing one into the tree and watching it fire; both probes were removed.

It found one straight away. models/lib/mongoSelectorSafety.js rejected `$where`
and nothing else - but `$where` stopped being the only way a FIND filter runs
JavaScript in MongoDB 4.4, which takes an aggregation expression inside a find
filter, and `$expr: { $function: { body, args, lang } }` there runs a JavaScript
body through the same client-supplied selector. `$accumulator` is the same again.
Both are rejected now, the helper is named for what it tests (hasServerSideJs,
with hasWhere as the alias every caller and the advisory use), and a cyclic
selector cannot spin it - an infinite recursion inside a security check is a
denial of service of its own. tests/mongoSelectorSafety.test.cjs gains those,
plus the negatives that keep it usable: a field literally called `function`, and
`$expr` doing ordinary comparison, are both fine.

randombleed moves from RECORDED to GUARDED in tests/securityRegressionCoverage.
test.cjs, and its gap count from 25 to 24: the rejection sampling CWE-1204 was
about is now held everywhere rather than in one file.

And one release entry had shipped with no test at all - the only one since v10.80
that is not a translation update. tests/databaseProblemsFixes.test.cjs covers it:
the default-swimlane self-heal calling the synchronous upsert Meteor 3 removed
(and the getter that starts the async one without awaiting it, which must handle
its own rejection or a self-heal failure takes the process with it), List.move()
inserting a list with no title and getting an error from the error formatter
rather than from the validator, and the two classifier rules that stop either
reading as "unknown / unclassified" in Admin Panel / Problems - on every database
WeKan runs on, and without swallowing an ordinary network error.

Coverage checked, not assumed: all 60 published vulnerabilities are named by a
suite, and every one of those suites carries negative assertions as well as
positive ones. New suites need no registration - build.sh's test run calls
tests/run-node-suites.cjs, which DISCOVERS every tests/*.test.cjs - so all three
files here are in the "Run WeKan's own tests" options already.

Verified by running the new suites and the whole node suite (380 suites, 0 failed).

Thanks to xet7 !
2026-08-12 15:06:45 +03:00

297 lines
14 KiB
JavaScript

'use strict';
// Every fix in https://wekan.fi/hall-of-fame/ has a suite of its own, pinning the
// place it was found. This one asks the other half of the question: is the same
// MISTAKE anywhere else - in WeKan, and in the FerretDB fork WeKan ships as its
// default database (.tools/FerretDB)?
// Run: node tests/fixedVulnerabilityClasses.test.cjs
//
// A per-site regression test cannot answer that. It knows one file, and the next
// occurrence of the pattern is written somewhere else - a new route, a new
// importer, a new backend - months later, by somebody who never read the advisory.
// So each check here is a CLASS, applied to the whole tree:
//
// ZipBleed an archive entry names its own destination path
// WhereBleed a client-supplied selector carrying $where / mapReduce
// TransitBleed TLS verification switched off to make a connection work
// SourceBleed a string turned back into code (eval, new Function)
// MimeBleed user-supplied SVG served inline, where it is script
// RandomBleed a secret from a non-cryptographic random number generator
//
// The rules for this file, so it stays worth running:
// * every check passes RIGHT NOW, and each one FAILED before its fix - so a red
// result means somebody has written the old mistake again, not that the check
// drifted;
// * comments and strings do not count as code, and the scanner strips them, or
// the advisory notes that explain a fix would trip the check that enforces it;
// * an allowed occurrence is listed WITH ITS REASON, not silently excluded.
// A file that appears here without a reason is a bug in this file.
//
// .tools/FerretDB is a separate repository, cloned by build.sh, and may be absent -
// then its checks SAY they were skipped rather than passing quietly.
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const repoRoot = path.resolve(__dirname, '..');
const FERRETDB = path.join(repoRoot, '.tools/FerretDB');
const hasFerretDB = fs.existsSync(path.join(FERRETDB, 'go.mod'));
let passed = 0;
let skipped = 0;
function test(name, fn) { fn(); passed += 1; console.log(' ok -', name); }
function ferretTest(name, fn) {
if (!hasFerretDB) {
skipped += 1;
console.log(' -- skipped (no .tools/FerretDB clone) -', name);
return;
}
test(name, fn);
}
console.log('fixedVulnerabilityClasses:');
// ── walking the sources ─────────────────────────────────────────────────────
// Everything WeKan itself ships. node_modules, builds and caches are other
// people's code and are not ours to guard here.
const WEKAN_DIRS = ['client', 'models', 'server', 'imports', 'config', 'packages', 'snap-src', 'sandstorm-src'];
const SKIP_DIRS = new Set([
'node_modules', '.git', '.build', '.meteor', '.tools', 'test-results',
'coverage', 'dist', 'build', 'vendor', 'fonts', 'webfonts',
]);
function walk(dir, extensions, out = []) {
let entries = [];
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
for (const entry of entries) {
if (SKIP_DIRS.has(entry.name)) continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) { walk(full, extensions, out); continue; }
if (extensions.some(ext => entry.name.endsWith(ext))) out.push(full);
}
return out;
}
const jsFiles = WEKAN_DIRS.flatMap(d => walk(path.join(repoRoot, d), ['.js', '.mjs', '.cjs', '.jsx']));
const goFiles = hasFerretDB ? walk(FERRETDB, ['.go']) : [];
// Comments and string literals are NOT code. An advisory note quoting the mistake
// it fixed, or a rejection list naming the operator it rejects, must not read as
// the mistake itself - that is how a guard like this starts lying.
function codeOnly(source) {
let out = '';
let i = 0;
const n = source.length;
while (i < n) {
const two = source.slice(i, i + 2);
if (two === '//') { while (i < n && source[i] !== '\n') i += 1; continue; }
if (two === '/*') { i += 2; while (i < n && source.slice(i, i + 2) !== '*/') i += 1; i += 2; continue; }
const ch = source[i];
if (ch === '"' || ch === "'" || ch === '`') {
const quote = ch;
out += ' '; // keep positions roughly sane
i += 1;
while (i < n) {
if (source[i] === '\\') { i += 2; continue; }
if (source[i] === quote) { i += 1; break; }
i += 1;
}
continue;
}
// A regular expression literal is code, but its BODY is a pattern, and a
// pattern that names $where is a rejection, not a use.
if (ch === '/' && /[=(,:[!&|?{;\n]\s*$/.test(out.slice(-40))) {
i += 1;
while (i < n && source[i] !== '\n') {
if (source[i] === '\\') { i += 2; continue; }
if (source[i] === '/') { i += 1; break; }
i += 1;
}
out += ' ';
continue;
}
out += ch;
i += 1;
}
return out;
}
const cache = new Map();
function codeOf(file) {
if (!cache.has(file)) {
try { cache.set(file, codeOnly(fs.readFileSync(file, 'utf8'))); }
catch { cache.set(file, ''); }
}
return cache.get(file);
}
const rel = file => path.relative(repoRoot, file);
// Files where an occurrence is CORRECT, each with the reason it is correct.
function findAll(files, regex, allowed = {}) {
const hits = [];
for (const file of files) {
const code = codeOf(file);
if (!regex.test(code)) { regex.lastIndex = 0; continue; }
regex.lastIndex = 0;
const relative = rel(file);
if (allowed[relative]) continue;
hits.push(relative);
}
return hits;
}
// ── TransitBleed: TLS verification switched off ─────────────────────────────
test('nothing turns off TLS certificate verification (TransitBleed)', () => {
// The fix was to TRUST a certificate the admin supplies, not to stop checking:
// `rejectUnauthorized: false` accepts ANY certificate, including the one the
// machine-in-the-middle just made up, and it is the shortest way to make an
// internal SMTP or webhook host "work".
const hits = findAll(jsFiles, /rejectUnauthorized\s*:\s*false/);
assert.deepStrictEqual(hits, [],
'these files accept any TLS certificate; supply the CA instead '
+ '(server/lib/mailTransport.js and server/lib/ssrfGuard.js show how)');
const envHits = findAll(
[...jsFiles, ...walk(path.join(repoRoot, 'snap-src'), ['.sh', '']), path.join(repoRoot, 'start-wekan.sh')],
/NODE_TLS_REJECT_UNAUTHORIZED/);
assert.deepStrictEqual(envHits, [],
'NODE_TLS_REJECT_UNAUTHORIZED=0 turns verification off for the whole process, '
+ 'which is the same hole with a wider blast radius');
});
ferretTest('the FerretDB fork does not skip TLS verification either', () => {
const hits = findAll(goFiles, /InsecureSkipVerify\s*:\s*true/);
assert.deepStrictEqual(hits, [],
'Go\'s spelling of the same mistake - the database WeKan ships speaks TLS to '
+ 'PostgreSQL/MySQL/HANA backends, and this would accept any certificate');
});
// ── SourceBleed: a string turned back into code ─────────────────────────────
test('no string is turned back into code on the server (SourceBleed)', () => {
const serverish = jsFiles.filter(f => /\/(server|models|imports)\//.test(f) && !/\/client\//.test(f));
const hits = findAll(serverish, /(^|[^.\w$])eval\s*\(|new\s+Function\s*\(/m, {
// None today. An entry here needs a reason, not a shrug.
});
assert.deepStrictEqual(hits, [],
'eval() and new Function() execute whatever reaches them; every WeKan use of '
+ 'them has been replaced by a parser or a lookup table');
});
// ── WhereBleed: a client selector carrying executable JavaScript ────────────
test('no publication runs a client selector with $where or mapReduce (WhereBleed)', () => {
// A selector is DATA sent by the client, and $where makes it CODE the database
// runs. The fix was to build selectors server-side from validated ids, and to
// reject a client selector that carries $where at all.
const pubs = jsFiles.filter(f => /\/server\/publications\//.test(f));
const hits = findAll(pubs, /\$where|mapReduce/, {
// The rejection itself has to name what it rejects.
'server/publications/cardsWindow.js': 'defines hasWhere(), the rejection',
});
assert.deepStrictEqual(hits, [],
'a publication naming $where in code is either running one or has grown its '
+ 'own copy of the rejection; the shared one is models/lib/mongoSelectorSafety.js');
const guard = fs.readFileSync(path.join(repoRoot, 'models/lib/mongoSelectorSafety.js'), 'utf8');
assert.ok(/\$where/.test(guard) && /mapReduce|\$function|\$accumulator/.test(guard),
'and the shared guard must still know every operator that executes code');
});
// ── ZipBleed: an archive entry naming its own destination ───────────────────
test('an archive entry cannot choose where it is written (ZipBleed)', () => {
// `path.join(dest, entry.path)` RESOLVES `..`, so an entry called
// `x/../../../etc/cron.d/wekan` was written outside the destination entirely.
// An ARCHIVE reader, not a directory listing: `fs.readdirSync(...).name` is one
// path component and cannot escape anything, while a zip or tar entry carries a
// whole path chosen by whoever built the file.
const ARCHIVE_READER = /unzipper|adm-?zip|AdmZip|yauzl|tar-stream|node-stream-zip|extract-zip/i;
const extractors = jsFiles.filter(f => {
const code = codeOf(f);
return ARCHIVE_READER.test(code) || /entry\.entryName|entry\.path/.test(code);
});
assert.ok(extractors.length > 0, 'the scanner must actually find the extract paths');
for (const file of extractors) {
const code = codeOf(file);
if (!/path\.join|path\.resolve|createWriteStream|mkdirSync/.test(code)) continue;
assert.ok(/safeEntryPath|isPathInside|storagePathContainment/.test(code),
`${rel(file)} builds a filesystem path from an archive entry without a `
+ 'containment check; safeEntryPath() refuses anything that escapes');
}
});
// ── MimeBleed: user-supplied SVG is script ─────────────────────────────────
test('a stored SVG is never served inline unsanitized (MimeBleed)', () => {
// An SVG is an XML document that may carry <script>, and served inline from
// WeKan's own origin it runs there. Either sanitize it or send it as a download.
// Code that WRITES a response, not code that merely knows the string: an
// extension table mapping image/svg+xml to ".svg" serves nothing.
const servers = jsFiles.filter(f => {
if (!/\/server\//.test(f)) return false;
const source = fs.readFileSync(f, 'utf8');
if (!/image\/svg/.test(source)) return false;
return /setHeader\(\s*['"]Content-Type|writeHead\(|res\.type\(/.test(source);
});
assert.ok(servers.length > 0, 'the scanner must find the file-serving routes');
for (const file of servers) {
const source = fs.readFileSync(file, 'utf8');
assert.ok(/sanitizeSvg|isDangerous|attachment;|Content-Disposition/.test(source),
`${rel(file)} names image/svg+xml but neither sanitizes it nor forces a download`);
}
});
// ── RandomBleed: a secret that is not as random as it looks ─────────────────
test('secrets do not come from Math.random() (RandomBleed)', () => {
// Math.random() is predictable from its own output; a token made of it can be
// guessed rather than brute-forced. Secrets come from crypto.randomBytes.
const secretish = jsFiles.filter(f => /\/(server|models)\//.test(f)
&& /token|secret|password|invitation|invite|otp|2fa|apikey|api_key/i.test(path.basename(f)));
const hits = [];
for (const file of secretish) {
if (/Math\.random/.test(codeOf(file))) hits.push(rel(file));
}
assert.deepStrictEqual(hits, [],
'these files generate something secret; crypto.randomBytes is the only source '
+ 'for that (server/lib/canaryTokens.js and the invitation code show the shape)');
});
test('random bytes are not folded onto an alphabet with a bare % (RandomBleed)', () => {
// RandomBleed itself: CWE-1204, modulo bias. 256 is not a multiple of a 55- or
// 62-character alphabet, so `bytes[i] % alphabet.length` makes the first
// characters more likely than the last - the id is shorter than it looks. The
// fix is rejection sampling: refuse every byte at or above the largest multiple
// of the alphabet size and draw again.
const users = jsFiles.filter(f => /crypto\.randomBytes|getRandomValues/.test(codeOf(f)));
assert.ok(users.length > 0, 'the scanner must find the random-id generators');
for (const file of users) {
const code = codeOf(file);
if (!/%\s*[A-Za-z_$][\w$]*\.length|%\s*\d+/.test(code)) continue; // no folding here
assert.ok(/limit|rejection|256 - \(256 %|< limit/.test(code),
`${rel(file)} maps random bytes onto an alphabet with % and no rejection `
+ 'sampling; see randomId() in server/lib/schemaUpgradeSteps.js');
}
});
// ── the map itself ─────────────────────────────────────────────────────────
test('every published vulnerability still has a suite naming it', () => {
// The Hall of Fame is the list of what WeKan has already got wrong. A fix whose
// test is deleted or renamed away leaves the door open again quietly, so the
// list and the tests directory are compared directly.
const hof = path.join(repoRoot, '../w/wekan.fi/hall-of-fame');
if (!fs.existsSync(hof)) {
console.log(' (the wekan.fi checkout is not beside this one; list not compared)');
return;
}
const names = fs.readdirSync(hof, { withFileTypes: true })
.filter(e => e.isDirectory() && /bleed$/i.test(e.name))
.map(e => e.name.toLowerCase());
assert.ok(names.length >= 50, `only ${names.length} vulnerabilities found - is this the right directory?`);
const testSources = walk(path.join(repoRoot, 'tests'), ['.cjs', '.js'])
.map(f => fs.readFileSync(f, 'utf8').toLowerCase())
.join('\n');
const missing = names.filter(name => !testSources.includes(name));
assert.deepStrictEqual(missing, [],
'these published vulnerabilities are not named by any test: a fix without a '
+ 'test is a fix that can be undone by the next refactor');
});
console.log(`\nfixedVulnerabilityClasses: ${passed} tests passed`
+ (skipped ? `, ${skipped} skipped (no .tools/FerretDB clone)` : ''));