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/<teamId>/<userId>/<ulid>/<file name>.
- 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/<ulid>/<name> 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>
This commit is contained in:
Yiling-J
2026-11-26 10:43:08 +08:00
committed by GitHub
co-authored by phj1081
parent f2febaf652
commit 1066900c78
21 changed files with 1425 additions and 158 deletions
+267 -7
View File
@@ -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<PromiseSettledResult<unknown>[]> | 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()
+49 -55
View File
@@ -1958,6 +1958,27 @@ export class AssetService {
}
}
private async lockCommentAttachments(
tx: Prisma.TransactionClient,
attachmentIds: string[],
owner?: { projectId: string | null; userId: string },
): Promise<string[]> {
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<void> {
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 },
})
}
+65
View File
@@ -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()
})
})
})
+4 -5
View File
@@ -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):
+296 -2
View File
@@ -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 }),
)
})
})
})
+224 -76
View File
@@ -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/<teamId>/<uploaderId>/<ulid>/<file name>`.
*/
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<KanbanTaskDetail> {
async getTask(taskId: string, viewerId?: string): Promise<KanbanTaskDetail> {
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<string, unknown>) ?? 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<Prisma.KanbanTaskWhereInput | undefined> {
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<Set<string> | 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<PostKanbanAttachmentResponse> {
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<KanbanCommentInfo[]> {
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<KanbanAttachmentInfo[]> {
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<KanbanEventInfo[]> {
const events = await prisma.kanbanTaskEvent.findMany({
where: { taskId },
include: { actor: true },
orderBy: { createdAt: 'desc' },
async listEvents(taskId: string, viewerId?: string): Promise<KanbanEventInfo[]> {
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<string> | undefined,
): Promise<KanbanEventInfo[]> {
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<string, unknown>) ?? 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<KanbanTaskInfo[]> {
async listTasksForAsset(
teamId: string,
assetId: string,
viewerId?: string,
): Promise<KanbanTaskInfo[]> {
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(
+12
View File
@@ -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)
+5
View File
@@ -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`)
+69
View File
@@ -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<typeof import('node:crypto')>()
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',
+13 -1
View File
@@ -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')
}