mirror of
https://github.com/wekan/wekan.git
synced 2026-11-24 18:10:06 -05:00
Every other pane under Problems answers what went WRONG. This one answers what is being DONE: `POST /api/boards` called 34 times by alice last month, 812 times yesterday by nobody with an account. Without it the only record of REST API use is whatever the reverse proxy happens to keep, and most instances keep none. The table is username, endpoint, calls, the window they fall in, and the addresses - sorted by calls, because a usage report's question is "what is used most" where a problem report's is "what happened last". THE NAME IS THE ROUTE PATTERN, NOT THE PATH. `/api/boards/:boardId/lists` is one endpoint; `/api/boards/abc123/lists` and ten thousand of its siblings are that one endpoint being used. Naming rows after paths would put a row per board in the collection - the one-row-per-event cost this whole page exists to remove - and a request that matched NO route is counted under a single "(no route)" name rather than under the path it invented, because a 404 sweep is an attacker walking a wordlist and a row per guess would let them fill the database. ONE ROW PER ACCOUNT AND ENDPOINT, which makes the account part of a row's identity - the one deliberate exception to the rule every other stream follows. For those the question is "what is happening" and the caller would multiply the rows; here "who called what" IS the report, and the cardinality is bounded by real accounts times real endpoints. The account is stored by ID, so a rename does not split its history in two. NOTHING PER REQUEST. Ordinary API traffic is not rare the way a guard firing is rare, so calls are counted in memory and folded on a timer - a thousand requests become one write. A few seconds of counts are lost if the process stops between flushes, which is acceptable here and nowhere else on this page: this report decides nothing and nothing is protected by it. The tracked pairs are capped and the rest counted, not dropped. Counting hooks the middleware chain, not the routes, so a route cannot be added without being counted - and it counts on the response's `finish` event, which is where Express has filled req.route.path and authentication has run. The pane is the SHARED event-stream report with a different column list, not a second table page. The API stream is deliberately NOT in EVENT_STREAMS: it is usage, not a problem, and an instance serving its API would otherwise report thousands of new problems. AND THE IPv4/IPv6 SPLIT IS FINISHED WHILE HERE. The summary rows have had ipv4 and ipv6 fields since the summaries were written, and not one of the four loggers ever filled them - so the columns the design asked for could not have worked. The fold splits the address now, once, for every stream, and the two columns are one shared pair used by both reports rather than a copy each. They fall back to classifying the stored `ip`, so rows written before today display correctly instead of showing two empty columns for all of history. Seven i18n keys in 239 language files, in en.i18n.json's order, English as the placeholder where nothing is translated yet. Thanks to xet7 !
143 lines
5.6 KiB
JavaScript
143 lines
5.6 KiB
JavaScript
// API middleware: body parsing, auth token handling, API gate, and JSON response helper.
|
|
// Replaces communitypackages:json-routes middleware chain.
|
|
// Must be imported before model files that register API routes.
|
|
|
|
const { Meteor } = require('meteor/meteor');
|
|
const { Accounts } = require('meteor/accounts-base');
|
|
const { WebApp } = require('meteor/webapp');
|
|
const bodyParser = require('body-parser');
|
|
const { safeJsonStringify } = require('/server/lib/apiResponseHelpers');
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1. Body parsing (previously registered by json-routes)
|
|
// ---------------------------------------------------------------------------
|
|
WebApp.handlers.use(bodyParser.urlencoded({ limit: '50mb', extended: false }));
|
|
WebApp.handlers.use(bodyParser.json({ limit: '50mb' }));
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 2. API gate — check WITH_API env var (previously in models/users.js)
|
|
// ---------------------------------------------------------------------------
|
|
WebApp.handlers.use(function apiGate(req, res, next) {
|
|
const api = req.url.startsWith('/api');
|
|
if ((api && process.env.WITH_API === 'true') || !api) {
|
|
return next();
|
|
}
|
|
res.writeHead(301, { Location: '/' });
|
|
return res.end();
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. Bearer token parser (replaces communitypackages:rest-bearer-token-parser)
|
|
// ---------------------------------------------------------------------------
|
|
WebApp.handlers.use(function parseBearerToken(req, res, next) {
|
|
// Check Authorization header first
|
|
const authHeader = req.headers.authorization;
|
|
if (authHeader) {
|
|
const match = authHeader.match(/^Bearer\s+(.+)$/i);
|
|
if (match) {
|
|
req.authToken = match[1];
|
|
}
|
|
}
|
|
|
|
// Fallback to access_token query param
|
|
if (!req.authToken && req.query && req.query.access_token) {
|
|
req.authToken = req.query.access_token;
|
|
}
|
|
|
|
next();
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. User authentication (replaces communitypackages:authenticate-user-by-token)
|
|
// ---------------------------------------------------------------------------
|
|
WebApp.handlers.use(async function authenticateByToken(req, res, next) {
|
|
if (req.authToken) {
|
|
try {
|
|
const hashedToken = Accounts._hashLoginToken(req.authToken);
|
|
const user = await Meteor.users.findOneAsync(
|
|
{ 'services.resume.loginTokens.hashedToken': hashedToken },
|
|
{ fields: { _id: 1 } },
|
|
);
|
|
if (user) {
|
|
req.userId = user._id;
|
|
}
|
|
} catch (e) {
|
|
// Ignore auth errors — routes handle missing userId themselves
|
|
}
|
|
}
|
|
next();
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4b. API usage counting (Admin Panel -> Problems -> API)
|
|
// ---------------------------------------------------------------------------
|
|
// After authentication, so a call has an account, and in front of the routes, so
|
|
// a route cannot be added without being counted. It counts on the response's
|
|
// `finish` event - by then Express has filled req.route.path, which is the route
|
|
// PATTERN and therefore one row per endpoint rather than one per board id.
|
|
WebApp.handlers.use(require('/server/lib/apiUsageLog').apiUsageMiddleware);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 5. sendJsonResult — drop-in replacement for JsonRoutes.sendResult
|
|
// ---------------------------------------------------------------------------
|
|
function sendJsonResult(res, options) {
|
|
options = options || {};
|
|
|
|
// Default response headers (matching json-routes behavior)
|
|
res.setHeader('Cache-Control', 'no-store');
|
|
res.setHeader('Pragma', 'no-cache');
|
|
|
|
// Custom headers
|
|
if (options.headers) {
|
|
Object.entries(options.headers).forEach(function ([key, value]) {
|
|
res.setHeader(key, value);
|
|
});
|
|
}
|
|
|
|
// Status code
|
|
res.statusCode = options.code || 200;
|
|
|
|
// JSON body
|
|
if (options.data !== undefined) {
|
|
const shouldPrettyPrint = process.env.NODE_ENV === 'development';
|
|
const spacer = shouldPrettyPrint ? 2 : null;
|
|
res.setHeader('Content-Type', 'application/json');
|
|
// Use a crash-proof serializer: some error payloads (e.g. a circular
|
|
// SimpleSchema validation error) would otherwise throw inside
|
|
// JSON.stringify and surface as a generic HTTP 500. See #5804.
|
|
res.write(safeJsonStringify(options.data, spacer));
|
|
}
|
|
|
|
res.end();
|
|
}
|
|
|
|
// GHSA-3gcg-g6rf-w2rx: an export route that throws must not escape as an unhandled
|
|
// promise rejection. This app turns one of those into a full process crash - the
|
|
// note in server/ldapGroupSync.js explains why - so a single crafted request could
|
|
// take the server down for everyone. Every route body wrapped in this answers with a
|
|
// 500 instead, and the request that caused it is logged.
|
|
//
|
|
// The guards inside the handlers are still the real fix; this is the net under them,
|
|
// so the next missing null check is one broken request rather than an outage.
|
|
function safeRoute(handler) {
|
|
return async function safeRouteHandler(req, res, ...rest) {
|
|
try {
|
|
return await handler.call(this, req, res, ...rest);
|
|
} catch (error) {
|
|
console.error('[api] unhandled error while serving',
|
|
(req && req.url) || 'a request', error);
|
|
try {
|
|
if (!res.headersSent) {
|
|
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
}
|
|
res.end('Internal server error');
|
|
} catch (_) {
|
|
// The response is already gone; nothing left to answer with.
|
|
}
|
|
return undefined;
|
|
}
|
|
};
|
|
}
|
|
|
|
module.exports = { sendJsonResult, safeRoute };
|