Files
wekan/server/lib/eventLogFold.js
T
Lauri Ojansivu 1319f01e17 Data access in the Audit log, and AUDIT_LOG_STDOUT=json for a SIEM.
docs/Compliance/README.md WP-11 (rows 4.2 and 4.3 b):

- Admin Panel / People / Audit log has a Data access tab: who downloaded
  what - a board as JSON, CSV, Excel, PDF or ZIP, a chart, a card, every
  board, a person's data, an Admin Panel list - one row per person, day,
  kind and target with a count, the first and last time and the last
  address, never a row per download. A raw middleware in front of every
  route (server/lib/dataAccessLog.js) counts each export that answers 200,
  and a test fails when an export route is not in its list. Kept as the
  audit log (ADMIN_AUDIT_RETENTION_DAYS); erasing an account removes its
  username and address from it. Export CSV on the tab.
- AUDIT_LOG_STDOUT=json writes every audit row, security problem and data
  access also to stdout as one JSON line ({"wekan":"audit"|"security"|
  "data-access", ...}), with only the fields the Admin Panel shows - the
  arguments as stored, already redacted (models/lib/auditStdout.js). On
  every platform's settings, the snap and the Helm chart.
- The admin CSV exports obey Admin Panel's switch that turns all export
  off.

Five new strings, translated in every language. Low confidence: ace, ak,
ay, bi, bm, bo, bua, chr, csb, cv, dz, ee, ff, fj, gn, gv, haw, fur, co, ba,
bho, as, br, an, ast-ES, ha, ht, fo, iu, kl, ks, kw, nah, lld, rup, qu, sah,
se, szl, nap, scn, sc, rm, pap, lg, rn, nd, ss, nso, st, sn, ny, om, mai,
kok, la, sm, mi, tig, ve-PP, vo, wal, tlh, zgh, uz-AR, to, tpi, ts, ve, wa,
wa-RR, wo, yo, yi.

Thanks to xet7 !
2026-11-24 04:17:13 +02:00

149 lines
6.3 KiB
JavaScript

// Fold one event into its problem's row (models/lib/eventLogSummary.js).
//
// Shared by the security, speed and test loggers, so "one row per problem, not
// per event" is a property of Admin Panel -> Problems rather than of one logger.
// All three sit on paths that repeat: a guard under attack, a slow query in a
// loop, a failing test on every run.
//
// Fire-and-forget and never throws into the caller: recording that something
// happened must never be able to stop it happening.
import { Meteor } from 'meteor/meteor';
import { DDP } from 'meteor/ddp';
import EventLog from '/models/eventLog';
import { currentReportRequest } from '/server/lib/requestReportContext';
const {
summaryIdentity, summaryUpdate, actorUpdate,
} = require('/models/lib/eventLogSummary');
const { classifyAddress } = require('/models/lib/ipAddress');
const { resolveClientKey } = require('/server/lib/loginAttemptThrottle');
const { locationFromHeaders } = require('/models/lib/geoHeaders');
// Which actor keys each problem row already names, so the per-actor cap can be
// applied without reading the row on every attempt. Under attack - exactly when
// this is hot - the same few actors repeat, so the answer is nearly always
// already known. Bounded, so a long-running server cannot accumulate one entry
// per problem for ever; dropping an entry costs one extra read.
const knownActors = new Map();
const MAX_CACHED_ROWS = 500;
const usernameCache = new Map();
const USERNAME_CACHE_MAX = 1000;
const USERNAME_CACHE_TTL_MS = 60 * 1000;
async function usernameFor(userId) {
const cached = usernameCache.get(userId);
if (cached && Date.now() - cached.at < USERNAME_CACHE_TTL_MS) {
return cached.username;
}
const user = await Meteor.users.findOneAsync(userId, { fields: { username: 1 } });
const username = (user && user.username) || '';
if (usernameCache.size >= USERNAME_CACHE_MAX) usernameCache.clear();
usernameCache.set(userId, { username, at: Date.now() });
return username;
}
export async function foldEvent(doc = {}) {
const { at, ...evt } = doc;
const when = at instanceof Date ? at : new Date();
const req = currentReportRequest();
if (req) {
if (!evt.userId && req.userId) evt.userId = String(req.userId);
if (!evt.ip) {
evt.ip = resolveClientKey({
headers: req.headers,
socketAddress: (req.socket && req.socket.remoteAddress)
|| (req.connection && req.connection.remoteAddress),
forwardedCount: process.env.HTTP_FORWARDED_COUNT,
});
}
if (!evt.location) evt.location = locationFromHeaders(req.headers);
}
// DDP methods do not traverse WebApp's HTTP middleware, but the method
// invocation retains the same proxy headers and socket address. Fill the
// identical report context here so Security, Speed, Tests, CPU, Database and
// Filesystem-integrity panes do not lose their origin merely because the
// event came through DDP instead of a REST route.
const invocation = DDP._CurrentMethodInvocation
&& DDP._CurrentMethodInvocation.get();
const connection = invocation && invocation.connection;
if (connection) {
if (!evt.userId && invocation.userId) evt.userId = String(invocation.userId);
if (!evt.ip) {
evt.ip = resolveClientKey({
headers: connection.httpHeaders,
socketAddress: connection.clientAddress,
forwardedCount: process.env.HTTP_FORWARDED_COUNT,
});
}
if (!evt.location) evt.location = locationFromHeaders(connection.httpHeaders);
}
if (evt.userId && !evt.username) {
try {
const username = await usernameFor(evt.userId);
if (username) evt.username = String(username).slice(0, 100);
} catch (e) { /* a deleted/unavailable account still keeps its user id */ }
}
// THE ADDRESS, SPLIT BY FAMILY, here rather than in each logger.
//
// Every report shows IPv4 and IPv6 in columns of their own, because an
// instance reached over IPv6 and one reached over IPv4 are different
// situations and a single column that sometimes holds one and sometimes the
// other cannot be scanned. Doing it in the fold means a logger cannot forget
// to - and none of the four did it, so the fields existed and were always
// empty. `::ffff:203.0.113.9` is unwrapped to the IPv4 it is
// (models/lib/ipAddress.js), or one client would be two addresses depending
// which listener it reached.
if (evt.ip && !evt.ipv4 && !evt.ipv6) {
const { ipv4, ipv6 } = classifyAddress(evt.ip);
if (ipv4) evt.ipv4 = ipv4;
if (ipv6) evt.ipv6 = ipv6;
}
const identity = summaryIdentity(evt);
const cacheKey = JSON.stringify(identity);
let known = knownActors.get(cacheKey);
if (!known) {
const row = await EventLog.findOneAsync(identity, { fields: { actors: 1 } });
known = new Set(Object.keys((row && row.actors) || {}));
if (knownActors.size >= MAX_CACHED_ROWS) knownActors.clear();
knownActors.set(cacheKey, known);
}
const summary = summaryUpdate(evt, when);
const actors = actorUpdate(evt, when, 1, known);
await EventLog.upsertAsync(identity, {
$set: { ...summary.$set, ...actors.$set },
$setOnInsert: summary.$setOnInsert,
$inc: { ...summary.$inc, ...actors.$inc },
// The latest fields this occurrence does not carry (summaryUpdate).
...(summary.$unset ? { $unset: summary.$unset } : {}),
});
// AUDIT_LOG_STDOUT=json (WP-11, models/lib/auditStdout.js): each security
// occurrence is also one JSON line on stdout, for a SIEM. The database keeps
// the summary; the line is the event, and stdout is not the database.
if (evt.stream === 'security') require('/models/lib/auditStdout').writeStdout('security', { ...evt, at: when });
// Remember what this attempt added, so the next one from the same actor
// increments instead of paying for a read.
for (const field of Object.keys(actors.$inc)) {
const m = /^actors\.([0-9a-f]{16})\.count$/.exec(field);
if (m) known.add(m[1]);
}
}
// The call every logger makes: fold, and swallow anything that goes wrong.
export function foldEventFireAndForget(doc, name = 'eventlog') {
try {
const p = foldEvent(doc);
if (typeof p?.catch === 'function') {
p.catch(e => {
if (process.env.DEBUG === 'true') console.warn(`${name} fold failed:`, e && e.message);
});
}
} catch (e) {
if (process.env.DEBUG === 'true') console.warn(`${name} fold failed:`, e && e.message);
}
}