From 0324b95c7eaf49da84db4106e219d598997bd049 Mon Sep 17 00:00:00 2001 From: yiling Date: Sat, 1 Aug 2026 11:03:50 +0800 Subject: [PATCH] feat(api): add missing audit log calls to API endpoints --- packages/api/src/agent.test.ts | 36 +++++++++++++++ packages/api/src/agent.ts | 30 ++++++++++++ packages/api/src/file.test.ts | 30 ++++++++++++ packages/api/src/file.ts | 76 ++++++++++++++++++++++++++++++- packages/api/src/folder.test.ts | 30 ++++++++++++ packages/api/src/folder.ts | 40 ++++++++++++++++ packages/api/src/invite.test.ts | 22 +++++++++ packages/api/src/invite.ts | 18 +++++++- packages/api/src/metadata.test.ts | 38 ++++++++++++++++ packages/api/src/metadata.ts | 64 ++++++++++++++++++++++++++ packages/api/src/project.test.ts | 51 +++++++++++++++++++++ packages/api/src/project.ts | 34 ++++++++++++++ packages/api/src/provider.test.ts | 25 ++++++++++ packages/api/src/provider.ts | 20 ++++++++ packages/api/src/share.test.ts | 27 +++++++++++ packages/api/src/share.ts | 53 +++++++++++++++++++++ packages/api/src/skill.test.ts | 50 ++++++++++++++++++++ packages/api/src/skill.ts | 53 +++++++++++++++++++++ 18 files changed, 695 insertions(+), 2 deletions(-) diff --git a/packages/api/src/agent.test.ts b/packages/api/src/agent.test.ts index 95f0a344..8904b0ef 100644 --- a/packages/api/src/agent.test.ts +++ b/packages/api/src/agent.test.ts @@ -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() + 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', + }) }) }) diff --git a/packages/api/src/agent.ts b/packages/api/src/agent.ts index 40000ba6..ceef5d97 100644 --- a/packages/api/src/agent.ts +++ b/packages/api/src/agent.ts @@ -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> @@ -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) => { diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index ec728e05..050ec33c 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -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, diff --git a/packages/api/src/file.ts b/packages/api/src/file.ts index 1b8a2aee..3a50e67f 100644 --- a/packages/api/src/file.ts +++ b/packages/api/src/file.ts @@ -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) => { diff --git a/packages/api/src/folder.test.ts b/packages/api/src/folder.test.ts index b51d98d8..d2f5c43d 100644 --- a/packages/api/src/folder.test.ts +++ b/packages/api/src/folder.test.ts @@ -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 () => { diff --git a/packages/api/src/folder.ts b/packages/api/src/folder.ts index 625d555b..fbcd086a 100644 --- a/packages/api/src/folder.ts +++ b/packages/api/src/folder.ts @@ -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> @@ -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) => { diff --git a/packages/api/src/invite.test.ts b/packages/api/src/invite.test.ts index 9fa3bf9d..472d65d2 100644 --- a/packages/api/src/invite.test.ts +++ b/packages/api/src/invite.test.ts @@ -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 () => { diff --git a/packages/api/src/invite.ts b/packages/api/src/invite.ts index 07725511..b074654b 100644 --- a/packages/api/src/invite.ts +++ b/packages/api/src/invite.ts @@ -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> @@ -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)) }, ) diff --git a/packages/api/src/metadata.test.ts b/packages/api/src/metadata.test.ts index 18c0d733..4bfab793 100644 --- a/packages/api/src/metadata.test.ts +++ b/packages/api/src/metadata.test.ts @@ -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() + 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', + }) }) }) diff --git a/packages/api/src/metadata.ts b/packages/api/src/metadata.ts index 82b95eb8..adf29d14 100644 --- a/packages/api/src/metadata.ts +++ b/packages/api/src/metadata.ts @@ -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> @@ -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) => { diff --git a/packages/api/src/project.test.ts b/packages/api/src/project.test.ts index 0ad90532..dbe355c9 100644 --- a/packages/api/src/project.test.ts +++ b/packages/api/src/project.test.ts @@ -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 () => { diff --git a/packages/api/src/project.ts b/packages/api/src/project.ts index 14cb14d6..9f9d5f3a 100644 --- a/packages/api/src/project.ts +++ b/packages/api/src/project.ts @@ -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( diff --git a/packages/api/src/provider.test.ts b/packages/api/src/provider.test.ts index 97121c86..8e89b09a 100644 --- a/packages/api/src/provider.test.ts +++ b/packages/api/src/provider.test.ts @@ -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', + }) }) }) diff --git a/packages/api/src/provider.ts b/packages/api/src/provider.ts index c9911f7b..c7734797 100644 --- a/packages/api/src/provider.ts +++ b/packages/api/src/provider.ts @@ -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> @@ -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 }) }) diff --git a/packages/api/src/share.test.ts b/packages/api/src/share.test.ts index b29102a4..ee1a5ea1 100644 --- a/packages/api/src/share.test.ts +++ b/packages/api/src/share.test.ts @@ -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() + 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', + }) }) }) diff --git a/packages/api/src/share.ts b/packages/api/src/share.ts index 91abd3df..9961c03f 100644 --- a/packages/api/src/share.ts +++ b/packages/api/src/share.ts @@ -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> @@ -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) => { diff --git a/packages/api/src/skill.test.ts b/packages/api/src/skill.test.ts index 174c1399..f4e7983b 100644 --- a/packages/api/src/skill.test.ts +++ b/packages/api/src/skill.test.ts @@ -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() + 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', + }) }) }) }) diff --git a/packages/api/src/skill.ts b/packages/api/src/skill.ts index 18a1f354..359615e5 100644 --- a/packages/api/src/skill.ts +++ b/packages/api/src/skill.ts @@ -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> @@ -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) }, )