Files
wekan/server/lib/eventLogFold.js
T
Lauri Ojansivu 80fb1c65fc Admin Panel / Problems: a row's address, location and user are one occurrence.
A summary row keeps the LATEST occurrence's username, address, location
and detail, but a field the newest occurrence did not carry was left
from an older one: summaryUpdate only dropped the other address family
from $set, so the old value stayed in the database. Security Report
showed a German IPv4 as "Vancouver, CA" - the location of somebody
else's IPv6 beside it - and JamBleed's "gerald" beside a lockout of
account trottola. The newest occurrence now replaces all the latest
fields and $unset clears the ones it does not carry, in the fold and in
the in-memory fold the legacy migration uses. Existing rows are correct
from their next occurrence on.

Thanks to xet7 !
2026-11-19 03:33:48 +02:00

144 lines
6.0 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 } : {}),
});
// 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);
}
}