Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: serialize file storage upload checks (#14829)

YuTengjing59d2915bf949
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index 2752793deec..56c3a6bed7b 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -176,8 +176,9 @@ export class FileModel {
return this.db.delete(globalFiles).where(eq(globalFiles.hashId, hashId));
};
- countUsage = async () => {
- const result = await this.db
+ countUsage = async (trx?: Transaction) => {
+ const db = trx ?? this.db;
+ const result = await db
.select({
totalSize: sum(files.size),
})
diff --git a/src/business/server/lambda-routers/file.ts b/src/business/server/lambda-routers/file.ts
index f01ecd1e5ef..b38c98d51dc 100644
--- a/src/business/server/lambda-routers/file.ts
+++ b/src/business/server/lambda-routers/file.ts
@@ -1,12 +1,14 @@
+import type { Transaction } from '@/database/type';
+
export interface BusinessFileUploadCheckParams {
actualSize: number;
clientIp?: string;
inputSize: number;
+ transaction?: Transaction;
url: string;
userId: string;
}
export async function businessFileUploadCheck(
-
_params: BusinessFileUploadCheckParams,
): Promise<void> {}
diff --git a/src/server/routers/lambda/__tests__/file.test.ts b/src/server/routers/lambda/__tests__/file.test.ts
index 1168b14e12d..86328f903e9 100644
--- a/src/server/routers/lambda/__tests__/file.test.ts
+++ b/src/server/routers/lambda/__tests__/file.test.ts
@@ -4,6 +4,20 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fileRouter } from '@/server/routers/lambda/file';
import { AsyncTaskStatus } from '@/types/asyncTask';
+const routerMocks = vi.hoisted(() => {
+ const transactionClient = {};
+
+ return {
+ businessFileUploadCheck: vi.fn(),
+ serverDB: {
+ transaction: vi.fn(async (callback: (trx: unknown) => unknown) =>
+ callback(transactionClient),
+ ),
+ },
+ transactionClient,
+ };
+});
+
// Patch: Use actual router context middleware to inject the correct models/services
function createCallerWithCtx(partialCtx: any = {}) {
// All mocks are spies
@@ -78,6 +92,14 @@ vi.mock('@/envs/app', () => ({
},
}));
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(() => routerMocks.serverDB),
+}));
+
+vi.mock('@/business/server/lambda-routers/file', () => ({
+ businessFileUploadCheck: routerMocks.businessFileUploadCheck,
+}));
+
const mockAsyncTaskFindByIds = vi.fn();
const mockAsyncTaskFindById = vi.fn();
const mockAsyncTaskDelete = vi.fn();
@@ -159,6 +181,7 @@ describe('fileRouter', () => {
beforeEach(() => {
vi.clearAllMocks();
+ routerMocks.businessFileUploadCheck.mockResolvedValue(undefined);
mockFile = {
id: 'test-id',
@@ -228,6 +251,33 @@ describe('fileRouter', () => {
});
});
+ it('should run business upload check and file creation in the same transaction', async () => {
+ mockFileModelCheckHash.mockResolvedValue({ isExist: false });
+ mockFileModelCreate.mockResolvedValue({ id: 'new-file-id' });
+
+ await caller.createFile({
+ hash: 'test-hash',
+ fileType: 'text',
+ name: 'test.txt',
+ size: 100,
+ url: 'files/test.txt',
+ metadata: {},
+ });
+
+ expect(routerMocks.serverDB.transaction).toHaveBeenCalledTimes(1);
+ expect(routerMocks.businessFileUploadCheck).toHaveBeenCalledWith(
+ expect.objectContaining({
+ actualSize: 100,
+ transaction: routerMocks.transactionClient,
+ }),
+ );
+ expect(mockFileModelCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ size: 100 }),
+ true,
+ routerMocks.transactionClient,
+ );
+ });
+
it('should use actual file size from S3 instead of client-provided size (security fix)', async () => {
// Setup: S3 returns actual size of 5000 bytes
mockFileServiceGetFileMetadata.mockResolvedValue({
@@ -256,6 +306,7 @@ describe('fileRouter', () => {
size: 5000, // Actual size from S3, not 100
}),
true,
+ routerMocks.transactionClient,
);
});
@@ -284,6 +335,7 @@ describe('fileRouter', () => {
size: 100,
}),
true,
+ routerMocks.transactionClient,
);
});
@@ -326,6 +378,7 @@ describe('fileRouter', () => {
size: 100,
}),
true,
+ routerMocks.transactionClient,
);
});
diff --git a/src/server/routers/lambda/file.ts b/src/server/routers/lambda/file.ts
index a2e9c71feac..919bf38df81 100644
--- a/src/server/routers/lambda/file.ts
+++ b/src/server/routers/lambda/file.ts
@@ -156,32 +156,43 @@ export const fileRouter = router({
// If metadata fetch fails, use original size from input
}
- await businessFileUploadCheck({
- actualSize,
- clientIp: ctx.clientIp ?? undefined,
- inputSize: input.size,
- url: input.url,
- userId: ctx.userId,
- });
-
if (actualSize < 0) {
+ await businessFileUploadCheck({
+ actualSize,
+ clientIp: ctx.clientIp ?? undefined,
+ inputSize: input.size,
+ url: input.url,
+ userId: ctx.userId,
+ });
throw new TRPCError({ code: 'BAD_REQUEST', message: 'File size cannot be negative' });
}
- const { id } = await ctx.fileModel.create(
- {
- fileHash: input.hash,
- fileType: input.fileType,
- knowledgeBaseId: input.knowledgeBaseId,
- metadata: input.metadata,
- name: input.name,
- parentId: resolvedParentId,
- size: actualSize,
+ const { id } = await ctx.serverDB.transaction(async (trx) => {
+ await businessFileUploadCheck({
+ actualSize,
+ clientIp: ctx.clientIp ?? undefined,
+ inputSize: input.size,
+ transaction: trx,
url: input.url,
- },
- // if the file is not exist in global file, create a new one
- !isExist,
- );
+ userId: ctx.userId,
+ });
+
+ return ctx.fileModel.create(
+ {
+ fileHash: input.hash,
+ fileType: input.fileType,
+ knowledgeBaseId: input.knowledgeBaseId,
+ metadata: input.metadata,
+ name: input.name,
+ parentId: resolvedParentId,
+ size: actualSize,
+ url: input.url,
+ },
+ // if the file is not exist in global file, create a new one
+ !isExist,
+ trx,
+ );
+ });
return { id, url: getFileProxyUrl(id) };
}),