feat(api): add missing audit log calls to API endpoints

This commit is contained in:
yiling
2026-08-01 11:03:50 +08:00
parent 7dfb2c7f2f
commit 0324b95c7e
18 changed files with 695 additions and 2 deletions
+36
View File
@@ -1,10 +1,27 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { agentService } from '@shumai/core/src/agent/agent'
import { authzService } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import app from './agent'
vi.mock('@shumai/core/src/agent/agent')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
agent: {
findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }),
},
},
}
})
describe('Agent API', () => {
beforeEach(() => {
@@ -90,6 +107,12 @@ describe('Agent API', () => {
expect(data.name).toBe('New Agent')
expect(data.soul).toBe('New Soul')
expect(data.deniedTools).toEqual(['bash'])
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'agent_create',
teamId: 'team1',
userId: undefined,
itemId: 'agent2',
})
})
it('validates request', async () => {
@@ -110,6 +133,7 @@ describe('Agent API', () => {
it('updates an agent', async () => {
const mockAgent = {
id: 'agent1',
teamId: 'team1',
user: { name: 'Updated Agent', image: 'avatar1' },
type: 'autofill',
providerId: 'prov1',
@@ -140,6 +164,12 @@ describe('Agent API', () => {
expect(data.name).toBe('Updated Agent')
expect(data.soul).toBe('Updated Soul')
expect(data.deniedTools).toEqual(['bash'])
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'agent_update',
teamId: 'team1',
userId: undefined,
itemId: 'agent1',
})
})
})
@@ -151,6 +181,12 @@ describe('Agent API', () => {
expect(res.status).toBe(204)
expect(agentService.deleteAgent).toHaveBeenCalledWith({ agentId: 'agent1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'agent_delete',
teamId: 'team1',
userId: undefined,
itemId: 'agent1',
})
})
})
+30
View File
@@ -12,6 +12,8 @@ import {
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { prisma, AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -94,6 +96,13 @@ const route = new Hono<{ Variables: { user: User } }>()
deniedTools: config.deniedTools || [],
}
await auditLogService.logAction({
action: AuditAction.agent_create,
teamId,
userId: userReq?.id,
itemId: agent.id,
})
return c.json(info, 200)
})
.put('/agents/:agentId', zValidator('json', updateAgentRequestSchema), async (c) => {
@@ -113,6 +122,13 @@ const route = new Hono<{ Variables: { user: User } }>()
...req,
})
await auditLogService.logAction({
action: AuditAction.agent_update,
teamId: agent.teamId,
userId: userReq?.id,
itemId: agent.id,
})
const config = agent.config as unknown as PrismaJson.AgentConfig
const info: AgentInfo = {
id: agent.id,
@@ -146,10 +162,24 @@ const route = new Hono<{ Variables: { user: User } }>()
id: agentId,
})
const existingAgent = await prisma.agent.findUnique({
where: { id: agentId },
select: { teamId: true },
})
await agentService.deleteAgent({
agentId,
})
if (existingAgent) {
await auditLogService.logAction({
action: AuditAction.agent_delete,
teamId: existingAgent.teamId,
userId: userReq?.id,
itemId: agentId,
})
}
return new Response(null, { status: 204 })
})
.get('/agent-sessions/:sessionId/entries', async (c) => {
+30
View File
@@ -40,6 +40,14 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
},
}))
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('./middleware/auth', () => ({
authMiddleware: async (c: Context, next: Next) => {
c.set('user', { id: 'user1', name: 'Test User' })
@@ -129,6 +137,13 @@ describe('file api', () => {
type: ResourceType.Asset,
id: 'test-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_update',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
})
it('DELETE /files', async () => {
@@ -150,6 +165,13 @@ describe('file api', () => {
id: 'test-id',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_delete',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
})
it('POST /files/restore', async () => {
@@ -208,6 +230,14 @@ describe('file api', () => {
const json = await res.json()
expect(json.message).toBe('hello')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'comment_create',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'comment-id',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user1', name: 'Test User' },
permission: Permission.Read,
+75 -1
View File
@@ -5,7 +5,8 @@ import { metadataService } from '@shumai/core/src/metadata/metadata'
import { notificationService } from '@shumai/core/src/notification/notification'
import { s3Service } from '@shumai/core/src/s3/s3'
import type { Prisma } from '@shumai/db'
import { prisma } from '@shumai/db'
import { prisma, AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import {
createCommentRequestSchema,
deleteFilesRequestSchema,
@@ -75,6 +76,17 @@ const route = new Hono<{ Variables: { user: User } }>()
name: req.name,
})
const context = await assetService.getAssetContext(fileId)
if (context?.teamId) {
await auditLogService.logAction({
action: AuditAction.asset_update,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: fileId,
})
}
return c.json(updatedAsset)
})
.delete('/files', zValidator('json', deleteFilesRequestSchema), async (c) => {
@@ -90,7 +102,23 @@ const route = new Hono<{ Variables: { user: User } }>()
})
}
const contexts = await Promise.all(req.ids.map((id) => assetService.getAssetContext(id)))
await assetService.deleteAssets(req.ids)
for (let i = 0; i < req.ids.length; i++) {
const ctx = contexts[i]
if (ctx?.teamId) {
await auditLogService.logAction({
action: AuditAction.asset_delete,
teamId: ctx.teamId,
userId: user.id,
projectId: ctx.projectId,
itemId: req.ids[i],
})
}
}
return c.body(null, 204)
})
.patch(
@@ -181,6 +209,14 @@ const route = new Hono<{ Variables: { user: User } }>()
userId: targetUserId,
commentMessage: req.message,
})
await auditLogService.logAction({
action: AuditAction.comment_create,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: comment.id,
})
}
return c.json(comment, 201)
@@ -216,7 +252,26 @@ const route = new Hono<{ Variables: { user: User } }>()
id: commentId,
})
const commentData = await prisma.assetComment.findUnique({
where: { id: commentId },
select: { assetId: true },
})
const updated = await assetService.completeComment(commentId, req.isCompleted, user.id)
if (commentData?.assetId) {
const context = await assetService.getAssetContext(commentData.assetId)
if (context?.teamId) {
await auditLogService.logAction({
action: AuditAction.comment_complete,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: commentId,
})
}
}
return c.json(updated)
},
)
@@ -231,7 +286,26 @@ const route = new Hono<{ Variables: { user: User } }>()
id: commentId,
})
const commentData = await prisma.assetComment.findUnique({
where: { id: commentId },
select: { assetId: true },
})
await assetService.deleteComment({ commentId, userId: user.id })
if (commentData?.assetId) {
const context = await assetService.getAssetContext(commentData.assetId)
if (context?.teamId) {
await auditLogService.logAction({
action: AuditAction.comment_delete,
teamId: context.teamId,
userId: user.id,
projectId: context.projectId,
itemId: commentId,
})
}
}
return c.json({ success: true })
})
.post('/files/restore', zValidator('json', restoreFilesRequestSchema), async (c) => {
+30
View File
@@ -6,6 +6,14 @@ import { searchService } from '@shumai/core/src/search/search'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { authMiddleware } from './middleware/auth'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('@shumai/core/src/authz/authz', () => ({
authzService: {
hasPermission: vi.fn().mockResolvedValue(undefined),
@@ -33,6 +41,7 @@ describe('folder api', () => {
vi.mocked(authzService.hasPermission).mockClear()
vi.spyOn(assetService, 'getAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'getAssetContext').mockResolvedValue({ teamId: 'test-team' })
vi.spyOn(assetService, 'createAsset').mockImplementation(vi.fn())
vi.spyOn(assetService, 'updateAssetName').mockImplementation(vi.fn())
vi.spyOn(assetService, 'deleteAssets').mockImplementation(vi.fn())
@@ -101,6 +110,13 @@ describe('folder api', () => {
type: ResourceType.Asset,
id: 'test-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_update',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
})
it('POST /folders', async () => {
@@ -132,6 +148,13 @@ describe('folder api', () => {
type: ResourceType.Asset,
id: 'parent-id',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_create',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'new-id',
})
})
it('GET /folders/:folderId/children', async () => {
@@ -186,6 +209,13 @@ describe('folder api', () => {
id: 'test-id',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['test-id'])
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_delete',
teamId: 'test-team',
userId: 'user1',
projectId: undefined,
itemId: 'test-id',
})
})
it('POST /folders/restore', async () => {
+40
View File
@@ -12,6 +12,8 @@ import {
import { listChildrenRequestSchema, updateAssetOrderRequestSchema } from '@shumai/dtos'
import { searchRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -33,6 +35,17 @@ const route = new Hono<{ Variables: { user: User } }>()
type: 'folder',
})
const parentCtx = await assetService.getAssetContext(req.parentId)
if (parentCtx?.teamId) {
await auditLogService.logAction({
action: AuditAction.asset_create,
teamId: parentCtx.teamId,
userId: user.id,
projectId: parentCtx.projectId,
itemId: newAsset.id,
})
}
return c.json(newAsset)
})
.patch(
@@ -71,6 +84,17 @@ const route = new Hono<{ Variables: { user: User } }>()
name: req.name,
})
const ctx = await assetService.getAssetContext(folderId)
if (ctx?.teamId) {
await auditLogService.logAction({
action: AuditAction.asset_update,
teamId: ctx.teamId,
userId: user.id,
projectId: ctx.projectId,
itemId: folderId,
})
}
return c.json(updatedAsset)
})
.get('/folders/:folderId', async (c) => {
@@ -122,7 +146,23 @@ const route = new Hono<{ Variables: { user: User } }>()
})
}
const contexts = await Promise.all(req.ids.map((id) => assetService.getAssetContext(id)))
await assetService.deleteAssets(req.ids)
for (let i = 0; i < req.ids.length; i++) {
const ctx = contexts[i]
if (ctx?.teamId) {
await auditLogService.logAction({
action: AuditAction.asset_delete,
teamId: ctx.teamId,
userId: user.id,
projectId: ctx.projectId,
itemId: req.ids[i],
})
}
}
return c.body(null, 204)
})
.post('/folders/restore', zValidator('json', restoreFoldersRequestSchema), async (c) => {
+22
View File
@@ -6,9 +6,16 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
import { inviteService } from '@shumai/core/src/invite/invite'
import { notificationService } from '@shumai/core/src/notification/notification'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('@shumai/core/src/invite/invite')
vi.mock('@shumai/core/src/notification/notification')
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
@@ -67,6 +74,7 @@ describe('Invite API', () => {
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(inviteService.createTeamInvite).mockResolvedValue({
id: 'inv1',
code: 'test-code',
role: 'editor',
teamId: 't1',
@@ -104,6 +112,12 @@ describe('Invite API', () => {
role: 'editor',
inviterId: 'u1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'invite_create',
teamId: 't1',
userId: 'u1',
itemId: 'inv1',
})
})
it('POST /projects/:projectId/invite', async () => {
@@ -111,6 +125,7 @@ describe('Invite API', () => {
// Using any here because mocking complex service return types or Hono context is overly verbose for this test.
vi.mocked(inviteService.createProjectInvite).mockResolvedValue({
id: 'inv2',
code: 'proj-code',
role: 'reviewer',
teamId: 't1',
@@ -151,6 +166,13 @@ describe('Invite API', () => {
role: 'reviewer',
inviterId: 'u1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'invite_create',
teamId: 't1',
userId: 'u1',
projectId: 'p1',
itemId: 'inv2',
})
})
it('POST /join (Team)', async () => {
+17 -1
View File
@@ -9,8 +9,9 @@ import {
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { inviteService } from '@shumai/core/src/invite/invite'
import { notificationService } from '@shumai/core/src/notification/notification'
import { NotificationType } from '@shumai/db'
import { NotificationType, AuditAction } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -53,6 +54,13 @@ const route = new Hono<{ Variables: { user: User } }>()
inviterId: user.id,
})
await auditLogService.logAction({
action: AuditAction.invite_create,
teamId,
userId: user.id,
itemId: inv.id,
})
return c.json(mapToInviteInfo(inv))
})
.post(
@@ -77,6 +85,14 @@ const route = new Hono<{ Variables: { user: User } }>()
inviterId: user.id,
})
await auditLogService.logAction({
action: AuditAction.invite_create,
teamId: inv.teamId,
userId: user.id,
projectId,
itemId: inv.id,
})
return c.json(mapToInviteInfo(inv))
},
)
+38
View File
@@ -4,6 +4,8 @@ import metadataRoute from './metadata'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
c: Context<{ Variables: { user: { id: string; name: string } } }>,
@@ -16,6 +18,22 @@ vi.mock('./middleware/auth', () => ({
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/metadata/metadata')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
project: {
findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }),
},
},
}
})
describe('metadata api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
@@ -91,6 +109,12 @@ describe('metadata api', () => {
type: ResourceType.Team,
id: 't1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'metadata_field_create',
teamId: 't1',
userId: 'user1',
itemId: 'newfield',
})
})
it('GET /projects/:projectId/fields', async () => {
@@ -167,6 +191,13 @@ describe('metadata api', () => {
type: ResourceType.MetadataField,
id: 'f1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'metadata_field_delete',
teamId: 't1',
userId: 'user1',
projectId: undefined,
itemId: 'f1',
})
})
it('PUT /fields/:fieldId', async () => {
@@ -204,5 +235,12 @@ describe('metadata api', () => {
type: ResourceType.MetadataField,
id: 'f1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'metadata_field_update',
teamId: 't1',
userId: 'user1',
projectId: undefined,
itemId: 'f1',
})
})
})
+64
View File
@@ -9,6 +9,8 @@ import {
FieldInfo,
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { prisma, AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -42,6 +44,14 @@ const route = new Hono<{ Variables: { user: User } }>()
})
const field = await metadataService.createTeamField(teamId, req)
await auditLogService.logAction({
action: AuditAction.metadata_field_create,
teamId,
userId: user.id,
itemId: field.key,
})
return c.json(toFieldInfo(field))
})
.get('/teams/:teamId/fields', async (c) => {
@@ -85,6 +95,25 @@ const route = new Hono<{ Variables: { user: User } }>()
throw new Error('Field has no context')
}
let teamId = field.teamId
if (field.projectId && !teamId) {
const proj = await prisma.project.findUnique({
where: { id: field.projectId },
select: { teamId: true },
})
teamId = proj?.teamId || null
}
if (teamId) {
await auditLogService.logAction({
action: AuditAction.metadata_field_update,
teamId,
userId: user.id,
projectId: field.projectId || undefined,
itemId: fieldId,
})
}
return c.json(toFieldInfo(updated))
})
.delete('/fields/:fieldId', async (c) => {
@@ -109,6 +138,25 @@ const route = new Hono<{ Variables: { user: User } }>()
throw new Error('Field has no context')
}
let teamId = field.teamId
if (field.projectId && !teamId) {
const proj = await prisma.project.findUnique({
where: { id: field.projectId },
select: { teamId: true },
})
teamId = proj?.teamId || null
}
if (teamId) {
await auditLogService.logAction({
action: AuditAction.metadata_field_delete,
teamId,
userId: user.id,
projectId: field.projectId || undefined,
itemId: fieldId,
})
}
return new Response(null, { status: 204 })
})
.post('/projects/:projectId/fields', zValidator('json', createFieldRequestSchema), async (c) => {
@@ -124,6 +172,22 @@ const route = new Hono<{ Variables: { user: User } }>()
})
const field = await metadataService.createProjectField(projectId, req)
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.metadata_field_create,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: field.key,
})
}
return c.json(toFieldInfo(field))
})
.get('/projects/:projectId/fields', async (c) => {
+51
View File
@@ -4,6 +4,7 @@ import projectRoute from './project'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
@@ -162,6 +163,10 @@ describe('project api', () => {
})
it('POST /projects/:projectId/reparent', async () => {
const { prisma } = await import('@shumai/db')
// Mocking partial Prisma project model in test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any)
vi.mocked(assetService.reparentAssets).mockResolvedValue(undefined)
const res = await app.request('/projects/p/reparent', {
@@ -197,6 +202,52 @@ describe('project api', () => {
assetIds: ['asset_1', 'asset_2'],
creatorId: 'user1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_reparent',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_reparent',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_2',
})
})
it('POST /projects/:projectId/copy', async () => {
const { prisma } = await import('@shumai/db')
// Mocking partial Prisma project model in test
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vi.mocked(prisma.project.findUnique).mockResolvedValue({ id: 'p', teamId: 't1' } as any)
vi.mocked(assetService.copyAssets).mockResolvedValue(undefined)
const res = await app.request('/projects/p/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newParentId: 'new_parent_id',
assetIds: ['asset_1'],
}),
})
expect(res.status).toBe(204)
expect(assetService.copyAssets).toHaveBeenCalledWith({
newParentId: 'new_parent_id',
assetIds: ['asset_1'],
withComments: false,
creatorId: 'user1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'asset_copy',
teamId: 't1',
userId: 'user1',
projectId: 'p',
itemId: 'asset_1',
})
})
it('POST /projects/:projectId/empty-trash', async () => {
+34
View File
@@ -299,6 +299,7 @@ const route = new Hono<{ Variables: { user: User } }>()
'/projects/:projectId/reparent',
zValidator('json', reparentAssetsRequestSchema),
async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
@@ -325,10 +326,27 @@ const route = new Hono<{ Variables: { user: User } }>()
creatorId: user.id,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
for (const assetId of req.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_reparent,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: assetId,
})
}
}
return c.body(null, 204)
},
)
.post('/projects/:projectId/copy', zValidator('json', copyAssetsRequestSchema), async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
const req = c.req.valid('json')
@@ -355,6 +373,22 @@ const route = new Hono<{ Variables: { user: User } }>()
creatorId: user.id,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
for (const assetId of req.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_copy,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: assetId,
})
}
}
return c.body(null, 204)
})
.patch(
+25
View File
@@ -4,6 +4,8 @@ import providerRoute from './provider'
import { providerService } from '@shumai/core/src/provider/provider'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
c: Context<{ Variables: { user: { id: string; name: string } } }>,
@@ -16,6 +18,11 @@ vi.mock('./middleware/auth', () => ({
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/provider/provider')
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
describe('provider api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
@@ -115,6 +122,12 @@ describe('provider api', () => {
type: ResourceType.Team,
id: 't1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'provider_create',
teamId: 't1',
userId: 'user1',
itemId: 'p1',
})
})
it('PUT /providers/:id updates provider', async () => {
@@ -163,6 +176,12 @@ describe('provider api', () => {
type: ResourceType.Provider,
id: 'p1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'provider_update',
teamId: 't1',
userId: 'user1',
itemId: 'p1',
})
})
it('DELETE /providers/:id deletes provider', async () => {
@@ -188,5 +207,11 @@ describe('provider api', () => {
type: ResourceType.Provider,
id: 'p1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'provider_delete',
teamId: 't1',
userId: 'user1',
itemId: 'p1',
})
})
})
+20
View File
@@ -3,7 +3,9 @@ import { Hono } from 'hono'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { providerService } from '@shumai/core/src/provider/provider'
import { createProviderRequestSchema, updateProviderRequestSchema } from '@shumai/dtos'
import { AuditAction } from '@shumai/db'
import type { Prisma } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -54,6 +56,12 @@ const route = new Hono<{ Variables: { user: User } }>()
})
const provider = await providerService.create(teamId, name, config, models)
await auditLogService.logAction({
action: AuditAction.provider_create,
teamId,
userId: user?.id,
itemId: provider.id,
})
return c.json(provider)
})
@@ -73,6 +81,12 @@ const route = new Hono<{ Variables: { user: User } }>()
if (!providerBefore) throw new Error('Provider not found')
const provider = await providerService.update(providerBefore.teamId, id, config, models)
await auditLogService.logAction({
action: AuditAction.provider_update,
teamId: providerBefore.teamId,
userId: user?.id,
itemId: id,
})
return c.json(provider)
})
@@ -91,6 +105,12 @@ const route = new Hono<{ Variables: { user: User } }>()
if (!providerBefore) throw new Error('Provider not found')
await providerService.delete(providerBefore.teamId, id)
await auditLogService.logAction({
action: AuditAction.provider_delete,
teamId: providerBefore.teamId,
userId: user?.id,
itemId: id,
})
return c.json({ success: true })
})
+27
View File
@@ -8,6 +8,8 @@ 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 { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('./middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
@@ -33,6 +35,24 @@ vi.mock('@shumai/core/src/authz/authz', () => ({
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
project: {
findUnique: vi.fn().mockResolvedValue({ teamId: 't1' }),
},
},
}
})
describe('Share API', () => {
const app = new Hono()
.route('/', publicShareRoute)
@@ -204,6 +224,13 @@ describe('Share API', () => {
{ name: 'My Share' },
'user1',
)
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'share_create',
teamId: 't1',
userId: 'user1',
projectId: 'project1',
itemId: 'share1',
})
})
})
+53
View File
@@ -9,6 +9,8 @@ import {
addAssetToShareRequestSchema,
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { prisma, AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -29,6 +31,21 @@ const route = new Hono<{ Variables: { user: User } }>()
})
const shareLink = await shareService.createShareLink(projectId, req, user.id)
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.share_create,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: shareLink.id,
})
}
return c.json(shareLink)
},
)
@@ -81,7 +98,25 @@ const route = new Hono<{ Variables: { user: User } }>()
id: shareId,
})
const existingShare = await shareService.getShareLink(shareId)
const updated = await shareService.updateShareLink(shareId, req)
if (existingShare) {
const proj = await prisma.project.findUnique({
where: { id: existingShare.projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.share_update,
teamId: proj.teamId,
userId: user.id,
projectId: existingShare.projectId,
itemId: shareId,
})
}
}
return c.json(updated)
})
.delete('/shares/:shareId', async (c) => {
@@ -95,7 +130,25 @@ const route = new Hono<{ Variables: { user: User } }>()
id: shareId,
})
const existingShare = await shareService.getShareLink(shareId)
await shareService.deleteShareLink(shareId)
if (existingShare) {
const proj = await prisma.project.findUnique({
where: { id: existingShare.projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.share_delete,
teamId: proj.teamId,
userId: user.id,
projectId: existingShare.projectId,
itemId: shareId,
})
}
}
return c.body(null, 204)
})
.post('/shares/:shareId/assets', zValidator('json', addAssetToShareRequestSchema), async (c) => {
+50
View File
@@ -5,6 +5,26 @@ import { skillService } from '@shumai/core/src/skill/skill'
import { authMiddleware } from './middleware/auth'
import { authzService, ResourceType, Permission } from '@shumai/core/src/authz/authz'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
},
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
skill: {
findUnique: vi.fn().mockResolvedValue({ teamId: 'team1' }),
},
},
}
})
vi.mock('./middleware/auth', () => ({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
authMiddleware: async (c: any, next: any) => {
@@ -102,6 +122,12 @@ describe('Skill API', () => {
}),
)
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', { assetId: 'asset1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'skill_create',
teamId: 'team1',
userId: 'user1',
itemId: 'skill1',
})
})
test('Success with githubUrl', async () => {
@@ -129,6 +155,12 @@ describe('Skill API', () => {
expect(skillService.upsertSkill).toHaveBeenCalledWith('team1', {
githubUrl: 'https://github.com/test/repo',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'skill_create',
teamId: 'team1',
userId: 'user1',
itemId: 'skill1',
})
})
test('Forbidden without Admin permission', async () => {
@@ -162,6 +194,12 @@ describe('Skill API', () => {
}),
)
expect(skillService.deleteSkill).toHaveBeenCalledWith('skill1')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'skill_delete',
teamId: 'team1',
userId: 'user1',
itemId: 'skill1',
})
})
})
@@ -199,6 +237,12 @@ describe('Skill API', () => {
}),
)
expect(skillService.updateSkillConfig).toHaveBeenCalledWith('skill1', mockConfig)
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'skill_update',
teamId: 'team1',
userId: 'user1',
itemId: 'skill1',
})
})
})
@@ -233,6 +277,12 @@ describe('Skill API', () => {
}),
)
expect(skillService.updateSkillPermission).toHaveBeenCalledWith('skill1', 'owner')
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: 'skill_update',
teamId: 'team1',
userId: 'user1',
itemId: 'skill1',
})
})
})
})
+53
View File
@@ -8,6 +8,8 @@ import {
updateSkillPermissionRequestSchema,
} from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
import { prisma, AuditAction } from '@shumai/db'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -40,6 +42,12 @@ const route = new Hono<{ Variables: { user: User } }>()
try {
const skill = await skillService.upsertSkill(teamId, req)
await auditLogService.logAction({
action: AuditAction.skill_create,
teamId,
userId: user?.id,
itemId: skill.id,
})
return c.json(skill)
} catch (err: unknown) {
if (err instanceof Error && err.name === 'ConflictError') {
@@ -59,7 +67,22 @@ const route = new Hono<{ Variables: { user: User } }>()
id,
})
const existingSkill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
await skillService.deleteSkill(id)
if (existingSkill) {
await auditLogService.logAction({
action: AuditAction.skill_delete,
teamId: existingSkill.teamId,
userId: user?.id,
itemId: id,
})
}
return new Response(null, { status: 204 })
})
.patch('/skills/:id/config', zValidator('json', updateSkillConfigRequestSchema), async (c) => {
@@ -74,7 +97,22 @@ const route = new Hono<{ Variables: { user: User } }>()
id,
})
const existingSkill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
const skill = await skillService.updateSkillConfig(id, req.config)
if (existingSkill) {
await auditLogService.logAction({
action: AuditAction.skill_update,
teamId: existingSkill.teamId,
userId: user?.id,
itemId: id,
})
}
return c.json(skill)
})
.patch(
@@ -92,7 +130,22 @@ const route = new Hono<{ Variables: { user: User } }>()
id,
})
const existingSkill = await prisma.skill.findUnique({
where: { id },
select: { teamId: true },
})
const skill = await skillService.updateSkillPermission(id, req.permission)
if (existingSkill) {
await auditLogService.logAction({
action: AuditAction.skill_update,
teamId: existingSkill.teamId,
userId: user?.id,
itemId: id,
})
}
return c.json(skill)
},
)