gongxiangp2/lib/__tests__/personnel-salary-http.test.ts

70 lines
4.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { salaryIdentity } from '@/lib/personnel-salary-http'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() } } }))
const session = getServerSession as jest.Mock
const user = prisma.user.findUnique as jest.Mock
const originKeys = ['NEXT_PUBLIC_APP_PUBLIC_URL', 'APP_PUBLIC_URL', 'NEXTAUTH_URL', 'CORS_ALLOWED_ORIGINS'] as const
const originalOrigins = Object.fromEntries(originKeys.map(key => [key, process.env[key]]))
const internalUrl = 'https://0.0.0.0:3000/api/organization/personnel-salary'
const request = (origin?: string, headers: Record<string, string> = {}, url = internalUrl) => new NextRequest(url, {
method: 'POST', headers: { host: 'sc.jiansun.vip', 'x-forwarded-proto': 'https', ...(origin === undefined ? {} : { origin }), ...headers }, body: '{}',
})
beforeEach(() => {
jest.resetAllMocks()
process.env.NEXT_PUBLIC_APP_PUBLIC_URL = 'https://sc.jiansun.vip'
process.env.APP_PUBLIC_URL = 'https://sc.jiansun.vip'
process.env.NEXTAUTH_URL = 'https://sc.jiansun.vip'
process.env.CORS_ALLOWED_ORIGINS = 'https://sc.jiansun.vip,http://192.168.58.20:4320'
session.mockResolvedValue({ user: { id: 'admin' } })
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
})
afterAll(() => {
for (const key of originKeys) {
if (originalOrigins[key] === undefined) delete process.env[key]
else process.env[key] = originalOrigins[key]
}
})
test.each([
['公网代理', 'https://sc.jiansun.vip', {}, internalUrl],
['显式默认端口', 'https://sc.jiansun.vip:443', {}, internalUrl],
['已配置内网入口', 'http://192.168.58.20:4320', { host: '192.168.58.20:4320', 'x-forwarded-proto': 'http' }, internalUrl],
['本地开发入口', 'http://localhost:4322', { host: 'localhost:4322', 'x-forwarded-proto': 'http' }, 'http://localhost:4322/api/organization/personnel-salary'],
] as [string, string, Record<string, string>, string][])('%s允许合法写入来源,不使用内部监听地址判断', async (_name, origin, headers, url) => {
await expect(salaryIdentity(true, request(origin, { 'sec-fetch-site': 'same-origin', ...headers }, url))).resolves.toBe('admin')
expect(user).toHaveBeenCalledWith(expect.objectContaining({ where: { id: 'admin' } }))
})
test.each(['https://foreign.example', 'https://sc.jiansun.vip.foreign.example', 'null', 'not-a-url', 'https://sc.jiansun.vip/path', 'https://user:password@sc.jiansun.vip'])('拒绝陌生或非法来源%s', async origin => {
await expect(salaryIdentity(true, request(origin))).rejects.toMatchObject({ status: 403, message: '请求来源不受信任,请在本站重试。' })
})
test.each([undefined, 'https://sc.jiansun.vip', 'http://192.168.58.20:4320'])('cross-site即使来源%s在白名单内也拒绝', async origin => {
await expect(salaryIdentity(true, request(origin, { 'sec-fetch-site': 'cross-site' }))).rejects.toMatchObject({ status: 403 })
})
test('没有Origin的非浏览器请求沿用当前权限校验', async () => {
await expect(salaryIdentity(true, request())).resolves.toBe('admin')
})
test('可信来源仍拒绝未登录用户', async () => {
session.mockResolvedValue(null)
await expect(salaryIdentity(true, request('https://sc.jiansun.vip'))).rejects.toMatchObject({ status: 401 })
expect(user).not.toHaveBeenCalled()
})
test('可信来源仍根据数据库当前权限拒绝只读账号和已撤销的超管', async () => {
session.mockResolvedValue({ user: { id: 'c041d8d8-93db-41f1-984d-5f76f114da48', isSuperAdmin: true } })
user.mockResolvedValue({ id: 'c041d8d8-93db-41f1-984d-5f76f114da48', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null })
await expect(salaryIdentity(true, request('https://sc.jiansun.vip'))).rejects.toMatchObject({ status: 403 })
await expect(salaryIdentity()).resolves.toBe('c041d8d8-93db-41f1-984d-5f76f114da48')
})