Files
wekan/server/apiAuthRoutes.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

297 lines
10 KiB
JavaScript

// Login and register REST endpoints.
// Replaces communitypackages:rest-accounts-password.
// Logic copied from the package source to maintain identical API behavior.
const { Meteor } = require('meteor/meteor');
const { Accounts } = require('meteor/accounts-base');
const { WebApp } = require('meteor/webapp');
const { check, Match } = require('meteor/check');
const { sendJsonResult } = require('/server/apiMiddleware');
const { buildLogoutPlan } = require('/models/lib/apiLogout');
const {
LoginAttemptThrottle,
resolveClientKey,
} = require('/server/lib/loginAttemptThrottle');
const {
hasLocalPassword,
equalizeMissingUserTiming,
} = require('/server/lib/loginTimingDefense');
const NonEmptyString = Match.Where(function (x) {
check(x, String);
return x.length > 0;
});
// GHSA-2g94-9x3m-hv37: this REST login path does NOT go through the DDP
// accounts-lockout validateLoginAttempt hooks, so on its own it had no
// brute-force protection. Throttle failed attempts per client address. Env-
// tunable, with the same defaults as the module. Only failures count and a
// success resets the key, so correct-credential clients are never impeded.
const restLoginThrottle = new LoginAttemptThrottle({
maxFailures: parseInt(process.env.REST_LOGIN_MAX_FAILURES, 10) || undefined,
windowMs:
(parseInt(process.env.REST_LOGIN_FAILURE_WINDOW_SECONDS, 10) || 0) * 1000 ||
undefined,
lockoutMs:
(parseInt(process.env.REST_LOGIN_LOCKOUT_SECONDS, 10) || 0) * 1000 ||
undefined,
});
// One uniform failure, thrown for BOTH "no such user" and "wrong password", so
// neither the status code, the message NOR the timing reveals which accounts
// exist (the old code threw a distinct 'not-found' message for missing users).
function uniformLoginError() {
const error = new Meteor.Error(
'login-failed',
'Incorrect username, email address or password.',
);
error.statusCode = 401;
return error;
}
function restLoginClientKey(req) {
return resolveClientKey({
headers: req.headers,
socketAddress:
(req.socket && req.socket.remoteAddress) ||
(req.connection && req.connection.remoteAddress),
forwardedCount: process.env.HTTP_FORWARDED_COUNT,
});
}
// ---------------------------------------------------------------------------
// POST /users/login
// ---------------------------------------------------------------------------
WebApp.handlers.options('/users/login', function (req, res) {
sendJsonResult(res);
});
WebApp.handlers.post('/users/login', async function (req, res) {
const clientKey = restLoginClientKey(req);
const now = Number(new Date());
try {
// GHSA-2g94-9x3m-hv37: refuse further attempts while this client is locked
// out, before doing any user lookup or password work.
const gate = restLoginThrottle.check(clientKey, now);
if (gate.blocked) {
// A canary: being locked out means this address already failed the
// configured number of logins in a row, which nobody typing their own
// password does. The 429 below is unchanged - the attacker learns only
// what the throttle already told them (docs/Security/Remediation/WeKan.md §12).
try {
require('/server/lib/canary').tripCanary('brute.login-lockout', {
req,
detail: 'REST login refused while locked out',
});
} catch (e) { /* a canary must never break the login path */ }
const retryAfterSeconds = Math.ceil(gate.retryAfterMs / 1000);
const error = new Meteor.Error(
'too-many-requests',
'Too many failed login attempts. Try again later.',
);
error.statusCode = 429;
error.retryAfterSeconds = retryAfterSeconds;
throw error;
}
const options = req.body;
let user;
if (options.email) {
check(options, {
email: String,
password: String,
code: Match.Optional(NonEmptyString),
});
user = await Meteor.users.findOneAsync({ 'emails.address': options.email });
} else {
check(options, {
username: String,
password: String,
code: Match.Optional(NonEmptyString),
});
user = await Meteor.users.findOneAsync({ username: options.username });
}
// GHSA-2g94-9x3m-hv37: a missing user — or a user with no local password
// (LDAP/OIDC only) — would otherwise return with no bcrypt work, leaking
// existence by timing. Burn one dummy bcrypt comparison and fail with the
// exact same uniform error as a wrong password, so neither text nor timing
// distinguishes the two.
if (!hasLocalPassword(user)) {
await equalizeMissingUserTiming(Accounts._checkPasswordAsync);
restLoginThrottle.recordFailure(clientKey, now);
throw uniformLoginError();
}
const result = await Accounts._checkPasswordAsync(user, options.password);
check(result, {
userId: String,
error: Match.Optional(Meteor.Error),
});
if (result.error) {
restLoginThrottle.recordFailure(clientKey, now);
throw uniformLoginError();
}
// 2FA support. The password already checked out here, so a demand for the
// second factor is not an enumeration signal; a WRONG second factor is a
// real failed attempt and is throttled.
if (Accounts._check2faEnabled && Accounts._check2faEnabled(user)) {
if (!options.code) {
Accounts._handleError('2FA code must be informed', true, 'no-2fa-code');
}
if (
!Accounts._isTokenValid(
user.services.twoFactorAuthentication.secret,
options.code,
)
) {
restLoginThrottle.recordFailure(clientKey, now);
Accounts._handleError('Invalid 2FA code', true, 'invalid-2fa-code');
}
}
const stampedLoginToken = Accounts._generateStampedLoginToken();
check(stampedLoginToken, { token: String, when: Date });
await Accounts._insertLoginToken(result.userId, stampedLoginToken);
const tokenExpiration = Accounts._tokenExpiration(stampedLoginToken.when);
check(tokenExpiration, Date);
// A successful login clears this client's failure counter.
restLoginThrottle.recordSuccess(clientKey);
restLoginThrottle.prune(now);
sendJsonResult(res, {
data: {
id: result.userId,
token: stampedLoginToken.token,
tokenExpires: tokenExpiration,
},
});
} catch (error) {
res.statusCode = error.statusCode || 401;
if (error.retryAfterSeconds) {
res.setHeader('Retry-After', String(error.retryAfterSeconds));
}
res.setHeader('Content-Type', 'application/json');
res.end(
JSON.stringify({
error: error.error || error.message || 'Login failed',
reason: error.reason || error.message,
}),
);
}
});
// ---------------------------------------------------------------------------
// POST /users/logout
// Fixes #1437 ("Old tokens are not replaced or set invalid"): the API could
// mint tokens via /users/login but never revoke them, so old/leaked tokens
// stayed valid until their expiry. Authenticate with the token to revoke
// (Authorization: Bearer <token>); by default only that token is removed.
// Send { "all": true } in the body to revoke every login token of the user.
// ---------------------------------------------------------------------------
WebApp.handlers.options('/users/logout', function (req, res) {
sendJsonResult(res);
});
WebApp.handlers.post('/users/logout', async function (req, res) {
try {
// req.userId / req.authToken are set by the apiMiddleware bearer-token
// and authenticateByToken middleware (loaded above via require).
const hashedToken = req.authToken
? Accounts._hashLoginToken(req.authToken)
: null;
const plan = buildLogoutPlan({
userId: req.userId,
hashedToken,
all: req.body && req.body.all,
});
if (!plan.ok) {
sendJsonResult(res, {
code: plan.status,
data: { error: plan.error, reason: plan.reason },
});
return;
}
await Meteor.users.updateAsync(plan.selector, plan.modifier);
sendJsonResult(res, {
data: {
message: plan.all
? 'All login tokens have been invalidated.'
: "You've been logged out!",
},
});
} catch (error) {
res.statusCode = error.statusCode || 500;
res.setHeader('Content-Type', 'application/json');
res.end(
JSON.stringify({
error: error.error || error.message || 'Logout failed',
reason: error.reason || error.message,
}),
);
}
});
// ---------------------------------------------------------------------------
// POST /users/register
// ---------------------------------------------------------------------------
WebApp.handlers.options('/users/register', function (req, res) {
sendJsonResult(res);
});
WebApp.handlers.post('/users/register', async function (req, res) {
try {
if (Accounts._options.forbidClientAccountCreation) {
sendJsonResult(res, { code: 403 });
return;
}
const options = req.body;
check(options, {
username: Match.Optional(String),
email: Match.Optional(String),
password: String,
});
const userOptions = { password: options.password };
if (options.username) userOptions.username = options.username;
if (options.email) userOptions.email = options.email;
const userId = await Accounts.createUserAsync(userOptions);
const stampedLoginToken = Accounts._generateStampedLoginToken();
check(stampedLoginToken, { token: String, when: Date });
await Accounts._insertLoginToken(userId, stampedLoginToken);
const tokenExpiration = Accounts._tokenExpiration(stampedLoginToken.when);
check(tokenExpiration, Date);
sendJsonResult(res, {
data: {
token: stampedLoginToken.token,
tokenExpires: tokenExpiration,
id: userId,
},
});
} catch (error) {
res.statusCode = error.statusCode || 400;
res.setHeader('Content-Type', 'application/json');
res.end(
JSON.stringify({
error: error.error || error.message || 'Registration failed',
reason: error.reason || error.message,
}),
);
}
});