A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(api): close multipart bypasses of body limit and filter (#3820)
Hampus9dc6dfb52931
diff --git a/fluxer_api/src/api/channel/controllers/MessageController.ts b/fluxer_api/src/api/channel/controllers/MessageController.tsindex 999b6ea18..bc716ea63 100644--- a/fluxer_api/src/api/channel/controllers/MessageController.ts+++ b/fluxer_api/src/api/channel/controllers/MessageController.ts@@ -8,6 +8,7 @@ import {isPersonalNotesChannelId} from '@app/api/channel/services/PersonalNotesCimport {viewerFromCtx} from '@app/api/experiment/ChannelThreadsGate';import {DefaultUserOnly, LoginRequired} from '@app/api/middleware/AuthMiddleware';import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';+import {MultipartUploadRoute} from '@app/api/middleware/RequestBodyLimitMiddleware';import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';import {SudoModeMiddleware} from '@app/api/middleware/SudoModeMiddleware';import {RateLimitConfigs} from '@app/api/RateLimitConfig';@@ -161,6 +162,7 @@ export function MessageController(app: HonoApp) {);app.post('/channels/:channel_id/messages',+ MultipartUploadRoute(),RateLimitMiddleware(RateLimitConfigs.CHANNEL_MESSAGE_CREATE),LoginRequired,Validator('param', ChannelIdParam),@@ -256,6 +258,7 @@ export function MessageController(app: HonoApp) {);app.patch('/channels/:channel_id/messages/:message_id',+ MultipartUploadRoute(),RateLimitMiddleware(RateLimitConfigs.CHANNEL_MESSAGE_UPDATE),LoginRequired,Validator('param', ChannelIdMessageIdParam),diff --git a/fluxer_api/src/api/channel/controllers/ThreadController.ts b/fluxer_api/src/api/channel/controllers/ThreadController.tsindex d2ad1aa71..cbe06e835 100644--- a/fluxer_api/src/api/channel/controllers/ThreadController.ts+++ b/fluxer_api/src/api/channel/controllers/ThreadController.ts@@ -9,6 +9,7 @@ import {ChannelThreadsRouteGuard} from '@app/api/channel/threads/ChannelThreadsRimport {viewerFromCtx} from '@app/api/experiment/ChannelThreadsGate';import {BotOnly, LoginRequired} from '@app/api/middleware/AuthMiddleware';import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';+import {isMultipartFormData, MultipartUploadRoute} from '@app/api/middleware/RequestBodyLimitMiddleware';import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';import {RateLimitConfigs} from '@app/api/RateLimitConfig';import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';@@ -53,7 +54,7 @@ const EXPERIMENT = 'channel_threads';const TAGS = 'Channels';function isMultipart(ctx: Context<HonoEnv>): boolean {- return (ctx.req.header('content-type') ?? '').includes('multipart/form-data');+ return isMultipartFormData(ctx.req.header('content-type'));}async function readPayloadJson(ctx: Context<HonoEnv>): Promise<unknown> {@@ -171,6 +172,7 @@ export function ThreadController(app: HonoApp) {);app.post('/channels/:channel_id/threads',+ MultipartUploadRoute(),ChannelThreadsRouteGuard(),RateLimitMiddleware(RateLimitConfigs.CHANNEL_THREAD_CREATE),LoginRequired,diff --git a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts b/fluxer_api/src/api/channel/services/message/MessageRequestParser.tsindex e60dad442..a593005b4 100644--- a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts+++ b/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts@@ -14,6 +14,7 @@ import type {GuildService} from '@app/api/guild/services/GuildService';import type {LimitConfigService} from '@app/api/limits/LimitConfigService';import {resolveLimitSafe} from '@app/api/limits/LimitConfigUtils';import {createLimitMatchContext} from '@app/api/limits/LimitMatchContextBuilder';+import {isMultipartFormData} from '@app/api/middleware/RequestBodyLimitMiddleware';import type {User} from '@app/api/models/User';import type {HonoEnv} from '@app/api/types/HonoEnv';import {parseJsonPreservingLargeIntegers} from '@app/api/utils/LosslessJsonParser';@@ -368,7 +369,7 @@ export async function parseMessageRequestBody<T extends z.ZodType<MessageRequestchannelId: ChannelID,schema: T,): Promise<z.output<T>> {- if (ctx.req.header('content-type')?.includes('multipart/form-data'))+ if (isMultipartFormData(ctx.req.header('content-type')))return (await parseMultipartMessageData(ctx, user, channelId, schema)) as z.output<T>;const result = schema.safeParse(normalizeMessageRequestPayload(await readMessageJsonBody(ctx)));if (!result.success) throw InputValidationError.fromCode('message_data', ValidationErrorCodes.INVALID_MESSAGE_DATA);diff --git a/fluxer_api/src/api/middleware/ContentFilterMiddleware.ts b/fluxer_api/src/api/middleware/ContentFilterMiddleware.tsindex 758999122..e5d8b8be7 100644--- a/fluxer_api/src/api/middleware/ContentFilterMiddleware.ts+++ b/fluxer_api/src/api/middleware/ContentFilterMiddleware.ts@@ -2,6 +2,7 @@import {Logger} from '@app/api/Logger';import {phraseBlocklistCache} from '@app/api/middleware/PhraseBlocklistCache';+import {isMultipartUploadRequest} from '@app/api/middleware/RequestBodyLimitMiddleware';import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';import {readRequestJsonBody} from '@app/api/utils/RequestJsonBody';import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBlockedError';@@ -128,8 +129,7 @@ const ContentFilterMiddleware = createMiddleware(async (ctx, next) => {if (shouldSkipContentFilterPath(path)) {return next();}- const contentType = ctx.req.header('content-type') ?? '';- if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {+ if (isMultipartUploadRequest(ctx)) {return next();}const body = await readRequestJsonBody(ctx.req);diff --git a/fluxer_api/src/api/middleware/RequestBodyLimitMiddleware.ts b/fluxer_api/src/api/middleware/RequestBodyLimitMiddleware.tsindex 47c329851..60069aaf8 100644--- a/fluxer_api/src/api/middleware/RequestBodyLimitMiddleware.ts+++ b/fluxer_api/src/api/middleware/RequestBodyLimitMiddleware.ts@@ -28,6 +28,7 @@ const largestJsonAssetKind = (Object.keys(ASSET_FORMAT_POLICY) as Array<AssetKinexport const DEFAULT_REQUEST_BODY_LIMIT = jsonAssetBodyLimit({[largestJsonAssetKind]: 1});const routeBodyLimits = new WeakMap<object, number>();+const multipartUploadRoutes = new WeakSet<object>();const limiters = new Map<number, MiddlewareHandler>();export function RequestBodyLimit(maxBytes: number): MiddlewareHandler<HonoEnv> {@@ -38,15 +39,40 @@ export function RequestBodyLimit(maxBytes: number): MiddlewareHandler<HonoEnv> {return marker;}-function resolveRouteBodyLimit(ctx: Context<HonoEnv>): number {- for (const route of matchedRoutes(ctx)) {+export function MultipartUploadRoute(): MiddlewareHandler<HonoEnv> {+ const marker: MiddlewareHandler<HonoEnv> = async (_ctx, next) => {+ await next();+ };+ multipartUploadRoutes.add(marker);+ return marker;+}++export function isMultipartFormData(contentType: string | undefined): boolean {+ return (contentType ?? '').split(';')[0]!.trim().toLowerCase() === 'multipart/form-data';+}++function matchedRouteHandlers(ctx: Context<HonoEnv>): Array<object> {+ return matchedRoutes(ctx).map((route) => {const handler = route.handler as MiddlewareHandler & {[COMPOSED_HANDLER]?: MiddlewareHandler};- const limit = routeBodyLimits.get(handler[COMPOSED_HANDLER] ?? handler);+ return handler[COMPOSED_HANDLER] ?? handler;+ });+}++function resolveRouteBodyLimit(ctx: Context<HonoEnv>): number {+ for (const handler of matchedRouteHandlers(ctx)) {+ const limit = routeBodyLimits.get(handler);if (limit !== undefined) return limit;}return DEFAULT_REQUEST_BODY_LIMIT;}+export function isMultipartUploadRequest(ctx: Context<HonoEnv>): boolean {+ return (+ isMultipartFormData(ctx.req.header('content-type')) &&+ matchedRouteHandlers(ctx).some((handler) => multipartUploadRoutes.has(handler))+ );+}+function limiterFor(maxSize: number): MiddlewareHandler {let limiter = limiters.get(maxSize);if (!limiter) {@@ -68,7 +94,7 @@ export const RequestBodyLimitMiddleware = createMiddleware<HonoEnv>(async (ctx,await next();return;}- if ((ctx.req.header('content-type') ?? '').includes('multipart/form-data')) {+ if (isMultipartUploadRequest(ctx)) {await next();return;}diff --git a/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.tsindex 1175396e9..4ba851f92 100644--- a/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts+++ b/fluxer_api/src/api/middleware/tests/ContentFilterMiddleware.test.ts@@ -1,7 +1,28 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {extractStringValues, shouldSkipContentFilterPath} from '@app/api/middleware/ContentFilterMiddleware';-import {describe, expect, test} from 'vitest';+import ContentFilterMiddleware, {+ extractStringValues,+ shouldSkipContentFilterPath,+} from '@app/api/middleware/ContentFilterMiddleware';+import {phraseBlocklistCache} from '@app/api/middleware/PhraseBlocklistCache';+import {MultipartUploadRoute} from '@app/api/middleware/RequestBodyLimitMiddleware';+import type {HonoEnv} from '@app/api/types/HonoEnv';+import {requireRequestJsonBody} from '@app/api/utils/RequestJsonBody';+import {AppErrorHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';+import {Hono} from 'hono';+import {afterEach, beforeEach, describe, expect, test} from 'vitest';++const BANNED = 'zebracrossingbanned';++function buildApp() {+ const app = new Hono<HonoEnv>({strict: true});+ app.use(ContentFilterMiddleware);+ app.patch('/profile', async (ctx) => ctx.json(await requireRequestJsonBody(ctx.req)));+ app.post('/upload', MultipartUploadRoute(), async (ctx) => ctx.json({ok: true}));+ app.post('/form', async (ctx) => ctx.json(Object.fromEntries(await ctx.req.formData())));+ app.onError(AppErrorHandler);+ return app;+}describe('extractStringValues', () => {test('omits fields with identifier and secret suffixes', () => {@@ -41,3 +62,41 @@ describe('shouldSkipContentFilterPath', () => {expect(result).toEqual([false, false, false]);});});++describe('content filter content type handling', () => {+ beforeEach(() => phraseBlocklistCache.add(BANNED));+ afterEach(() => phraseBlocklistCache.remove(BANNED));++ test.each([+ 'application/json',+ 'application/json; x=multipart/form-data',+ 'application/json; x=application/x-www-form-urlencoded',+ 'multipart/form-data; boundary=x',+ 'application/x-www-form-urlencoded',+ ])('blocks a banned phrase in a JSON body sent as %s', async (contentType) => {+ const response = await buildApp().request('/profile', {+ method: 'PATCH',+ headers: {'Content-Type': contentType},+ body: JSON.stringify({bio: `hello ${BANNED}`}),+ });+ expect(response.status).toBe(403);+ });++ test('leaves multipart bodies on upload routes unread', async () => {+ const form = new FormData();+ form.set('payload_json', JSON.stringify({content: `hello ${BANNED}`}));+ form.set('files[0]', new File([new Uint8Array([1, 2, 3])], 'a.bin'));+ const response = await buildApp().request('/upload', {method: 'POST', body: form});+ expect(response.status).toBe(200);+ });++ test('keeps form bodies readable on form routes', async () => {+ const response = await buildApp().request('/form', {+ method: 'POST',+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},+ body: 'grant_type=client_credentials&scope=bot',+ });+ expect(response.status).toBe(200);+ expect(await response.json()).toEqual({grant_type: 'client_credentials', scope: 'bot'});+ });+});diff --git a/fluxer_api/src/api/middleware/tests/RequestBodyLimitMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/RequestBodyLimitMiddleware.test.tsindex 05181d941..bcdcd3fd0 100644--- a/fluxer_api/src/api/middleware/tests/RequestBodyLimitMiddleware.test.ts+++ b/fluxer_api/src/api/middleware/tests/RequestBodyLimitMiddleware.test.ts@@ -1,10 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {createMultipartFormData, sendMessageWithAttachments} from '@app/api/channel/tests/AttachmentTestUtils';+import {THREADS_FEATURE, THREADS_FEATURE_HEADER} from '@app/api/channel/tests/ThreadTestUtils';import {VALID_PNG_BASE64} from '@app/api/emoji/tests/EmojiTestUtils';import {createGuild} from '@app/api/guild/tests/GuildTestUtils';import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';-import {DEFAULT_REQUEST_BODY_LIMIT, jsonAssetBodyLimit} from '@app/api/middleware/RequestBodyLimitMiddleware';+import {+ DEFAULT_REQUEST_BODY_LIMIT,+ isMultipartFormData,+ jsonAssetBodyLimit,+} from '@app/api/middleware/RequestBodyLimitMiddleware';import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';import {AVATAR_MAX_SIZE} from '@fluxer/constants/src/LimitConstants';import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';@@ -20,6 +26,19 @@ function jsonBodyOfLength(length: number): string {return `${prefix}${'a'.repeat(length - prefix.length - suffix.length)}${suffix}`;}+const MIB = 1024 * 1024;++describe('isMultipartFormData', () => {+ it('matches only the multipart/form-data media type', () => {+ expect(isMultipartFormData('multipart/form-data; boundary=x')).toBe(true);+ expect(isMultipartFormData(' Multipart/Form-Data ;boundary=x')).toBe(true);+ expect(isMultipartFormData('application/json; x=multipart/form-data')).toBe(false);+ expect(isMultipartFormData('multipart/form-data-ish')).toBe(false);+ expect(isMultipartFormData('multipart/mixed')).toBe(false);+ expect(isMultipartFormData(undefined)).toBe(false);+ });+});+describe('request body size limit', () => {let harness: ApiTestHarness;let owner: TestAccount;@@ -106,4 +125,72 @@ describe('request body size limit', () => {expect((await send(path, 'POST', jsonBodyOfLength(DEFAULT_REQUEST_BODY_LIMIT + 1))).status).not.toBe(413);expect((await send(path, 'POST', jsonBodyOfLength(25 * 1024 * 1024 + 1))).status).toBe(413);});++ it('applies the default limit to multipart bodies on routes that do not take uploads', async () => {+ const {body, contentType} = createMultipartFormData({}, [], {+ includePayloadJson: false,+ fields: {grant_type: 'authorization_code', code: 'a'.repeat(DEFAULT_REQUEST_BODY_LIMIT)},+ });+ expect(body.length).toBeGreaterThan(DEFAULT_REQUEST_BODY_LIMIT);++ const response = await harness.app.request('/oauth2/token', {+ method: 'POST',+ headers: {'Content-Type': contentType, 'x-forwarded-for': '127.0.0.1'},+ body,+ });++ expect(response.status).toBe(413);+ expect(await response.json()).toMatchObject({code: 'FILE_SIZE_TOO_LARGE'});+ });++ it('does not treat a content type that only mentions multipart/form-data as multipart', async () => {+ const response = await harness.app.request('/webhooks/livekit', {+ method: 'POST',+ headers: {'Content-Type': 'application/json; x=multipart/form-data', 'x-forwarded-for': '127.0.0.1'},+ body: Buffer.alloc(20 * MIB),+ });++ expect(response.status).toBe(413);+ });++ it('applies the default limit to multipart bodies when starting a thread from a message', async () => {+ const {body, contentType} = createMultipartFormData({name: 'thread'}, [+ {index: 0, filename: 'big.bin', data: Buffer.alloc(20 * MIB)},+ ]);++ const response = await harness.app.request(`/channels/${channelId}/messages/1/threads`, {+ method: 'POST',+ headers: {+ Authorization: owner.token,+ 'Content-Type': contentType,+ [THREADS_FEATURE_HEADER]: THREADS_FEATURE,+ 'x-forwarded-for': '127.0.0.1',+ },+ body,+ });++ expect(response.status).toBe(413);+ });++ it('keeps the default limit for JSON bodies on upload routes', async () => {+ const response = await send(+ `/channels/${channelId}/messages`,+ 'POST',+ jsonBodyOfLength(DEFAULT_REQUEST_BODY_LIMIT + 1),+ );++ expect(response.status).toBe(413);+ });++ it('lets multipart uploads above the default limit through on upload routes', async () => {+ const {response} = await sendMessageWithAttachments(+ harness,+ owner.token,+ channelId,+ {content: 'upload', attachments: [{id: 0, filename: 'big.bin'}]},+ [{index: 0, filename: 'big.bin', data: Buffer.alloc(DEFAULT_REQUEST_BODY_LIMIT + MIB)}],+ );++ expect(response.status).toBe(200);+ });});diff --git a/fluxer_api/src/api/webhook/WebhookController.ts b/fluxer_api/src/api/webhook/WebhookController.tsindex f5f2e6543..8adb782d9 100644--- a/fluxer_api/src/api/webhook/WebhookController.ts+++ b/fluxer_api/src/api/webhook/WebhookController.ts@@ -15,7 +15,11 @@ import {viewerFromCtx} from '@app/api/experiment/ChannelThreadsGate';import {LoginRequired} from '@app/api/middleware/AuthMiddleware';import {BlockAppOriginMiddleware} from '@app/api/middleware/BlockAppOriginMiddleware';import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';-import {RequestBodyLimit} from '@app/api/middleware/RequestBodyLimitMiddleware';+import {+ isMultipartFormData,+ MultipartUploadRoute,+ RequestBodyLimit,+} from '@app/api/middleware/RequestBodyLimitMiddleware';import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';import {RateLimitConfigs} from '@app/api/RateLimitConfig';import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';@@ -377,6 +381,7 @@ export function WebhookController(app: HonoApp) {);app.post('/webhooks/:webhook_id/:token',+ MultipartUploadRoute(),RateLimitMiddleware(RateLimitConfigs.WEBHOOK_EXECUTE),BlockAppOriginMiddleware,OpenAPI({@@ -395,8 +400,7 @@ export function WebhookController(app: HonoApp) {async (ctx) => {const {webhook_id: webhookId, token} = ctx.req.valid('param');const {wait} = ctx.req.valid('query');- const contentType = ctx.req.header('content-type') ?? '';- const data = contentType.includes('multipart/form-data')+ const data = isMultipartFormData(ctx.req.header('content-type'))? await parseWebhookMultipartMessageData(ctx, webhookId, token): await parseWebhookJsonMessageData(ctx);const response = await ctx.get('webhookRequestService').executeWebhook({