feat(audit): add audit log support for APIs and WebUI dashboard

This commit is contained in:
yiling
2026-08-01 10:39:31 +08:00
parent 7a83f7d406
commit 118107ebc9
58 changed files with 4298 additions and 23 deletions
+19 -8
View File
@@ -18,16 +18,27 @@ vi.mock('./middleware/auth', () => ({
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/project/project')
vi.mock('@shumai/core/src/asset/asset')
vi.mock('@shumai/db', () => ({
prisma: {
teamMember: {
findMany: vi.fn(),
},
project: {
findMany: vi.fn(),
},
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
listAuditLogs: vi.fn().mockResolvedValue({ nodes: [], pageInfo: {}, total: 0 }),
},
}))
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
teamMember: {
findMany: vi.fn(),
},
project: {
findMany: vi.fn(),
findUnique: vi.fn(),
},
},
}
})
describe('project api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
+95 -1
View File
@@ -14,7 +14,8 @@ import {
} from '@shumai/dtos'
import { listMembersQuerySchema, paginationParamsSchema } from '@shumai/dtos'
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'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -79,6 +80,14 @@ const route = new Hono<{ Variables: { user: User } }>()
...req,
})
await auditLogService.logAction({
action: AuditAction.project_create,
teamId,
userId: user.id,
projectId: newProject.id,
itemId: newProject.id,
})
return c.json(newProject)
})
.put('/projects/:projectId', zValidator('json', updateProjectRequestSchema), async (c) => {
@@ -98,6 +107,20 @@ const route = new Hono<{ Variables: { user: User } }>()
...req,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_update,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: projectId,
})
}
return c.json(updatedProject)
})
.get(
@@ -138,6 +161,20 @@ const route = new Hono<{ Variables: { user: User } }>()
await assetService.emptyTrash(projectId)
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_empty_trash,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: projectId,
})
}
return c.json({ success: true })
})
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
@@ -193,7 +230,22 @@ const route = new Hono<{ Variables: { user: User } }>()
id: projectId,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
await projectService.deleteProject(projectId)
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_delete,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: projectId,
})
}
return c.json({ success: true })
})
.get('/projects/:projectId/team', async (c) => {
@@ -327,6 +379,20 @@ const route = new Hono<{ Variables: { user: User } }>()
role: req.role,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_member_update,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: userId,
})
}
return c.json({ success: true })
},
)
@@ -342,8 +408,22 @@ const route = new Hono<{ Variables: { user: User } }>()
id: projectId,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
await projectService.removeMember(projectId, userId)
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_member_remove,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: userId,
})
}
return c.json({ success: true })
})
.post(
@@ -367,6 +447,20 @@ const route = new Hono<{ Variables: { user: User } }>()
role: req.role,
})
const proj = await prisma.project.findUnique({
where: { id: projectId },
select: { teamId: true },
})
if (proj) {
await auditLogService.logAction({
action: AuditAction.project_member_add,
teamId: proj.teamId,
userId: user.id,
projectId,
itemId: req.userId,
})
}
return c.json({ success: true })
},
)
+44
View File
@@ -1,5 +1,6 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import { AuditAction } from '@shumai/db'
import teamRoute from './team'
import { authMiddleware } from './middleware/auth'
import { teamService } from '@shumai/core/src/team/team'
@@ -44,6 +45,13 @@ vi.mock('@shumai/core/src/ai-usage/ai-usage', () => ({
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn(),
listAuditLogs: vi.fn(),
},
}))
describe('team api', () => {
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
@@ -471,5 +479,41 @@ describe('team api', () => {
userId: 'user1',
})
})
it('GET /teams/:teamId/audit-logs returns list of audit logs for team owner', async () => {
const { auditLogService } = await import('@shumai/core/src/auditLog/auditLog')
vi.mocked(auditLogService.listAuditLogs).mockResolvedValue({
nodes: [
{
id: 'log1',
action: AuditAction.project_create,
teamId: 't1',
userId: 'user1',
projectId: 'p1',
itemId: 'p1',
createdAt: new Date().toISOString(),
},
],
pageInfo: {
hasNextPage: false,
endCursor: null,
},
total: 1,
})
const res = await app.request('/teams/t1/audit-logs')
expect(res.status).toBe(200)
const data = await res.json()
expect(data.nodes).toHaveLength(1)
expect(data.nodes[0].id).toBe('log1')
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
permission: Permission.Admin,
type: ResourceType.Team,
id: 't1',
}),
)
})
})
})
+61 -1
View File
@@ -4,7 +4,6 @@ import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/a
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 { NotificationType } from '@shumai/db'
import {
createTeamRequestSchema,
getUserTeamsRequestSchema,
@@ -14,10 +13,13 @@ import {
updateMeRequestSchema,
updateTeamMemberRoleRequestSchema,
createApiTokenRequestSchema,
listAuditLogsQuerySchema,
} from '@shumai/dtos'
import { updateUserMetadataRequestSchema, getTeamAiUsageQuerySchema } from '@shumai/dtos'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { NotificationType, AuditAction } from '@shumai/db'
import type { Prisma } from '@shumai/db'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -28,6 +30,12 @@ const route = new Hono<{ Variables: { user: User } }>()
const req = c.req.valid('json')
const newTeam = await teamService.createTeam(user, req)
await auditLogService.logAction({
action: AuditAction.team_create,
teamId: newTeam.id,
userId: user.id,
itemId: newTeam.id,
})
return c.json(newTeam)
})
.get('/teams', zValidator('query', getUserTeamsRequestSchema), async (c) => {
@@ -62,6 +70,13 @@ const route = new Hono<{ Variables: { user: User } }>()
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) => {
@@ -139,6 +154,13 @@ const route = new Hono<{ Variables: { user: User } }>()
role: req.role,
})
await auditLogService.logAction({
action: AuditAction.team_member_update,
teamId,
userId: user.id,
itemId: userId,
})
return c.json({ success: true })
},
)
@@ -156,6 +178,13 @@ const route = new Hono<{ Variables: { user: User } }>()
await teamService.removeMember(teamId, userId)
await auditLogService.logAction({
action: AuditAction.team_member_remove,
teamId,
userId: user.id,
itemId: userId,
})
return c.json({ success: true })
})
.get('/teams/:teamId/settings', async (c) => {
@@ -188,6 +217,14 @@ const route = new Hono<{ Variables: { user: User } }>()
})
const settings = await teamService.updateSettings(teamId, req.key, req.value)
await auditLogService.logAction({
action: AuditAction.team_update,
teamId,
userId: user.id,
itemId: teamId,
})
return c.json(settings)
},
)
@@ -334,5 +371,28 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(stats)
})
.get('/teams/:teamId/audit-logs', zValidator('query', listAuditLogsQuerySchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const query = c.req.valid('query')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Team,
id: teamId,
})
const logs = await auditLogService.listAuditLogs({
teamId,
actions: query.actions,
userIds: query.userIds,
itemId: query.itemId,
first: query.first,
after: query.after,
})
return c.json(logs)
})
export default route