Files
wekan/tests/adminAudit.test.cjs
T
Lauri Ojansivu 77986e1d65 Emergency access, a hash-chained audit log, a minimum age on sign-up, and a records of processing draft.
From docs/Compliance/README.md's P3 list and row 2.2:

- Emergency access: Admin Panel / People's user popup has "Emergency
  access" with a note before Impersonate. It is kept as reason emergency
  with the note (shown in the Impersonation Report), and every other
  administrator who can sign in gets an e-mail at once; a failed e-mail
  never stops the impersonation (models/lib/emergencyAccess.js).
- The administrators' audit log is hash-chained: each row carries its
  place, the previous row's hash and its own. Its _id is its place, so two
  servers writing at once cannot both take it - the unique _id refuses the
  second, which takes the next. A daily check, and verifyAdminAuditChain,
  walk it from the oldest row kept and report an edited or removed row in
  Problems / Filesystem integrity (models/lib/auditChain.js).
- REGISTRATION_MINIMUM_AGE: the sign-up form asks "I am at least N years
  old" and a password sign-up without it is refused; administrators'
  accounts and identity providers' are not asked, and nothing is stored
  (models/lib/registrationAge.js). On every platform and the Helm chart.
- Records of processing (draft) in Admin Panel / Settings / Legal pages:
  every collection holding personal data, why, how long with this server's
  values, and the outside services this server really uses, as Markdown to
  complete (models/lib/ropaDraft.js).

Seven new strings, translated in every language. Low confidence: chr, dz,
bo, gv, ak, ay, bm, ee, ff, fj, gn, haw, bua, cv, ba, csb, ace, bi, fur, an,
ast-ES, co, fo, hsb, gd, ht, bho, as, iu, kl, kw, ks, nah, rup, sah, lld,
szl, sm, ss, nd, qu, om, pap, lg, rn, rw, nso, st, sn, ny, mai, kok, sc,
scn, nap, mg, la, ig, ky, ja-HI, tig, tlh, vo, ve-PP, wal, zgh, uz-AR, to,
tpi, ts, tn, ve, wa, wa-RR, wo, wuu-Hans, yi, yo, tk_TM, ug, tt, ti, oc, rm,
sd, ps. The wrong-language catalog values the translators saw are in
TODO.md.

Thanks to xet7 !
2026-11-24 05:35:15 +02:00

214 lines
12 KiB
JavaScript

'use strict';
// Admin Panel / People / Audit log (models/lib/adminAudit.js,
// server/adminAudit.js, client/components/settings/adminAuditLog.*).
//
// - test: an administrator's call of an audited method is recorded with who,
// what, the outcome and where from - a refused call too;
// - negative: no password or secret reaches the trail, by key, by position or
// inside a URL; a member who is not a site administrator is not recorded;
// a failure to record never changes what the method did; the 2FA wrapper
// and this one never wrap each other twice;
// - every audited name is a real method, and the trail is admin-only.
//
// Run: node tests/adminAudit.test.cjs
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const { execFileSync } = require('child_process');
const repoRoot = path.resolve(__dirname, '..');
const read = rel => fs.readFileSync(path.join(repoRoot, rel), 'utf8');
const audit = require('../models/lib/adminAudit');
let passed = 0;
const pending = [];
function test(name, fn) {
pending.push(async () => { await fn(); passed += 1; console.log(' ok -', name); });
}
test('no password or secret reaches the trail', () => {
const pw = 'Hunter2-correct-horse';
const stored = [
audit.auditArgs('setPassword', [pw, 'userId1']),
audit.auditArgs('setCreateUser', ['Full', 'alice', 'A', pw, 'false', 'false', 'a@example.com', [], [], []]),
audit.auditArgs('saveAuthConfigSettings', ['ldap', { host: 'ldap.example', bindPassword: pw }]),
audit.auditArgs('saveOauthProviderSettings', ['google', { clientId: 'c', secret: pw }]),
audit.auditArgs('updateAttachmentStorageSettings', [{ s3: { accessKeyId: pw, secretAccessKey: pw }, azure: { accountKey: pw, connectionString: pw } }]),
audit.auditArgs('saveAdminMailSettings', [{ mailUrl: `smtps://user:${pw}@mail.example:465` }]),
audit.auditArgs('saveAccountWebhook', [{ url: 'https://hook.example', token: pw }]),
];
for (const text of stored) assert.ok(!text.includes(pw), text);
assert.match(stored[0], /^\["\[redacted\]","userId1"\]$/);
assert.match(stored[1], /"alice"/, 'what is not secret stays readable');
assert.match(stored[5], /smtps:\/\/user:\[redacted\]@mail\.example/);
});
test('long and deep arguments are cut short', () => {
assert.ok(audit.auditArgs('uploadSiteLogo', ['logo', 'A'.repeat(100000)]).length < 2100);
const deep = { a: { b: { c: { d: { e: 'x' } } } } };
assert.match(audit.auditArgs('saveInstanceFeatures', [deep]), /\[…\]/);
});
// server/adminAudit.js with an in-memory trail.
function loadServer(storedUsers, { failInsert = false } = {}) {
const handlers = {};
const trail = [];
const Meteor = {
Error: class extends Error { constructor(e) { super(e); this.error = e; } },
methods(defs) { Object.assign(handlers, defs); },
startup() {}, defer() {}, setInterval() {},
server: { method_handlers: handlers },
users: { findOneAsync: async id => storedUsers[id] || null },
};
const context = {
Meteor, Symbol, Object, Date, console: { error() {} }, process: { env: {} },
Mongo: { Collection: function Collection() {
return { insertAsync: async doc => { if (failInsert) throw new Error('db down'); trail.push(doc); } };
} },
check() {}, Match: { ObjectIncluding: () => null, Optional: () => null, Integer: null },
ensureIndex: async () => {},
// server/lib/argumentChecks.js; the audit itself is tests/wrappedHandlerArgumentChecks.test.cjs.
deferArgumentAudit() {}, applyAudited: (handler, self, args) => handler.apply(self, args),
require: p => {
if (p === '/models/lib/adminAudit') return audit;
if (p === '/server/lib/loginAttemptThrottle') return { resolveClientKey: ({ socketAddress }) => socketAddress };
if (p === '/models/lib/auditStdout') return require('../models/lib/auditStdout');
// The hash chain (models/lib/auditChain.js, tests/auditChain.test.cjs):
// here, the row as it is appended.
if (p === '/server/lib/auditChainAppend') {
return { appendAuditRow: async doc => { if (failInsert) throw new Error('db down'); trail.push(doc); return doc; } };
}
return require(p);
},
module: { exports: {} },
};
handlers.setPassword = async function setPassword(pw, userId) { return `set ${userId}`; };
handlers.removeUser = async function removeUser() { throw new Meteor.Error('not-authorized'); };
handlers.updateCard = async function updateCard() { return 'card'; };
const src = read('server/adminAudit.js')
.replace(/^import .*;\n/gm, '')
.replace(/^export const AdminAuditLog/m, 'const AdminAuditLog')
.replace(/^export function wrapAuditedMethods/m, 'function wrapAuditedMethods')
+ '\nmodule.exports = { wrapAuditedMethods };\n';
vm.runInNewContext(src, context);
context.module.exports.wrapAuditedMethods();
return { handlers, trail, wrap: context.module.exports.wrapAuditedMethods };
}
const users = {
admin: { _id: 'admin', username: 'root', isAdmin: true },
member: { _id: 'member', username: 'bob', isAdmin: false },
};
const inv = userId => ({ userId, connection: { clientAddress: '192.0.2.7', httpHeaders: {} } });
test('an administrator\'s action is recorded with who, what, outcome and address', async () => {
const s = loadServer(users);
assert.strictEqual(await s.handlers.setPassword.call(inv('admin'), 'Secret-123456', 'u2'), 'set u2');
await assert.rejects(() => s.handlers.removeUser.call(inv('admin'), 'u3'));
assert.strictEqual(s.trail.length, 2);
const [set, removed] = s.trail;
assert.deepStrictEqual([set.actorUsername, set.method, set.ok, set.ip], ['root', 'setPassword', true, '192.0.2.7']);
assert.ok(!set.args.includes('Secret-123456'));
assert.deepStrictEqual([removed.method, removed.ok, removed.error], ['removeUser', false, 'not-authorized']);
await s.handlers.updateCard.call(inv('admin'));
assert.strictEqual(s.trail.length, 2, 'editing a card is not an administrative action');
});
test('negative: a member who is not a site administrator is not in the trail', async () => {
const s = loadServer(users);
await s.handlers.setPassword.call(inv('member'), 'x', 'u2');
assert.strictEqual(s.trail.length, 0);
});
test('negative: a trail that cannot be written never changes the answer', async () => {
const s = loadServer(users, { failInsert: true });
assert.strictEqual(await s.handlers.setPassword.call(inv('admin'), 'x', 'u9'), 'set u9');
});
test('negative: wrapping again, also over the 2FA wrapper, records once', async () => {
const s = loadServer(users);
const audited = s.handlers.setPassword;
// The 2FA wrapper copies the marks of what it wraps (server/requireTwoFactor.js).
const outer = async function twoFactor(...args) { return audited.apply(this, args); };
for (const mark of Object.getOwnPropertySymbols(audited)) outer[mark] = audited[mark];
s.handlers.setPassword = outer;
s.wrap();
assert.strictEqual(s.handlers.setPassword, outer);
await s.handlers.setPassword.call(inv('admin'), 'x', 'u2');
assert.strictEqual(s.trail.length, 1);
assert.match(read('server/requireTwoFactor.js'), /Object\.getOwnPropertySymbols\(original\)/);
});
test('every audited name is a Meteor method that exists', () => {
const files = execFileSync('git', ['ls-files', 'server', 'models', 'packages'], { cwd: repoRoot, encoding: 'utf8' })
.split('\n').filter(f => f.endsWith('.js') && !/test/i.test(f));
const source = files.map(f => read(f)).join('\n');
const missing = audit.AUDITED_METHODS.filter(name =>
!new RegExp(`^\\s+(async\\s+)?['"]?${name}['"]?\\s*(\\(|:\\s*(async\\s+)?function)`, 'm').test(source));
assert.deepStrictEqual(missing, []);
for (const [name, positions] of Object.entries(audit.SECRET_POSITIONS)) {
assert.ok(audit.AUDITED_METHODS.includes(name), name);
assert.ok(positions.every(Number.isInteger));
}
});
test('the Admin Panel\'s own collection writes are audited: every one is a site-admin-only collection', () => {
// WP-1 of docs/Compliance/README.md: Settings / Appearance, Features and the
// rest are saved from the browser through /<collection>/update, and were not
// in the trail.
assert.ok(audit.isAudited('/settings/update') && audit.isAudited('/announcements/insert') && audit.isAudited('anonymizeUser'));
assert.ok(!audit.isAudited('/cards/update'), 'negative: a member editing a card is not an admin action');
const files = execFileSync('git', ['ls-files', 'server', 'models'], { cwd: repoRoot, encoding: 'utf8' })
.split('\n').filter(f => f.endsWith('.js') && !/test/i.test(f));
const source = files.map(f => read(f)).join('\n');
for (const collection of audit.AUDITED_COLLECTIONS) {
assert.match(source, new RegExp(`new Mongo\\.Collection\\('${collection}'`), `${collection} is a collection`);
}
assert.match(read('server/adminAudit.js'), /\[\.\.\.AUDITED_METHODS, \.\.\.auditedMutationMethods\(\)\]/, 'and they are wrapped');
});
test('the trail is for site administrators, and the Admin Panel shows it', () => {
const server = read('server/adminAudit.js');
assert.match(server, /user\.isAdmin !== true \|\| user\.loginDisabled === true\) throw new Meteor\.Error\('error-notAuthorized'\)/);
// Kept ADMIN_AUDIT_RETENTION_DAYS (WP-7, 2026-11-24) - a year by default,
// AUDIT_KEEP_DAYS - then removed; tests/retentionSettings.test.cjs pins the days.
assert.match(server, /cutoffDate\(retentionDays\('ADMIN_AUDIT_RETENTION_DAYS', \{ ADMIN_AUDIT_RETENTION_DAYS: process\.env\.ADMIN_AUDIT_RETENTION_DAYS \}\)\)/, 'kept for the configured days');
assert.match(server, /AdminAuditLog\.removeAsync\(\{ at: \{ \$lt: cutoff \} \}\)/, 'then removed');
assert.equal(require('../models/lib/retentionSettings').retentionDays('ADMIN_AUDIT_RETENTION_DAYS', {}), audit.AUDIT_KEEP_DAYS, 'a year by default');
assert.match(read('server/imports.js'), /import '\/server\/adminAudit';/);
// The pane has two tabs since WP-11 - the audit log and Data access - and
// calls the method of the open one; the audit log is still the first.
const pane = read('client/components/settings/adminAuditLog.js');
assert.match(pane, /const method = this\.tab\.get\(\) === 'access' \? 'adminDataAccessPage' : 'adminAuditLogPage';\s*this\.loading\.set\(true\);\s*Meteor\.call\(method,/);
assert.match(pane, /this\.tab = new ReactiveVar\('audit'\);/);
assert.match(read('client/components/settings/peopleBody.js'), /id: 'audit-log-setting'/);
assert.match(read('client/components/settings/peopleBody.jade'), /\+adminAuditLog/);
});
// Commit 2017f2871f: the pane has its own address and title, and the table
// aligns to the START of the line so it reads right to left in RTL languages.
test('the audit log has its own URL and title, and its table follows the text direction', () => {
const { ADMIN_PAGES, adminPath, adminPaneTitle } = require('../models/lib/adminUrls');
assert.strictEqual(ADMIN_PAGES.people.panes['audit-log'], 'audit-log-setting');
assert.strictEqual(adminPath('people', 'audit-log-setting'), '/admin/people/audit-log');
assert.deepStrictEqual(adminPaneTitle('people', 'audit-log'), { titleKey: 'admin-audit-log' });
assert.match(read('docs/Features/Admin-Panel/Admin-Panel-URLs.md'),
/`\/admin\/people\/audit-log` \| Audit log \| `audit-log-setting`/);
const css = read('client/components/settings/adminAuditLog.css').replace(/\/\*[\s\S]*?\*\//g, '');
const cell = /\.admin-audit-log-table th, \.admin-audit-log-table td \{([^}]*)\}/.exec(css);
assert.ok(cell, 'the table cell rule exists');
assert.match(cell[1], /text-align:\s*start;/);
// negative: no physical direction anywhere in the audit log's styles - left
// or right would stay put when the page turns right to left.
assert.doesNotMatch(css, /text-align:\s*(left|right)\b/);
assert.doesNotMatch(css, /(margin|padding|border)-(left|right)\s*:/);
assert.doesNotMatch(css, /(^|[\s;{])(left|right)\s*:/);
});
(async () => {
for (const run of pending) await run();
console.log(`adminAudit: ${passed} tests passed`);
})().catch(e => { console.error(e); process.exit(1); });