gongxiangp2/lib/__tests__/desktop-agent-rules-route.test.ts

39 lines
2.5 KiB
TypeScript

/** @jest-environment node */
import { GET } from '@/app/api/desktop/agent-rules/route'
import { requireDesktop } from '@/lib/desktop-client/service'
import { DesktopClientError } from '@/lib/desktop-client/contract.mjs'
jest.mock('@/lib/desktop-client/service', () => ({ requireDesktop: jest.fn() }))
describe('Agent rules endpoint preserves live authorization and private responses', () => {
beforeEach(() => jest.clearAllMocks())
test('unauthenticated, revoked and unauthorized sessions cannot read rule sources', async () => {
for (const status of [401, 403]) {
;(requireDesktop as jest.Mock).mockRejectedValueOnce(new DesktopClientError('无权访问', status, 'denied'))
const response = await GET(new Request('https://platform.test/api/desktop/agent-rules'))
expect(response.status).toBe(status)
expect(await response.json()).not.toHaveProperty('catalog')
expect(response.headers.get('cache-control')).toBe('private, no-store')
}
})
test('each request rechecks authority; missing combinations are not substituted', async () => {
;(requireDesktop as jest.Mock).mockResolvedValue({ account: { id: 'owner' } })
const list = await GET(new Request('https://platform.test/api/desktop/agent-rules'))
expect(list.status).toBe(200)
const selected = await GET(new Request('https://platform.test/api/desktop/agent-rules?binding=GJ-DESK-DNZ0385'))
expect((await selected.json()).catalog.bindings[0].id).toBe('GJ-DESK-DNZ0385')
const missing = await GET(new Request('https://platform.test/api/desktop/agent-rules?binding=missing'))
expect(missing.status).toBe(404)
expect(requireDesktop).toHaveBeenCalledTimes(3)
})
test('conditional metadata checks still reauthorize before any 304 response', async () => {
;(requireDesktop as jest.Mock).mockResolvedValue({ account: { id: 'owner' } })
const first = await GET(new Request('https://platform.test/api/desktop/agent-rules'))
const etag = first.headers.get('etag')!
expect(etag).toMatch(/^"[a-f0-9]{64}"$/)
const hit = await GET(new Request('https://platform.test/api/desktop/agent-rules', { headers: { 'If-None-Match': etag } }))
expect(hit.status).toBe(304); expect(await hit.text()).toBe('')
;(requireDesktop as jest.Mock).mockRejectedValueOnce(new DesktopClientError('无权访问', 403, 'denied'))
const denied = await GET(new Request('https://platform.test/api/desktop/agent-rules', { headers: { 'If-None-Match': etag } }))
expect(denied.status).toBe(403); expect(requireDesktop).toHaveBeenCalledTimes(3)
})
})