Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

fix(api): stream multipart message uploads to storage (#3821)

Hampus79428b638ad3
diff --git a/fluxer_api/package.json b/fluxer_api/package.json
index ba9c11b57..7baec2198 100644
--- a/fluxer_api/package.json
+++ b/fluxer_api/package.json
@@ -20,6 +20,7 @@
"@aws-sdk/s3-request-presigner": "catalog:",
"@bufbuild/protobuf": "^2.16.0",
"@elastic/elasticsearch": "catalog:",
+ "@fastify/busboy": "catalog:",
"@fluxer/config": "workspace:*",
"@fluxer/constants": "workspace:*",
"@fluxer/date_utils": "workspace:*",
diff --git a/fluxer_api/src/api/Config.ts b/fluxer_api/src/api/Config.ts
index f8ecb2504..f4487dd22 100644
--- a/fluxer_api/src/api/Config.ts
+++ b/fluxer_api/src/api/Config.ts
@@ -363,6 +363,7 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {
headersTimeoutMs: master.services.api.headers_timeout_ms,
requestTimeoutMs: master.services.api.request_timeout_ms,
maxInflightRequests: master.services.api.max_inflight_requests,
+ maxConcurrentFormUploads: master.services.api.max_concurrent_form_uploads,
automatedMessageDeletionDelayDays: master.services.api.automated_message_deletion_delay_days,
ipBanExemptIps: normalizeIpBanExemptIps(master.services.api.ip_ban_exempt_ips),
cassandra: {
diff --git a/fluxer_api/src/api/channel/controllers/ThreadController.ts b/fluxer_api/src/api/channel/controllers/ThreadController.ts
index cbe06e835..233be7c84 100644
--- a/fluxer_api/src/api/channel/controllers/ThreadController.ts
+++ b/fluxer_api/src/api/channel/controllers/ThreadController.ts
@@ -4,12 +4,17 @@ import {type ChannelID, createChannelID, createGuildID, createMessageID, createU
import type {MessageRequest} from '@app/api/channel/MessageTypes';
import {normalizeMessageRequestPayload} from '@app/api/channel/services/message/MessageRequestCompatibility';
import {parseMultipartMessageData, readMessageJsonBody} from '@app/api/channel/services/message/MessageRequestParser';
+import {readMultipartStream} from '@app/api/channel/services/message/MultipartStreamReader';
import type {ForumPostInput} from '@app/api/channel/services/thread/ThreadCreationService';
import {ChannelThreadsRouteGuard} from '@app/api/channel/threads/ChannelThreadsRouteGuard';
import {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 {
+ DEFAULT_REQUEST_BODY_LIMIT,
+ 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';
@@ -58,19 +63,24 @@ function isMultipart(ctx: Context<HonoEnv>): boolean {
}
async function readPayloadJson(ctx: Context<HonoEnv>): Promise<unknown> {
- let payloadJson: unknown;
+ let payloadJson: string | undefined;
+ await readMultipartStream(ctx, {
+ maxFiles: 0,
+ maxFileSize: DEFAULT_REQUEST_BODY_LIMIT,
+ maxFieldBytes: DEFAULT_REQUEST_BODY_LIMIT,
+ onField(name, value) {
+ if (name === 'payload_json') payloadJson = value;
+ },
+ async onFile({stream}) {
+ stream.resume();
+ },
+ });
+ if (payloadJson === undefined) return {};
try {
- payloadJson = (await ctx.req.parseBody())['payload_json'];
+ return parseJsonPreservingLargeIntegers(payloadJson);
} catch {
- throw InputValidationError.fromCode('multipart_form', ValidationErrorCodes.FAILED_TO_PARSE_MULTIPART_FORM_DATA);
- }
- if (payloadJson === undefined) return {};
- if (typeof payloadJson === 'string') {
- try {
- return parseJsonPreservingLargeIntegers(payloadJson);
- } catch {}
+ throw InputValidationError.fromCode('payload_json', ValidationErrorCodes.INVALID_JSON_IN_PAYLOAD_JSON);
}
- throw InputValidationError.fromCode('payload_json', ValidationErrorCodes.INVALID_JSON_IN_PAYLOAD_JSON);
}
async function readJsonBody(ctx: Context<HonoEnv>): Promise<unknown> {
diff --git a/fluxer_api/src/api/channel/services/AttachmentUploadService.ts b/fluxer_api/src/api/channel/services/AttachmentUploadService.ts
index 571eade49..7e6dcd9a8 100644
--- a/fluxer_api/src/api/channel/services/AttachmentUploadService.ts
+++ b/fluxer_api/src/api/channel/services/AttachmentUploadService.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import type {Readable} from 'node:stream';
import type {AttachmentID, ChannelID, MessageID, UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import type {UploadedAttachment} from '@app/api/channel/AttachmentDTOs';
@@ -8,6 +9,7 @@ import type {
AttachmentUploadMode,
AttachmentUploadTraceRepository,
} from '@app/api/channel/repositories/message/AttachmentUploadTraceRepository';
+import {acquireFormUploadSlot} from '@app/api/channel/services/FormUploadSlots';
import type {MessageInteractionService} from '@app/api/channel/services/MessageInteractionService';
import type {MessageService} from '@app/api/channel/services/MessageService';
import {dispatchMessageUpdateBroadcast} from '@app/api/channel/services/message/MessageGatewayDispatch';
@@ -34,7 +36,6 @@ import type {Attachment} from '@app/api/models/Attachment';
import type {Channel} from '@app/api/models/Channel';
import type {Message} from '@app/api/models/Message';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import {assertGuildMemberCanCommunicate} from '@app/api/utils/GuildCommunicationUtils';
import {Permissions, TEXT_BASED_CHANNEL_TYPES} from '@fluxer/constants/src/ChannelConstants';
import {GuildOperations} from '@fluxer/constants/src/GuildConstants';
@@ -76,20 +77,33 @@ interface DeleteAttachmentParams {
type UploadActor = 'member' | 'webhook';
-interface UploadFormDataAttachmentsParams {
+interface FormDataUploadTarget {
userId: UserID;
viewer: ThreadViewer;
channelId: ChannelID;
+ actor?: UploadActor;
+}
+
+export interface FormDataUpload {
+ maxFileSize: number;
+ assertCanAttachFiles: () => Promise<void>;
+}
+
+interface StoredFormDataFile {
+ index: number;
+ uploadKey: string;
+ size: number;
+}
+
+interface UploadFormDataAttachmentsParams {
+ userId: UserID;
+ channelId: ChannelID;
clientIp: string;
- files: Array<{
- file: File;
- index: number;
- }>;
+ files: Array<StoredFormDataFile>;
attachmentMetadata: Array<{
id: number;
filename: string;
}>;
- actor?: UploadActor;
}
interface RequestPresignedAttachmentUploadUrlsParams {
@@ -108,7 +122,11 @@ interface CompleteMultipartAttachmentUploadsParams {
uploads: Array<CompleteMultipartAttachmentUploadItem>;
}
-const FORM_DATA_UPLOAD_CONCURRENCY = 2;
+interface UploadChannel {
+ channel: Channel;
+ guild: GuildResponse | null;
+ assertCanAttachFiles: () => Promise<void>;
+}
export class AttachmentUploadService {
constructor(
@@ -123,59 +141,72 @@ export class AttachmentUploadService {
private gatewayService: IGatewayService,
) {}
+ async storeFormDataFile({body, filename}: {body: Readable; filename: string}): Promise<string> {
+ const uploadKey = crypto.randomUUID();
+ const bucket = Config.s3.buckets.uploads;
+ const contentType = getContentTypeFromFilename(filename);
+ const releaseSlot = await acquireFormUploadSlot();
+ try {
+ await runAttachmentStorageOperation(() =>
+ this.storageService.uploadObject({
+ bucket,
+ key: uploadKey,
+ body,
+ contentType,
+ }),
+ );
+ } catch (error) {
+ await this.storageService.deleteObject(bucket, uploadKey).catch(() => undefined);
+ throw body.errored ?? error;
+ } finally {
+ releaseSlot();
+ }
+ return uploadKey;
+ }
+
+ async deleteFormDataFiles(uploadKeys: Array<string>): Promise<void> {
+ await Promise.all(
+ uploadKeys.map((uploadKey) =>
+ this.storageService.deleteObject(Config.s3.buckets.uploads, uploadKey).catch(() => undefined),
+ ),
+ );
+ }
+
async uploadFormDataAttachments({
userId,
- viewer,
channelId,
clientIp,
files,
attachmentMetadata,
- actor = 'member',
}: UploadFormDataAttachmentsParams): Promise<Array<UploadedAttachment>> {
- const {maxFileSize} = await this.getUploadPermissionAndLimit({userId, viewer, channelId, actor});
- assertAttachmentFileSizesWithinLimit(
- files.map(({file}) => file.size),
- maxFileSize,
- );
const metadataMap = new Map(attachmentMetadata.map((m) => [m.id, m]));
- const uploadedAttachments = await mapWithConcurrency(files, FORM_DATA_UPLOAD_CONCURRENCY, async (fileWithIndex) => {
- const {file, index} = fileWithIndex;
- const metadata = metadataMap.get(index);
- if (!metadata) {
- throw new Error(`Internal error: metadata not found for file index ${index}`);
- }
- const filename = metadata.filename;
- const uploadKey = crypto.randomUUID();
- const arrayBuffer = await file.arrayBuffer();
- const body = new Uint8Array(arrayBuffer);
- const contentType = getContentTypeFromFilename(filename);
- await runAttachmentStorageOperation(() =>
- this.storageService.uploadObject({
- bucket: Config.s3.buckets.uploads,
- key: uploadKey,
- body,
+ return Promise.all(
+ files.map(async ({index, uploadKey, size}) => {
+ const metadata = metadataMap.get(index);
+ if (!metadata) {
+ throw new Error(`Internal error: metadata not found for file index ${index}`);
+ }
+ const filename = metadata.filename;
+ const contentType = getContentTypeFromFilename(filename);
+ await this.attachmentUploadTraceRepository.recordRequestedUpload({
+ uploadKey,
+ userId,
+ channelId,
+ filename,
contentType,
- }),
- );
- await this.attachmentUploadTraceRepository.recordRequestedUpload({
- uploadKey,
- userId,
- channelId,
- filename,
- contentType,
- uploadMode: 'form_data',
- requestIp: clientIp,
- });
- const uploaded: UploadedAttachment = {
- id: index,
- upload_filename: uploadKey,
- filename: filename,
- file_size: file.size,
- content_type: contentType,
- };
- return uploaded;
- });
- return uploadedAttachments;
+ uploadMode: 'form_data',
+ requestIp: clientIp,
+ });
+ const uploaded: UploadedAttachment = {
+ id: index,
+ upload_filename: uploadKey,
+ filename,
+ file_size: size,
+ content_type: contentType,
+ };
+ return uploaded;
+ }),
+ );
}
async requestPresignedAttachmentUploadUrls({
@@ -188,7 +219,8 @@ export class AttachmentUploadService {
if (!Config.presignedAttachmentUploadsEnabled) {
throw new FeatureTemporarilyDisabledError();
}
- const {maxFileSize} = await this.getUploadPermissionAndLimit({userId, viewer, channelId, actor: 'member'});
+ const {maxFileSize, assertCanAttachFiles} = await this.prepareFormDataUpload({userId, viewer, channelId});
+ await assertCanAttachFiles();
assertAttachmentFileSizesWithinLimit(
attachments.map(({file_size}) => file_size),
maxFileSize,
@@ -296,7 +328,8 @@ export class AttachmentUploadService {
if (!Config.presignedAttachmentUploadsEnabled) {
throw new FeatureTemporarilyDisabledError();
}
- const {maxFileSize} = await this.getUploadPermissionAndLimit({userId, viewer, channelId, actor: 'member'});
+ const {maxFileSize, assertCanAttachFiles} = await this.prepareFormDataUpload({userId, viewer, channelId});
+ await assertCanAttachFiles();
const bucket = Config.s3.buckets.uploads;
return Promise.all(
uploads.map(async ({upload_filename, upload_id}, index) => {
@@ -461,20 +494,13 @@ export class AttachmentUploadService {
}
}
- private async getUploadPermissionAndLimit({
+ async prepareFormDataUpload({
userId,
viewer,
channelId,
- actor,
- }: {
- userId: UserID;
- viewer: ThreadViewer;
- channelId: ChannelID;
- actor: UploadActor;
- }): Promise<{
- maxFileSize: number;
- }> {
- const {channel, guild} =
+ actor = 'member',
+ }: FormDataUploadTarget): Promise<FormDataUpload> {
+ const {channel, guild, assertCanAttachFiles} =
actor === 'webhook'
? await this.getWebhookUploadChannel(channelId)
: await this.getMemberUploadChannel({userId, viewer, channelId});
@@ -491,7 +517,7 @@ export class AttachmentUploadService {
resolveLimitSafe(this.limitConfigService.getConfigSnapshot(), ctx, 'max_attachment_file_size', fallbackMaxSize),
);
const maxFileSize = user.isBot ? Math.min(resolvedMaxFileSize, ATTACHMENT_MAX_SIZE_BOT) : resolvedMaxFileSize;
- return {maxFileSize};
+ return {maxFileSize, assertCanAttachFiles};
}
private async getMemberUploadChannel({
@@ -502,40 +528,36 @@ export class AttachmentUploadService {
userId: UserID;
viewer: ThreadViewer;
channelId: ChannelID;
- }): Promise<{
- channel: Channel;
- guild: GuildResponse | null;
- }> {
+ }): Promise<UploadChannel> {
const {channel, guild, checkPermission, member} =
await this.messageInteractionService.authService.getChannelAuthenticated({
userId,
channelId,
viewer,
});
- if (guild) {
- await checkPermission(Permissions.SEND_MESSAGES | Permissions.ATTACH_FILES);
- assertGuildMemberCanCommunicate(member);
- }
- return {channel, guild};
+ const assertCanAttachFiles = async () => {
+ if (guild) {
+ await checkPermission(Permissions.SEND_MESSAGES | Permissions.ATTACH_FILES);
+ assertGuildMemberCanCommunicate(member);
+ }
+ };
+ return {channel, guild, assertCanAttachFiles};
}
- private async getWebhookUploadChannel(channelId: ChannelID): Promise<{
- channel: Channel;
- guild: GuildResponse | null;
- }> {
+ private async getWebhookUploadChannel(channelId: ChannelID): Promise<UploadChannel> {
const channel = await this.channelRepository.channelData.findUnique(channelId);
if (!channel) {
throw new UnknownChannelError();
}
if (!channel.guildId) {
- return {channel, guild: null};
+ return {channel, guild: null, assertCanAttachFiles: async () => {}};
}
const guild = await this.gatewayService.getGuildData({
guildId: channel.guildId,
userId: SYSTEM_USER_ID,
skipMembershipCheck: true,
});
- return {channel, guild};
+ return {channel, guild, assertCanAttachFiles: async () => {}};
}
}
diff --git a/fluxer_api/src/api/channel/services/FormUploadSlots.ts b/fluxer_api/src/api/channel/services/FormUploadSlots.ts
new file mode 100644
index 000000000..a414f166a
--- /dev/null
+++ b/fluxer_api/src/api/channel/services/FormUploadSlots.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Config} from '@app/api/Config';
+import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
+import {ms} from 'itty-time';
+
+const SLOT_WAIT_MS = ms('10 seconds');
+const RETRY_AFTER_SECONDS = 5;
+
+let activeSlots = 0;
+const waiters: Array<() => void> = [];
+
+function waitForSlot(): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const waiter = () => {
+ clearTimeout(timer);
+ resolve();
+ };
+ const timer = setTimeout(() => {
+ waiters.splice(waiters.indexOf(waiter), 1);
+ reject(new ServiceUnavailableError({headers: {'Retry-After': String(RETRY_AFTER_SECONDS)}}));
+ }, SLOT_WAIT_MS);
+ waiters.push(waiter);
+ });
+}
+
+export async function acquireFormUploadSlot(): Promise<() => void> {
+ if (activeSlots < Config.maxConcurrentFormUploads) {
+ activeSlots++;
+ } else {
+ await waitForSlot();
+ }
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const next = waiters.shift();
+ if (next) {
+ next();
+ } else {
+ activeSlots--;
+ }
+ };
+}
diff --git a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts b/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
index a593005b4..c25400f50 100644
--- a/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageRequestParser.ts
@@ -8,13 +8,15 @@ import {
} from '@app/api/channel/AttachmentDTOs';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import type {MessageRequest, MessageUpdateRequest} from '@app/api/channel/MessageTypes';
+import type {FormDataUpload} from '@app/api/channel/services/AttachmentUploadService';
import {normalizeMessageRequestPayload} from '@app/api/channel/services/message/MessageRequestCompatibility';
+import {type MultipartFilePart, readMultipartStream} from '@app/api/channel/services/message/MultipartStreamReader';
import {SYSTEM_THREAD_VIEWER, viewerFromCtx} from '@app/api/experiment/ChannelThreadsGate';
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 {DEFAULT_REQUEST_BODY_LIMIT, 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';
@@ -34,7 +36,7 @@ import type {z} from 'zod';
const FIELD_NAME_PATTERN = /^files\[(\d+)\]$/;
const LEGACY_FILE_FIELD_NAME_PATTERN = /^file(\d+)?$/;
-type MultipartBody = Record<string, string | File | Array<string | File>>;
+type MultipartBody = Record<string, string>;
type AttachmentMetadata = ClientAttachmentRequest | ClientUploadedAttachmentRequest | ClientAttachmentReferenceRequest;
interface ParseMultipartMessageDataOptions {
@@ -49,83 +51,129 @@ export async function parseMultipartMessageData(
schema: z.ZodType<MessageRequest | MessageUpdateRequest>,
options?: ParseMultipartMessageDataOptions,
): Promise<MessageRequest | MessageUpdateRequest> {
- let body: MultipartBody;
+ const attachmentService = ctx.get('channelService').attachments;
+ const maxAttachments = await resolveMessageAttachmentLimit(ctx, user, channelId);
+ const upload = await attachmentService.prepareFormDataUpload({
+ userId: user.id,
+ viewer: options?.actor === 'webhook' ? SYSTEM_THREAD_VIEWER : viewerFromCtx(ctx),
+ channelId,
+ actor: options?.actor,
+ });
+ const body: MultipartBody = {};
+ const storedFiles: Array<StoredMultipartFile> = [];
try {
- body = await ctx.req.parseBody();
- } catch (_error) {
- throw InputValidationError.fromCode('multipart_form', ValidationErrorCodes.FAILED_TO_PARSE_MULTIPART_FORM_DATA);
- }
- const jsonData = parseMultipartPayload(body);
- const mergedJsonData = normalizeMessageRequestPayload(mergeMultipartScalarFields(body, jsonData));
- options?.onPayloadParsed?.(mergedJsonData);
- const validationResult = schema.safeParse(mergedJsonData);
- if (!validationResult.success) {
- throw inputValidationErrorFromZodIssues(validationResult.error.issues);
+ const data = await readMultipartMessageBody(ctx, {
+ body,
+ storedFiles,
+ maxAttachments,
+ upload,
+ storeFile: (stream, filename) => attachmentService.storeFormDataFile({body: stream, filename}),
+ });
+ const mergedJsonData = normalizeMessageRequestPayload(mergeMultipartScalarFields(body, data));
+ options?.onPayloadParsed?.(mergedJsonData);
+ const validationResult = schema.safeParse(mergedJsonData);
+ if (!validationResult.success) {
+ throw inputValidationErrorFromZodIssues(validationResult.error.issues);
+ }
+ return await attachStoredFiles(ctx, user, channelId, validationResult.data, storedFiles);
+ } catch (error) {
+ await attachmentService.deleteFormDataFiles(storedFiles.map((file) => file.uploadKey));
+ throw error;
}
- const data = validationResult.data as Partial<MessageRequest> &
- Partial<MessageUpdateRequest> & {
- attachments?: Array<AttachmentRequestData>;
- };
- const maxAttachments = await resolveMessageAttachmentLimit(ctx, user, channelId);
+}
+
+interface StoredMultipartFile {
+ index: number;
+ filename: string;
+ uploadKey: string;
+ size: number;
+}
+
+async function readMultipartMessageBody(
+ ctx: Context<HonoEnv>,
+ params: {
+ body: MultipartBody;
+ storedFiles: Array<StoredMultipartFile>;
+ maxAttachments: number;
+ upload: FormDataUpload;
+ storeFile: (stream: MultipartFilePart['stream'], filename: string) => Promise<string>;
+ },
+): Promise<unknown> {
+ const {body, storedFiles, maxAttachments, upload, storeFile} = params;
const maxIndexLabel = maxAttachments > 0 ? maxAttachments - 1 : 0;
- const filesWithIndices: Array<{
- file: File;
- index: number;
- }> = [];
const seenIndices = new Set<number>();
let nextLegacyFileIndex = 0;
- for (const [key, fieldValue] of Object.entries(body)) {
- const fileIndex = getMultipartFileFieldIndex(key, nextLegacyFileIndex);
- if (fileIndex === null) {
- continue;
- }
- if (fileIndex.isLegacy) {
- nextLegacyFileIndex = Math.max(nextLegacyFileIndex, fileIndex.index + 1);
- }
- const {index} = fileIndex;
- if (Number.isNaN(index) || index < 0 || index > 10000) {
- throw InputValidationError.fromCode('files', ValidationErrorCodes.FILE_INDEX_EXCEEDS_MAXIMUM, {
- index,
- maxIndex: 10000,
- });
- }
- if (maxAttachments <= 0) {
- throw InputValidationError.fromCode('files', ValidationErrorCodes.ATTACHMENTS_NOT_ALLOWED_FOR_MESSAGE);
- }
- if (index >= maxAttachments) {
- throw InputValidationError.fromCode('files', ValidationErrorCodes.FILE_INDEX_EXCEEDS_MAXIMUM, {
- index,
- maxIndex: maxIndexLabel,
- });
- }
- if (seenIndices.has(index)) {
- throw InputValidationError.fromCode('files', ValidationErrorCodes.DUPLICATE_FILE_INDEX, {
- index,
- });
- }
- if (fieldValue instanceof File) {
- filesWithIndices.push({file: fieldValue, index});
- seenIndices.add(index);
- } else if (Array.isArray(fieldValue)) {
- const validFiles = fieldValue.filter((f) => f instanceof File);
- if (validFiles.length > 0) {
- if (fileIndex.isLegacy && validFiles.length === 1) {
- filesWithIndices.push({file: validFiles[0], index});
- seenIndices.add(index);
- continue;
- }
- throw InputValidationError.fromCode('files', ValidationErrorCodes.MULTIPLE_FILES_FOR_INDEX_NOT_ALLOWED, {
+ let canAttachFiles = false;
+ let payload: unknown = {};
+ await readMultipartStream(ctx, {
+ maxFiles: maxAttachments,
+ maxFileSize: upload.maxFileSize,
+ maxFieldBytes: DEFAULT_REQUEST_BODY_LIMIT,
+ onField(name, value) {
+ if (getMultipartFileFieldIndex(name, 0) !== null) {
+ return;
+ }
+ body[name] = value;
+ if (name === 'payload_json') {
+ payload = parseMultipartPayload(value);
+ }
+ },
+ async onFile({fieldName, filename, stream}) {
+ const fileIndex = getMultipartFileFieldIndex(fieldName, nextLegacyFileIndex);
+ if (fileIndex === null) {
+ stream.resume();
+ return;
+ }
+ if (fileIndex.isLegacy) {
+ nextLegacyFileIndex = Math.max(nextLegacyFileIndex, fileIndex.index + 1);
+ }
+ const {index} = fileIndex;
+ if (Number.isNaN(index) || index < 0 || index > 10000) {
+ throw InputValidationError.fromCode('files', ValidationErrorCodes.FILE_INDEX_EXCEEDS_MAXIMUM, {
index,
+ maxIndex: 10000,
});
}
- }
- }
- filesWithIndices.sort((left, right) => left.index - right.index);
- if (filesWithIndices.length > maxAttachments) {
- throw InputValidationError.fromCode('files', ValidationErrorCodes.TOO_MANY_FILES, {maxFiles: maxAttachments});
- }
+ if (maxAttachments <= 0) {
+ throw InputValidationError.fromCode('files', ValidationErrorCodes.ATTACHMENTS_NOT_ALLOWED_FOR_MESSAGE);
+ }
+ if (index >= maxAttachments) {
+ throw InputValidationError.fromCode('files', ValidationErrorCodes.FILE_INDEX_EXCEEDS_MAXIMUM, {
+ index,
+ maxIndex: maxIndexLabel,
+ });
+ }
+ if (seenIndices.has(index)) {
+ throw InputValidationError.fromCode('files', ValidationErrorCodes.DUPLICATE_FILE_INDEX, {
+ index,
+ });
+ }
+ seenIndices.add(index);
+ if (!canAttachFiles) {
+ await upload.assertCanAttachFiles();
+ canAttachFiles = true;
+ }
+ const uploadKey = await storeFile(stream, filename);
+ storedFiles.push({index, filename, uploadKey, size: stream.bytesRead});
+ },
+ });
+ return payload;
+}
+
+async function attachStoredFiles(
+ ctx: Context<HonoEnv>,
+ user: User,
+ channelId: ChannelID,
+ validated: MessageRequest | MessageUpdateRequest,
+ storedFiles: Array<StoredMultipartFile>,
+): Promise<MessageRequest | MessageUpdateRequest> {
+ const data = validated as Partial<MessageRequest> &
+ Partial<MessageUpdateRequest> & {
+ attachments?: Array<AttachmentRequestData>;
+ };
+ storedFiles.sort((left, right) => left.index - right.index);
const attachmentMetadata = Array.isArray(data.attachments) ? (data.attachments as Array<AttachmentMetadata>) : [];
- const fileIds = new Set(filesWithIndices.map((file) => file.index));
+ const fileIds = new Set(storedFiles.map((file) => file.index));
const inlineAttachmentMetadata = new Map<number, AttachmentMetadata>();
const existingAttachments: Array<ClientAttachmentReferenceRequest> = [];
for (const metadata of attachmentMetadata) {
@@ -144,11 +192,11 @@ export async function parseMultipartMessageData(
}
existingAttachments.push(metadata);
}
- if (filesWithIndices.length > 0) {
+ if (storedFiles.length > 0) {
const clientIp = requireRequestClientIp(ctx);
- const inlineNewAttachments = filesWithIndices.map(({file, index}) =>
+ const inlineNewAttachments = storedFiles.map(({filename, index}) =>
buildInlineAttachmentMetadata({
- file,
+ filename,
index,
metadata: inlineAttachmentMetadata.get(index),
}),
@@ -157,12 +205,10 @@ export async function parseMultipartMessageData(
.get('channelService')
.attachments.uploadFormDataAttachments({
userId: user.id,
- viewer: options?.actor === 'webhook' ? SYSTEM_THREAD_VIEWER : viewerFromCtx(ctx),
channelId,
clientIp,
- files: filesWithIndices,
+ files: storedFiles,
attachmentMetadata: inlineNewAttachments,
- actor: options?.actor,
});
const uploadedMap = new Map(uploadedAttachments.map((attachment) => [attachment.id, attachment]));
const processedInlineAttachments = inlineNewAttachments.map((clientData) => {
@@ -181,14 +227,7 @@ export async function parseMultipartMessageData(
return data as MessageRequest | MessageUpdateRequest;
}
-function parseMultipartPayload(body: MultipartBody): unknown {
- const payloadJson = body['payload_json'];
- if (payloadJson === undefined) {
- return {};
- }
- if (typeof payloadJson !== 'string') {
- throw InputValidationError.fromCode('payload_json', ValidationErrorCodes.INVALID_JSON_IN_PAYLOAD_JSON);
- }
+function parseMultipartPayload(payloadJson: string): unknown {
try {
return parseJsonPreservingLargeIntegers(payloadJson);
} catch (_error) {
@@ -205,26 +244,22 @@ function mergeMultipartScalarFields(body: MultipartBody, payload: unknown): unkn
if (key === 'payload_json' || getMultipartFileFieldIndex(key, 0) !== null) {
continue;
}
- const values = getMultipartStringValues(value);
- if (values.length === 0) {
- continue;
- }
switch (key) {
case 'content':
case 'nonce':
- mergedPayload[key] = values[values.length - 1];
+ mergedPayload[key] = value;
break;
case 'tts':
- mergedPayload.tts = parseMultipartBoolean(values[values.length - 1]!);
+ mergedPayload.tts = parseMultipartBoolean(value);
break;
case 'flags':
- mergedPayload.flags = parseMultipartInteger(values[values.length - 1]!);
+ mergedPayload.flags = parseMultipartInteger(value);
break;
case 'favorite_meme_id':
- mergedPayload.favorite_meme_id = values[values.length - 1];
+ mergedPayload.favorite_meme_id = value;
break;
case 'sticker_ids':
- mergedPayload.sticker_ids = values;
+ mergedPayload.sticker_ids = [value];
break;
default:
break;
@@ -259,16 +294,6 @@ function getMultipartFileFieldIndex(
};
}
-function getMultipartStringValues(value: MultipartBody[string]): Array<string> {
- if (typeof value === 'string') {
- return [value];
- }
- if (value instanceof File) {
- return [];
- }
- return value.filter((entry): entry is string => typeof entry === 'string');
-}
-
function parseMultipartBoolean(value: string): boolean | string {
const normalized = value.trim().toLowerCase();
if (normalized === 'true') {
@@ -304,14 +329,14 @@ function getMatchingMultipartFileIndex(id: number | bigint, fileIds: Set<number>
}
function buildInlineAttachmentMetadata(params: {
- file: File;
+ filename: string;
index: number;
metadata?: AttachmentMetadata;
}): ClientAttachmentRequest {
- const {file, index, metadata} = params;
+ const {filename, index, metadata} = params;
return {
id: index,
- filename: metadata && 'filename' in metadata && metadata.filename ? metadata.filename : file.name,
+ filename: metadata && 'filename' in metadata && metadata.filename ? metadata.filename : filename,
content_type:
metadata && 'content_type' in metadata ? (metadata as ClientUploadedAttachmentRequest).content_type : undefined,
title: metadata?.title ?? null,
diff --git a/fluxer_api/src/api/channel/services/message/MultipartStreamReader.ts b/fluxer_api/src/api/channel/services/message/MultipartStreamReader.ts
new file mode 100644
index 000000000..5a1b947fd
--- /dev/null
+++ b/fluxer_api/src/api/channel/services/message/MultipartStreamReader.ts
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {Readable} from 'node:stream';
+import type {ReadableStream as NodeReadableStream} from 'node:stream/web';
+import type {HonoEnv} from '@app/api/types/HonoEnv';
+import Busboy, {type BusboyFileStream} from '@fastify/busboy';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {FileSizeTooLargeError} from '@fluxer/errors/src/domains/core/FileSizeTooLargeError';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
+import {RequestBodyTooLargeError} from '@fluxer/errors/src/domains/core/RequestBodyTooLargeError';
+import type {Context} from 'hono';
+import {ms} from 'itty-time';
+
+const MAX_MULTIPART_FIELDS = 64;
+const DISCARD_MAX_BYTES = 64 * 1024 * 1024;
+const DISCARD_TIMEOUT_MS = ms('30 seconds');
+
+export interface MultipartFilePart {
+ fieldName: string;
+ filename: string;
+ stream: BusboyFileStream;
+}
+
+interface ReadMultipartStreamOptions {
+ maxFiles: number;
+ maxFileSize: number;
+ maxFieldBytes: number;
+ onField: (name: string, value: string) => void;
+ onFile: (part: MultipartFilePart) => Promise<void>;
+}
+
+function multipartParseError(): InputValidationError {
+ return InputValidationError.fromCode('multipart_form', ValidationErrorCodes.FAILED_TO_PARSE_MULTIPART_FORM_DATA);
+}
+
+function multipartBodyBudget({
+ maxFiles,
+ maxFileSize,
+ maxFieldBytes,
+}: Pick<ReadMultipartStreamOptions, 'maxFiles' | 'maxFileSize' | 'maxFieldBytes'>): number {
+ return Math.max(0, maxFiles) * Math.max(0, maxFileSize) + maxFieldBytes;
+}
+
+function discardRest(source: Readable, remaining: number | null): Promise<void> {
+ if (source.readableEnded || source.destroyed || (remaining !== null && remaining > DISCARD_MAX_BYTES)) {
+ source.destroy();
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ let discarded = 0;
+ const done = () => {
+ clearTimeout(timer);
+ source.off('data', onData);
+ source.off('end', done);
+ source.off('error', done);
+ resolve();
+ };
+ const stop = () => {
+ done();
+ source.destroy();
+ };
+ const onData = (chunk: Buffer) => {
+ discarded += chunk.length;
+ if (discarded > DISCARD_MAX_BYTES) stop();
+ };
+ const timer = setTimeout(stop, DISCARD_TIMEOUT_MS);
+ source.on('data', onData);
+ source.once('end', done);
+ source.once('error', done);
+ source.resume();
+ });
+}
+
+export async function readMultipartStream(ctx: Context<HonoEnv>, options: ReadMultipartStreamOptions): Promise<void> {
+ const {maxFiles, maxFileSize, maxFieldBytes, onField, onFile} = options;
+ const budget = multipartBodyBudget(options);
+ const declaredLength = Number(ctx.req.header('content-length'));
+ const knownLength = Number.isFinite(declaredLength) ? declaredLength : null;
+ const body = ctx.req.raw.body;
+ if (!body) {
+ return;
+ }
+ const source = Readable.fromWeb(body as NodeReadableStream<Uint8Array>);
+ if (knownLength !== null && knownLength > budget) {
+ await discardRest(source, knownLength);
+ throw new RequestBodyTooLargeError(budget);
+ }
+ let parser: ReturnType<typeof Busboy>;
+ try {
+ parser = Busboy({
+ headers: {'content-type': ctx.req.header('content-type') ?? ''},
+ isPartAFile: (_fieldName, _contentType, filename) => filename !== undefined,
+ limits: {
+ fileSize: maxFileSize,
+ fields: MAX_MULTIPART_FIELDS,
+ fieldSize: maxFieldBytes,
+ parts: Math.max(0, maxFiles) + MAX_MULTIPART_FIELDS,
+ },
+ });
+ } catch {
+ await discardRest(source, knownLength);
+ throw multipartParseError();
+ }
+ await new Promise<void>((resolve, reject) => {
+ let settled = false;
+ let bytesRead = 0;
+ let fieldBytes = 0;
+ let pending: Promise<void> = Promise.resolve();
+ let currentFile: BusboyFileStream | null = null;
+ const fail = (error: unknown) => {
+ if (settled) return;
+ settled = true;
+ source.unpipe(parser);
+ currentFile?.destroy();
+ const remaining = knownLength === null ? null : knownLength - bytesRead;
+ Promise.all([pending.catch(() => undefined), discardRest(source, remaining)]).then(() => reject(error));
+ };
+ source.on('data', (chunk: Buffer) => {
+ bytesRead += chunk.length;
+ if (bytesRead > budget) fail(new RequestBodyTooLargeError(budget));
+ });
+ parser.on('field', (name, value, _nameTruncated, valueTruncated) => {
+ if (settled) return;
+ try {
+ if (name === undefined) throw multipartParseError();
+ fieldBytes += Buffer.byteLength(name) + Buffer.byteLength(value);
+ if (valueTruncated || fieldBytes > maxFieldBytes) throw new RequestBodyTooLargeError(maxFieldBytes);
+ onField(name, value);
+ } catch (error) {
+ fail(error);
+ }
+ });
+ parser.on('file', (fieldName, stream, filename) => {
+ if (settled || fieldName === undefined) {
+ stream.resume();
+ fail(multipartParseError());
+ return;
+ }
+ stream.once('limit', () => fail(new FileSizeTooLargeError(maxFileSize)));
+ pending = pending.then(async () => {
+ if (settled) {
+ stream.resume();
+ return;
+ }
+ currentFile = stream;
+ try {
+ await onFile({fieldName, filename, stream});
+ } finally {
+ currentFile = null;
+ }
+ if (stream.truncated) {
+ throw new FileSizeTooLargeError(maxFileSize);
+ }
+ });
+ pending.catch(fail);
+ });
+ parser.on('fieldsLimit', () => fail(multipartParseError()));
+ parser.on('partsLimit', () => fail(multipartParseError()));
+ parser.on('error', () => fail(multipartParseError()));
+ source.on('error', () => fail(multipartParseError()));
+ parser.on('finish', () => {
+ pending.then(() => {
+ if (settled) return;
+ settled = true;
+ resolve();
+ }, fail);
+ });
+ source.pipe(parser);
+ });
+}
diff --git a/fluxer_api/src/api/channel/tests/AttachmentFormDataStreaming.test.ts b/fluxer_api/src/api/channel/tests/AttachmentFormDataStreaming.test.ts
new file mode 100644
index 000000000..2f476332c
--- /dev/null
+++ b/fluxer_api/src/api/channel/tests/AttachmentFormDataStreaming.test.ts
@@ -0,0 +1,463 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createHash, randomUUID} from 'node:crypto';
+import {once} from 'node:events';
+import net, {type AddressInfo} from 'node:net';
+import {Readable} from 'node:stream';
+import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {authorizeBot, createTestBotAccount} from '@app/api/bot/tests/BotTestUtils';
+import {Config, getConfig} from '@app/api/Config';
+import {createChannel, createGuild} from '@app/api/channel/tests/AttachmentTestUtils';
+import {THREADS_FEATURE, THREADS_FEATURE_HEADER} from '@app/api/channel/tests/ThreadTestUtils';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
+import {setInjectedMediaService} from '@app/api/middleware/ServiceRegistry';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {TestMediaService} from '@app/api/test/TestMediaService';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
+import {ATTACHMENT_MAX_SIZE_BOT} from '@fluxer/constants/src/LimitConstants';
+import type {WebhookCreateResponse} from '@fluxer/schema/src/domains/webhook/WebhookSchemas';
+import {serve} from '@hono/node-server';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+const MIB = 1024 * 1024;
+
+type Part =
+ | {name: string; value: string}
+ | {headers: string; value: string}
+ | {name: string; filename: string; size: number; fill?: number};
+
+interface StreamedBody {
+ boundary: string;
+ pieces: Array<Buffer | {size: number; fill: number}>;
+ stream: ReadableStream<Uint8Array>;
+ contentType: string;
+ length: number;
+ bytesRead: () => number;
+}
+
+function streamedMultipart(parts: Array<Part>): StreamedBody {
+ const boundary = `----Boundary${randomUUID()}`;
+ const pieces: Array<Buffer | {size: number; fill: number}> = [];
+ for (const part of parts) {
+ if ('headers' in part) {
+ pieces.push(Buffer.from(`--${boundary}\r\n${part.headers}\r\n\r\n${part.value}\r\n`));
+ continue;
+ }
+ if ('value' in part) {
+ pieces.push(
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${part.name}"\r\n\r\n${part.value}\r\n`),
+ );
+ continue;
+ }
+ pieces.push(
+ Buffer.from(
+ `--${boundary}\r\nContent-Disposition: form-data; name="${part.name}"; filename="${part.filename}"\r\nContent-Type: application/octet-stream\r\n\r\n`,
+ ),
+ );
+ pieces.push({size: part.size, fill: part.fill ?? 0x61});
+ pieces.push(Buffer.from('\r\n'));
+ }
+ pieces.push(Buffer.from(`--${boundary}--\r\n`));
+ const length = pieces.reduce((sum, piece) => sum + (Buffer.isBuffer(piece) ? piece.length : piece.size), 0);
+ let read = 0;
+ let pieceIndex = 0;
+ let offset = 0;
+ const stream = new ReadableStream<Uint8Array>(
+ {
+ pull(controller) {
+ const piece = pieces[pieceIndex];
+ if (!piece) {
+ controller.close();
+ return;
+ }
+ if (Buffer.isBuffer(piece)) {
+ pieceIndex++;
+ read += piece.length;
+ controller.enqueue(new Uint8Array(piece));
+ return;
+ }
+ const chunkSize = Math.min(MIB, piece.size - offset);
+ offset += chunkSize;
+ read += chunkSize;
+ if (offset >= piece.size) {
+ pieceIndex++;
+ offset = 0;
+ }
+ controller.enqueue(new Uint8Array(chunkSize).fill(piece.fill));
+ },
+ },
+ {highWaterMark: 0},
+ );
+ return {
+ boundary,
+ pieces,
+ stream,
+ contentType: `multipart/form-data; boundary=${boundary}`,
+ length,
+ bytesRead: () => read,
+ };
+}
+
+function sha256OfFill(size: number, fill: number): string {
+ return createHash('sha256').update(Buffer.alloc(size, fill)).digest('hex');
+}
+
+describe('streamed multipart attachment uploads', () => {
+ let harness: ApiTestHarness;
+ let owner: TestAccount;
+ let guildId: string;
+ let channelId: string;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ setInjectedMediaService(new TestMediaService(harness.storageService));
+ owner = await createTestAccount(harness);
+ await ensureSessionStarted(harness, owner.token);
+ const guild = await createGuild(harness, owner.token, 'Streaming Guild');
+ guildId = guild.id;
+ channelId = guild.system_channel_id ?? (await createChannel(harness, owner.token, guild.id, 'general')).id;
+ });
+
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
+ async function post(
+ path: string,
+ body: StreamedBody,
+ authorization: string | null,
+ headers: Record<string, string> = {},
+ method = 'POST',
+ ): Promise<Response> {
+ return harness.app.request(path, {
+ method,
+ headers: {
+ ...(authorization ? {Authorization: authorization} : {}),
+ 'Content-Type': body.contentType,
+ 'x-forwarded-for': '127.0.0.1',
+ ...headers,
+ },
+ body: body.stream,
+ duplex: 'half',
+ } as RequestInit);
+ }
+
+ async function botAuthorization(): Promise<string> {
+ const bot = await createTestBotAccount(harness);
+ await authorizeBot(harness, owner.token, bot.appId, ['bot'], guildId, Permissions.ADMINISTRATOR.toString());
+ return `Bot ${bot.botToken}`;
+ }
+
+ function uploadedKeys(): Array<string> {
+ return harness.storageService.uploadObjectSpy.mock.calls
+ .map(([params]) => params as {bucket: string; key: string})
+ .filter((params) => params.bucket === Config.s3.buckets.uploads)
+ .map((params) => params.key);
+ }
+
+ it('reads the rest of a slightly oversized bot upload before answering', async () => {
+ const authorization = await botAuthorization();
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({content: 'big'})},
+ {name: 'files[0]', filename: 'big.bin', size: 60 * MIB},
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, authorization);
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toMatchObject({code: 'FILE_SIZE_TOO_LARGE'});
+ expect(body.bytesRead()).toBe(body.length);
+ for (const key of uploadedKeys()) {
+ expect(harness.storageService.hasObject(Config.s3.buckets.uploads, key)).toBe(false);
+ }
+ });
+
+ it('stops reading a bot upload that runs far past the bot limit', async () => {
+ const authorization = await botAuthorization();
+ const body = streamedMultipart([{name: 'files[0]', filename: 'huge.bin', size: 200 * MIB}]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, authorization);
+
+ expect(response.status).toBe(400);
+ expect(await response.json()).toMatchObject({code: 'FILE_SIZE_TOO_LARGE'});
+ expect(body.bytesRead()).toBeLessThan(ATTACHMENT_MAX_SIZE_BOT + 70 * MIB);
+ });
+
+ it('answers a client that keeps sending past the limit with the JSON error', async () => {
+ const authorization = await botAuthorization();
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({content: 'big'})},
+ {name: 'files[0]', filename: 'big.bin', size: 60 * MIB},
+ ]);
+ const server = serve({fetch: harness.app.fetch, port: 0, hostname: '127.0.0.1'});
+ await once(server, 'listening');
+ const {port} = server.address() as AddressInfo;
+
+ const outcome = await new Promise<string>((resolve) => {
+ const socket = net.connect(port, '127.0.0.1');
+ let received = '';
+ socket.on('data', (chunk) => {
+ received += chunk.toString('latin1');
+ });
+ socket.on('error', (error: NodeJS.ErrnoException) => resolve(`socket error ${error.code}`));
+ socket.on('end', () => resolve(received));
+ socket.write(
+ [
+ `POST /channels/${channelId}/messages HTTP/1.1`,
+ 'Host: 127.0.0.1',
+ `Authorization: ${authorization}`,
+ `Content-Type: ${body.contentType}`,
+ `Content-Length: ${body.length}`,
+ 'x-forwarded-for: 127.0.0.1',
+ 'Connection: close',
+ '',
+ '',
+ ].join('\r\n'),
+ );
+ const pieces = [...body.pieces];
+ const pump = () => {
+ for (let piece = pieces.shift(); piece; piece = pieces.shift()) {
+ const chunk = Buffer.isBuffer(piece) ? piece : Buffer.alloc(piece.size, piece.fill);
+ if (!socket.write(chunk)) {
+ socket.once('drain', pump);
+ return;
+ }
+ }
+ };
+ pump();
+ });
+ server.close();
+
+ expect(outcome).toMatch(/^HTTP\/1\.1 400 /);
+ expect(outcome).toContain('"code":"FILE_SIZE_TOO_LARGE"');
+ });
+
+ it('rejects a declared length above the upload budget before reading the body', async () => {
+ const authorization = await botAuthorization();
+ const body = streamedMultipart([{name: 'files[0]', filename: 'big.bin', size: 600 * MIB}]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, authorization, {
+ 'content-length': String(body.length),
+ });
+
+ expect(response.status).toBe(413);
+ expect(body.bytesRead()).toBe(0);
+ });
+
+ it('streams an accepted file to storage without changing it', async () => {
+ const size = 20 * MIB;
+ const body = streamedMultipart([
+ {
+ name: 'payload_json',
+ value: JSON.stringify({content: 'ok', attachments: [{id: 0, filename: 'data.bin'}]}),
+ },
+ {name: 'files[0]', filename: 'data.bin', size, fill: 0x42},
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, owner.token);
+
+ expect(response.status).toBe(200);
+ const [params] = harness.storageService.uploadObjectSpy.mock.calls.find(
+ ([call]) => (call as {bucket: string}).bucket === Config.s3.buckets.uploads,
+ )!;
+ expect((params as {body: unknown}).body).toBeInstanceOf(Readable);
+ const message = (await response.json()) as {attachments: Array<{size: number; filename: string}>};
+ expect(message.attachments[0]).toMatchObject({size, filename: 'data.bin'});
+ const copied = harness.storageService.getCopiedObjects().find((copy) => copy.destinationKey.endsWith('data.bin'));
+ expect(copied).toBeDefined();
+ const stored = await harness.storageService.readObject(Config.s3.buckets.cdn, copied!.destinationKey);
+ expect(createHash('sha256').update(stored).digest('hex')).toBe(sha256OfFill(size, 0x42));
+ });
+
+ it('deletes a stored file when payload_json after it is invalid', async () => {
+ const body = streamedMultipart([
+ {name: 'files[0]', filename: 'first.bin', size: MIB},
+ {name: 'payload_json', value: '{not json'},
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, owner.token);
+
+ expect(response.status).toBe(400);
+ const keys = uploadedKeys();
+ expect(keys).toHaveLength(1);
+ expect(harness.storageService.hasObject(Config.s3.buckets.uploads, keys[0]!)).toBe(false);
+ });
+
+ it('deletes a stored file when the merged payload fails validation', async () => {
+ const body = streamedMultipart([
+ {name: 'files[0]', filename: 'first.bin', size: MIB},
+ {name: 'payload_json', value: JSON.stringify({flags: 'not a number'})},
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, owner.token);
+
+ expect(response.status).toBe(400);
+ const keys = uploadedKeys();
+ expect(keys).toHaveLength(1);
+ expect(harness.storageService.hasObject(Config.s3.buckets.uploads, keys[0]!)).toBe(false);
+ });
+
+ it('rejects a text channel thread body above the request body limit', async () => {
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({name: 'thread', type: ChannelTypes.PUBLIC_THREAD})},
+ {name: 'files[0]', filename: 'big.bin', size: 20 * MIB},
+ ]);
+
+ const response = await post(`/channels/${channelId}/threads`, body, owner.token, {
+ [THREADS_FEATURE_HEADER]: THREADS_FEATURE,
+ });
+
+ expect(response.status).toBe(413);
+ expect(await response.json()).toMatchObject({code: 'FILE_SIZE_TOO_LARGE'});
+ });
+
+ it('ignores a small file part when creating a text channel thread', async () => {
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({name: 'thread', type: ChannelTypes.PUBLIC_THREAD})},
+ {name: 'files[0]', filename: 'small.bin', size: 1024},
+ ]);
+
+ const response = await post(`/channels/${channelId}/threads`, body, owner.token, {
+ [THREADS_FEATURE_HEADER]: THREADS_FEATURE,
+ });
+
+ expect(response.status).toBe(201);
+ expect(uploadedKeys()).toHaveLength(0);
+ });
+
+ it('reads an octet-stream part without a filename as a field', async () => {
+ const body = streamedMultipart([
+ {
+ headers: 'Content-Disposition: form-data; name="payload_json"\r\nContent-Type: application/octet-stream',
+ value: JSON.stringify({content: 'octet'}),
+ },
+ {
+ headers: 'Content-Disposition: form-data; name="files[0]"\r\nContent-Type: application/octet-stream',
+ value: 'not a file',
+ },
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages`, body, owner.token);
+
+ expect(response.status).toBe(200);
+ const message = (await response.json()) as {content: string; attachments?: Array<unknown>};
+ expect(message.content).toBe('octet');
+ expect(message.attachments ?? []).toHaveLength(0);
+ expect(uploadedKeys()).toHaveLength(0);
+ });
+
+ it('does not count unrecognised file parts toward the attachment limit', async () => {
+ const parts: Array<Part> = [{name: 'payload_json', value: JSON.stringify({content: 'ten'})}];
+ for (let index = 0; index < 10; index++) {
+ parts.push({name: `files[${index}]`, filename: `f${index}.bin`, size: 1024});
+ }
+ parts.push({name: 'thumbnail', filename: 'thumb.bin', size: 1024});
+ parts.push({name: 'attachment', filename: 'extra.bin', size: 1024});
+
+ const response = await post(`/channels/${channelId}/messages`, streamedMultipart(parts), owner.token);
+
+ expect(response.status).toBe(200);
+ expect(((await response.json()) as {attachments: Array<unknown>}).attachments).toHaveLength(10);
+ });
+
+ it('rejects a part without a name on every multipart route', async () => {
+ const webhook = await createBuilder<WebhookCreateResponse>(harness, owner.token)
+ .post(`/channels/${channelId}/webhooks`)
+ .body({name: 'Nameless'})
+ .execute();
+ const nameless: Array<Part> = [
+ {headers: 'Content-Disposition: form-data', value: 'value'},
+ {headers: 'Content-Disposition: form-data; filename="a.bin"', value: 'abc'},
+ ];
+ const statuses: Array<number> = [];
+ for (const part of nameless) {
+ statuses.push((await post(`/channels/${channelId}/messages`, streamedMultipart([part]), owner.token)).status);
+ statuses.push((await post(`/webhooks/${webhook.id}/${webhook.token}`, streamedMultipart([part]), null)).status);
+ statuses.push(
+ (
+ await post(`/channels/${channelId}/threads`, streamedMultipart([part]), owner.token, {
+ [THREADS_FEATURE_HEADER]: THREADS_FEATURE,
+ })
+ ).status,
+ );
+ }
+
+ expect(statuses).toEqual([400, 400, 400, 400, 400, 400]);
+ });
+
+ it('limits how many files stream to storage at once', async () => {
+ const config = getConfig();
+ const previousLimit = config.maxConcurrentFormUploads;
+ config.maxConcurrentFormUploads = 2;
+ const storage = harness.storageService;
+ const uploadObject = storage.uploadObject.bind(storage);
+ let inflight = 0;
+ let peak = 0;
+ storage.uploadObject = async (params) => {
+ inflight++;
+ peak = Math.max(peak, inflight);
+ try {
+ return await uploadObject(params);
+ } finally {
+ inflight--;
+ }
+ };
+ try {
+ const statuses = await Promise.all(
+ Array.from({length: 6}, async (_, index) => {
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({content: `upload ${index}`})},
+ {name: 'files[0]', filename: 'part.bin', size: 4 * MIB},
+ ]);
+ return (await post(`/channels/${channelId}/messages`, body, owner.token)).status;
+ }),
+ );
+
+ expect(statuses).toEqual([200, 200, 200, 200, 200, 200]);
+ expect(peak).toBe(2);
+ } finally {
+ storage.uploadObject = uploadObject;
+ config.maxConcurrentFormUploads = previousLimit;
+ }
+ });
+
+ it('still accepts a file on message edit', async () => {
+ const created = await createBuilder<{id: string}>(harness, owner.token)
+ .post(`/channels/${channelId}/messages`)
+ .body({content: 'before'})
+ .execute();
+ const body = streamedMultipart([
+ {
+ name: 'payload_json',
+ value: JSON.stringify({content: 'after', attachments: [{id: 0, filename: 'edit.bin'}]}),
+ },
+ {name: 'files[0]', filename: 'edit.bin', size: MIB},
+ ]);
+
+ const response = await post(`/channels/${channelId}/messages/${created.id}`, body, owner.token, {}, 'PATCH');
+
+ expect(response.status).toBe(200);
+ expect(((await response.json()) as {attachments: Array<unknown>}).attachments).toHaveLength(1);
+ });
+
+ it('still accepts a file on webhook execute', async () => {
+ const webhook = await createBuilder<WebhookCreateResponse>(harness, owner.token)
+ .post(`/channels/${channelId}/webhooks`)
+ .body({name: 'Uploader'})
+ .execute();
+ const body = streamedMultipart([
+ {name: 'payload_json', value: JSON.stringify({content: 'hook'})},
+ {name: 'files[0]', filename: 'hook.bin', size: MIB},
+ ]);
+
+ const response = await post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`, body, null);
+
+ expect(response.status).toBe(200);
+ expect(((await response.json()) as {attachments: Array<unknown>}).attachments).toHaveLength(1);
+ });
+});
diff --git a/fluxer_api/src/api/config/APIConfig.ts b/fluxer_api/src/api/config/APIConfig.ts
index bdb897ac0..ccf4da3de 100644
--- a/fluxer_api/src/api/config/APIConfig.ts
+++ b/fluxer_api/src/api/config/APIConfig.ts
@@ -87,6 +87,7 @@ export interface APIConfig {
headersTimeoutMs: number;
requestTimeoutMs: number;
maxInflightRequests: number;
+ maxConcurrentFormUploads: number;
automatedMessageDeletionDelayDays: number;
ipBanExemptIps: Array<string>;
cassandra: {
diff --git a/fluxer_api/src/api/infrastructure/StorageService.ts b/fluxer_api/src/api/infrastructure/StorageService.ts
index 9c8ec418a..3375765e7 100644
--- a/fluxer_api/src/api/infrastructure/StorageService.ts
+++ b/fluxer_api/src/api/infrastructure/StorageService.ts
@@ -37,6 +37,8 @@ import {temporaryFile} from 'tempy';
const STREAM_UPLOAD_PART_BYTES = 8 * 1024 * 1024;
const STREAM_UPLOAD_CONCURRENCY = 4;
+const READABLE_UPLOAD_PART_BYTES = 5 * 1024 * 1024;
+const READABLE_UPLOAD_QUEUE_SIZE = 1;
interface PooledS3Options {
endpoint: string;
@@ -223,8 +225,8 @@ export class StorageService implements IStorageService {
ContentType: contentType,
Expires: expiresAt,
},
- partSize: STREAM_UPLOAD_PART_BYTES,
- queueSize: STREAM_UPLOAD_CONCURRENCY,
+ partSize: READABLE_UPLOAD_PART_BYTES,
+ queueSize: READABLE_UPLOAD_QUEUE_SIZE,
leavePartsOnError: false,
});
await upload.done();
diff --git a/fluxer_docs/src/content/docs/operator/environment.mdx b/fluxer_docs/src/content/docs/operator/environment.mdx
index 3adc67763..c76f7d276 100644
--- a/fluxer_docs/src/content/docs/operator/environment.mdx
+++ b/fluxer_docs/src/content/docs/operator/environment.mdx
@@ -1152,6 +1152,10 @@ How long a client may take over a whole request to the API, in milliseconds from
How many requests the API handles at once before it responds to new ones with 503 and a Retry-After header, from 1 to 100000. When it's empty, the API uses `512`. With rexctl, use `rexctl config set FLUXER_API_MAX_INFLIGHT_REQUESTS`.
+### `FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS`
+
+How many attachment files sent as multipart form data the API streams to the object store at once, from 1 to 10000. Each one can use up to about 25 MiB of memory. A file that waits more than 10 seconds for a turn gets 503 with a Retry-After header. When it's empty, the API uses `16`. With rexctl, use `rexctl config set FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS`.
+
### `FLUXER_TRUST_CLIENT_IP_HEADER`
Whether Fluxer trusts the client address in the `FLUXER_CLIENT_IP_HEADER_NAME` header. Use `true` or `false`. The api, worker, admin and gateway services and the push relay use it. With `false`, they use the address of the connection, which behind the edge is the edge itself. Outside Docker Compose, the services use `false` when it's empty. The default is `true`. With rexctl, use `rexctl config set FLUXER_TRUST_CLIENT_IP_HEADER`.
diff --git a/fluxer_rexctl/internal/instance/envvars.go b/fluxer_rexctl/internal/instance/envvars.go
index d71a81a99..729396ede 100644
--- a/fluxer_rexctl/internal/instance/envvars.go
+++ b/fluxer_rexctl/internal/instance/envvars.go
@@ -304,6 +304,7 @@ var envVars = []envVar{
{"FLUXER_API_HEADERS_TIMEOUT_MS", "api", "How long a client may take to send the request line and headers to the API, in milliseconds from 1000 to 3600000. It is capped at FLUXER_API_REQUEST_TIMEOUT_MS. When it's empty, the API uses `30000`."},
{"FLUXER_API_REQUEST_TIMEOUT_MS", "api", "How long a client may take over a whole request to the API, in milliseconds from 1000 to 3600000. Raise it for large uploads or slow links. When it's empty, the API uses `120000`."},
{"FLUXER_API_MAX_INFLIGHT_REQUESTS", "api", "How many requests the API handles at once before it responds to new ones with 503 and a Retry-After header, from 1 to 100000. When it's empty, the API uses `512`."},
+ {"FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS", "api", "How many attachment files sent as multipart form data the API streams to the object store at once, from 1 to 10000. Each one can use up to about 25 MiB of memory. A file that waits more than 10 seconds for a turn gets 503 with a Retry-After header. When it's empty, the API uses `16`."},
{"FLUXER_TRUST_CLIENT_IP_HEADER", "api", "Whether Fluxer trusts the client address in the FLUXER_CLIENT_IP_HEADER_NAME header. Use `true` or `false`. The api, worker, admin and gateway services and the push relay use it. With `false`, they use the address of the connection, which behind the edge is the edge itself. Outside Docker Compose, the services use `false` when it's empty."},
{"FLUXER_CLIENT_IP_HEADER_NAME", "api", "The request header that has the client's IP address. When it's empty, the api, worker, admin and gateway services and the push relay use `x-forwarded-for`, the header the edge sets."},
{"FLUXER_API_IP_BAN_EXEMPT_IPS", "api", "IP addresses and CIDR ranges, separated by commas, that IP bans never apply to, such as `203.0.113.7,2001:db8::/56`. The API refuses to start when an entry doesn't parse."},
diff --git a/fluxer_rexctl/internal/stack/files/.env.example b/fluxer_rexctl/internal/stack/files/.env.example
index 9a20eb475..abd20d72e 100644
--- a/fluxer_rexctl/internal/stack/files/.env.example
+++ b/fluxer_rexctl/internal/stack/files/.env.example
@@ -1656,6 +1656,13 @@ FLUXER_VAPID_PRIVATE_KEY=
# rexctl: rexctl config set FLUXER_API_MAX_INFLIGHT_REQUESTS
# FLUXER_API_MAX_INFLIGHT_REQUESTS=
+# How many attachment files sent as multipart form data the API streams to the
+# object store at once, from 1 to 10000. Each one can use up to about 25 MiB
+# of memory. A file that waits more than 10 seconds for a turn gets 503 with a
+# Retry-After header. When it's empty, the API uses 16.
+# rexctl: rexctl config set FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS
+# FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS=
+
# Whether Fluxer trusts the client address in the FLUXER_CLIENT_IP_HEADER_NAME
# header. Use true or false. The api, worker, admin and gateway services and
# the push relay use it. With false, they use the address of the connection,
diff --git a/fluxer_rexctl/internal/stack/files/docker-compose.yml b/fluxer_rexctl/internal/stack/files/docker-compose.yml
index 1052d4626..0e11977b6 100644
--- a/fluxer_rexctl/internal/stack/files/docker-compose.yml
+++ b/fluxer_rexctl/internal/stack/files/docker-compose.yml
@@ -36,6 +36,7 @@ x-fluxer-env: &fluxer-env
FLUXER_API_HEADERS_TIMEOUT_MS: ${FLUXER_API_HEADERS_TIMEOUT_MS:-}
FLUXER_API_REQUEST_TIMEOUT_MS: ${FLUXER_API_REQUEST_TIMEOUT_MS:-}
FLUXER_API_MAX_INFLIGHT_REQUESTS: ${FLUXER_API_MAX_INFLIGHT_REQUESTS:-}
+ FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS: ${FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS:-}
FLUXER_API_IP_BAN_EXEMPT_IPS: ${FLUXER_API_IP_BAN_EXEMPT_IPS:-}
FLUXER_IP_BAN_REFRESH_INTERVAL_MS: ${FLUXER_IP_BAN_REFRESH_INTERVAL_MS:-}
FLUXER_APP_ORIGIN_ALIASES: ${FLUXER_APP_ORIGIN_ALIASES:-}
diff --git a/packages/config/src/ConfigLoader.ts b/packages/config/src/ConfigLoader.ts
index 8a43938f5..19c66dd14 100644
--- a/packages/config/src/ConfigLoader.ts
+++ b/packages/config/src/ConfigLoader.ts
@@ -109,6 +109,7 @@ function defaultConfig(): MasterConfig {
headers_timeout_ms: 30_000,
request_timeout_ms: 120_000,
max_inflight_requests: 512,
+ max_concurrent_form_uploads: 16,
automated_message_deletion_delay_days: 7,
ip_ban_exempt_ips: [],
donation_proxy_key: '',
@@ -746,6 +747,12 @@ function normalizeConfig(config: MasterConfig): MasterConfig {
normalizeAppOriginAliases(config);
normalizeAgePolicyConfig(config);
assertIntegerInRange(config.services.api.max_inflight_requests, 'FLUXER_API_MAX_INFLIGHT_REQUESTS', 1, 100_000);
+ assertIntegerInRange(
+ config.services.api.max_concurrent_form_uploads,
+ 'FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS',
+ 1,
+ 10_000,
+ );
assertIntegerInRange(
config.services.api.automated_message_deletion_delay_days,
'FLUXER_API_AUTOMATED_MESSAGE_DELETION_DELAY_DAYS',
diff --git a/packages/config/src/MasterConfig.ts b/packages/config/src/MasterConfig.ts
index 70afd9931..1a5c81898 100644
--- a/packages/config/src/MasterConfig.ts
+++ b/packages/config/src/MasterConfig.ts
@@ -110,6 +110,7 @@ export interface MasterConfig {
headers_timeout_ms: number;
request_timeout_ms: number;
max_inflight_requests: number;
+ max_concurrent_form_uploads: number;
automated_message_deletion_delay_days: number;
ip_ban_exempt_ips: Array<string>;
donation_proxy_key: string;
diff --git a/packages/config/src/config_loader/EnvironmentOverrides.ts b/packages/config/src/config_loader/EnvironmentOverrides.ts
index b7377b4c7..1eabe888b 100644
--- a/packages/config/src/config_loader/EnvironmentOverrides.ts
+++ b/packages/config/src/config_loader/EnvironmentOverrides.ts
@@ -72,6 +72,10 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {
FLUXER_API_HEADERS_TIMEOUT_MS: {path: ['services', 'api', 'headers_timeout_ms'], parse: parseInteger},
FLUXER_API_REQUEST_TIMEOUT_MS: {path: ['services', 'api', 'request_timeout_ms'], parse: parseInteger},
FLUXER_API_MAX_INFLIGHT_REQUESTS: {path: ['services', 'api', 'max_inflight_requests'], parse: parseInteger},
+ FLUXER_API_MAX_CONCURRENT_FORM_UPLOADS: {
+ path: ['services', 'api', 'max_concurrent_form_uploads'],
+ parse: parseInteger,
+ },
FLUXER_API_AUTOMATED_MESSAGE_DELETION_DELAY_DAYS: {
path: ['services', 'api', 'automated_message_deletion_delay_days'],
parse: parseInteger,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4e51e10c2..d1220d84c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -48,6 +48,9 @@ catalogs:
'@elastic/elasticsearch':
specifier: 9.5.1
version: 9.5.1
+ '@fastify/busboy':
+ specifier: 3.2.4
+ version: 3.2.4
'@floating-ui/react':
specifier: 0.27.20
version: 0.27.20
@@ -527,6 +530,9 @@ importers:
'@elastic/elasticsearch':
specifier: 'catalog:'
version: 9.5.1([email protected])
+ '@fastify/busboy':
+ specifier: 'catalog:'
+ version: 3.2.4
'@fluxer/config':
specifier: workspace:*
version: link:../packages/config
@@ -4496,6 +4502,9 @@ packages:
'@expressive-code/[email protected]':
resolution: {integrity: sha512-4Ae2xRSDV5kdWPsi40xWbOtoihbzM0zLVjQKkDAnD5KzFXl+6/kd+VhuWOlTRVaJ5cqGk++vCbAaf0MR1XbZlw==}
+ '@fastify/[email protected]':
+ resolution: {integrity: sha512-lQS8xcXT54rdJb+wlG/Q7SMSdtkZEpLPHooSDUZyyZm9LJD7X1kONPhVoPaHq+dsPtWUGGLIz9gBNhs9qKbylw==}
+
'@floating-ui/[email protected]':
resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}
@@ -14191,6 +14200,8 @@ snapshots:
dependencies:
'@expressive-code/core': 0.44.3
+ '@fastify/[email protected]': {}
+
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.12
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index b8c9dc4d2..f765bba62 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -41,6 +41,7 @@ catalog:
'@base-ui/react': 1.9.0
'@biomejs/biome': 2.6.4
'@elastic/elasticsearch': 9.5.1
+ '@fastify/busboy': 3.2.4
'@floating-ui/react': 0.27.20
'@floating-ui/react-dom': 2.1.9
'@hono/node-server': 2.1.5