gongxiangp2/lib/__tests__/finished-web-sso.test.ts

155 lines
6.4 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 { getEmployeeByUserId, type EmployeeDirectoryEntry } from '@/lib/employee-directory'
import { issueFinishedWebLink } from '@/lib/finished-web-sso'
jest.mock('@/lib/employee-directory', () => ({ getEmployeeByUserId: jest.fn() }))
const endpoint = 'https://pddg.jiansuntuzhi.cn/api/sso/finished-web/token'
const base = 'https://pddg.jiansuntuzhi.cn/finished-web/'
const secret = 'test-configuration'
const valid = {
success: true,
url: base + '#token=simulated-link',
expiresAt: '2027-01-02T07:04:20.518Z',
user: { id: 123, username: 'operator', name: '在职花名', role: 'operator' },
}
function employee(employmentState = 'ACTIVE', flowerName: string | null = ' 在职花名 ') {
return { employmentState, flowerName, displayName: '其他名字', realName: '实名' } as EmployeeDirectoryEntry
}
beforeEach(() => {
jest.replaceProperty(process, 'env', { ...process.env, FINISHED_WEB_ACCESS_KEY: secret })
jest.mocked(getEmployeeByUserId).mockResolvedValue(employee())
})
afterEach(() => {
jest.restoreAllMocks()
jest.resetAllMocks()
})
test('仅以正式在职花名签发,响应仅包含工作台链接、过期时间和账号信息', async () => {
const fetch = jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({
...valid,
token: 'discarded-test-field',
user: { ...valid.user, secret },
}))
const timeout = jest.spyOn(AbortSignal, 'timeout')
await expect(issueFinishedWebLink('library-user')).resolves.toEqual({
url: valid.url, expiresAt: valid.expiresAt, user: valid.user,
})
expect(getEmployeeByUserId).toHaveBeenCalledWith('library-user', { allowDingtalkFallback: false })
expect(timeout).toHaveBeenCalledWith(15_000)
expect(fetch).toHaveBeenCalledTimes(1)
expect(fetch).toHaveBeenCalledWith(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ secret, nickname: '在职花名' }),
redirect: 'error',
cache: 'no-store',
signal: expect.any(AbortSignal),
})
})
test.each([undefined, '', ' '])('未配置服务密钥时返回 503', async value => {
if (value === undefined) delete process.env.FINISHED_WEB_ACCESS_KEY
else process.env.FINISHED_WEB_ACCESS_KEY = value
const fetch = jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error())
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, message: expect.stringContaining('登录密钥尚未配置'),
})
expect(getEmployeeByUserId).not.toHaveBeenCalled()
expect(fetch).not.toHaveBeenCalled()
})
test.each([
['未绑定', null],
['离职', employee('RESIGNED')],
['状态未知', employee('UNKNOWN')],
['缺少花名', employee('ACTIVE', null)],
['花名全为空格', employee('ACTIVE', ' ')],
])('%s时拒绝签发', async (_label, entry) => {
const fetch = jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error())
jest.mocked(getEmployeeByUserId).mockResolvedValue(entry)
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 404, message: expect.stringContaining('没有绑定在职花名'),
})
expect(fetch).not.toHaveBeenCalled()
})
test.each([
['HTTP', 'http://pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link'],
['其他域名', 'https://pddg.jiansuntuzhi.cn.example/finished-web/#token=simulated-link'],
['非默认端口', 'https://pddg.jiansuntuzhi.cn:8443/finished-web/#token=simulated-link'],
['用户名', 'https://operator@pddg.jiansuntuzhi.cn/finished-web/#token=simulated-link'],
['其他路径', 'https://pddg.jiansuntuzhi.cn/finished-web/other/#token=simulated-link'],
['查询参数', base + '?token=simulated-link'],
['包含查询参数的片段链接', base + '?source=x#token=simulated-link'],
['缺少片段', base],
['空令牌', base + '#token='],
['多余片段字段', base + '#token=simulated-link&extra=1'],
['末尾控制字符', base + '#token=simulated-link\n'],
])('拒绝工作台地址中的%s', async (_label, url) => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ...valid, url }))
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, code: 'finished_web_invalid_receipt',
})
})
test.each([
{ success: false },
{ expiresAt: 'invalid-date' },
{ user: null },
])('拒绝错误的成功响应字段 %j', async fields => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ ...valid, ...fields }))
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, code: 'finished_web_invalid_receipt',
})
})
test.each([
[400, '无法识别当前花名'],
[401, '拒绝了服务授权'],
[404, '没有在职账号'],
[429, '过于频繁'],
[503, '登录服务暂不可用'],
[500, '登录服务暂不可用'],
])('将上游 HTTP %i 转为中文错误', async (status, message) => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ error: 'untrusted-upstream-error' }, { status }))
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: status === 500 ? 503 : status,
code: 'finished_web_upstream',
message: expect.stringContaining(message),
})
})
test.each([false, true])('签发请求超时后返回 503(是否在读取响应体时超时:%s)', async duringRead => {
const controller = new AbortController()
jest.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
const abort = () => {
controller.abort()
return Promise.reject(new DOMException('request aborted', 'TimeoutError'))
}
jest.spyOn(globalThis, 'fetch').mockImplementation(() => duringRead
? Promise.resolve({ ok: true, json: abort } as unknown as Response)
: abort())
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, message: expect.stringContaining('连接成品上架工作台超时'),
})
})
test('签发连线错误不会透出请求细节', async () => {
jest.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('untrusted-network-error'))
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, message: expect.stringContaining('暂时无法连接'),
})
})
test('HTTP 200 时拒绝无效 JSON', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('not JSON'))
await expect(issueFinishedWebLink('library-user')).rejects.toMatchObject({
status: 503, code: 'finished_web_invalid_receipt',
})
})