Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

admin.test.ts

47 lines1.5 KB

1import { describe, expect, it } from 'vitest'
2​
3import { isAdminRequest, jsonError } from './admin.ts'
4​
5const req = (headers: Record<string, string> = {}) =>
6 new Request('https://example.com/v1/admin/sync/openai', {
7 method: 'POST',
8 headers,
9 })
10​
11describe('isAdminRequest', () => {
12 it('accepts the key via X-Admin-Key or Authorization: Bearer', () => {
13 expect(isAdminRequest(req({ 'x-admin-key': 'sekret' }), 'sekret')).toBe(
14 true,
15 )
16 expect(
17 isAdminRequest(req({ authorization: 'Bearer sekret' }), 'sekret'),
18 ).toBe(true)
19 })
20​
21 it('rejects wrong or missing keys', () => {
22 expect(isAdminRequest(req({ 'x-admin-key': 'nope' }), 'sekret')).toBe(false)
23 expect(isAdminRequest(req(), 'sekret')).toBe(false)
24 // Prefix and extension of the key, which a length-blind loop could pass.
25 expect(isAdminRequest(req({ 'x-admin-key': 'sek' }), 'sekret')).toBe(false)
26 expect(isAdminRequest(req({ 'x-admin-key': 'sekretx' }), 'sekret')).toBe(
27 false,
28 )
29 })
30​
31 it('fails closed when no admin key is configured', () => {
32 expect(isAdminRequest(req({ 'x-admin-key': 'anything' }), undefined)).toBe(
33 false,
34 )
35 expect(isAdminRequest(req({ 'x-admin-key': '' }), '')).toBe(false)
36 })
37})
38​
39describe('jsonError', () => {
40 it('produces the standard error envelope', async () => {
41 const response = jsonError(404, 'unknown_provider', 'nope')
42 expect(response.status).toBe(404)
43 expect(await response.json()).toEqual({
44 error: { code: 'unknown_provider', message: 'nope' },
45 })
46 })
47})