authProtocol.test.ts 3.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { bootstrap, login } from '@/api/auth'
  3. import {
  4. apiRequest,
  5. clearApiSecurityContext,
  6. onApiUnauthorized,
  7. setApiCsrfToken,
  8. } from '@/api/client'
  9. afterEach(() => {
  10. clearApiSecurityContext()
  11. vi.unstubAllGlobals()
  12. })
  13. describe('authentication and CSRF protocol', () => {
  14. it('keeps credentials in cookies and forwards the bootstrap CSRF token on login', async () => {
  15. const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {
  16. const path = new URL(String(input), 'http://localhost').pathname
  17. const body = path.endsWith('/bootstrap')
  18. ? { authRequired: true, authenticated: false, profiles: [], csrfToken: 'csrf-from-bootstrap' }
  19. : {
  20. authRequired: true,
  21. authenticated: true,
  22. user: { user_id: 'user-1', display_name: '夭夭' },
  23. profiles: [{ name: 'yaoyao', is_default: true }],
  24. csrfToken: 'csrf-after-login',
  25. }
  26. return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })
  27. })
  28. vi.stubGlobal('fetch', fetchMock)
  29. const initial = await bootstrap()
  30. expect(initial.user).toBeUndefined()
  31. const authenticated = await login({ username: 'name', password: 'secret' })
  32. expect(authenticated.user).toMatchObject({ id: 'user-1', username: '夭夭' })
  33. const loginInit = fetchMock.mock.calls[1][1]!
  34. expect(loginInit.credentials).toBe('include')
  35. expect(new Headers(loginInit.headers).get('X-CSRF-Token')).toBe('csrf-from-bootstrap')
  36. })
  37. it('keeps the CSRF context after a rejected password so login can be retried', async () => {
  38. let loginAttempts = 0
  39. const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
  40. const path = new URL(String(input), 'http://localhost').pathname
  41. if (path.endsWith('/bootstrap')) {
  42. return new Response(JSON.stringify({ authRequired: true, profiles: [], csrfToken: 'retry-token' }), {
  43. status: 200, headers: { 'content-type': 'application/json' },
  44. })
  45. }
  46. loginAttempts += 1
  47. if (loginAttempts === 1) {
  48. return new Response(JSON.stringify({ error: 'Invalid credentials', code: 'login_failed' }), {
  49. status: 401, headers: { 'content-type': 'application/json' },
  50. })
  51. }
  52. expect(new Headers(init?.headers).get('X-CSRF-Token')).toBe('retry-token')
  53. return new Response(JSON.stringify({
  54. authRequired: true,
  55. user: { user_id: 'user-1', display_name: '夭夭' },
  56. profiles: [{ name: 'yaoyao', is_default: true }],
  57. csrfToken: 'after-retry',
  58. }), { status: 200, headers: { 'content-type': 'application/json' } })
  59. })
  60. vi.stubGlobal('fetch', fetchMock)
  61. await bootstrap()
  62. await expect(login({ username: 'name', password: 'wrong' })).rejects.toMatchObject({ status: 401 })
  63. await expect(login({ username: 'name', password: 'correct' })).resolves.toMatchObject({ user: { id: 'user-1' } })
  64. })
  65. it('keeps the login session for an authenticated 403 permission error', async () => {
  66. let expirations = 0
  67. const unsubscribe = onApiUnauthorized(() => { expirations += 1 })
  68. setApiCsrfToken('csrf-permission')
  69. vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
  70. message: '系统升级默认只允许在本机执行',
  71. code: 'remote_system_update_disabled',
  72. }), { status: 403, headers: { 'content-type': 'application/json' } })))
  73. try {
  74. await expect(apiRequest('/api/app/system/update/apply', {
  75. method: 'POST',
  76. body: { targetVersion: '0.3.0' },
  77. })).rejects.toMatchObject({
  78. status: 403,
  79. code: 'remote_system_update_disabled',
  80. message: '系统升级默认只允许在本机执行',
  81. })
  82. expect(expirations).toBe(0)
  83. } finally {
  84. unsubscribe()
  85. }
  86. })
  87. })