Files
wekan/server/models/cardComments.js
T
Lauri Ojansivu d577f07700 Canary tokens: who tried to override permissions, and from where.
The security event log said what a guard DID - a request blocked, a filename
sanitized - which answers "is WeKan defending itself" and not the question an
admin asks next: who did that, and from where. It also could not tell a browser
that got confused from somebody working through the Hall of Fame one entry at a
time.

A CANARY is a tripwire at a point that only a permission-override attempt
reaches. Ordinary use never gets there - the code path runs when a request asks
for something the rules forbid - so a trip is not noise, and it is worth an
admin's attention with the actor attached. Design:
docs/Security/Remediation/WeKan.md §12.

Three properties, each enforced by a test:

SILENT. Tripping one changes NOTHING the caller can observe. tripCanary()
always returns false and tripCanaryDeny() always returns true, so a call site
reads as the refusal it replaces:

    if (forbidden) return false;                          // before
    if (forbidden) return tripCanary('card.vote-field', { userId });

The return value is decided before any reporting is attempted and the reporting
is wrapped, so a canary can never throw into, delay or disturb the request it
watches. The REST handler re-throws the ORIGINAL error object. This is not
politeness: a canary that announces itself is a map of which paths are watched,
and a probe would simply avoid them.

BOUNDED. A canary sits where an attacker can loop, so one row per attempt would
be a denial of service they get for free. models/lib/canaryTokens.js - pure, no
Meteor, no clock of its own - records the first trip of a (canary, actor) pair
at once, COUNTS the rest of the window, flushes one summary carrying the total
when the window closes, and stops writing after 60 summaries for a pair that
never gives up. The tracked-pair map is capped at 5000 and evicts the LEAST
RECENTLY seen, so a long-running attacker is not pushed out by a passing one and
a botnet varying its address cannot grow it. Idle pairs are swept on a timer. A
thousand attempts in a minute cost ONE row, and a suppressed trip costs one map
lookup. The username lookup is cached and capped, and neither it nor the insert
is awaited on the caller's path.

ATTRIBUTED. Every event carries userId, username, ip and count. The username is
denormalised at write time on purpose: it is what the account was CALLED when it
tried, so a rename does not rewrite history and a deletion does not erase it.
The address uses the same spoofing-safe resolver as the login throttle -
X-Forwarded-For only as far as HTTP_FORWARDED_COUNT says to trust it - or an
attacker could write a colleague's address into the security log by sending a
header. `detail` says what was attempted in the words of the feature, never the
payload.

Seventeen canaries are wired at the permission checks that refuse the attempts
behind BoardBleed, ParentBleed, ChecklistBleed, PathBleed and CommentBleed, plus
the direct vote/poker field writes and a stored path that points outside the
storage root. All server-side: no Playwright, no browser, nothing to install.

Admin Panel / Problems / Security gains Username, IP address and Attempts
columns, and both new columns are searchable - the thing an admin does with one
security event is pivot on it.

tests/canaryTokens.test.cjs (25 checks) drives the limiter through bursts, an
endless probe, eviction order and junk input; tests/canaryCoverage.test.cjs (18)
pins every canary to its call site and asserts none of them changes what the
caller gets back.

Thanks to xet7 !
2026-08-09 03:29:20 +03:00

249 lines
8.1 KiB
JavaScript

import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { Authentication } from '/server/authentication';
import { sendJsonResult } from '/server/apiMiddleware';
import {
validateCommentBody,
httpStatusForError,
extractErrorMessage,
} from '/server/lib/apiResponseHelpers';
import { ReactiveCache } from '/imports/reactiveCache';
import Activities from '/models/activities';
import CardComments, { assertCanMutateComment } from '/models/cardComments';
import { ensureIndex } from '/server/lib/mongoStartup';
import { tripCanary } from '/server/lib/canary';
async function commentCreation(userId, doc) {
const card = await ReactiveCache.getCard(doc.cardId);
if (!card) {
console.warn('[commentCreation] Card not found for cardId:', doc.cardId, '— skipping activity insert.');
return;
}
await Activities.insertAsync({
userId,
activityType: 'addComment',
boardId: doc.boardId,
cardId: doc.cardId,
commentId: doc._id,
listId: card.listId,
swimlaneId: card.swimlaneId,
});
}
Meteor.startup(async () => {
await ensureIndex(CardComments, { modifiedAt: -1 });
await ensureIndex(CardComments, { cardId: 1, createdAt: -1 });
// The board publication now publishes all of a board's comments with one cursor on
// the denormalized boardId (replacing a per-card N+1, #6480); index it so that
// board-level query is not a full collection scan.
await ensureIndex(CardComments, { boardId: 1 });
});
CardComments.after.insert(async (userId, doc) => {
await commentCreation(userId, doc);
});
CardComments.after.update(async (userId, doc) => {
const card = await ReactiveCache.getCard(doc.cardId);
if (!card) {
console.warn('[CardComments.after.update] Card not found for cardId:', doc.cardId, '— skipping activity insert.');
return;
}
await Activities.insertAsync({
userId,
activityType: 'editComment',
boardId: doc.boardId,
cardId: doc.cardId,
commentId: doc._id,
// #3606: store the comment text so the activity feed shows it instead of
// "undefined" (the id was passed before, and a deleted comment cannot be
// looked up live).
commentText: doc.text,
listId: card.listId,
swimlaneId: card.swimlaneId,
});
});
CardComments.before.remove(async (userId, doc) => {
try {
const card = await ReactiveCache.getCard(doc.cardId);
if (!card) {
console.warn('[CardComments.before.remove] Card not found for cardId:', doc.cardId, '— skipping deleteComment activity.');
} else {
await Activities.insertAsync({
userId,
activityType: 'deleteComment',
boardId: doc.boardId,
cardId: doc.cardId,
commentId: doc._id,
// #3606: capture the text before the comment doc is removed, so the
// feed shows the deleted comment instead of "undefined".
commentText: doc.text,
listId: card.listId,
swimlaneId: card.swimlaneId,
});
}
const activity = await ReactiveCache.getActivity({ commentId: doc._id });
if (activity) {
await Activities.removeAsync(activity._id);
}
} catch (e) {
console.error('[CardComments.before.remove] Error while processing comment deletion for doc._id:', doc._id, e);
}
});
WebApp.handlers.get('/api/boards/:boardId/cards/:cardId/comments', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
sendJsonResult(res, {
code: 200,
data: (await ReactiveCache.getCardComments({
boardId: paramBoardId,
cardId: paramCardId,
})).map(doc => ({
_id: doc._id,
comment: doc.text,
authorId: doc.userId,
})),
});
} catch (error) {
sendJsonResult(res, {
code: httpStatusForError(error),
data: { error: extractErrorMessage(error) },
});
}
});
WebApp.handlers.get(
'/api/boards/:boardId/cards/:cardId/comments/:commentId',
async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramCommentId = req.params.commentId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
sendJsonResult(res, {
code: 200,
data: await ReactiveCache.getCardComment({
_id: paramCommentId,
cardId: paramCardId,
boardId: paramBoardId,
}),
});
} catch (error) {
sendJsonResult(res, {
code: httpStatusForError(error),
data: { error: extractErrorMessage(error) },
});
}
},
);
WebApp.handlers.post('/api/boards/:boardId/cards/:cardId/comments', async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
// Validate the required `comment` parameter before inserting. Without this
// an empty/missing comment reaches the schema-validated insert and throws a
// circular validation error that previously surfaced as HTTP 500. See #5804.
const validation = validateCommentBody(req.body);
if (!validation.valid) {
sendJsonResult(res, {
code: 400,
data: { error: validation.error },
});
return;
}
const id = await CardComments.direct.insertAsync({
userId: req.userId,
text: validation.comment,
cardId: paramCardId,
boardId: paramBoardId,
});
sendJsonResult(res, {
code: 200,
data: {
_id: id,
},
});
const cardComment = await ReactiveCache.getCardComment({
_id: id,
cardId: paramCardId,
boardId: paramBoardId,
});
await commentCreation(req.userId, cardComment);
} catch (error) {
sendJsonResult(res, {
code: httpStatusForError(error),
data: { error: extractErrorMessage(error) },
});
}
});
WebApp.handlers.delete(
'/api/boards/:boardId/cards/:cardId/comments/:commentId',
async function(req, res) {
try {
const paramBoardId = req.params.boardId;
const paramCommentId = req.params.commentId;
const paramCardId = req.params.cardId;
await Authentication.checkBoardAccess(req.userId, paramBoardId);
// GHSA-pqr4-rxgp-hv2m: board membership is not permission to delete
// ANOTHER member's comment. This used to be the only check here, and the
// object-level rule (author, or a board admin unless the board sets
// restrictCommentEditing) lived in a collection hook keyed off the Meteor
// userId — which an HTTP request does not carry, so the hook took its
// "server-internal, no user" path and allowed every deletion. Load the
// comment and apply the same rule DDP applies, before removing anything.
const comment = await ReactiveCache.getCardComment({
_id: paramCommentId,
cardId: paramCardId,
boardId: paramBoardId,
});
if (!comment) {
sendJsonResult(res, { code: 404, data: { error: 'Comment not found' } });
return;
}
// A canary with the REQUEST in hand, so the event carries the real client
// address and not just the account (docs/Security/Remediation/WeKan.md §12).
// Deleting somebody else's comment is refused exactly as before - the
// canary only records the attempt, and the 403 below is unchanged.
if (comment.userId && comment.userId !== req.userId) {
try {
await assertCanMutateComment(req.userId, comment);
} catch (refusal) {
tripCanary('comment.foreign-delete', { req, userId: req.userId });
throw refusal;
}
} else {
await assertCanMutateComment(req.userId, comment);
}
await CardComments.removeAsync({
_id: paramCommentId,
cardId: paramCardId,
boardId: paramBoardId,
});
sendJsonResult(res, {
code: 200,
data: {
_id: paramCardId,
},
});
} catch (error) {
sendJsonResult(res, {
code: httpStatusForError(error),
data: { error: extractErrorMessage(error) },
});
}
},
);