Files
wekan/tests/fixedVulnerabilityClasses.test.cjs
T
Lauri Ojansivu f532f30462 Fix the last two red suites: a missing utility and a stale sibling checkout.
bundleSmokeBoot. releases/bundle-smoke-boot.sh runs the bundle under `timeout`,
which is GNU coreutils and is not on macOS. It died with "timeout: command not
found" and exit 127 - which the script's own checks then read as "the bundle
exited without reaching its database", reporting a startup failure for a
missing utility. It now uses timeout, or gtimeout, or a shell fallback that
backgrounds the command and kills it, which needs nothing but the shell.

fixedVulnerabilityClasses. The Hall of Fame comparison demanded at least 50
*bleed directories in the wekan.fi checkout as a "is this the right directory?"
sanity check. That number is a count of what was published when the line was
written, so a checkout two months old has fewer and the suite went red over the
state of ANOTHER repository, which no change here can fix.

A stale checkout cannot cause a false failure there: the test asks, of each
vulnerability it lists, whether some test names it, so listing fewer makes the
check smaller and never wrong. What the threshold has to catch is a directory
that is not the Hall of Fame at all, and those have none - so that is what it
asks now. It also looks in .tools/wekan.fi first, which is where CLAUDE.md puts
the website companion, before the older paths beside the repo.

The check itself passes: all 31 vulnerabilities in that checkout are named by a
test.

The node suites are now 721 run, 0 failed.

Thanks to xet7 !
2026-09-05 04:57:22 +03:00

316 lines
15 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', '.goroot',
'gopath', 'gomodcache', 'gocache',
]);
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.
// CLAUDE.md puts the website companion at .tools/wekan.fi; older checkouts
// keep it beside the repo. Try the documented place first, then those.
const candidates = [
path.join(repoRoot, '.tools/wekan.fi/hall-of-fame'),
path.join(repoRoot, '../w/wekan.fi/hall-of-fame'),
path.join(repoRoot, '../wekan.fi/hall-of-fame'),
];
const hof = candidates.find(p => fs.existsSync(p));
if (!hof) {
console.log(' (no wekan.fi checkout found; 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());
// "Is this the right directory?", not "is it up to date". This used to demand
// at least 50 - a count of what was published when the line was written - and
// a checkout two months old has fewer, so the suite went red over the state of
// ANOTHER repository that no change here can fix.
//
// A stale checkout cannot cause a false failure below: the comparison asks, of
// each vulnerability it lists, whether some test names it. Listing fewer makes
// that a smaller check, never a wrong one. What the threshold has to catch is
// a directory that is not the Hall of Fame at all, and any of those has none.
assert.ok(names.length > 0,
`no *bleed directories under ${hof} - is this the Hall of Fame?`);
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)` : ''));