fix(security): improve access control and storage security (#518)

* fix(security): improve access control and storage security

* fix(security): set NODE_ENV in dockerfiles and sign local storage get urls with lru cache
This commit is contained in:
Yiling-J
2026-11-05 20:49:38 +08:00
committed by GitHub
parent 0dc0bbeb03
commit 65e2ac1383
26 changed files with 811 additions and 208 deletions
+15 -1
View File
@@ -2,16 +2,19 @@ import { Hono } from 'hono'
import { teamService } from '@shumai/core/src/team/team'
import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth'
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { isArchiveStorageEnabled } from '@shumai/core/src/s3/archive-storage'
import { z } from 'zod'
import { zValidator } from '@hono/zod-validator'
import { ulid } from 'ulid'
import { setCookie } from 'hono/cookie'
const app = new Hono()
const identifySchema = z.object({
username: z.string().min(1),
email: z.string().email(),
shareId: z.string().min(1).optional(),
})
const route = app
@@ -30,7 +33,7 @@ const route = app
return c.json({ id: session?.user?.id ?? null })
})
.post('/identify', zValidator('json', identifySchema), async (c) => {
const { username, email } = c.req.valid('json')
const { username, email, shareId } = c.req.valid('json')
const dummyEmail = `guest_${ulid()}@guest.local`
const user = await userService.createGuestUser({
@@ -39,6 +42,17 @@ const route = app
guestEmail: email,
})
if (shareId) {
const token = createGuestToken({ userId: user.id, shareId })
setCookie(c, `shumai_guest_${shareId}`, token, {
httpOnly: true,
path: '/',
sameSite: 'Lax',
secure: c.req.url.startsWith('https://') || process.env.NODE_ENV === 'production',
maxAge: 30 * 24 * 60 * 60,
})
}
return c.json({ id: user.id })
})
.all('/auth/*', (c) => {
+49 -17
View File
@@ -1,5 +1,6 @@
import { Hono } from 'hono'
import type { Context } from 'hono'
import { getCookie } from 'hono/cookie'
import { zValidator } from '@hono/zod-validator'
import { shareService } from '@shumai/core/src/share/share'
import { assetService } from '@shumai/core/src/asset/asset'
@@ -12,6 +13,7 @@ import type { Prisma as PrismaType } from '@shumai/db'
import { projectService } from '@shumai/core/src/project/project'
import { userService } from '@shumai/core/src/user/user'
import { auth } from '@shumai/core/src/auth/auth'
import { verifyGuestToken } from '@shumai/core/src/auth/guest-token'
import { createCommentRequestSchema } from '@shumai/dtos'
import { notificationService } from '@shumai/core/src/notification/notification'
import {
@@ -160,7 +162,7 @@ const route = app
const password = c.req.header('x-share-password')
try {
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
await shareService.verifyPublicAccess(shareId, shareLink.rootFolderId, password)
return c.json({
id: shareLink.id,
name: shareLink.name,
@@ -184,7 +186,7 @@ const route = app
try {
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(shareLink.rootFolderId, password)
await shareService.verifyPublicAccess(shareId, shareLink.rootFolderId, password)
const fields = await metadataService.listProjectFields(null, shareLink.projectId)
const fieldVisibility = (shareLink.fieldVisibility || {}) as Record<string, boolean>
@@ -202,13 +204,14 @@ const route = app
'/shares/:shareId/folders/:folderId/children',
zValidator('query', sharedChildrenRequestSchema),
async (c) => {
const shareId = c.req.param('shareId')
const folderId = c.req.param('folderId')
const password =
c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
const req = c.req.valid('query')
try {
const shareLink = await shareService.verifyPublicAccess(folderId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, folderId, password)
let sort: string | undefined
let order: string | undefined
@@ -264,11 +267,12 @@ const route = app
},
)
.get('/shares/:shareId/files/:fileId', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
let asset = await assetService.getAsset({ assetId: fileId })
@@ -303,12 +307,13 @@ const route = app
'/shares/:shareId/files/:fileId/download-url',
zValidator('json', z.object({ key: z.string().min(1) })),
async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const { key } = c.req.valid('json')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
if (!shareLink.allowDownload) {
throw new ShareLinkDownloadDisabledError('Download is disabled for this share link')
@@ -329,12 +334,13 @@ const route = app
'/shares/:shareId/files/:fileId/comments',
zValidator('query', paginationParamsSchema),
async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const req = c.req.valid('query')
try {
await shareService.verifyPublicAccess(fileId, password)
await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
let userId: string | undefined
@@ -343,6 +349,18 @@ const route = app
})
if (session?.user) {
userId = session.user.id
} else {
const cookieName = `shumai_guest_${shareId}`
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
if (token) {
const verified = verifyGuestToken(token, shareId)
if (verified) {
const guestUser = await userService.getUserById(verified.userId)
if (guestUser && guestUser.guestEmail) {
userId = guestUser.id
}
}
}
}
const res = await assetService.listComments(targetFileId, req, userId)
return c.json(res)
@@ -358,12 +376,15 @@ const route = app
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password')
const guestUserId = c.req.header('x-guest-user-id')
const req = c.req.valid('json')
if (req.attachmentIds && req.attachmentIds.length > 0) {
return c.json({ error: 'Attachments are not allowed on public share comments' }, 400)
}
try {
const shareLink = await shareService.getShareLink(shareId)
await shareService.verifyPublicAccess(fileId, password)
await shareService.verifyPublicAccess(shareId, fileId, password)
const targetFileId = await assetService.resolveTargetAssetId(fileId)
@@ -377,10 +398,17 @@ const route = app
if (session?.user) {
userId = session.user.id
} else if (guestUserId) {
const guestUser = await userService.getUserById(guestUserId)
if (guestUser) {
userId = guestUser.id
} else {
const cookieName = `shumai_guest_${shareId}`
const token = getCookie(c, cookieName) || getCookie(c, 'shumai_guest')
if (token) {
const verified = verifyGuestToken(token, shareId)
if (verified) {
const guestUser = await userService.getUserById(verified.userId)
if (guestUser && guestUser.guestEmail) {
userId = guestUser.id
}
}
}
}
@@ -400,7 +428,7 @@ const route = app
const notifType = req.replyToId ? 'reply_created' : 'comment_created'
notificationService.create({
await notificationService.create({
type: notifType,
teamId: teamId,
creatorId: userId,
@@ -415,11 +443,12 @@ const route = app
},
)
.get('/shares/:shareId/files/:fileId/m3u8', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
let playlist = await assetService.getHlsMasterPlaylist({
assetId: targetAssetId,
@@ -438,11 +467,12 @@ const route = app
}
})
.get('/shares/:shareId/files/:fileId/m3u8/master.m3u8', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
let playlist = await assetService.getHlsMasterPlaylist({
assetId: targetAssetId,
@@ -461,6 +491,7 @@ const route = app
}
})
.get('/shares/:shareId/files/:fileId/m3u8/:resolution', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
let resolution = c.req.param('resolution')
if (resolution.endsWith('.m3u8')) {
@@ -469,7 +500,7 @@ const route = app
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
const playlist = await assetService.getHlsVariantPlaylist({
assetId: targetAssetId,
@@ -483,12 +514,13 @@ const route = app
}
})
.get('/shares/:shareId/files/:fileId/m3u8/:resolution/index.m3u8', async (c) => {
const shareId = c.req.param('shareId')
const fileId = c.req.param('fileId')
const resolution = c.req.param('resolution')
const password = c.req.header('x-share-password') || c.req.query('password') || c.req.query('p')
try {
const shareLink = await shareService.verifyPublicAccess(fileId, password)
const shareLink = await shareService.verifyPublicAccess(shareId, fileId, password)
const targetAssetId = await assetService.resolveLatestVersionId(fileId)
const playlist = await assetService.getHlsVariantPlaylist({
assetId: targetAssetId,
+54 -15
View File
@@ -16,11 +16,14 @@ describe('S3 API', () => {
vi.resetModules()
})
it('GET /files/* calls serveStatic with correct options', async () => {
it('GET /files/* calls serveStatic with correct options when valid signature is provided', async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request('/files/b1/test.webp')
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
expect(res.status).toBe(200)
expect(await res.text()).toBe('static-file')
@@ -39,7 +42,40 @@ describe('S3 API', () => {
}
})
it('GET /files/* returns 403 Forbidden when signature is missing', async () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request('/files/b1/test.webp')
expect(res.status).toBe(403)
const json = await res.json()
expect(json.error).toContain('Forbidden')
})
it('GET /files/* returns 403 Forbidden when signature is invalid', async () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request('/files/b1/test.webp?Signature=invalidsig&Expires=9999999999')
expect(res.status).toBe(403)
})
it('GET /files/* returns 403 Forbidden when signature is expired', async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
// Signed with -10 seconds (expired)
const { signature, expires } = signLocalGetUrl('b1', 'test.webp', -10)
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request(`/files/b1/test.webp?Signature=${signature}&Expires=${expires}`)
expect(res.status).toBe(403)
})
it('GET /files/* sets Content-Disposition with filename when download=1 & filename query params are present', async () => {
const { signLocalGetUrl } = await import('@shumai/core/src/s3/s3')
const { signature, expires } = signLocalGetUrl('b1', 'test.webp')
// We need to capture the onFound callback from serveStatic options
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let onFoundCallback: ((path: string, c: any) => void) | undefined
@@ -54,7 +90,9 @@ describe('S3 API', () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
await app.request('/files/b1/test.webp?download=1&filename=foo.png')
await app.request(
`/files/b1/test.webp?Signature=${signature}&Expires=${expires}&download=1&filename=foo.png`,
)
expect(onFoundCallback).toBeDefined()
@@ -101,10 +139,7 @@ describe('S3 API', () => {
}
})
it('PUT /files/:bucket/:key calls s3Service.putObject', async () => {
const { s3Service: service } = await import('@shumai/core/src/s3/s3')
const mockPut = vi.spyOn(service, 'putObject').mockResolvedValue(undefined)
it('PUT /files/:bucket/:key returns 404', async () => {
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const body = new TextEncoder().encode('test-data')
@@ -117,13 +152,17 @@ describe('S3 API', () => {
body,
})
expect(res.status).toBe(200)
expect(await res.text()).toBe('OK')
expect(mockPut).toHaveBeenCalledWith(
'b1',
'test.webp',
expect.any(ReadableStream),
body.byteLength,
)
expect(res.status).toBe(404)
})
it('GET /files/* returns 404 when STORAGE_BACKEND is not local', async () => {
const s3Module = await import('@shumai/core/src/s3/s3')
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3')
const { default: route } = await import('./s3')
const app = new Hono().route('/files', route)
const res = await app.request('/files/b1/test.webp')
expect(res.status).toBe(404)
})
})
+29 -15
View File
@@ -1,10 +1,38 @@
import { Hono } from 'hono'
import { buildContentDisposition, s3Service } from '@shumai/core/src/s3/s3'
import {
buildContentDisposition,
getStorageBackend,
verifyLocalGetUrlSignature,
} from '@shumai/core/src/s3/s3'
import { serveStatic } from 'hono/bun'
const route = new Hono()
.use('*', async (c, next) => {
if (getStorageBackend() !== 'local') {
return c.notFound()
}
return next()
})
.get(
'/*',
async (c, next) => {
const fullPath = c.req.path.replace(/^\/files\//, '').replace(/^\//, '')
const slashIdx = fullPath.indexOf('/')
if (slashIdx === -1) {
return c.notFound()
}
const bucket = fullPath.slice(0, slashIdx)
const key = fullPath.slice(slashIdx + 1)
const signature = c.req.query('Signature')
const expires = c.req.query('Expires')
if (!verifyLocalGetUrlSignature(bucket, key, signature, expires)) {
return c.json({ error: 'Forbidden: invalid or expired signature' }, 403)
}
return next()
},
serveStatic({
root: './data',
rewriteRequestPath: (path) => path.replace(/^\/files\//, ''),
@@ -15,19 +43,5 @@ const route = new Hono()
},
}),
)
.put('/:bucket/:key{.+}', async (c) => {
const bucket = c.req.param('bucket')
const key = c.req.param('key')
const contentLength = parseInt(c.req.header('content-length') || '0', 10)
try {
const body = c.req.raw.body ?? (await c.req.arrayBuffer())
await s3Service.putObject(bucket, key, body, contentLength)
return c.text('OK')
} catch (e: unknown) {
const error = e as Error
return c.text(error.message || 'Internal Server Error', 500)
}
})
export default route
+109 -4
View File
@@ -7,6 +7,9 @@ import { shareService } from '@shumai/core/src/share/share'
import { assetService } from '@shumai/core/src/asset/asset'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { ShareLinkPasswordInvalidError, ShareLinkExpiredError } from '@shumai/core/src/share/errors'
import { createGuestToken } from '@shumai/core/src/auth/guest-token'
import { userService } from '@shumai/core/src/user/user'
import { notificationService } from '@shumai/core/src/notification/notification'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
@@ -121,7 +124,7 @@ describe('Share API', () => {
expect(body.name).toBe('Public Share')
expect(body.hasPassword).toBe(true)
expect(body.allowDownload).toBe(false)
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass')
})
test('Unauthorized', async () => {
@@ -206,7 +209,7 @@ describe('Share API', () => {
})
expect(res.status).toBe(200)
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('folder1', 'pass')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'folder1', 'pass')
expect(assetService.listChildren).toHaveBeenCalledWith(
expect.objectContaining({
assetId: 'folder1',
@@ -989,7 +992,7 @@ describe('Share API', () => {
expect(res.status).toBe(200)
const body = await res.json()
expect(body.url).toBe('https://s3.example.com/download')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('symlink1', undefined)
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'symlink1', undefined)
expect(assetService.getDownloadUrl).toHaveBeenCalledWith('symlink1', 'files/target1/fly.png')
})
@@ -1033,7 +1036,7 @@ describe('Share API', () => {
expect(res.headers.get('content-type')).toContain('application/vnd.apple.mpegurl')
const text = await res.text()
expect(text).toContain('1080p/index.m3u8?p=secret123')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('file1', 'secret123')
expect(shareService.verifyPublicAccess).toHaveBeenCalledWith('share1', 'file1', 'secret123')
expect(assetService.getHlsMasterPlaylist).toHaveBeenCalledWith({
assetId: 'file1',
watermarkConfigId: null,
@@ -1093,4 +1096,106 @@ describe('Share API', () => {
})
})
})
describe('POST /shares/:shareId/files/:fileId/comments', () => {
test('rejects comments with attachmentIds on public shares', async () => {
const res = await app.request('/shares/share1/files/file1/comments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: 'hi',
attachmentIds: ['att1'],
}),
})
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error).toContain('Attachments are not allowed')
})
test('rejects spoofed x-guest-user-id header without cookie', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
projectId: 'p1',
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share1',
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1')
const res = await app.request('/shares/share1/files/file1/comments', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-guest-user-id': 'victim_user',
},
body: JSON.stringify({ message: 'spoofed comment', attachmentIds: [] }),
})
expect(res.status).toBe(401)
})
test('allows valid guest cookie bound to shareId and creates comment', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
projectId: 'p1',
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share1',
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
vi.spyOn(assetService, 'resolveTargetAssetId').mockResolvedValue('file1')
vi.spyOn(userService, 'getUserById').mockResolvedValue({
id: 'guest1',
name: 'Guest Alice',
guestEmail: 'alice@guest.com',
} as unknown as Awaited<ReturnType<typeof userService.getUserById>>)
vi.spyOn(assetService, 'createComment').mockResolvedValue({
id: 'comm1',
message: 'hello from alice',
} as unknown as Awaited<ReturnType<typeof assetService.createComment>>)
vi.spyOn(notificationService, 'create').mockResolvedValue(
undefined as unknown as Awaited<ReturnType<typeof notificationService.create>>,
)
const token = createGuestToken({ userId: 'guest1', shareId: 'share1' })
const res = await app.request('/shares/share1/files/file1/comments', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: `shumai_guest_share1=${token}`,
},
body: JSON.stringify({ message: 'hello from alice', attachmentIds: [] }),
})
expect(res.status).toBe(201)
expect(assetService.createComment).toHaveBeenCalledWith(
expect.objectContaining({
userId: 'guest1',
message: 'hello from alice',
}),
)
})
test('rejects guest cookie bound to a different shareId', async () => {
vi.spyOn(shareService, 'getShareLink').mockResolvedValue({
id: 'share1',
projectId: 'p1',
} as unknown as Awaited<ReturnType<typeof shareService.getShareLink>>)
vi.spyOn(shareService, 'verifyPublicAccess').mockResolvedValue({
id: 'share1',
} as unknown as Awaited<ReturnType<typeof shareService.verifyPublicAccess>>)
const wrongToken = createGuestToken({ userId: 'guest1', shareId: 'other-share' })
const res = await app.request('/shares/share1/files/file1/comments', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Cookie: `shumai_guest_share1=${wrongToken}`,
},
body: JSON.stringify({ message: 'should fail', attachmentIds: [] }),
})
expect(res.status).toBe(401)
})
})
})
+2 -18
View File
@@ -5,7 +5,6 @@ import teamRoute from './team'
import { authMiddleware } from './middleware/auth'
import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
vi.mock('@shumai/core/src/authz/authz', () => ({
@@ -80,14 +79,12 @@ describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockJoinTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetTeamMembers: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -95,14 +92,12 @@ describe('team api', () => {
beforeEach(() => {
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
mockGetUserTeams = vi.spyOn(teamService, 'getUserTeams')
mockJoinTeam = vi.spyOn(teamService, 'joinTeam')
mockGetMe = vi.spyOn(teamService, 'getMe')
mockGetTeamMembers = vi.spyOn(teamService, 'getTeamMembers')
mockGetSettings = vi.spyOn(teamService, 'getSettings')
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
mockUpdateMe = vi.spyOn(teamService, 'updateMe')
@@ -148,20 +143,9 @@ describe('team api', () => {
expect(mockGetUserTeams).toHaveBeenCalledWith(expect.objectContaining({ userId: 'user1' }))
})
it('POST /teams/:teamId/members joins team and sends notification', async () => {
mockJoinTeam.mockResolvedValue(undefined)
it('POST /teams/:teamId/members returns 404', async () => {
const res = await app.request('/teams/t1/members', { method: 'POST' })
expect(res.status).toBe(204)
expect(mockJoinTeam).toHaveBeenCalledWith({ teamId: 't1', userId: 'user1' })
expect(mockCreateNotification).toHaveBeenCalledWith(
expect.objectContaining({
type: 'new_user_join_team',
teamId: 't1',
userId: 'user1',
}),
)
expect(res.status).toBe(404)
})
it('GET /teams/:teamId/me returns user role in team', async () => {
-26
View File
@@ -3,7 +3,6 @@ import { zValidator } from '@hono/zod-validator'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { teamService } from '@shumai/core/src/team/team'
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import {
createTeamRequestSchema,
getUserTeamsRequestSchema,
@@ -31,7 +30,6 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import { NotificationType } from '@shumai/db'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -67,30 +65,6 @@ const route = new Hono<{ Variables: { user: User } }>()
},
})
})
.post('/teams/:teamId/members', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
await teamService.joinTeam({
teamId,
userId: user.id,
})
await notificationService.create({
type: NotificationType.new_user_join_team,
teamId,
userId: user.id,
})
await auditLogService.logAction({
action: AuditAction.team_member_add,
teamId,
userId: user.id,
itemId: user.id,
})
return new Response(null, { status: 204 })
})
.get('/teams/:teamId/me', async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
+13 -1
View File
@@ -1,8 +1,9 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import uploadRoute from './upload'
import uploadRoute, { localUploadRoute } from './upload'
import { authMiddleware } from './middleware/auth'
import { uploadService } from '@shumai/core/src/upload/upload'
import * as s3Module from '@shumai/core/src/s3/s3'
import type { CreateUploadTaskResponse, TaskInfo } from '@shumai/dtos'
import type { PaginatedData } from '@shumai/core/src/pagination'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
@@ -243,4 +244,15 @@ describe('Upload API', () => {
)
expect(uploadService.cancelUploadTask).toHaveBeenCalledWith('team1', 'user1', 'task1')
})
describe('PUT /upload/local', () => {
it('returns 404 when STORAGE_BACKEND is s3', async () => {
vi.spyOn(s3Module, 'getStorageBackend').mockReturnValue('s3')
const localApp = new Hono().route('/', localUploadRoute)
const res = await localApp.request('/upload/local?bucket=b&key=k&Signature=sig', {
method: 'PUT',
})
expect(res.status).toBe(404)
})
})
})
+5 -1
View File
@@ -14,7 +14,7 @@ import { notificationService } from '@shumai/core/src/notification/notification'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { assetService } from '@shumai/core/src/asset/asset'
import { NotificationType } from '@shumai/db'
import { s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
import { getStorageBackend, s3Service, verifyLocalUrlSignature } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -23,6 +23,10 @@ export const localUploadRoute = new Hono().put(
'/upload/local',
zValidator('query', localUploadQuerySchema),
async (c) => {
if (getStorageBackend() !== 'local') {
return c.text('Not found', 404)
}
const { bucket, key, Signature } = c.req.valid('query')
if (!verifyLocalUrlSignature(bucket, key, Signature)) {