From a0379964f9c759fa2625fd3ead81c7869a9cb1f4 Mon Sep 17 00:00:00 2001 From: yiling Date: Mon, 25 May 2026 10:45:10 +0800 Subject: [PATCH] fix(asset): prevent infinite recursion in copy and fix cross-project attachment scoping --- AGENTS.md | 4 ++ src/services/asset/asset.test.ts | 87 ++++++++++++++++++++++++++++++++ src/services/asset/asset.ts | 31 +++++++++--- 3 files changed, 114 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index efeceb71..731ae260 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,6 +163,10 @@ The frontend is built with: We use **Vitest** for testing (via `bun run test`). **Do not use `bun test`** as it uses Bun's native test runner which is not compatible with this project's test suite. +### Bug Fixes + +- **Mandatory Reproduction**: When fixing a backend bug, you MUST first write a test case that reproduces the bug (demonstrates the failure) before applying the fix. This ensures the bug is truly understood and prevents future regressions. + ### Test Maintenance Rule - **Do not delete tests** unless the feature or code being tested is permanently removed from the codebase. diff --git a/src/services/asset/asset.test.ts b/src/services/asset/asset.test.ts index d972129e..8b9aaa57 100644 --- a/src/services/asset/asset.test.ts +++ b/src/services/asset/asset.test.ts @@ -448,6 +448,93 @@ describe('AssetService', () => { expect(newAttachmentAsset.type).toBe(AssetType.attachment) }) + it('rejects copying a folder into its own descendant', async () => { + const { user, assets } = await setupBasicAssets() + + // Create a subfolder inside folderA + const subfolder = await prisma.asset.create({ + data: { + name: 'subfolder', + type: AssetType.folder, + projectId: assets.folderA.projectId, + parentId: assets.folderA.id, + status: 'uploaded', + }, + }) + + await expect( + assetService.copyAssets({ + assetIds: [assets.folderA.id], + newParentId: subfolder.id, + creatorId: user.id, + withComments: false, + }), + ).rejects.toThrow('Cannot copy a folder into its own descendant') + }) + + it('uses destination project when copying comment attachments', async () => { + const { user, assets, project } = await setupBasicAssets() + + // Set up project 2 + const project2 = await prisma.project.create({ + data: { name: 'Project 2', teamId: project.teamId }, + }) + const root2 = await prisma.asset.create({ + data: { name: 'root2', type: AssetType.folder, projectId: project2.id, status: 'uploaded' }, + }) + + // Create a comment with attachment on fileA1 + const attachmentAsset = await prisma.asset.create({ + data: { + name: 'attach.png', + type: AssetType.attachment, + projectId: project.id, + creatorId: user.id, + status: 'uploaded', + sizeByte: 50, + }, + }) + + const comment = await prisma.assetComment.create({ + data: { + assetId: assets.fileA1.id, + creatorId: user.id, + message: 'Original Comment', + }, + }) + + await prisma.assetCommentAttachment.create({ + data: { + commentId: comment.id, + assetId: attachmentAsset.id, + }, + }) + + // Copy to project 2 + await assetService.copyAssets({ + assetIds: [assets.fileA1.id], + newParentId: root2.id, + creatorId: user.id, + withComments: true, + }) + + // Find the copied file in project 2 + const newFileA1 = await prisma.asset.findFirstOrThrow({ + where: { parentId: root2.id, name: 'fileA1' }, + }) + + // Verify comments were copied + const newComments = await prisma.assetComment.findMany({ + where: { assetId: newFileA1.id }, + include: { attachments: { include: { asset: true } } }, + }) + expect(newComments.length).toBe(1) + + // Verify attachment asset belongs to PROJECT 2 + const newAttachmentAsset = newComments[0].attachments[0].asset + expect(newAttachmentAsset.projectId).toBe(project2.id) + }) + it('handles reparenting - Version Stack: move into stack', async () => { const { user, assets } = await setupBasicAssets() await assetService.reparentAssets({ diff --git a/src/services/asset/asset.ts b/src/services/asset/asset.ts index c45efc7d..4235e0a2 100644 --- a/src/services/asset/asset.ts +++ b/src/services/asset/asset.ts @@ -1,5 +1,4 @@ import { prisma } from '@/db' -import { logger } from '@/logger' import { AncestorFolder, AssetInfo, @@ -19,6 +18,7 @@ import { UserInfo, } from '@/dtos/asset' import { Asset, AssetStatus, AssetType, Prisma, StorageKey } from '@/generated/prisma/client.ts' +import { logger } from '@/logger' import { PaginatedData, paginateQuery, PaginationParams } from '@/services/pagination' import { s3Service } from '@/services/s3/s3' import { generateKeyBetween } from 'jittered-fractional-indexing' @@ -289,6 +289,20 @@ export class AssetService { throw new Error('Not all assets to be copied were found') } + // Check if newParentId is a descendant of any asset being copied + const ancestors = await tx.$queryRaw<{ id: string }[]>` + WITH RECURSIVE ancestor AS ( + SELECT id, parent_id FROM assets WHERE id = ${newParent.id} + UNION ALL + SELECT a.id, a.parent_id FROM assets a + INNER JOIN ancestor d ON a.id = d.parent_id + ) + SELECT id FROM ancestor WHERE id IN (${Prisma.join(req.assetIds)}) LIMIT 1; + ` + if (ancestors.length > 0) { + throw new Error('Cannot copy a folder into its own descendant') + } + for (const a of assetsToCopy) { if (!a.project || !a.project.team) { throw new Error(`Asset ${a.id} is not associated with a team`) @@ -354,7 +368,7 @@ export class AssetService { sizeByte: asset.sizeByte, status: asset.status, transcodeTaskId: asset.transcodeTaskId, - media: (asset.media as unknown as PrismaJson.MediaInfo) || undefined, + media: asset.media || undefined, isDeleted: asset.isDeleted, deletedAt: asset.deletedAt, sortIndex: sortIndex, @@ -362,14 +376,13 @@ export class AssetService { projectId: projectId, creatorId: creatorId || asset.creatorId, taskId: asset.taskId, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - targetId: asset.targetId as any, + targetId: asset.targetId, storageKeyId: asset.storageKeyId, }, }) if (withComments) { - await this.copyComments(tx, asset.id, newAsset.id, creatorId) + await this.copyComments(tx, asset.id, newAsset.id, projectId, creatorId) } if (asset.type === AssetType.folder) { @@ -397,6 +410,7 @@ export class AssetService { tx: Prisma.TransactionClient, oldAssetId: string, newAssetId: string, + projectId: string | null, creatorId?: string, ) { const comments = await tx.assetComment.findMany({ @@ -412,7 +426,7 @@ export class AssetService { }) for (const comment of comments) { - await this.copyCommentRecursive(tx, comment, newAssetId, null, creatorId) + await this.copyCommentRecursive(tx, comment, newAssetId, null, projectId, creatorId) } } @@ -421,6 +435,7 @@ export class AssetService { comment: any, // eslint-disable-line @typescript-eslint/no-explicit-any newAssetId: string, newReplyToId: string | null, + projectId: string | null, creatorId?: string, ) { // eslint-disable-next-line @typescript-eslint/no-unused-vars @@ -441,7 +456,7 @@ export class AssetService { tx, attachment.asset, null, // attachment usually has no parent - attachment.asset.projectId, + projectId, attachment.asset.sortIndex, creatorId, false, @@ -457,7 +472,7 @@ export class AssetService { if (replies) { for (const reply of replies) { - await this.copyCommentRecursive(tx, reply, newAssetId, newComment.id, creatorId) + await this.copyCommentRecursive(tx, reply, newAssetId, newComment.id, projectId, creatorId) } } }