allowedHostsProtocol.test.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { getAllowedHostsSettings, saveAllowedHostsSettings } from '@/api/admin'
  3. import { clearApiSecurityContext, setApiCsrfToken } from '@/api/client'
  4. afterEach(() => {
  5. clearApiSecurityContext()
  6. vi.unstubAllGlobals()
  7. })
  8. describe('allowed hosts client protocol', () => {
  9. it('reads and saves domains and IP addresses inside the protected system API', async () => {
  10. const calls: Array<{ path: string; init?: RequestInit }> = []
  11. vi.stubGlobal('fetch', vi.fn(async (path: string, init?: RequestInit) => {
  12. calls.push({ path, init })
  13. return new Response(JSON.stringify({
  14. source: 'file',
  15. hosts: ['127.0.0.1', '203.0.113.10', 'yaoyao.example.com'],
  16. editableHosts: ['203.0.113.10', 'yaoyao.example.com'],
  17. environmentHosts: ['127.0.0.1'],
  18. }), { status: 200, headers: { 'content-type': 'application/json' } })
  19. }))
  20. setApiCsrfToken('csrf-allowed-hosts')
  21. await expect(getAllowedHostsSettings()).resolves.toMatchObject({ source: 'file' })
  22. await expect(saveAllowedHostsSettings(['yaoyao.example.com', '203.0.113.10']))
  23. .resolves.toMatchObject({ editableHosts: ['203.0.113.10', 'yaoyao.example.com'] })
  24. expect(calls.map(call => call.path)).toEqual([
  25. '/api/app/system/allowed-hosts',
  26. '/api/app/system/allowed-hosts',
  27. ])
  28. expect(new Headers(calls[1]!.init?.headers).get('X-CSRF-Token')).toBe('csrf-allowed-hosts')
  29. expect(calls[1]!.init?.body).toBe(JSON.stringify({
  30. hosts: ['yaoyao.example.com', '203.0.113.10'],
  31. }))
  32. })
  33. })