Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/parse-body-after-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@hyperdx/api': patch
---

fix: read request bodies only after the caller is authenticated. An anonymous
request could make the API parse up to 32 MB before answering 401. Public
routes such as login and register now accept bodies up to 100 KB; signed-in
users and API keys keep the 32 MB limit.
49 changes: 25 additions & 24 deletions packages/api/src/api-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import onHeaders from 'on-headers';
import * as config from './config';
import mcpRouter from './mcp/app';
import { isUserAuthenticated } from './middleware/auth';
import { parseBody } from './middleware/bodyParser';
import defaultCors from './middleware/cors';
import { appErrorHandler } from './middleware/error';
import routers from './routers/api';
Expand All @@ -22,7 +23,6 @@ import usageStats from './tasks/usageStats';
import { registerAITelemetry } from './utils/aiTelemetry';
import logger, { expressLogger } from './utils/logger';
import passport from './utils/passport';
import { captureProxyBody } from './utils/proxyBody';

registerAITelemetry();

Expand Down Expand Up @@ -57,15 +57,6 @@ if (!config.IS_CI && config.FRONTEND_URL) {

app.disable('x-powered-by');
app.use(compression());
app.use(express.json({ limit: '32mb', verify: captureProxyBody }));
app.use(express.text({ limit: '32mb', verify: captureProxyBody }));
app.use(
express.urlencoded({
extended: false,
limit: '32mb',
verify: captureProxyBody,
}),
);
app.use(session(sess));

if (!config.IS_LOCAL_APP_MODE) {
Expand Down Expand Up @@ -107,21 +98,31 @@ app.use('/', routers.rootRouter);
app.use('/mcp', mcpRouter);

// PRIVATE ROUTES
app.use('/ai', isUserAuthenticated, routers.aiRouter);
app.use('/alerts', isUserAuthenticated, routers.alertsRouter);
app.use('/dashboards', isUserAuthenticated, routers.dashboardRouter);
app.use('/me', isUserAuthenticated, routers.meRouter);
app.use('/team', isUserAuthenticated, routers.teamRouter);
app.use('/webhooks', isUserAuthenticated, routers.webhooksRouter);
app.use('/connections', isUserAuthenticated, connectionsRouter);
app.use('/sources', isUserAuthenticated, sourcesRouter);
app.use('/saved-search', isUserAuthenticated, savedSearchRouter);
app.use('/favorites', isUserAuthenticated, favoritesRouter);
app.use('/pinned-filters', isUserAuthenticated, pinnedFiltersRouter);
app.use('/clickhouse-proxy', isUserAuthenticated, clickhouseProxyRouter);
app.use('/iac', isUserAuthenticated, iacRouter);
app.use('/ai', isUserAuthenticated, parseBody, routers.aiRouter);
app.use('/alerts', isUserAuthenticated, parseBody, routers.alertsRouter);
app.use('/dashboards', isUserAuthenticated, parseBody, routers.dashboardRouter);
app.use('/me', isUserAuthenticated, parseBody, routers.meRouter);
app.use('/team', isUserAuthenticated, parseBody, routers.teamRouter);
app.use('/webhooks', isUserAuthenticated, parseBody, routers.webhooksRouter);
app.use('/connections', isUserAuthenticated, parseBody, connectionsRouter);
app.use('/sources', isUserAuthenticated, parseBody, sourcesRouter);
app.use('/saved-search', isUserAuthenticated, parseBody, savedSearchRouter);
app.use('/favorites', isUserAuthenticated, parseBody, favoritesRouter);
app.use('/pinned-filters', isUserAuthenticated, parseBody, pinnedFiltersRouter);
app.use(
'/clickhouse-proxy',
isUserAuthenticated,
parseBody,
clickhouseProxyRouter,
);
app.use('/iac', isUserAuthenticated, parseBody, iacRouter);
if (config.IS_PROMQL_ENABLED) {
app.use('/v1/prometheus', isUserAuthenticated, routers.prometheusRouter);
app.use(
'/v1/prometheus',
isUserAuthenticated,
parseBody,
routers.prometheusRouter,
);
}
// ---------------------------------------------------------------------

Expand Down
12 changes: 9 additions & 3 deletions packages/api/src/mcp/app.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js';
import { localhostHostValidation } from '@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import express from 'express';

import { validateUserAccessKey } from '@/middleware/auth';
import { parseBody } from '@/middleware/bodyParser';
import { setBusinessContext } from '@/utils/instrumentation';
import logger from '@/utils/logger';
import rateLimiter, { rateLimiterKeyGenerator } from '@/utils/rateLimiter';
Expand All @@ -11,7 +12,10 @@ import { createServer } from './mcpServer';
import { McpContext } from './tools/types';
import { userAgentClientInfo } from './utils/mcpClient';

const app = createMcpExpressApp();
// createMcpExpressApp minus its pre-auth JSON parser: bodies are parsed after
// the access key check.
const app = express();
app.use(localhostHostValidation());

const mcpRateLimiter = rateLimiter({
windowMs: 60 * 1000, // 1 minute
Expand All @@ -37,7 +41,9 @@ const methodNotAllowed = (_req: express.Request, res: express.Response) => {
app.get('/', mcpRateLimiter, methodNotAllowed);
app.delete('/', mcpRateLimiter, methodNotAllowed);

app.post('/', mcpRateLimiter, validateUserAccessKey, async (req, res) => {
const authorizePost = [mcpRateLimiter, validateUserAccessKey, ...parseBody];

app.post('/', authorizePost, async (req, res) => {
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined, // stateless
});
Expand Down
61 changes: 61 additions & 0 deletions packages/api/src/middleware/__tests__/bodyParser.int.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { getAgent, getLoggedInAgent, getServer } from '@/fixtures';

// Malformed JSON answers 400 only if the parser ran, so an anonymous 401 shows
// the body was never read.
const MALFORMED_JSON = '{"a":';
const OVER_PUBLIC_LIMIT = `{"a":"${'x'.repeat(200 * 1024)}"`;

describe('request body parsing', () => {
const server = getServer();
let signedInAgent: ReturnType<typeof getAgent>;

beforeAll(async () => {
await server.start();
({ agent: signedInAgent } = await getLoggedInAgent(server));
});

afterAll(async () => {
await server.clearDBs();
await server.stop();
});

it.each(['/dashboards', '/api/v2/dashboards', '/mcp'])(
'rejects an anonymous POST to %s without parsing its body',
async path => {
await getAgent(server)
.post(path)
.set('Content-Type', 'application/json')
.send(MALFORMED_JSON)
.expect(401);
},
);

it.each(['/register/password', '/team/setup/some-token'])(
'caps public bodies on %s at 100kb',
async path => {
await getAgent(server)
.post(path)
.set('Content-Type', 'application/json')
.send(OVER_PUBLIC_LIMIT)
.expect(413);
},
);

// The login route's own error handlers turn the 413 into a redirect.
it('sends an oversized login back to the login page', async () => {
const res = await getAgent(server)
.post('/login/password')
.set('Content-Type', 'application/json')
.send(OVER_PUBLIC_LIMIT)
.expect(303);
expect(res.headers.location).toContain('/login?err=unknown');
});

it('parses bodies over 100kb once signed in', async () => {
await signedInAgent
.post('/dashboards')
.set('Content-Type', 'application/json')
.send(OVER_PUBLIC_LIMIT)
.expect(400);
});
});
16 changes: 16 additions & 0 deletions packages/api/src/middleware/bodyParser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import express from 'express';

import { captureProxyBody } from '@/utils/proxyBody';

const bodyParsers = (limit: string) => [
express.json({ limit, verify: captureProxyBody }),
express.text({ limit, verify: captureProxyBody }),
express.urlencoded({ extended: false, limit, verify: captureProxyBody }),
];

// Mount after the auth check, so an anonymous caller can't make the API buffer
// and parse 32 MB before it is rejected.
export const parseBody = bodyParsers('32mb');

// For routes that take bodies before anyone is logged in (login, register).
export const parsePublicBody = bodyParsers('100kb');
5 changes: 4 additions & 1 deletion packages/api/src/routers/api/root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { validateRequest } from 'zod-express-middleware';
import * as config from '@/config';
import { createTeam, isTeamExisting } from '@/controllers/team';
import { handleAuthError, redirectToDashboard } from '@/middleware/auth';
import { parsePublicBody } from '@/middleware/bodyParser';
import {
loginRateLimiter,
markRejectedLogin,
Expand Down Expand Up @@ -74,6 +75,7 @@ router.get('/installation', async (_, res: InstallationEspRes, next) => {

router.post(
'/login/password',
parsePublicBody,
loginRateLimiter,
passport.authenticate('local', {
failWithError: true,
Expand All @@ -86,6 +88,7 @@ router.post(

router.post(
'/register/password',
parsePublicBody,
validateRequest({ body: registrationSchema }),
async (req, res, next) => {
try {
Expand Down Expand Up @@ -155,7 +158,7 @@ router.get('/logout', (req, res, next) => {
});

// TODO: rename this ?
router.post('/team/setup/:token', async (req, res, next) => {
router.post('/team/setup/:token', parsePublicBody, async (req, res, next) => {
try {
const { password } = req.body;
const { token } = req.params;
Expand Down
38 changes: 34 additions & 4 deletions packages/api/src/routers/external-api/v2/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import omit from 'lodash/omit';

import { EXTERNAL_API_RATE_LIMIT_MAX } from '@/config';
import { validateUserAccessKey } from '@/middleware/auth';
import { parseBody } from '@/middleware/bodyParser';
import alertsRouter from '@/routers/external-api/v2/alerts';
import chartsRouter from '@/routers/external-api/v2/charts';
import connectionsRouter from '@/routers/external-api/v2/connections';
Expand Down Expand Up @@ -33,47 +34,76 @@ router.get('/', validateUserAccessKey, (req, res) => {
});
});

router.use('/alerts', defaultRateLimiter, validateUserAccessKey, alertsRouter);
router.use(
'/alerts',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
alertsRouter,
);

router.use('/charts', defaultRateLimiter, validateUserAccessKey, chartsRouter);
router.use(
'/charts',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
chartsRouter,
);

router.use(
'/connections',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
connectionsRouter,
);

router.use(
'/dashboards',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
dashboardRouter,
);

router.use(
'/sources',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
sourcesRouter,
);

router.use(
'/saved-searches',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
savedSearchesRouter,
);

router.use('/search', defaultRateLimiter, validateUserAccessKey, searchRouter);
router.use(
'/search',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
searchRouter,
);

router.use(
'/webhooks',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
webhooksRouter,
);

router.use('/team', defaultRateLimiter, validateUserAccessKey, teamRouter);
router.use(
'/team',
defaultRateLimiter,
validateUserAccessKey,
parseBody,
teamRouter,
);

export default router;
11 changes: 11 additions & 0 deletions packages/api/src/utils/__tests__/proxyBody.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ describe('ClickHouse proxy body capture', () => {
expect(req._hdxProxyBody).toBe(body);
});

it('retains the inflated bytes when parsed inside the router mount', () => {
const req = Object.assign(makeRequest('/', '/'), {
baseUrl: '/clickhouse-proxy',
});
const body = Buffer.from('SELECT 1');

captureProxyBody(req, response, body);

expect(req._hdxProxyBody).toBe(body);
});

it.each([
undefined,
'',
Expand Down
7 changes: 5 additions & 2 deletions packages/api/src/utils/proxyBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ type ProxyRequest = Pick<
>;

export function captureProxyBody(
req: IncomingMessage & ParsedRequest & { path?: string },
req: IncomingMessage & ParsedRequest & { baseUrl?: string; path?: string },
_res: ServerResponse,
body: Buffer,
) {
if (/^\/clickhouse-proxy(?:\/|$)/i.test(req.path ?? '')) {
// The parser runs inside the router mount, where req.path drops the mount path.
if (
/^\/clickhouse-proxy(?:\/|$)/i.test(`${req.baseUrl ?? ''}${req.path ?? ''}`)
) {
// verify receives inflated bytes before parsing can change their values.
req._hdxProxyBody = body;
}
Expand Down
Loading