162 lines
7.9 KiB
TypeScript

/** @jest-environment node */
import { getServerSession } from 'next-auth'
import { isSuperAdmin } from '@/lib/department-permission'
import { AutoListingCallbackError } from '@/lib/external-auto-listing-callback'
import {
createExternalNotificationTarget,
listExternalNotificationDeliveries,
listExternalNotificationTargets,
setExternalNotificationTargetActive,
testExternalNotificationTarget,
updateExternalNotificationTarget,
XIAOYI_AUTO_LISTING_EVENT_TYPE,
} from '@/lib/external-auto-listing'
import { GET, PATCH, POST } from './route'
import { POST as TEST } from './test/route'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: {} }))
jest.mock('@/lib/department-permission', () => ({ isSuperAdmin: jest.fn() }))
jest.mock('@/lib/external-auto-listing', () => ({
...jest.requireActual('@/lib/external-auto-listing'),
createExternalNotificationTarget: jest.fn(),
listExternalNotificationDeliveries: jest.fn(),
listExternalNotificationTargets: jest.fn(),
setExternalNotificationTargetActive: jest.fn(),
testExternalNotificationTarget: jest.fn(),
updateExternalNotificationTarget: jest.fn(),
}))
const operator = { id: 'operator', name: '操作员', email: 'operator@example.com' }
const route = 'https://material.example.com/api/admin/auto-listing-targets'
const target = {
id: 'target-1',
name: '上架系统',
callbackUrl: 'https://listing.example.com/callback',
isActive: false,
authType: 'header',
authConfig: { headerName: 'X-Signature', headerValue: 'private-callback-secret' },
eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE],
createdAt: '2026-12-04T08:00:00.000Z',
updatedAt: '2026-12-04T08:00:00.000Z',
}
function request(method: string, body?: unknown, path = '') {
return new Request(route + path, { method, body: body === undefined ? undefined : JSON.stringify(body) })
}
beforeEach(() => {
jest.resetAllMocks()
jest.mocked(getServerSession).mockResolvedValue({ user: { ...operator, role: 'USER' }, expires: '2026-12-05' })
jest.mocked(isSuperAdmin).mockResolvedValue(true)
})
test.each(['USER', 'DEPT_ADMIN', 'SYSTEM_ADMIN'] as const)('拒绝没有超管权限的 %s', async (role) => {
jest.mocked(getServerSession).mockResolvedValue({ user: { ...operator, role, isSuperAdmin: true }, expires: '2026-12-05' })
jest.mocked(isSuperAdmin).mockResolvedValue(false)
const responses = await Promise.all([
GET(request('GET')),
POST(request('POST', {})),
PATCH(request('PATCH', {})),
TEST(request('POST', {}, '/test')),
])
expect(responses.map((response) => response.status)).toEqual([403, 403, 403, 403])
expect(isSuperAdmin).toHaveBeenCalledWith('operator')
for (const operation of [listExternalNotificationTargets, listExternalNotificationDeliveries,
createExternalNotificationTarget, updateExternalNotificationTarget, setExternalNotificationTargetActive,
testExternalNotificationTarget]) {
expect(operation).not.toHaveBeenCalled()
}
})
test('超管列表只返回鉴权状态和安全的投递摘要', async () => {
jest.mocked(listExternalNotificationTargets).mockResolvedValue([{
...target,
callbackUrl: 'https://user:private-url-secret@listing.example.com/callback?token=private-query-secret',
}])
jest.mocked(listExternalNotificationDeliveries).mockResolvedValue([{
id: 'delivery-1', targetId: target.id, targetName: target.name,
eventType: XIAOYI_AUTO_LISTING_EVENT_TYPE, materialId: 'material-1', materialType: '详情',
taskNo: null, status: 'retrying', attemptCount: 1, maxAttempts: 5, nextRetryAt: null,
lastStatusCode: 401, lastResponseBody: 'Authorization: private-response-secret',
lastError: 'Authorization: private-error-secret', payload: { token: 'private-payload-secret', projectId: 'project-1', eventId: 'event-1' },
createdAt: target.createdAt, updatedAt: target.updatedAt, completedAt: null,
}])
const response = await GET(request('GET', undefined, '?status=retrying&q=%20project-1%20'))
const data = (await response.json()).data
expect(response.status).toBe(200)
expect(response.headers.get('Cache-Control')).toBe('no-store')
expect(data.targets[0]).toMatchObject({
callbackUrl: target.callbackUrl, authConfigured: true,
authConfig: { headerName: 'X-Signature' },
})
expect(data.recentDeliveries[0]).toMatchObject({
lastError: '接收方返回 HTTP 401', projectId: 'project-1', eventId: 'event-1',
})
expect(data.recentDeliveries[0]).not.toHaveProperty('lastResponseBody')
expect(data.recentDeliveries[0]).not.toHaveProperty('payload')
expect(JSON.stringify(data)).not.toContain('private-')
expect(listExternalNotificationDeliveries).toHaveBeenCalledWith({
canAccessOperationsG: true, status: 'retrying', query: 'project-1', limit: 50,
})
})
test('超管可新增、编辑及启停目标,响应都不含明文凭据', async () => {
jest.mocked(createExternalNotificationTarget).mockResolvedValue(target)
jest.mocked(updateExternalNotificationTarget).mockResolvedValue(target)
jest.mocked(setExternalNotificationTargetActive)
.mockResolvedValueOnce({ ...target, isActive: true })
.mockResolvedValueOnce(target)
const { name, callbackUrl, authType, authConfig } = target
const input = { name, callbackUrl, authType, authConfig }
const responses = [
await POST(request('POST', input)),
await POST(request('POST', { id: target.id, name, callbackUrl, authType })),
await PATCH(request('PATCH', { id: target.id, isActive: true })),
await PATCH(request('PATCH', { id: target.id, isActive: false })),
]
expect(responses.map((response) => response.status)).toEqual([200, 200, 200, 200])
for (const response of responses) expect(await response.text()).not.toContain('private-callback-secret')
expect(createExternalNotificationTarget).toHaveBeenCalledWith({
...input, isActive: false, eventTypes: [XIAOYI_AUTO_LISTING_EVENT_TYPE],
})
expect(updateExternalNotificationTarget).toHaveBeenCalledWith(target.id, { name, callbackUrl, authType })
expect(setExternalNotificationTargetActive).toHaveBeenNthCalledWith(1, target.id, true)
expect(setExternalNotificationTargetActive).toHaveBeenNthCalledWith(2, target.id, false)
})
test('拒绝无效请求和回调地址,未知目标返回 404', async () => {
jest.mocked(createExternalNotificationTarget).mockRejectedValue(new AutoListingCallbackError('回调地址指向受保护的网络'))
jest.mocked(updateExternalNotificationTarget).mockResolvedValue(null)
jest.mocked(setExternalNotificationTargetActive).mockResolvedValue(null)
const { name, callbackUrl } = target
expect((await POST(request('POST', { name, callbackUrl, eventTypes: ['unknown'] }))).status).toBe(400)
expect((await POST(request('POST', { name, callbackUrl: 'https://127.0.0.1/callback' }))).status).toBe(400)
expect((await POST(request('POST', { id: target.id, name, callbackUrl }))).status).toBe(404)
expect((await PATCH(request('PATCH', { id: target.id, isActive: false }))).status).toBe(404)
})
test('测试接口只接收已保存目标的编号并报告接收方状态', async () => {
jest.mocked(testExternalNotificationTarget)
.mockResolvedValueOnce({ statusCode: 204, error: null })
.mockResolvedValueOnce({ statusCode: 401, error: '接收方返回 HTTP 401' })
.mockResolvedValueOnce(null)
expect((await TEST(request('POST', { id: target.id, callbackUrl: target.callbackUrl }, '/test'))).status).toBe(400)
expect(testExternalNotificationTarget).not.toHaveBeenCalled()
const send = () => TEST(request('POST', { id: target.id }, '/test'))
const success = await send()
expect(success.status).toBe(200)
expect(await success.json()).toEqual({ success: true, statusCode: 204 })
const failure = await send()
expect(failure.status).toBe(502)
expect(await failure.json()).toEqual({ success: false, statusCode: 401, error: '接收方返回 HTTP 401' })
expect((await send()).status).toBe(404)
expect(testExternalNotificationTarget).toHaveBeenCalledWith(target.id)
})