upstreamServiceSession.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. // @vitest-environment node
  2. import { describe, expect, it, vi } from 'vitest'
  3. import { UpstreamServiceSession } from '../../src/server/localAuth.js'
  4. import { CookieJar, UpstreamClient } from '../../src/server/upstream.js'
  5. describe('upstream service validation lease', () => {
  6. function fixture() {
  7. let now = 0, expire = false
  8. const paths: string[] = []
  9. const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
  10. const path = new URL(String(input)).pathname; paths.push(path)
  11. if (path === '/api/status') return Response.json({ auth_required: true })
  12. if (path === '/api/auth/me') {
  13. return expire && new Headers(init?.headers).get('cookie') === 'session=old'
  14. ? Response.json({ detail: 'expired' }, { status: 401 })
  15. : Response.json({ user_id: 'service' })
  16. }
  17. if (path === '/api/auth/providers') return Response.json({ providers: [] })
  18. if (path === '/auth/password-login') return Response.json({ ok: true }, { headers: { 'set-cookie': 'session=new; Path=/' } })
  19. if (expire && new Headers(init?.headers).get('cookie') === 'session=old') return Response.json({ error: 'expired' }, { status: 401 })
  20. return Response.json({ path })
  21. })
  22. const client = new UpstreamClient(new URL('http://localhost:9119'), fetch, false, () => now)
  23. const session = new UpstreamServiceSession(client, () => ({ username: 'service', password: 'fixture' }), { now: () => now })
  24. session.jar.replace(new CookieJar('session=old'))
  25. return { session, client, fetch, paths, advance: (n: number) => { now += n }, expire: () => { expire = true } }
  26. }
  27. it('validates once for concurrent requests and rechecks only after thirty seconds', async () => {
  28. const f = fixture()
  29. await Promise.all(Array.from({ length: 10 }, (_, i) => f.session.request(`/api/sessions/${i}`)))
  30. expect(f.paths.filter(p => p === '/api/status')).toHaveLength(1)
  31. expect(f.paths.filter(p => p === '/api/auth/me')).toHaveLength(1)
  32. await f.session.request('/api/sessions/a')
  33. expect(f.paths).toHaveLength(13)
  34. f.advance(30_001); await f.session.request('/api/sessions/b')
  35. expect(f.paths.filter(p => p === '/api/status')).toHaveLength(2)
  36. })
  37. it('reduces repeated protected reads to zero upstream calls on a warm hit', async () => {
  38. const f = fixture()
  39. const read = () => f.client.withReadScope('alice', false, () => f.session.request('/api/sessions'))
  40. await Promise.all([read(), read(), read()])
  41. expect(f.paths).toEqual(['/api/status', '/api/auth/me', '/api/sessions'])
  42. await read(); await read()
  43. expect(f.paths).toHaveLength(3)
  44. })
  45. it('repairs parallel 401s once, including raw withJar-style reads', async () => {
  46. const f = fixture(); await f.session.ensure(); f.expire()
  47. await Promise.all([f.client.request('/api/sessions/a', f.session.jar), f.client.request('/api/sessions/b', f.session.jar)])
  48. expect(f.paths.filter(p => p === '/auth/password-login')).toHaveLength(1)
  49. expect(f.paths.filter(p => p === '/api/sessions/a')).toHaveLength(2)
  50. expect(f.paths.filter(p => p === '/api/sessions/b')).toHaveLength(2)
  51. expect(f.session.jar.header).toBe('session=new')
  52. })
  53. it('never replays a write on a timeout or 500 response', async () => {
  54. const f = fixture(); await f.session.ensure()
  55. f.fetch.mockImplementation(async () => Response.json({ error: 'failed' }, { status: 500 }))
  56. const before = f.fetch.mock.calls.length
  57. expect((await f.session.request('/api/sessions/s', { method: 'POST', body: { text: 'once' } })).status).toBe(500)
  58. expect(f.fetch.mock.calls.length - before).toBe(1)
  59. })
  60. it('invalidates validation and cached data on configured credential changes', async () => {
  61. const f = fixture()
  62. let password = 'first'
  63. const session = new UpstreamServiceSession(f.client, () => ({ username: 'service', password }), { now: () => 0 })
  64. await session.ensure()
  65. await f.client.withReadScope('alice', false, () => session.request('/api/sessions'))
  66. expect(f.client.readCache.stats().entries).toBe(1)
  67. password = 'second'; await session.ensure()
  68. expect(f.paths.filter(p => p === '/api/status')).toHaveLength(2)
  69. expect(f.client.readCache.stats().entries).toBe(0)
  70. })
  71. it('does not memoize failed validation', async () => {
  72. const f = fixture()
  73. f.fetch.mockResolvedValueOnce(Response.json({ error: 'offline' }, { status: 503 }))
  74. await expect(f.session.ensure()).rejects.toThrow('9119')
  75. await f.session.ensure()
  76. expect(f.fetch).toHaveBeenCalledTimes(3)
  77. })
  78. it('cannot overwrite new credentials with a late old login response', async () => {
  79. let username = 'old', started = false
  80. let release!: () => void
  81. const blocked = new Promise<void>(r => { release = r })
  82. const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
  83. const path = new URL(String(input)).pathname
  84. if (path === '/api/status') return Response.json({ auth_required: true })
  85. if (path === '/api/auth/me') return Response.json({}, { status: 401 })
  86. if (path === '/api/auth/providers') return Response.json({ providers: [] })
  87. const body = JSON.parse(String(init?.body))
  88. if (body.username === 'old') { started = true; await blocked }
  89. return Response.json({ ok: true }, { headers: { 'set-cookie': `session=${body.username}; Path=/` } })
  90. })
  91. const client = new UpstreamClient(new URL('http://localhost:9119'), fetch)
  92. const session = new UpstreamServiceSession(client, () => ({ username, password: 'fixture' }))
  93. const old = session.ensure().then(() => undefined, error => error)
  94. await vi.waitFor(() => expect(started).toBe(true))
  95. username = 'new'
  96. await session.ensure()
  97. expect(session.jar.header).toBe('session=new')
  98. release()
  99. expect(await old).toMatchObject({ code: 'upstream_credentials_changed' })
  100. expect(session.jar.header).toBe('session=new')
  101. })
  102. it('uses the injected loopback session token without password login', async () => {
  103. const paths: string[] = []
  104. const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
  105. const path = new URL(String(input)).pathname
  106. paths.push(path)
  107. if (path === '/api/status') return Response.json({ auth_required: false })
  108. if (path === '/') {
  109. return new Response('<script>window.__HERMES_SESSION_TOKEN__="loopback-token-123456";</script>', {
  110. headers: { 'content-type': 'text/html' },
  111. })
  112. }
  113. const token = new Headers(init?.headers).get('x-hermes-session-token')
  114. return token === 'loopback-token-123456'
  115. ? Response.json({ ok: true })
  116. : Response.json({ detail: 'Unauthorized' }, { status: 401 })
  117. })
  118. const client = new UpstreamClient(new URL('http://127.0.0.1:9119'), fetch)
  119. const session = new UpstreamServiceSession(client, () => ({ username: 'unused', password: 'unused' }))
  120. expect((await session.request('/api/sessions')).status).toBe(200)
  121. expect(paths).toEqual(['/api/status', '/', '/api/sessions'])
  122. expect(session.connectionInfo()).toMatchObject({
  123. endpoint: 'http://127.0.0.1:9119',
  124. authMode: 'loopback-token',
  125. networkScope: 'local',
  126. })
  127. })
  128. it('refreshes a rotated loopback token once and replays parallel reads', async () => {
  129. let activeToken = 'loopback-token-first'
  130. let pageLoads = 0
  131. const fetch = vi.fn<typeof globalThis.fetch>(async (input, init) => {
  132. const path = new URL(String(input)).pathname
  133. if (path === '/api/status') return Response.json({ auth_required: false })
  134. if (path === '/') {
  135. pageLoads += 1
  136. return new Response(`<script>window.__HERMES_SESSION_TOKEN__=${JSON.stringify(activeToken)};</script>`)
  137. }
  138. return new Headers(init?.headers).get('x-hermes-session-token') === activeToken
  139. ? Response.json({ ok: true })
  140. : Response.json({ detail: 'Unauthorized' }, { status: 401 })
  141. })
  142. const client = new UpstreamClient(new URL('http://localhost:9119'), fetch)
  143. const session = new UpstreamServiceSession(client, () => undefined)
  144. await session.ensure()
  145. activeToken = 'loopback-token-second'
  146. const responses = await Promise.all([
  147. client.request('/api/sessions/a', session.jar),
  148. client.request('/api/sessions/b', session.jar),
  149. ])
  150. expect(responses.map(response => response.status)).toEqual([200, 200])
  151. expect(pageLoads).toBe(2)
  152. })
  153. it('refuses token discovery from a non-loopback upstream', async () => {
  154. const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({ auth_required: false }))
  155. const client = new UpstreamClient(new URL('http://192.168.1.20:9119'), fetch)
  156. const session = new UpstreamServiceSession(client, () => undefined)
  157. await expect(session.ensure()).rejects.toMatchObject({ code: 'upstream_auth_unsafe' })
  158. expect(fetch).toHaveBeenCalledTimes(1)
  159. })
  160. it('keeps older unauthenticated loopback dashboards compatible when no token is injected', async () => {
  161. const fetch = vi.fn<typeof globalThis.fetch>(async (input) => {
  162. const path = new URL(String(input)).pathname
  163. if (path === '/api/status') return Response.json({ auth_required: false })
  164. if (path === '/') return new Response('<html>legacy dashboard</html>')
  165. return Response.json({ ok: true })
  166. })
  167. const client = new UpstreamClient(new URL('http://127.0.0.1:9119'), fetch)
  168. const session = new UpstreamServiceSession(client, () => undefined)
  169. expect((await session.request('/api/sessions')).status).toBe(200)
  170. expect(session.connectionInfo().authMode).toBe('loopback-direct')
  171. })
  172. })