From 1066900c784e991b6d68f2d8cef49d327df7bdce Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Thu, 26 Nov 2026 10:43:08 +0800 Subject: [PATCH] Merge commit from fork * fix(share): only return share-visible field values on public share links The public share children and file detail endpoints returned every custom field value on an asset, while the share's field settings only hid them in the share UI. Filter fieldValues server-side to the fields turned on for the share, matching what GET /shares/:shareId/fields already returns. * fix(share): stop returning share passwords and compare them in constant time Share link responses included the saved password in plain text. Remove it from ShareLinkInfo; clients already get hasPassword. Check the password a guest enters with a constant-time comparison of SHA-256 digests instead of a string comparison. The share settings panel no longer pre-fills the saved password. When a password is set, the field starts empty with a hint, Save stays disabled until a new password is typed, and the field clears after saving. Turning the password off still removes it. * fix(kanban): limit task lists and task reads to the caller's projects Kanban checked only team membership for task reads, so a member invited to one project could list every task in the team and open any task, its linked files, comments and activity. - Task lists and the tasks linked to a file now include, for project-scoped members, only tasks in projects they belong to plus tasks they created, report, or are assigned to. Team-scoped members see every task as before. - Reading a task, its files, comments and activity follows the same rule: a project-scoped member outside the task's project needs to be its creator, reporter or assignee. - Linking a file to a task (create, update, or the link endpoints) now requires Read on that file, since linked files are shown to everyone who can read the task. * fix(security): sign only issued comment attachments and keep files on comment delete Kanban comment attachments: - Upload keys now include the team and the uploader: kanban/attachments////. - addComment rejects any attachment key that was not issued to the comment author for the task's team, so a client can no longer store an arbitrary storage key in a comment. - When comments are read, only keys of kanban comment attachments for the task's team (or the previous kanban/attachments// form) are presigned. Keys stored earlier that point anywhere else are dropped. Asset comment attachments: - createComment only links attachment uploads made by the commenter in the same project that are not linked to another comment. Project files can no longer be linked as comment attachments. - deleteComment deletes the stored object and asset only for attachment uploads not linked elsewhere; anything else linked to the comment is only unlinked. Upload keys: - Sanitize the file name in kanban and project attachment upload keys, as regular uploads already do, so a name cannot add path segments. - The local storage backend rejects keys with a '..' segment instead of resolving them into another object's path. * fix(security): enforce visibility and protect comment attachments --------- Co-authored-by: phj1081 <5908832+phj1081@users.noreply.github.com> --- CHANGELOG.md | 1 + packages/api/src/attachment.test.ts | 25 ++ packages/api/src/attachment.ts | 3 +- packages/api/src/kanban/comments.ts | 4 +- packages/api/src/kanban/kanban.test.ts | 81 ++++- packages/api/src/kanban/tasks.ts | 29 +- packages/api/src/public-share.print.test.ts | 7 + packages/api/src/public-share.ts | 23 +- packages/api/src/share.test.ts | 113 +++++++ packages/core/src/asset/asset.test.ts | 274 +++++++++++++++- packages/core/src/asset/asset.ts | 104 +++--- packages/core/src/authz/authz.test.ts | 65 ++++ packages/core/src/authz/authz.ts | 9 +- packages/core/src/kanban/kanban.test.ts | 298 ++++++++++++++++- packages/core/src/kanban/kanban.ts | 300 +++++++++++++----- packages/core/src/s3/s3.test.ts | 12 + packages/core/src/s3/s3.ts | 5 + packages/core/src/share/share.test.ts | 69 ++++ packages/core/src/share/share.ts | 14 +- packages/db/src/prisma-testing-helper.ts | 4 + .../share-settings-sidebar.test.tsx | 143 +++++++++ 21 files changed, 1425 insertions(+), 158 deletions(-) create mode 100644 packages/webui/components/share-settings-sidebar.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d7374eb..89f674bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed - **comments**: Keep password-protected print links on the share password prompt, keep private folder names out of shared print data, and wait for thumbnails and reply drawings before printing. +- **security**: Security improvements. ### Changed diff --git a/packages/api/src/attachment.test.ts b/packages/api/src/attachment.test.ts index 7eb4ab2f..8c89f4be 100644 --- a/packages/api/src/attachment.test.ts +++ b/packages/api/src/attachment.test.ts @@ -6,6 +6,7 @@ import { AssetType } from '@shumai/db' import { authMiddleware } from './middleware/auth' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' +import { s3Service } from '@shumai/core/src/s3/s3' vi.mock('./middleware/auth', () => ({ // any is used here because Hono's Context and Next types are complex to mock in vitest.mock @@ -84,4 +85,28 @@ describe('Attachment API', () => { itemId: 'asset1', }) }) + + it('keeps the upload key inside the attachment folder', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(assetService.createAsset).mockResolvedValue({ id: 'asset1' } as any) + vi.mocked(s3Service.presign).mockResolvedValue('http://mock-s3-url') + + const fileName = '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov' + const res = await app.request('/projects/project1/attachments', { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: 'Bearer test' }, + body: JSON.stringify({ fileName, contentType: 'video/quicktime', size: 100 }), + }) + + expect(res.status).toBe(200) + const key = vi.mocked(assetService.createAsset).mock.lastCall?.[0].key as string + const parts = key.split('/') + expect(parts[0]).toBe('attachments') + expect(parts).toHaveLength(3) + expect(parts).not.toContain('..') + expect(s3Service.presign).toHaveBeenCalledWith(expect.any(String), key, 'PUT') + expect(assetService.createAsset).toHaveBeenCalledWith( + expect.objectContaining({ name: fileName }), + ) + }) }) diff --git a/packages/api/src/attachment.ts b/packages/api/src/attachment.ts index 551ae78c..cab24e0b 100644 --- a/packages/api/src/attachment.ts +++ b/packages/api/src/attachment.ts @@ -7,6 +7,7 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { projectService } from '@shumai/core/src/project/project' import { AssetType } from '@shumai/db' import { ulid } from 'ulid' +import { sanitizeFilename } from '@shumai/core/src/utils/filename' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import type { Prisma } from '@shumai/db' @@ -27,7 +28,7 @@ const route = new Hono<{ Variables: { user: User } }>().post( id: projectId, }) - const key = `attachments/${ulid()}/${req.fileName}` + const key = `attachments/${ulid()}/${sanitizeFilename(req.fileName)}` const assetInfo = await assetService.createAsset({ name: req.fileName, diff --git a/packages/api/src/kanban/comments.ts b/packages/api/src/kanban/comments.ts index bd443d72..1577e678 100644 --- a/packages/api/src/kanban/comments.ts +++ b/packages/api/src/kanban/comments.ts @@ -30,7 +30,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: teamId, }) - const attachment = await kanbanService.createAttachment(teamId, req) + const attachment = await kanbanService.createAttachment(teamId, user.id, req) return c.json(attachment) }, ) @@ -123,7 +123,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: taskId, }) - const events = await kanbanService.listEvents(taskId) + const events = await kanbanService.listEvents(taskId, user.id) return c.json({ data: events }) }) diff --git a/packages/api/src/kanban/kanban.test.ts b/packages/api/src/kanban/kanban.test.ts index 5509d51e..a3b6cd49 100644 --- a/packages/api/src/kanban/kanban.test.ts +++ b/packages/api/src/kanban/kanban.test.ts @@ -4,6 +4,8 @@ import { kanbanService } from '@shumai/core/src/kanban/kanban' import { auditLogService } from '@shumai/core/src/auditLog/auditLog' import { notificationService } from '@shumai/core/src/notification/notification' import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums' +import { HTTPException } from 'hono/http-exception' +import { authzService } from '@shumai/core/src/authz/authz' import kanbanRoute from './index' vi.mock('@shumai/core/src/authz/authz', () => ({ @@ -19,6 +21,7 @@ vi.mock('@shumai/core/src/authz/authz', () => ({ ResourceType: { Team: 'team', Project: 'project', + Asset: 'asset', KanbanGoal: 'kanbanGoal', KanbanTask: 'kanbanTask', }, @@ -51,6 +54,7 @@ describe('Kanban API Routes', () => { beforeEach(() => { vi.clearAllMocks() + vi.mocked(authzService.hasPermission).mockResolvedValue(undefined) vi.mocked(auditLogService.logAction).mockResolvedValue({} as any) // eslint-disable-line @typescript-eslint/no-explicit-any vi.mocked(notificationService.notifyKanbanTaskEvent).mockResolvedValue(undefined as any) // eslint-disable-line @typescript-eslint/no-explicit-any app = new Hono() @@ -218,6 +222,7 @@ describe('Kanban API Routes', () => { status: 'READY', goalId: 'goal-1', }), + 'user-1', ) }) @@ -248,7 +253,7 @@ describe('Kanban API Routes', () => { expect(res.status).toBe(200) const json = await res.json() expect(json.id).toBe(taskId) - expect(mockGet).toHaveBeenCalledWith(taskId) + expect(mockGet).toHaveBeenCalledWith(taskId, 'user-1') }) it('PATCH /teams/:teamId/kanban/tasks/:taskId', async () => { @@ -493,6 +498,74 @@ describe('Kanban API Routes', () => { expect(mockLinkAssets).toHaveBeenCalledWith(teamId, taskId, ['asset-1', 'asset-2']) }) + describe('linking files the caller cannot read', () => { + const denyAsset = (deniedAssetId: string) => + vi.mocked(authzService.hasPermission).mockImplementation(async (req) => { + if (req.type === 'asset' && req.id === deniedAssetId) { + throw new HTTPException(403, { message: 'User has only project scope' }) + } + }) + + it('checks Read on every file linked to a task', async () => { + const mockLinkAssets = vi.spyOn(kanbanService, 'linkAssets').mockResolvedValue(undefined) + denyAsset('asset-2') + + const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}/assets`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ assetIds: ['asset-1', 'asset-2'] }), + }) + + expect(res.status).toBe(403) + expect(mockLinkAssets).not.toHaveBeenCalled() + expect(authzService.hasPermission).toHaveBeenCalledWith( + expect.objectContaining({ type: 'asset', id: 'asset-1', permission: 'Read' }), + ) + }) + + it('checks Read on the file when linking it from the file side', async () => { + const mockLinkAsset = vi.spyOn(kanbanService, 'linkAsset').mockResolvedValue(undefined) + denyAsset('asset-1') + + const res = await app.request(`/teams/${teamId}/kanban/assets/asset-1/tasks`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ taskId }), + }) + + expect(res.status).toBe(403) + expect(mockLinkAsset).not.toHaveBeenCalled() + }) + + it('checks Read on files passed when updating a task', async () => { + const mockUpdate = vi.spyOn(kanbanService, 'updateTask') + denyAsset('asset-9') + + const res = await app.request(`/teams/${teamId}/kanban/tasks/${taskId}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ assetIds: ['asset-9'] }), + }) + + expect(res.status).toBe(403) + expect(mockUpdate).not.toHaveBeenCalled() + }) + + it('checks Read on files passed when creating a task', async () => { + const mockCreate = vi.spyOn(kanbanService, 'createTask') + denyAsset('asset-9') + + const res = await app.request(`/teams/${teamId}/kanban/tasks`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title: 'Task', assetIds: ['asset-9'] }), + }) + + expect(res.status).toBe(403) + expect(mockCreate).not.toHaveBeenCalled() + }) + }) + it('DELETE /teams/:teamId/kanban/tasks/:taskId/assets/:assetId', async () => { const mockUnlinkAsset = vi.spyOn(kanbanService, 'unlinkAsset').mockResolvedValue(undefined) @@ -530,7 +603,7 @@ describe('Kanban API Routes', () => { const json = await res.json() expect(json.total).toBe(1) expect(json.data).toHaveLength(1) - expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1') + expect(mockListTasksForAsset).toHaveBeenCalledWith(teamId, 'asset-1', 'user-1') }) it('POST /teams/:teamId/kanban/assets/:assetId/tasks', async () => { @@ -585,7 +658,7 @@ describe('Kanban API Routes', () => { expect(res.status).toBe(200) const json = await res.json() expect(json.id).toBe('att-1') - expect(mockAttachment).toHaveBeenCalledWith(teamId, { + expect(mockAttachment).toHaveBeenCalledWith(teamId, 'user-1', { fileName: 'test.png', size: 1024, contentType: 'image/png', @@ -683,7 +756,7 @@ describe('Kanban API Routes', () => { expect(res.status).toBe(200) const json = await res.json() expect(json.data).toHaveLength(1) - expect(mockEvents).toHaveBeenCalledWith(taskId) + expect(mockEvents).toHaveBeenCalledWith(taskId, 'user-1') }) }) }) diff --git a/packages/api/src/kanban/tasks.ts b/packages/api/src/kanban/tasks.ts index 86832872..8d8d8c4d 100644 --- a/packages/api/src/kanban/tasks.ts +++ b/packages/api/src/kanban/tasks.ts @@ -22,6 +22,21 @@ import { HTTPException } from 'hono/http-exception' type User = Prisma.UserGetPayload> +/** + * Linking a file to a task shows its name, folder path and thumbnail to everyone + * who can read the task, so the caller must be able to read each linked file. + */ +async function assertCanReadAssets(user: User, assetIds: string[] | undefined) { + for (const id of new Set(assetIds ?? [])) { + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Asset, + id, + }) + } +} + const route = new Hono<{ Variables: { user: User } }>() .post('/teams/:teamId/kanban/tasks', zValidator('json', createKanbanTaskSchema), async (c) => { const { teamId } = c.req.param() @@ -40,6 +55,8 @@ const route = new Hono<{ Variables: { user: User } }>() throw new HTTPException(403, { message: 'User is not a member of the team' }) } + await assertCanReadAssets(user, req.assetIds) + const task = await kanbanService.createTask(teamId, req, user.id, role) await auditLogService.logAction({ @@ -89,7 +106,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: teamId, }) - const result = await kanbanService.listTasks(teamId, req) + const result = await kanbanService.listTasks(teamId, req, user.id) return c.json(result) }, ) @@ -104,7 +121,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: taskId, }) - const task = await kanbanService.getTask(taskId) + const task = await kanbanService.getTask(taskId, user.id) return c.json(task) }) .patch( @@ -122,6 +139,8 @@ const route = new Hono<{ Variables: { user: User } }>() id: taskId, }) + await assertCanReadAssets(user, req.assetIds) + const existing = await kanbanService.getTask(taskId) const role = await resolveEffectiveRole(teamId, existing.projectId ?? undefined, user.id) const task = await kanbanService.updateTask(taskId, req, user.id, role) @@ -262,6 +281,8 @@ const route = new Hono<{ Variables: { user: User } }>() id: taskId, }) + await assertCanReadAssets(user, req.assetIds) + await kanbanService.linkAssets(teamId, taskId, req.assetIds) return c.json({ success: true }) }, @@ -291,7 +312,7 @@ const route = new Hono<{ Variables: { user: User } }>() id: teamId, }) - const tasks = await kanbanService.listTasksForAsset(teamId, assetId) + const tasks = await kanbanService.listTasksForAsset(teamId, assetId, user.id) return c.json({ data: tasks, total: tasks.length }) }) .post( @@ -309,6 +330,8 @@ const route = new Hono<{ Variables: { user: User } }>() id: req.taskId, }) + await assertCanReadAssets(user, [assetId]) + await kanbanService.linkAsset(teamId, req.taskId, assetId) return c.json({ success: true }) }, diff --git a/packages/api/src/public-share.print.test.ts b/packages/api/src/public-share.print.test.ts index 53a0c960..23965463 100644 --- a/packages/api/src/public-share.print.test.ts +++ b/packages/api/src/public-share.print.test.ts @@ -24,6 +24,7 @@ describe('public share print comments and frame api', () => { rootFolderId: 'share-root', projectId: 'proj-1', watermarkConfigId: null, + fieldVisibility: { status: true, internalNote: false }, } as never) vi.spyOn(assetService, 'getAsset').mockResolvedValue({ @@ -34,6 +35,11 @@ describe('public share print comments and frame api', () => { type: 'file', status: 'active', proxyType: 'video', + fieldValues: [ + { fieldId: 'status', value: 'Approved' }, + { fieldId: 'internalNote', value: 'Private note' }, + { fieldId: 'rating', value: 3 }, + ], ancestorFolders: [ { id: 'inner', name: 'Inner Folder' }, { id: 'share-root', name: 'Share Root' }, @@ -73,6 +79,7 @@ describe('public share print comments and frame api', () => { const body = await res.json() expect(body.breadcrumbs).toEqual(['Client Review', 'Inner Folder']) expect(body.asset.ancestorFolders).toEqual([{ id: 'inner', name: 'Inner Folder' }]) + expect(body.asset.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) expect(JSON.stringify(body)).not.toContain('Secret Project Folder') expect(JSON.stringify(body)).not.toContain('private-parent') expect(body.comments).toHaveLength(1) diff --git a/packages/api/src/public-share.ts b/packages/api/src/public-share.ts index 4f5af64e..790c1d1d 100644 --- a/packages/api/src/public-share.ts +++ b/packages/api/src/public-share.ts @@ -123,6 +123,20 @@ async function applyWatermarkToAssetMedia( } } +/** + * Keeps only the custom field values the share link is configured to show. + * Fields are hidden by default; `fieldVisibility` lists the keys turned on + * for this share, matching what `GET /shares/:shareId/fields` returns. + */ +function filterSharedFieldValues(asset: AssetInfo, fieldVisibility: unknown): AssetInfo { + if (!asset.fieldValues) return asset + const visibility = (fieldVisibility || {}) as Record + return { + ...asset, + fieldValues: asset.fieldValues.filter((fv) => Boolean(visibility[fv.fieldId])), + } +} + const app = new Hono() function toFieldInfo( @@ -297,6 +311,8 @@ const route = app } } + res.data = res.data.map((item) => filterSharedFieldValues(item, shareLink.fieldVisibility)) + return c.json(res) } catch (err) { return handlePublicShareError(c, err) @@ -335,7 +351,7 @@ const route = app asset.media.hls.url = `/api/shares/${shareLink.id}/files/${asset.id}/m3u8/master.m3u8${pwQuery}` } - return c.json(asset) + return c.json(filterSharedFieldValues(asset, shareLink.fieldVisibility)) } catch (err) { return handlePublicShareError(c, err) } @@ -445,7 +461,10 @@ const route = app const breadcrumbs = shareLink.name ? [shareLink.name, ...scopedFolders] : scopedFolders return c.json({ - asset: { ...asset, ancestorFolders: scopedAncestors }, + asset: { + ...filterSharedFieldValues(asset, shareLink.fieldVisibility), + ancestorFolders: scopedAncestors, + }, breadcrumbs, comments, }) diff --git a/packages/api/src/share.test.ts b/packages/api/src/share.test.ts index c2595c77..d1fcbed5 100644 --- a/packages/api/src/share.test.ts +++ b/packages/api/src/share.test.ts @@ -438,6 +438,119 @@ describe('Share API', () => { }) }) + describe('public share field values', () => { + const shareLinkWithFields = { + id: 'share1', + name: 'My Share', + isDisabled: false, + allowDownload: false, + rootFolderId: 'folder1', + projectId: 'project1', + password: null, + expireAt: null, + watermarkConfigId: null, + fieldVisibility: { status: true, internalNote: false }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any + + const assetWithFields = { + id: 'file1', + name: 'a.png', + sizeByte: 1, + fileCount: 0, + type: 'file', + status: 'processed', + proxyType: 'pdf', + fieldValues: [ + { fieldId: 'status', value: 'Approved' }, + { fieldId: 'internalNote', value: 'not for guests' }, + { fieldId: 'rating', value: 3 }, + ], + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } as any + + test('children only include field values visible on the share', async () => { + vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields) + vi.spyOn(assetService, 'listChildren').mockResolvedValue({ + data: [assetWithFields], + pageInfo: { total: 1, cursor: undefined }, + }) + + const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') + + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) + }) + + test('children with watermark only include field values visible on the share', async () => { + vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ + ...shareLinkWithFields, + watermarkConfigId: 'cfg1', + }) + vi.spyOn(assetService, 'listChildren').mockResolvedValue({ + data: [assetWithFields], + pageInfo: { total: 1, cursor: undefined }, + }) + vi.spyOn(assetService, 'resolveLatestVersionId').mockImplementation(async (id) => id) + vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) + + const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') + + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data[0].fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) + }) + + test('children include no field values when the share shows no fields', async () => { + vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ + ...shareLinkWithFields, + fieldVisibility: null, + }) + vi.spyOn(assetService, 'listChildren').mockResolvedValue({ + data: [assetWithFields], + pageInfo: { total: 1, cursor: undefined }, + }) + + const res = await app.request('/shares/share1/folders/folder1/children?assetType=file') + + expect(res.status).toBe(200) + const body = await res.json() + expect(body.data[0].fieldValues).toEqual([]) + }) + + test('file detail only includes field values visible on the share', async () => { + vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue(shareLinkWithFields) + vi.spyOn(assetService, 'getAsset').mockResolvedValue(assetWithFields) + + const res = await app.request('/shares/share1/files/file1') + + expect(res.status).toBe(200) + const body = await res.json() + expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) + }) + + test('file detail with watermark only includes field values visible on the share', async () => { + vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({ + ...shareLinkWithFields, + watermarkConfigId: 'cfg1', + }) + vi.spyOn(assetService, 'getAsset').mockResolvedValue({ + ...assetWithFields, + proxyType: 'image', + media: { proxyType: 'image', videoTranscodes: [], imageTranscodes: [] }, + }) + vi.spyOn(assetService, 'resolveLatestVersionId').mockResolvedValue('file1') + vi.spyOn(watermarkService, 'getCompletedWatermarkMediaMap').mockResolvedValue(new Map()) + + const res = await app.request('/shares/share1/files/file1') + + expect(res.status).toBe(200) + const body = await res.json() + expect(body.fieldValues).toEqual([{ fieldId: 'status', value: 'Approved' }]) + }) + }) + describe('GET /shares/:shareId/files/:fileId', () => { const shareLinkWithWatermark = { id: 'share1', diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 0b6dedcf..b2be9c66 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' -import { prisma } from '@shumai/db' +import { getPrismaTestingHelper, prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { HTTPException } from 'hono/http-exception' @@ -941,7 +941,7 @@ describe('AssetService', () => { ).resolves.not.toThrow() }) - it('deleteComment cleans up S3 attachment files and database records', async () => { + it('cleans up deleted comment attachments through the asset cleanup job', async () => { const { user, project, assets } = await setupBasicAssets() // 1. Create StorageKey and Asset for attachment @@ -949,15 +949,15 @@ describe('AssetService', () => { data: { key: 'attachments/test-attachment-file.png', status: 'active', + createdAt: new Date(Date.now() - 60_000), }, }) const attachmentAsset = await prisma.asset.create({ data: { name: 'test-attachment-file.png', - type: AssetType.file, + type: AssetType.attachment, projectId: project.id, - parentId: assets.root.id, creatorId: user.id, storageKeyId: storageKey.id, sizeByte: 100, @@ -988,18 +988,278 @@ describe('AssetService', () => { // 5. Verify the comment is deleted from DB await expect(prisma.assetComment.findUnique({ where: { id: comment.id } })).resolves.toBeNull() - // 6. Verify that the attachment Asset and StorageKey are deleted from DB + // 6. The attachment is removed immediately; the storage cleanup owns object deletion. await expect(prisma.asset.findUnique({ where: { id: attachmentAsset.id } })).resolves.toBeNull() + expect(s3Service.deleteObject).not.toHaveBeenCalled() + + await assetService.emptyTrash(project.id) + await expect(prisma.storageKey.findUnique({ where: { id: storageKey.id } })).resolves.toBeNull() - // 7. Verify S3 deletion was called - const { s3Service } = await import('@shumai/core/src/s3/s3') expect(s3Service.deleteObject).toHaveBeenCalledWith( 'shumai', 'attachments/test-attachment-file.png', ) }) + describe('comment attachments', () => { + const addProjectReviewer = async (teamId: string) => { + const reviewer = await prisma.user.create({ + data: { name: 'Reviewer', type: 'human', email: `reviewer-${Date.now()}@example.com` }, + }) + await prisma.teamMember.create({ + data: { teamId, userId: reviewer.id, role: 'reviewer' }, + }) + return reviewer + } + + const createUpload = async (projectId: string, creatorId: string, name: string) => { + const storageKey = await prisma.storageKey.create({ + data: { key: `attachments/${name}`, status: 'active' }, + }) + return await prisma.asset.create({ + data: { + name, + type: AssetType.attachment, + projectId, + creatorId, + sizeByte: 1, + status: 'uploaded', + storageKeyId: storageKey.id, + }, + }) + } + + it('only attaches comment uploads made by the commenter', async () => { + const { user, project, assets } = await setupBasicAssets() + const reviewer = await addProjectReviewer(project.teamId) + const ownerUpload = await createUpload(project.id, user.id, 'owner-upload.png') + const reviewerUpload = await createUpload(project.id, reviewer.id, 'reviewer-upload.png') + + const comment = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: reviewer.id, + message: 'looks good', + attachmentIds: [assets.fileA2.id, ownerUpload.id, reviewerUpload.id], + }) + + const links = await prisma.assetCommentAttachment.findMany({ + where: { commentId: comment.id }, + }) + expect(links.map((l) => l.assetId)).toEqual([reviewerUpload.id]) + }) + + it('does not attach an upload that already belongs to another comment', async () => { + const { user, assets, project } = await setupBasicAssets() + const upload = await createUpload(project.id, user.id, 'shared.png') + + await assetService.createComment({ + assetId: assets.fileA1.id, + userId: user.id, + message: 'first', + attachmentIds: [upload.id], + }) + const second = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: user.id, + message: 'second', + attachmentIds: [upload.id], + }) + + const links = await prisma.assetCommentAttachment.findMany({ + where: { commentId: second.id }, + }) + expect(links).toHaveLength(0) + }) + + it('allows only one concurrent comment to claim an upload', async () => { + // The normal test proxy serializes transactions on a single connection. + const db = getPrismaTestingHelper().getUnderlyingClient() as typeof prisma + const service = new AssetService(db) + const { user, team, project, file, upload } = await db.$transaction(async (tx) => { + const user = await tx.user.create({ + data: { name: 'Commenter', email: `attachment-race-${crypto.randomUUID()}@example.com` }, + }) + const team = await tx.team.create({ data: { name: 'Attachment race' } }) + const project = await tx.project.create({ data: { name: 'Project', teamId: team.id } }) + const file = await tx.asset.create({ + data: { + name: 'File', + type: AssetType.file, + status: AssetStatus.processed, + projectId: project.id, + creatorId: user.id, + }, + }) + const upload = await tx.asset.create({ + data: { + name: 'Upload', + type: AssetType.attachment, + status: AssetStatus.uploaded, + projectId: project.id, + creatorId: user.id, + }, + }) + return { user, team, project, file, upload } + }) + + let claims: Promise[]> | undefined + try { + await db.$transaction(async (tx) => { + await tx.$queryRaw`SELECT id FROM assets WHERE id = ${upload.id} FOR UPDATE` + claims = Promise.allSettled( + ['First comment', 'Second comment'].map((message) => + service.createComment( + { assetId: file.id, userId: user.id, message, attachmentIds: [upload.id] }, + { triggerAgents: false }, + ), + ), + ) + + // Release the upload only after both requests are waiting on its row lock. + await vi.waitFor( + async () => { + const [waiters] = await tx.$queryRaw<{ count: number }[]>` + WITH RECURSIVE waiters(pid) AS ( + SELECT pg_backend_pid() + UNION + SELECT pending.pid + FROM waiters + JOIN (SELECT DISTINCT pid FROM pg_locks WHERE NOT granted) pending + ON waiters.pid = ANY(pg_blocking_pids(pending.pid)) + ) + SELECT count(*)::int - 1 AS count FROM waiters + ` + expect(waiters.count).toBe(2) + }, + { timeout: 3_000 }, + ) + }) + + expect(await claims).toEqual([ + expect.objectContaining({ status: 'fulfilled' }), + expect.objectContaining({ status: 'fulfilled' }), + ]) + await expect( + db.assetCommentAttachment.count({ where: { assetId: upload.id } }), + ).resolves.toBe(1) + } finally { + await claims + await db.asset.deleteMany({ where: { projectId: project.id } }) + await db.project.delete({ where: { id: project.id } }) + await db.team.delete({ where: { id: team.id } }) + await db.user.delete({ where: { id: user.id } }) + } + }) + + it('deleteComment keeps project files that are linked to the comment', async () => { + const { project, assets } = await setupBasicAssets() + const reviewer = await addProjectReviewer(project.teamId) + const fileKey = await prisma.storageKey.create({ + data: { key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov', status: 'active' }, + }) + await prisma.asset.update({ + where: { id: assets.fileA2.id }, + data: { storageKeyId: fileKey.id }, + }) + + const comment = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: reviewer.id, + message: 'note', + attachmentIds: [], + }) + // A link to a project file, as comments created before attachment checks could hold. + await prisma.assetCommentAttachment.create({ + data: { commentId: comment.id, assetId: assets.fileA2.id }, + }) + + await assetService.deleteComment({ commentId: comment.id, userId: reviewer.id }) + + await expect( + prisma.assetComment.findUnique({ where: { id: comment.id } }), + ).resolves.toBeNull() + await expect( + prisma.asset.findUnique({ where: { id: assets.fileA2.id } }), + ).resolves.not.toBeNull() + await expect( + prisma.storageKey.findUnique({ where: { id: fileKey.id } }), + ).resolves.not.toBeNull() + expect(s3Service.deleteObject).not.toHaveBeenCalledWith( + expect.anything(), + 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/deliverable.mov', + ) + }) + + it('keeps an attachment object until the original and copied comments are deleted', async () => { + const { user, project, assets } = await setupBasicAssets() + const upload = await createUpload(project.id, user.id, 'copied-upload.png') + const originalComment = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: user.id, + message: 'Original comment', + attachmentIds: [upload.id], + }) + const [copiedFileId] = await assetService.copyAssets({ + assetIds: [assets.fileA1.id], + newParentId: assets.root3.id, + creatorId: user.id, + withComments: true, + }) + const copiedComment = await prisma.assetComment.findFirstOrThrow({ + where: { assetId: copiedFileId }, + }) + const storageKey = await prisma.storageKey.findFirstOrThrow({ + where: { key: 'attachments/copied-upload.png' }, + }) + await prisma.storageKey.update({ + where: { id: storageKey.id }, + data: { createdAt: new Date(Date.now() - 60_000) }, + }) + + await assetService.deleteComment({ commentId: copiedComment.id, userId: user.id }) + await assetService.emptyTrash(project.id) + + const survivingUpload = await prisma.asset.findUniqueOrThrow({ where: { id: upload.id } }) + expect(survivingUpload.storageKeyId).toBe(storageKey.id) + expect(s3Service.deleteObject).not.toHaveBeenCalledWith(expect.any(String), storageKey.key) + + await assetService.deleteComment({ commentId: originalComment.id, userId: user.id }) + await assetService.emptyTrash(project.id) + + await expect( + prisma.storageKey.findUnique({ where: { id: storageKey.id } }), + ).resolves.toBeNull() + expect(s3Service.deleteObject).toHaveBeenCalledWith(expect.any(String), storageKey.key) + }) + + it('keeps a legacy attachment asset while another comment still links to it', async () => { + const { user, project, assets } = await setupBasicAssets() + const upload = await createUpload(project.id, user.id, 'legacy-upload.png') + const first = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: user.id, + message: 'First comment', + attachmentIds: [upload.id], + }) + const second = await assetService.createComment({ + assetId: assets.fileA1.id, + userId: user.id, + message: 'Second comment', + attachmentIds: [], + }) + await prisma.assetCommentAttachment.create({ + data: { assetId: upload.id, commentId: second.id }, + }) + + await assetService.deleteComment({ commentId: first.id, userId: user.id }) + await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.not.toBeNull() + + await assetService.deleteComment({ commentId: second.id, userId: user.id }) + await expect(prisma.asset.findUnique({ where: { id: upload.id } })).resolves.toBeNull() + }) + }) + it('can create and retrieve comments with video timestamp', async () => { const { user, assets } = await setupBasicAssets() diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index bd3bac07..fdbc4ef6 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -1958,6 +1958,27 @@ export class AssetService { } } + private async lockCommentAttachments( + tx: Prisma.TransactionClient, + attachmentIds: string[], + owner?: { projectId: string | null; userId: string }, + ): Promise { + if (attachmentIds.length === 0) return [] + + // Lock the same rows in the same order when claiming or removing attachments. + const ownerFilter = owner + ? Prisma.sql`AND project_id IS NOT DISTINCT FROM ${owner.projectId} AND creator_id = ${owner.userId}` + : Prisma.empty + const attachments = await tx.$queryRaw<{ id: string }[]>` + SELECT id FROM assets + WHERE id IN (${Prisma.join(attachmentIds)}) AND type = 'attachment' + ${ownerFilter} + ORDER BY id + FOR NO KEY UPDATE + ` + return attachments.map(({ id }) => id) + } + /** * Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them * unless `triggerAgents` is false, which keeps an agent's own comments from starting @@ -1990,6 +2011,10 @@ export class AssetService { } } + const attachmentIds = await this.lockCommentAttachments(tx, req.attachmentIds, { + projectId: a.projectId, + userId: req.userId, + }) const comment = await tx.assetComment.create({ data: { assetId: a.id, @@ -2002,23 +2027,15 @@ export class AssetService { }) commentId = comment.id - for (const attachmentId of req.attachmentIds) { - const attachmentAsset = await tx.asset.findUnique({ - where: { id: attachmentId }, + if (attachmentIds.length > 0) { + // Read the links after acquiring the locks to see any claims that committed while waiting. + const unclaimed = await tx.asset.findMany({ + where: { id: { in: attachmentIds }, commentAttachments: { none: {} } }, + select: { id: true }, + }) + await tx.assetCommentAttachment.createMany({ + data: unclaimed.map(({ id }) => ({ assetId: id, commentId: comment.id })), }) - if ( - attachmentAsset && - (attachmentAsset.type === AssetType.attachment || - attachmentAsset.type === AssetType.file) && - attachmentAsset.projectId === a.projectId - ) { - await tx.assetCommentAttachment.create({ - data: { - assetId: attachmentAsset.id, - commentId: comment.id, - }, - }) - } } if (options.shareLinkId) { @@ -2207,19 +2224,12 @@ export class AssetService { async deleteComment({ commentId, userId }: { commentId: string; userId: string }): Promise { const comment = await this.prismaClient.assetComment.findUnique({ where: { id: commentId }, - include: { - attachments: { - include: { - asset: { - include: { - storageKey: true, - }, - }, - }, - }, + select: { + creatorId: true, + attachments: { select: { assetId: true } }, asset: { select: { - project: { select: { id: true, teamId: true } }, + project: { select: { teamId: true } }, }, }, }, @@ -2257,35 +2267,19 @@ export class AssetService { throw new HTTPException(403, { message: 'You do not have permission to delete this comment' }) } - // Clean up attachment files from S3/storage and delete their DB records - const bucket = process.env.S3_BUCKET || 'shumai' - for (const att of comment.attachments) { - const asset = att.asset - if (asset.storageKey) { - try { - await s3Service.deleteObject(bucket, asset.storageKey.key) - } catch (err) { - logger.error({ err, assetId: asset.id }, 'Failed to delete attachment file from S3') - } + await this.prismaClient.$transaction(async (tx) => { + const attachmentIds = await this.lockCommentAttachments( + tx, + comment.attachments.map(({ assetId }) => assetId), + ) + await tx.assetComment.delete({ where: { id: commentId } }) + + if (attachmentIds.length > 0) { + // The storage cleanup job removes objects once every asset using their storage key is gone. + await tx.asset.deleteMany({ + where: { id: { in: attachmentIds }, commentAttachments: { none: {} } }, + }) } - - await this.prismaClient.asset.delete({ - where: { id: asset.id }, - }) - - if (asset.storageKey) { - await this.prismaClient.storageKey - .delete({ - where: { id: asset.storageKey.id }, - }) - .catch(() => { - // Silently ignore if already deleted - }) - } - } - - await this.prismaClient.assetComment.delete({ - where: { id: commentId }, }) } diff --git a/packages/core/src/authz/authz.test.ts b/packages/core/src/authz/authz.test.ts index b0067063..21158624 100644 --- a/packages/core/src/authz/authz.test.ts +++ b/packages/core/src/authz/authz.test.ts @@ -595,5 +595,70 @@ describe('AuthzService', () => { }), ).rejects.toThrow('Permission denied') }) + + it('limits Kanban task reads for project-scoped members to their projects and their own tasks', async () => { + const owner = await prisma.user.create({ + data: { name: 'Owner User', email: 'owner-kanban-read@example.com', password: 'pass' }, + }) + const client = await prisma.user.create({ + data: { name: 'Client User', email: 'client-kanban-read@example.com', password: 'pass' }, + }) + const teamReviewer = await prisma.user.create({ + data: { name: 'Team Reviewer', email: 'rev-kanban-read@example.com', password: 'pass' }, + }) + + const team = await prisma.team.create({ data: { name: 'Kanban Read Team' } }) + const ownProject = await prisma.project.create({ + data: { name: 'Client Project', teamId: team.id }, + }) + const otherProject = await prisma.project.create({ + data: { name: 'Internal Project', teamId: team.id }, + }) + + await prisma.teamMember.create({ + data: { teamId: team.id, userId: owner.id, role: 'owner', scope: 'team' }, + }) + const clientMember = await prisma.teamMember.create({ + data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' }, + }) + await prisma.projectMember.create({ + data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' }, + }) + await prisma.teamMember.create({ + data: { teamId: team.id, userId: teamReviewer.id, role: 'reviewer', scope: 'team' }, + }) + + const createTask = (title: string, projectId?: string, assigneeId?: string) => + prisma.kanbanTask.create({ + data: { + teamId: team.id, + title, + projectId, + creatorId: owner.id, + reporterId: owner.id, + assigneeId, + }, + }) + const ownTask = await createTask('Client task', ownProject.id) + const otherTask = await createTask('Internal task', otherProject.id) + const teamTask = await createTask('Team task') + const assignedTask = await createTask('Assigned task', otherProject.id, client.id) + + const read = (user: { id: string }, id: string) => + authzService.hasPermission({ + type: ResourceType.KanbanTask, + id, + user, + permission: Permission.Read, + }) + + await expect(read(client, ownTask.id)).resolves.toBeUndefined() + await expect(read(client, assignedTask.id)).resolves.toBeUndefined() + await expect(read(client, otherTask.id)).rejects.toThrow('User has only project scope') + await expect(read(client, teamTask.id)).rejects.toThrow('User has only project scope') + + await expect(read(teamReviewer, otherTask.id)).resolves.toBeUndefined() + await expect(read(teamReviewer, teamTask.id)).resolves.toBeUndefined() + }) }) }) diff --git a/packages/core/src/authz/authz.ts b/packages/core/src/authz/authz.ts index d772ff4d..71a7c625 100644 --- a/packages/core/src/authz/authz.ts +++ b/packages/core/src/authz/authz.ts @@ -122,17 +122,16 @@ export class AuthzService { }) if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' }) - // If this is a KanbanTask and user is a team member, check if they are the assignee, reporter, or creator + // A project-scoped member can read or edit a KanbanTask outside their projects + // only when they are its assignee, reporter, or creator. if (req.type === ResourceType.KanbanTask) { - if (req.permission === Permission.Read) { - return - } - if (req.permission === Permission.Edit) { + if (req.permission === Permission.Read || req.permission === Permission.Edit) { const isParticipant = await this.isKanbanTaskParticipant(req.id, req.user.id) if (isParticipant) { return } } + throw new HTTPException(403, { message: 'User has only project scope' }) } // Project-scoped member on a team-level resource (no project context): diff --git a/packages/core/src/kanban/kanban.test.ts b/packages/core/src/kanban/kanban.test.ts index f73b9cd6..290e2302 100644 --- a/packages/core/src/kanban/kanban.test.ts +++ b/packages/core/src/kanban/kanban.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect } from 'vitest' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' -import { KanbanTaskStatus, KanbanTaskPriority } from '@shumai/db/enums' +import { KanbanTaskStatus, KanbanTaskPriority, KanbanTaskEventType } from '@shumai/db/enums' import { UNASSIGNED_GOAL_ID } from '@shumai/dtos' import { kanbanService } from './kanban' @@ -646,7 +646,7 @@ describe('KanbanService', () => { ) // Create attachment - const att = await kanbanService.createAttachment(team.id, { + const att = await kanbanService.createAttachment(team.id, editor.id, { fileName: 'design.png', size: 1024, contentType: 'image/png', @@ -688,6 +688,119 @@ describe('KanbanService', () => { }) }) + describe('Comment attachment keys', () => { + function payload(key: string) { + return [{ id: 'att-1', name: 'file.txt', key, sizeByte: 1, contentType: 'text/plain' }] + } + + it('rejects attachment keys that were not issued to the author for the task team', async () => { + const { team, editor, reviewer } = await setupTeamAndUsers() + const otherTeam = await prisma.team.create({ data: { name: 'Other Team' } }) + const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor') + + const foreignTeam = await kanbanService.createAttachment(otherTeam.id, editor.id, { + fileName: 'other.png', + size: 1, + }) + const otherUser = await kanbanService.createAttachment(team.id, reviewer.id, { + fileName: 'theirs.png', + size: 1, + }) + const own = await kanbanService.createAttachment(team.id, editor.id, { + fileName: 'own.png', + size: 1, + }) + const ownDir = own.key.slice(0, own.key.lastIndexOf('/')) + + for (const key of [ + 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov', + 'avatars/someone.png', + 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/old.png', + foreignTeam.key, + otherUser.key, + `${ownDir}/../../../../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov`, + `kanban/attachments/${team.id}/${editor.id}/not-a-ulid/own.png`, + ]) { + await expect( + kanbanService.addComment(task.id, editor.id, 'see attached', payload(key)), + ).rejects.toThrow(/Invalid attachment/) + } + + const comments = await kanbanService.listComments(task.id) + expect(comments).toHaveLength(0) + + const accepted = await kanbanService.addComment( + task.id, + editor.id, + 'see attached', + payload(own.key), + ) + expect(accepted.attachments.map((a) => a.id)).toEqual(['att-1']) + }) + + it('does not sign stored attachment keys outside kanban attachments', async () => { + const { team, editor } = await setupTeamAndUsers() + const task = await kanbanService.createTask(team.id, { title: 'Task' }, editor.id, 'editor') + const legacyKey = 'kanban/attachments/01JAAAAAAAAAAAAAAAAAAAAAAA/notes.txt' + + await prisma.kanbanTaskComment.create({ + data: { + taskId: task.id, + authorId: editor.id, + body: 'stored before validation', + attachments: [ + { + id: 'a', + name: 'secret', + key: 'files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov', + sizeByte: 1, + }, + { + id: 'b', + name: 'escape', + key: 'kanban/attachments/../files/x/master.mov', + sizeByte: 1, + }, + { id: 'c', name: 'notes.txt', key: legacyKey, sizeByte: 1 }, + { + id: 'd', + name: 'other-team.txt', + key: `kanban/attachments/other-team/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/x.txt`, + sizeByte: 1, + }, + { + id: 'e', + name: 'current.txt', + key: `kanban/attachments/${team.id}/${editor.id}/01JAAAAAAAAAAAAAAAAAAAAAAA/y.txt`, + sizeByte: 1, + }, + ], + }, + }) + + const [comment] = await kanbanService.listComments(task.id) + expect(comment.attachments.map((a) => a.id)).toEqual(['c', 'e']) + + const detail = await kanbanService.getTask(task.id) + expect(detail.comments[0].attachments.map((a) => a.id)).toEqual(['c', 'e']) + }) + + it('keeps attachment uploads inside the team attachment folder', async () => { + const { team, editor } = await setupTeamAndUsers() + + const att = await kanbanService.createAttachment(team.id, editor.id, { + fileName: '../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov', + size: 1, + }) + + const parts = att.key.split('/') + expect(parts.slice(0, 4)).toEqual(['kanban', 'attachments', team.id, editor.id]) + expect(parts).toHaveLength(6) + expect(parts).not.toContain('..') + expect(att.name).toBe('../../files/01JAAAAAAAAAAAAAAAAAAAAAAA/master.mov') + }) + }) + // -------------------------------------------------------------------------- // Task Ordering & Fractional Indexing // -------------------------------------------------------------------------- @@ -1139,4 +1252,185 @@ describe('KanbanService', () => { expect(pdfDetail?.thumbnailUrl).toContain('posters/doc_poster.webp') }) }) + + // -------------------------------------------------------------------------- + // Project membership + // -------------------------------------------------------------------------- + describe('Project membership', () => { + async function setupProjectScopedMember() { + const { team, owner, reviewer } = await setupTeamAndUsers() + const client = await prisma.user.create({ + data: { name: 'Client Reviewer', email: 'client@example.com' }, + }) + const ownProject = await prisma.project.create({ + data: { name: 'Client Project', teamId: team.id }, + }) + const otherProject = await prisma.project.create({ + data: { name: 'Internal Project', teamId: team.id }, + }) + const clientMember = await prisma.teamMember.create({ + data: { teamId: team.id, userId: client.id, role: 'reviewer', scope: 'project' }, + }) + await prisma.projectMember.create({ + data: { projectId: ownProject.id, teamMemberId: clientMember.id, role: 'reviewer' }, + }) + + const ownTask = await kanbanService.createTask( + team.id, + { title: 'Client task', projectId: ownProject.id }, + owner.id, + 'owner', + ) + const otherTask = await kanbanService.createTask( + team.id, + { title: 'Internal task', projectId: otherProject.id }, + owner.id, + 'owner', + ) + const teamTask = await kanbanService.createTask( + team.id, + { title: 'Team task' }, + owner.id, + 'owner', + ) + const assignedTask = await kanbanService.createTask( + team.id, + { title: 'Assigned internal task', projectId: otherProject.id, assigneeId: client.id }, + owner.id, + 'owner', + ) + + return { + team, + owner, + reviewer, + client, + otherProject, + ownTask, + otherTask, + teamTask, + assignedTask, + } + } + + it('lists only tasks in their projects, or that they take part in, for project-scoped members', async () => { + const { team, client, otherProject, ownTask, assignedTask } = await setupProjectScopedMember() + + const list = await kanbanService.listTasks(team.id, {}, client.id) + expect(list.data.map((t) => t.id).sort()).toEqual([ownTask.id, assignedTask.id].sort()) + expect(list.pageInfo.total).toBe(2) + + const filtered = await kanbanService.listTasks( + team.id, + { projectId: otherProject.id }, + client.id, + ) + expect(filtered.data.map((t) => t.id)).toEqual([assignedTask.id]) + }) + + it('lists every team task for team-scoped members', async () => { + const { team, reviewer, ownTask, otherTask, teamTask, assignedTask } = + await setupProjectScopedMember() + + const list = await kanbanService.listTasks(team.id, {}, reviewer.id) + expect(list.data.map((t) => t.id).sort()).toEqual( + [ownTask.id, otherTask.id, teamTask.id, assignedTask.id].sort(), + ) + }) + + it('shows only readable dependencies, dependents, and dependency events', async () => { + const { owner, team, client, reviewer, ownTask, otherTask, teamTask, assignedTask } = + await setupProjectScopedMember() + + await kanbanService.setDependencies( + ownTask.id, + [otherTask.id, assignedTask.id, teamTask.id], + owner.id, + ) + await kanbanService.setDependencies(ownTask.id, [otherTask.id, assignedTask.id], owner.id) + await kanbanService.setDependencies(teamTask.id, [ownTask.id], owner.id) + await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id) + + const detail = await kanbanService.getTask(ownTask.id, client.id) + expect(detail.dependencies.map((task) => task.id)).toEqual([assignedTask.id]) + expect(detail.dependents).toEqual([]) + expect(detail.dependencyCount).toBe(1) + expect(detail.dependentCount).toBe(0) + + const events = await kanbanService.listEvents(ownTask.id, client.id) + for (const history of [detail.events, events]) { + expect( + history.filter((event) => event.type === KanbanTaskEventType.DEPENDENCY_ADDED), + ).toEqual([expect.objectContaining({ data: { parentId: assignedTask.id } })]) + expect(history).toContainEqual( + expect.objectContaining({ type: KanbanTaskEventType.CREATED }), + ) + expect(history).not.toContainEqual( + expect.objectContaining({ type: KanbanTaskEventType.DEPENDENCY_REMOVED }), + ) + } + + const teamDetail = await kanbanService.getTask(ownTask.id, reviewer.id) + expect(teamDetail.dependencies.map((task) => task.id).sort()).toEqual( + [otherTask.id, assignedTask.id].sort(), + ) + expect(teamDetail.dependents.map((task) => task.id)).toEqual([teamTask.id]) + expect(teamDetail.events).toContainEqual( + expect.objectContaining({ + type: KanbanTaskEventType.DEPENDENCY_REMOVED, + data: { parentId: teamTask.id }, + }), + ) + + const summary = await kanbanService.listTasks(team.id, {}, client.id) + expect(summary.data).toContainEqual( + expect.objectContaining({ id: ownTask.id, dependencyCount: 1, dependentCount: 0 }), + ) + + const updated = await kanbanService.updateTask( + assignedTask.id, + { title: 'Updated assigned task' }, + client.id, + null, + ) + expect(updated).toMatchObject({ dependencyCount: 0, dependentCount: 1 }) + }) + + it('lists no tasks for users outside the team', async () => { + const { team } = await setupProjectScopedMember() + const outsider = await prisma.user.create({ + data: { name: 'Outsider', email: 'outsider@example.com' }, + }) + + const list = await kanbanService.listTasks(team.id, {}, outsider.id) + expect(list.data).toEqual([]) + }) + + it('lists only readable tasks linked to an asset', async () => { + const { team, owner, client, reviewer, otherProject, otherTask, assignedTask } = + await setupProjectScopedMember() + const asset = await prisma.asset.create({ + data: { + name: 'internal.mp4', + type: 'file', + status: 'processed', + projectId: otherProject.id, + creatorId: owner.id, + }, + }) + await kanbanService.linkAsset(team.id, otherTask.id, asset.id) + await kanbanService.linkAsset(team.id, assignedTask.id, asset.id) + await kanbanService.setDependencies(assignedTask.id, [otherTask.id], owner.id) + + const forClient = await kanbanService.listTasksForAsset(team.id, asset.id, client.id) + expect(forClient.map((t) => t.id)).toEqual([assignedTask.id]) + expect(forClient[0].dependencyCount).toBe(0) + + const forReviewer = await kanbanService.listTasksForAsset(team.id, asset.id, reviewer.id) + expect(forReviewer.map((t) => t.id).sort()).toEqual([otherTask.id, assignedTask.id].sort()) + expect(forReviewer).toContainEqual( + expect.objectContaining({ id: assignedTask.id, dependencyCount: 1 }), + ) + }) + }) }) diff --git a/packages/core/src/kanban/kanban.ts b/packages/core/src/kanban/kanban.ts index c3896679..8e96b312 100644 --- a/packages/core/src/kanban/kanban.ts +++ b/packages/core/src/kanban/kanban.ts @@ -7,6 +7,7 @@ import { paginateQuery } from '../pagination' import { getAvatarUrl } from '../user/avatar' import { s3Service } from '../s3/s3' import { getProxyType } from '../utils/mime' +import { sanitizeFilename } from '../utils/filename' import { assetService } from '../asset/asset' import type { CreateKanbanGoalRequest, @@ -28,6 +29,73 @@ import type { } from '@shumai/dtos' import { UNASSIGNED_GOAL_ID } from '@shumai/dtos' +type TaskEventWithActor = Prisma.KanbanTaskEventGetPayload<{ include: { actor: true } }> + +function dependencyEventParentId(event: TaskEventWithActor): string | undefined { + if ( + event.type === KanbanTaskEventType.DEPENDENCY_ADDED || + event.type === KanbanTaskEventType.DEPENDENCY_REMOVED + ) { + const parentId = event.data?.parentId + if (typeof parentId === 'string') return parentId + } +} + +function taskRelationCountSelect( + taskFilter: Prisma.KanbanTaskWhereInput | undefined, +): Prisma.KanbanTaskCountOutputTypeSelect { + return { + comments: true, + assets: true, + dependencies: taskFilter ? { where: { parent: taskFilter } } : true, + dependents: taskFilter ? { where: { child: taskFilter } } : true, + } +} + +const ULID_PATTERN = /^[0-9A-HJKMNP-TV-Z]{26}$/ + +function isSafeKeySegment(segment: string): boolean { + // eslint-disable-next-line no-control-regex + return segment !== '' && segment !== '.' && segment !== '..' && !/[\\\x00-\x1f\x7f]/.test(segment) +} + +/** + * Parses a comment attachment key issued by `createAttachment`: + * `kanban/attachments////`. + */ +function parseAttachmentKey(key: string): { teamId: string; uploaderId: string } | null { + const parts = key.split('/') + if ( + parts.length !== 6 || + parts[0] !== 'kanban' || + parts[1] !== 'attachments' || + !isSafeKeySegment(parts[2]) || + !isSafeKeySegment(parts[3]) || + !ULID_PATTERN.test(parts[4]) || + !isSafeKeySegment(parts[5]) + ) { + return null + } + return { teamId: parts[2], uploaderId: parts[3] } +} + +/** Keys of comment attachments stored before keys carried the team and uploader. */ +function isLegacyAttachmentKey(key: string): boolean { + const parts = key.split('/') + return ( + parts.length === 4 && + parts[0] === 'kanban' && + parts[1] === 'attachments' && + ULID_PATTERN.test(parts[2]) && + isSafeKeySegment(parts[3]) + ) +} + +/** Whether a stored attachment key may be signed for a comment on a task in `teamId`. */ +function isReadableAttachmentKey(key: string, teamId: string): boolean { + return parseAttachmentKey(key)?.teamId === teamId || isLegacyAttachmentKey(key) +} + export class KanbanService { // -------------------------------------------------------------------------- // Goal CRUD @@ -314,7 +382,7 @@ export class KanbanService { }) } - async getTask(taskId: string): Promise { + async getTask(taskId: string, viewerId?: string): Promise { const task = await prisma.kanbanTask.findUnique({ where: { id: taskId }, include: { @@ -354,27 +422,38 @@ export class KanbanService { throw new HTTPException(404, { message: 'Task not found' }) } + const readableIds = await this.readableRelatedTaskIds(task.teamId, viewerId, [ + ...task.dependencies.map((link) => link.parentId), + ...task.dependents.map((link) => link.childId), + ...task.events.map(dependencyEventParentId).filter((id) => id !== undefined), + ]) + const dependencies = task.dependencies.filter( + (link) => !readableIds || readableIds.has(link.parentId), + ) + const dependents = task.dependents.filter( + (link) => !readableIds || readableIds.has(link.childId), + ) const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, task.status) const resolvedAssets = await this.resolveTaskAssetInfos(task.assets) const baseInfo = await this.toTaskInfo(task, { latestStatusEvent, - dependencyCount: task.dependencies.length, - dependentCount: task.dependents.length, + dependencyCount: dependencies.length, + dependentCount: dependents.length, commentCount: task.comments.length, assetCount: task.assets.length, }) return { ...baseInfo, - dependencies: task.dependencies.map((d) => ({ + dependencies: dependencies.map((d) => ({ id: d.parent.id, title: d.parent.title, isAgentTask: d.parent.isAgentTask, status: d.parent.status, priority: d.parent.priority, })), - dependents: task.dependents.map((d) => ({ + dependents: dependents.map((d) => ({ id: d.child.id, title: d.child.title, isAgentTask: d.child.isAgentTask, @@ -392,29 +471,12 @@ export class KanbanService { image: await getAvatarUrl(c.author.image), }, body: c.body, - attachments: await this.resolveCommentAttachments(c.attachments), + attachments: await this.resolveCommentAttachments(c.attachments, task.teamId), createdAt: c.createdAt.toISOString(), updatedAt: c.updatedAt.toISOString(), })), ), - events: await Promise.all( - task.events.map(async (e) => ({ - id: e.id, - taskId: e.taskId, - actor: e.actor - ? { - id: e.actor.id, - name: e.actor.name, - image: await getAvatarUrl(e.actor.image), - } - : null, - type: e.type, - fromStatus: e.fromStatus, - toStatus: e.toStatus, - data: (e.data as Record) ?? null, - createdAt: e.createdAt.toISOString(), - })), - ), + events: await this.resolveTaskEvents(task.events, readableIds), } } @@ -659,7 +721,8 @@ export class KanbanService { } const latestStatusEvent = await this.resolveLatestStatusEvent(taskId, updated.status) - const counts = await this.getTaskCounts(taskId) + const taskFilter = await this.readableTaskFilter(updated.teamId, actorId) + const counts = await this.getTaskCounts(taskId, taskFilter) return await this.toTaskInfo(updated, { latestStatusEvent, @@ -704,10 +767,54 @@ export class KanbanService { return taskInfo } + /** + * Limits kanban tasks to those a user may read. Team-scoped members see every + * task in the team; project-scoped members see tasks in the projects they + * belong to and tasks they created, report, or are assigned to. + */ + private async readableTaskFilter( + teamId: string, + userId: string | undefined, + ): Promise { + if (!userId) return + const member = await prisma.teamMember.findUnique({ + where: { teamIdUserId: { teamId, userId } }, + }) + if (!member) return { id: { in: [] } } + if (member.scope === 'team') return + return { + teamId, + OR: [ + { project: { members: { some: { teamMemberId: member.id } } } }, + { creatorId: userId }, + { reporterId: userId }, + { assigneeId: userId }, + ], + } + } + + private async readableRelatedTaskIds( + teamId: string, + viewerId: string | undefined, + relatedIds: string[], + ): Promise | undefined> { + if (relatedIds.length === 0) return + const filter = await this.readableTaskFilter(teamId, viewerId) + if (!filter) return + + const tasks = await prisma.kanbanTask.findMany({ + where: { id: { in: [...new Set(relatedIds)] }, AND: [filter] }, + select: { id: true }, + }) + return new Set(tasks.map((task) => task.id)) + } + async listTasks( teamId: string, params: ListKanbanTasksRequest, + viewerId?: string, ): Promise<{ data: KanbanTaskInfo[]; pageInfo: { total?: number; cursor?: string } }> { + const taskFilter = await this.readableTaskFilter(teamId, viewerId) const where: Prisma.KanbanTaskWhereInput = { teamId, ...(params.status && { status: params.status }), @@ -721,6 +828,7 @@ export class KanbanService { ...(params.priority && { priority: params.priority }), ...(params.assigneeId && { assigneeId: params.assigneeId }), ...(params.reporterId && { reporterId: params.reporterId }), + ...(taskFilter && { AND: [taskFilter] }), } return await paginateQuery( @@ -732,14 +840,7 @@ export class KanbanService { reporter: true, assignee: true, goal: true, - _count: { - select: { - comments: true, - dependencies: true, - dependents: true, - assets: true, - }, - }, + _count: { select: taskRelationCountSelect(taskFilter) }, }, orderBy: [{ sortIndex: 'asc' }, { id: 'asc' }], skip, @@ -869,9 +970,10 @@ export class KanbanService { async createAttachment( teamId: string, + uploaderId: string, req: { fileName: string; size: number; contentType?: string }, ): Promise { - const key = `kanban/attachments/${ulid()}/${req.fileName}` + const key = `kanban/attachments/${teamId}/${uploaderId}/${ulid()}/${sanitizeFilename(req.fileName)}` const uploadUrl = await s3Service.presign(process.env.S3_BUCKET || 'shumai', key, 'PUT') const proxyType = getProxyType(req.contentType, req.fileName) @@ -895,6 +997,16 @@ export class KanbanService { const task = await prisma.kanbanTask.findUnique({ where: { id: taskId } }) if (!task) throw new HTTPException(404, { message: 'Task not found' }) + // Attachments are uploaded through createAttachment. Only keys it issued to the + // comment author for this task's team may be stored and signed later. + const isOwnUpload = (key: string) => { + const parsed = parseAttachmentKey(key) + return parsed?.teamId === task.teamId && parsed.uploaderId === authorId + } + if (attachments?.some((att) => !isOwnUpload(att.key))) { + throw new HTTPException(400, { message: 'Invalid attachment' }) + } + const comment = await prisma.$transaction(async (tx) => { const c = await tx.kanbanTaskComment.create({ data: { @@ -917,7 +1029,10 @@ export class KanbanService { return c }) - const resolvedAttachments = await this.resolveCommentAttachments(comment.attachments) + const resolvedAttachments = await this.resolveCommentAttachments( + comment.attachments, + task.teamId, + ) return { id: comment.id, @@ -935,6 +1050,12 @@ export class KanbanService { } async listComments(taskId: string): Promise { + const task = await prisma.kanbanTask.findUnique({ + where: { id: taskId }, + select: { teamId: true }, + }) + if (!task) throw new HTTPException(404, { message: 'Task not found' }) + const comments = await prisma.kanbanTaskComment.findMany({ where: { taskId }, include: { author: true }, @@ -951,7 +1072,7 @@ export class KanbanService { image: await getAvatarUrl(c.author.image), }, body: c.body, - attachments: await this.resolveCommentAttachments(c.attachments), + attachments: await this.resolveCommentAttachments(c.attachments, task.teamId), createdAt: c.createdAt.toISOString(), updatedAt: c.updatedAt.toISOString(), })), @@ -981,7 +1102,8 @@ export class KanbanService { } private async resolveCommentAttachments( - attachments?: PrismaJson.KanbanCommentAttachmentList | null, + attachments: PrismaJson.KanbanCommentAttachmentList | null | undefined, + teamId: string, ): Promise { if (!attachments || !Array.isArray(attachments) || attachments.length === 0) { return [] @@ -989,29 +1111,50 @@ export class KanbanService { const bucket = process.env.S3_BUCKET || 'shumai' return await Promise.all( - attachments.map(async (att) => { - const url = await s3Service.presign(bucket, att.key, 'GET') - return { - id: att.id, - name: att.name, - sizeByte: att.sizeByte, - contentType: att.contentType, - url, - proxyType: att.proxyType, - } - }), + attachments + .filter((att) => typeof att.key === 'string' && isReadableAttachmentKey(att.key, teamId)) + .map(async (att) => { + const url = await s3Service.presign(bucket, att.key, 'GET') + return { + id: att.id, + name: att.name, + sizeByte: att.sizeByte, + contentType: att.contentType, + url, + proxyType: att.proxyType, + } + }), ) } - async listEvents(taskId: string): Promise { - const events = await prisma.kanbanTaskEvent.findMany({ - where: { taskId }, - include: { actor: true }, - orderBy: { createdAt: 'desc' }, + async listEvents(taskId: string, viewerId?: string): Promise { + const task = await prisma.kanbanTask.findUnique({ + where: { id: taskId }, + select: { + teamId: true, + events: { include: { actor: true }, orderBy: { createdAt: 'desc' } }, + }, + }) + if (!task) return [] + const readableIds = await this.readableRelatedTaskIds( + task.teamId, + viewerId, + task.events.map(dependencyEventParentId).filter((id) => id !== undefined), + ) + return await this.resolveTaskEvents(task.events, readableIds) + } + + private async resolveTaskEvents( + events: TaskEventWithActor[], + readableIds: Set | undefined, + ): Promise { + const visibleEvents = events.filter((event) => { + const parentId = dependencyEventParentId(event) + return !readableIds || parentId === undefined || readableIds.has(parentId) }) return await Promise.all( - events.map(async (e) => ({ + visibleEvents.map(async (e) => ({ id: e.id, taskId: e.taskId, actor: e.actor @@ -1024,7 +1167,7 @@ export class KanbanService { type: e.type, fromStatus: e.fromStatus, toStatus: e.toStatus, - data: (e.data as Record) ?? null, + data: e.data ?? null, createdAt: e.createdAt.toISOString(), })), ) @@ -1115,9 +1258,17 @@ export class KanbanService { return await this.resolveTaskAssetInfos(links) } - async listTasksForAsset(teamId: string, assetId: string): Promise { + async listTasksForAsset( + teamId: string, + assetId: string, + viewerId?: string, + ): Promise { + const taskFilter = await this.readableTaskFilter(teamId, viewerId) const links = await prisma.kanbanTaskAsset.findMany({ - where: { assetId }, + where: { + assetId, + task: { teamId, ...taskFilter }, + }, include: { task: { include: { @@ -1125,24 +1276,15 @@ export class KanbanService { reporter: true, assignee: true, goal: true, - _count: { - select: { - comments: true, - dependencies: true, - dependents: true, - assets: true, - }, - }, + _count: { select: taskRelationCountSelect(taskFilter) }, }, }, }, orderBy: { createdAt: 'desc' }, }) - const matchingLinks = links.filter((l) => l.task && l.task.teamId === teamId) - return await Promise.all( - matchingLinks.map(async (l) => { + links.map(async (l) => { const t = l.task const latestStatusEvent = await this.resolveLatestStatusEvent(t.id, t.status) return await this.toTaskInfo(t, { @@ -1195,19 +1337,25 @@ export class KanbanService { } } - private async getTaskCounts(taskId: string): Promise<{ + private async getTaskCounts( + taskId: string, + taskFilter?: Prisma.KanbanTaskWhereInput, + ): Promise<{ commentCount: number dependencyCount: number dependentCount: number assetCount: number }> { - const [commentCount, dependencyCount, dependentCount, assetCount] = await Promise.all([ - prisma.kanbanTaskComment.count({ where: { taskId } }), - prisma.kanbanTaskLink.count({ where: { childId: taskId } }), - prisma.kanbanTaskLink.count({ where: { parentId: taskId } }), - prisma.kanbanTaskAsset.count({ where: { taskId } }), - ]) - return { commentCount, dependencyCount, dependentCount, assetCount } + const task = await prisma.kanbanTask.findUnique({ + where: { id: taskId }, + select: { _count: { select: taskRelationCountSelect(taskFilter) } }, + }) + return { + commentCount: task?._count.comments ?? 0, + dependencyCount: task?._count.dependencies ?? 0, + dependentCount: task?._count.dependents ?? 0, + assetCount: task?._count.assets ?? 0, + } } private async resolveTaskAssetInfos( diff --git a/packages/core/src/s3/s3.test.ts b/packages/core/src/s3/s3.test.ts index c6cf4a40..c88aee8e 100644 --- a/packages/core/src/s3/s3.test.ts +++ b/packages/core/src/s3/s3.test.ts @@ -752,6 +752,18 @@ describe('S3Service implementations', () => { expect(size).toBe(11) }) + it('rejects keys with parent directory segments', async () => { + await localS3.putObject('test-bucket', 'files/a/master.mov', 'original', 8) + + await expect( + localS3.putObject('test-bucket', 'attachments/x/../../files/a/master.mov', 'evil', 4), + ).rejects.toThrow(/path traversal/) + await expect( + localS3.getObjectSize('test-bucket', 'attachments/x/..\\..\\files/a/master.mov'), + ).rejects.toThrow(/path traversal/) + expect(await localS3.getObjectSize('test-bucket', 'files/a/master.mov')).toBe(8) + }) + it('removes empty embedding chunk directories after deleting the last chunk', async () => { const key = 'files/asset-1/tmp-embedding-chunks/chunk.mp4' await localS3.putObject('test-bucket', key, 'chunk', 5) diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 8e852cd5..b3155651 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -850,6 +850,11 @@ export class LocalStorageService implements S3Service { } private getFilePath(bucket: string, key: string): string { + // Object keys are flat names: a `..` segment must not be resolved into another + // object's path (S3 keeps it literally). + if (key.split(/[\\/]/).includes('..') || bucket.split(/[\\/]/).includes('..')) { + throw new Error(`Invalid path: potential path traversal detected`) + } const filePath = path.join(this.basePath, bucket, key) if (!filePath.startsWith(this.basePath)) { throw new Error(`Invalid path: potential path traversal detected`) diff --git a/packages/core/src/share/share.test.ts b/packages/core/src/share/share.test.ts index fd487735..81ea74f8 100644 --- a/packages/core/src/share/share.test.ts +++ b/packages/core/src/share/share.test.ts @@ -6,6 +6,12 @@ import { assetService } from '@shumai/core/src/asset/asset' import { projectService } from '@shumai/core/src/project/project' import { AssetType } from '@shumai/db' import { s3Service } from '@shumai/core/src/s3/s3' +import { timingSafeEqual } from 'node:crypto' + +vi.mock('node:crypto', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, timingSafeEqual: vi.fn(actual.timingSafeEqual) } +}) vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { @@ -167,6 +173,69 @@ describe('ShareService', () => { ).rejects.toThrow('expired') }) + it('includes the saved password in share link settings', async () => { + const created = await shareService.createShareLink(projectId, { + name: 'Protected Share', + password: 'secret-password', + }) + expect(created.hasPassword).toBe(true) + expect(created.password).toBe('secret-password') + + const fetched = await shareService.getShareLink(created.id) + expect(fetched.hasPassword).toBe(true) + expect(fetched.password).toBe('secret-password') + + const updated = await shareService.updateShareLink(created.id, { password: 'other' }) + expect(updated.hasPassword).toBe(true) + expect(updated.password).toBe('other') + + const list = await shareService.listProjectShareLinks({ projectId }) + expect(list.data).toContainEqual(expect.objectContaining({ id: created.id, password: 'other' })) + + const cleared = await shareService.updateShareLink(created.id, { password: null }) + expect(cleared.hasPassword).toBe(false) + expect(cleared.password).toBeNull() + }) + + it('rejects missing or different-length share passwords', async () => { + const shareLink = await shareService.createShareLink(projectId, { + name: 'Protected Share', + password: 'secret-password', + }) + + await expect( + shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId), + ).rejects.toThrow('Invalid password') + await expect( + shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, ''), + ).rejects.toThrow('Invalid password') + await expect( + shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret'), + ).rejects.toThrow('Invalid password') + await expect( + shareService.verifyPublicAccess( + shareLink.id, + shareLink.rootFolderId, + 'secret-password-and-more', + ), + ).rejects.toThrow('Invalid password') + await expect( + shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'secret-password'), + ).resolves.toBeDefined() + }) + + it('compares share passwords in constant time', async () => { + const shareLink = await shareService.createShareLink(projectId, { + name: 'Protected Share', + password: 'secret-password', + }) + + await expect( + shareService.verifyPublicAccess(shareLink.id, shareLink.rootFolderId, 'wrong'), + ).rejects.toThrow('Invalid password') + expect(timingSafeEqual).toHaveBeenCalled() + }) + it('traces deep ancestors for public access', async () => { const shareLink = await shareService.createShareLink(projectId, { name: 'Deep Share', diff --git a/packages/core/src/share/share.ts b/packages/core/src/share/share.ts index 728ece5d..d54be1a5 100644 --- a/packages/core/src/share/share.ts +++ b/packages/core/src/share/share.ts @@ -1,3 +1,4 @@ +import { createHash, timingSafeEqual } from 'node:crypto' import { prisma } from '@shumai/db' import { AssetType, Prisma } from '@shumai/db' import { @@ -18,6 +19,17 @@ import { ShareLinkPasswordInvalidError, } from './errors' +/** + * Compares a provided share password with the stored one in constant time. + * Both values are hashed first so the comparison does not depend on their lengths. + */ +function sharePasswordMatches(stored: string, provided: string | undefined): boolean { + if (provided === undefined) return false + const a = createHash('sha256').update(stored).digest() + const b = createHash('sha256').update(provided).digest() + return timingSafeEqual(a, b) +} + export class ShareService { async createShareLink( projectId: string, @@ -269,7 +281,7 @@ export class ShareService { throw new ShareLinkExpiredError('Share link has expired') } - if (shareLink.password && shareLink.password !== providedPassword) { + if (shareLink.password && !sharePasswordMatches(shareLink.password, providedPassword)) { throw new ShareLinkPasswordInvalidError('Invalid password for share link') } diff --git a/packages/db/src/prisma-testing-helper.ts b/packages/db/src/prisma-testing-helper.ts index 77deda33..f77c5f72 100644 --- a/packages/db/src/prisma-testing-helper.ts +++ b/packages/db/src/prisma-testing-helper.ts @@ -217,6 +217,10 @@ export class PrismaTestingHelper< return this.proxyClient } + public getUnderlyingClient(): T { + return this.prismaClient + } + public async startNewTransaction(opts?: { timeout?: number; maxWait?: number }): Promise { if (this.endCurrentTransactionPromise != null) { throw new Error( diff --git a/packages/webui/components/share-settings-sidebar.test.tsx b/packages/webui/components/share-settings-sidebar.test.tsx new file mode 100644 index 00000000..a7b60f76 --- /dev/null +++ b/packages/webui/components/share-settings-sidebar.test.tsx @@ -0,0 +1,143 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import type { ShareLinkInfo } from '@shumai/dtos' +import { client } from '@/ui/api/client' +import { m } from '@/ui/paraglide/messages.js' +import { ShareSettingsSidebar } from './share-settings-sidebar' + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + shares: { + ':shareId': { + $put: vi.fn(), + watermark: { + $get: vi.fn(), + $put: vi.fn(), + }, + }, + }, + projects: { + ':projectId': { + fields: { + $get: vi.fn(), + }, + }, + }, + }, + }, +})) + +vi.mock('@/ui/components/watermark-editor-dialog', () => ({ + WatermarkEditorDialog: () => null, +})) + +vi.mock('sonner', () => ({ + toast: { success: vi.fn(), error: vi.fn() }, +})) + +const shareLink: ShareLinkInfo = { + id: 'share-1', + name: 'Client review', + isDisabled: false, + allowDownload: true, + hasPassword: true, + password: 'saved-secret', + rootFolderId: 'folder-1', + projectId: 'project-1', + isExpired: false, + watermarkStatus: 'disabled', + views: 0, + lastViewedAt: null, + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), +} + +function renderSidebar(link: ShareLinkInfo) { + const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + return render( + + {}} + defaultSortOrder={null} + onSortOrderChange={() => {}} + /> + , + ) +} + +function openSecuritySection() { + fireEvent.click(screen.getByText(m.security())) +} + +describe('ShareSettingsSidebar password', () => { + beforeEach(() => { + vi.mocked(client.api.shares[':shareId'].watermark.$get).mockResolvedValue({ + ok: false, + } as never) + vi.mocked(client.api.projects[':projectId'].fields.$get).mockResolvedValue({ + ok: true, + json: async () => [], + } as never) + vi.mocked(client.api.shares[':shareId'].$put).mockResolvedValue({ + ok: true, + json: async () => ({ ...shareLink }), + } as never) + }) + + afterEach(() => { + cleanup() + vi.clearAllMocks() + }) + + it('shows the saved password when password protection is enabled', () => { + renderSidebar(shareLink) + openSecuritySection() + + const input = screen.getByPlaceholderText(m.enter_password()) + expect(input).toHaveProperty('value', 'saved-secret') + }) + + it('saves and displays a replacement password', async () => { + renderSidebar(shareLink) + openSecuritySection() + + const input = screen.getByPlaceholderText(m.enter_password()) + fireEvent.change(input, { target: { value: 'new-secret' } }) + fireEvent.click(screen.getByRole('button', { name: m.save() })) + + await waitFor(() => { + expect(client.api.shares[':shareId'].$put).toHaveBeenCalledWith({ + param: { shareId: 'share-1' }, + json: { password: 'new-secret' }, + }) + }) + expect(input).toHaveProperty('value', 'new-secret') + }) + + it('turning the password off clears it', async () => { + renderSidebar(shareLink) + openSecuritySection() + + const toggles = screen.getAllByRole('switch') + const passwordToggle = toggles.find( + (el) => + el.getAttribute('aria-checked') === 'true' && + el.closest('div')?.textContent?.includes(m.password()), + ) + expect(passwordToggle).toBeDefined() + fireEvent.click(passwordToggle!) + + await waitFor(() => { + expect(client.api.shares[':shareId'].$put).toHaveBeenCalledWith({ + param: { shareId: 'share-1' }, + json: { password: null }, + }) + }) + }) +})