embeddedMultiUser.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. // @vitest-environment node
  2. import { randomUUID } from 'node:crypto'
  3. import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
  4. import { createServer, type Server } from 'node:http'
  5. import { tmpdir } from 'node:os'
  6. import { join } from 'node:path'
  7. import request from 'supertest'
  8. import { afterEach, describe, expect, it } from 'vitest'
  9. import { createApplication, type ApplicationRuntime } from '../../src/server/app'
  10. import { loadServerConfig } from '../../src/server/config'
  11. import { createEmbeddedHermes } from '../../src/server/hermes/embedded'
  12. import { kernelPaths } from '../../src/server/hermes/paths'
  13. const kernel = existsSync(kernelPaths().python)
  14. const host = '127.0.0.1:15300'
  15. type Client = ReturnType<typeof request.agent>
  16. describe.skipIf(!kernel)('multiple accounts on the embedded Hermes kernel', () => {
  17. let home = '', runtime: ApplicationRuntime | undefined, model: Server | undefined
  18. const prompts: string[] = []
  19. afterEach(() => {
  20. runtime?.close(); runtime = undefined
  21. model?.close(); model = undefined
  22. prompts.length = 0
  23. if (home) rmSync(home, { recursive: true, force: true })
  24. })
  25. const call = (client: Client, method: 'get' | 'post' | 'put' | 'patch' | 'delete', path: string, csrf = '') =>
  26. client[method](path).set('Host', host).set('Origin', `http://${host}`).set('X-CSRF-Token', csrf)
  27. async function setup() {
  28. model = createServer((req, res) => {
  29. let raw = ''
  30. req.on('data', chunk => { raw += chunk })
  31. req.on('end', () => {
  32. let body: any
  33. try { body = JSON.parse(raw) } catch { body = undefined }
  34. if (!Array.isArray(body?.messages)) { res.setHeader('content-type', 'application/json'); res.end('{"data":[]}'); return }
  35. const last = JSON.stringify(body.messages.at(-1)?.content ?? '')
  36. prompts.push(last)
  37. // Echo a marker from the request so each account's reply is distinguishable.
  38. const marker = /MARK-[A-Z]+/.exec(last)?.[0] ?? 'NONE'
  39. res.writeHead(200, { 'content-type': 'text/event-stream' })
  40. res.write(`data: ${JSON.stringify({ id: 't', object: 'chat.completion.chunk', model: 'm', choices: [{ index: 0, delta: { role: 'assistant', content: `回复 ${marker}` }, finish_reason: null }] })}\n\n`)
  41. res.write(`data: ${JSON.stringify({ id: 't', object: 'chat.completion.chunk', model: 'm', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } })}\n\n`)
  42. res.end('data: [DONE]\n\n')
  43. })
  44. })
  45. await new Promise<void>(resolve => model!.listen(0, '127.0.0.1', resolve))
  46. const port = (model.address() as { port: number }).port
  47. home = mkdtempSync(join(tmpdir(), 'yaoyao-multiuser-'))
  48. const modelConfig = `model:\n provider: custom\n default: m\n base_url: http://127.0.0.1:${port}/v1\n api_key: k\n`
  49. for (const dir of ['hermes', 'hermes/profiles/allowed', 'hermes/profiles/private']) {
  50. mkdirSync(join(home, dir), { recursive: true })
  51. writeFileSync(join(home, dir, 'config.yaml'), modelConfig)
  52. }
  53. const config = loadServerConfig({ HERMES_YAOYAO_HOME: home, HERMES_YAOYAO_MEDIA_ROOT: join(home, 'media') })
  54. const hermes = createEmbeddedHermes(home, { env: { ...process.env, YAOVI_HERMES_TEST_OFFLINE: '1', YAOYAO_KERNEL_STANDBY: '0' }, defaultCwd: config.mediaRoot, policy: () => ({ approval: 'ask', denyHostTools: false }) })
  55. runtime = createApplication({ config, hermes })
  56. const admin = request.agent(runtime.app.callback()), child = request.agent(runtime.app.callback())
  57. const boot = await call(admin, 'get', '/api/app/bootstrap').expect(200)
  58. const adminCSRF = (await call(admin, 'post', '/api/app/setup', boot.body.csrfToken).send({ username: 'owner', password: 'owner-password' }).expect(200)).body.csrfToken
  59. const created = await call(admin, 'post', '/api/app/admin/users', adminCSRF).send({ username: 'child', password: 'temporary-password', assignedProfiles: ['allowed'] }).expect(201)
  60. const childBoot = await call(child, 'get', '/api/app/bootstrap').expect(200)
  61. let childCSRF = (await call(child, 'post', '/api/app/login', childBoot.body.csrfToken).send({ username: 'child', password: 'temporary-password' }).expect(200)).body.csrfToken
  62. childCSRF = (await call(child, 'put', '/api/app/account/credentials', childCSRF).send({ currentPassword: 'temporary-password', newPassword: 'child-password' }).expect(200)).body.csrfToken
  63. return { runtime, admin, child, adminCSRF, childCSRF, childID: created.body.id as string }
  64. }
  65. async function botReply(client: Client, csrf: string, conversationId: string, content: string) {
  66. await call(client, 'post', `/api/app/conversations/${conversationId}/messages`, csrf).send({ requestId: randomUUID(), content }).expect(202)
  67. const deadline = Date.now() + 120_000
  68. while (Date.now() < deadline) {
  69. const messages = (await call(client, 'get', `/api/app/conversations/${conversationId}`).expect(200)).body.messages as Array<{ role: string; status: string; content: string; error?: string }>
  70. const reply = messages.filter(m => m.role === 'assistant' && ['complete', 'failed', 'uncertain'].includes(m.status)).at(-1)
  71. if (reply) return reply
  72. await new Promise(resolve => setTimeout(resolve, 200))
  73. }
  74. throw new Error('no Bot reply')
  75. }
  76. it('isolates Bots, conversations and Hermes homes between an administrator and a sub-account', async () => {
  77. const { admin, child, adminCSRF, childCSRF } = await setup()
  78. // Sub-accounts may only build Bots on their assigned Profiles.
  79. await call(child, 'post', '/api/app/agents', childCSRF).send({ name: '越权', profile: 'private' }).expect(403)
  80. const childAgent = (await call(child, 'post', '/api/app/agents', childCSRF).send({ name: '子账号助手', profile: 'allowed' }).expect(201)).body.agent
  81. const adminAgent = (await call(admin, 'post', '/api/app/agents', adminCSRF).send({ name: '管理员助手', profile: 'private' }).expect(201)).body.agent
  82. const childConversation = (await call(child, 'get', '/api/app/conversations').expect(200)).body.conversations[0]
  83. const adminConversation = (await call(admin, 'get', '/api/app/conversations').expect(200)).body.conversations[0]
  84. expect(childConversation.id).not.toBe(adminConversation.id)
  85. // Both accounts run real turns on the embedded kernel, concurrently.
  86. const [childReply, adminReply] = await Promise.all([
  87. botReply(child, childCSRF, childConversation.id, '你好 MARK-CHILD'),
  88. botReply(admin, adminCSRF, adminConversation.id, '你好 MARK-ADMIN'),
  89. ])
  90. expect(childReply.status, childReply.error).toBe('complete')
  91. expect(adminReply.status, adminReply.error).toBe('complete')
  92. expect(childReply.content).toContain('MARK-CHILD')
  93. expect(adminReply.content).toContain('MARK-ADMIN')
  94. // Each Bot keeps its own Hermes runtime home; neither prompt carried the other account's text.
  95. expect(existsSync(join(home, 'bots', childAgent.id, 'runtime', 'state.db'))).toBe(true)
  96. expect(existsSync(join(home, 'bots', adminAgent.id, 'runtime', 'state.db'))).toBe(true)
  97. expect(prompts.filter(p => p.includes('MARK-CHILD')).every(p => !p.includes('MARK-ADMIN'))).toBe(true)
  98. // Lists and direct reads are owner-scoped.
  99. expect((await call(child, 'get', '/api/app/agents').expect(200)).body.agents.map((a: { id: string }) => a.id)).toEqual([childAgent.id])
  100. expect((await call(admin, 'get', '/api/app/agents').expect(200)).body.agents.map((a: { id: string }) => a.id)).toEqual([adminAgent.id])
  101. expect((await call(child, 'get', `/api/app/conversations/${adminConversation.id}`)).status).toBe(404)
  102. expect((await call(admin, 'get', `/api/app/conversations/${childConversation.id}`)).status).toBe(404)
  103. await call(child, 'post', `/api/app/conversations/${adminConversation.id}/messages`, childCSRF).send({ requestId: randomUUID(), content: '越权' }).expect(404)
  104. }, 240_000)
  105. it('serves only Bot mode: native chat surfaces are gone and Hermes data stays out of reach of a sub-account', async () => {
  106. const { admin, child } = await setup()
  107. // Ordinary (native Hermes) chat is retired for every account.
  108. for (const client of [admin, child]) {
  109. for (const path of ['/api/app/sessions', '/api/app/sessions/abc/messages', '/api/sessions', '/api/sessions/abc/messages']) {
  110. expect([403, 404], path).toContain((await call(client, 'get', path)).status)
  111. }
  112. expect([403, 404]).toContain((await call(client, 'post', '/api/realtime/channels').send({ channel: 'chat' })).status)
  113. }
  114. // Hermes data and administration remain denied to the sub-account.
  115. for (const path of ['/api/config', '/api/model/options', '/api/app/admin/model-services', '/api/app/admin/upstream-connection',
  116. `/api/files/download?path=${encodeURIComponent(join(home, 'hermes', 'config.yaml'))}`]) expect((await call(child, 'get', path)).status, path).toBe(403)
  117. // Profile names are not disclosed to sub-accounts; the administrator sees the embedded Profiles.
  118. expect((await call(child, 'get', '/api/profiles').expect(200)).body.profiles).toEqual([])
  119. const names = (await call(admin, 'get', '/api/profiles').expect(200)).body.profiles.map((p: { name: string }) => p.name)
  120. expect(names).toEqual(expect.arrayContaining(['default', 'allowed', 'private']))
  121. // Unread counts only Bot conversations.
  122. expect((await call(admin, 'get', '/api/app/unread').expect(200)).body).toMatchObject({ chat: 0 })
  123. }, 240_000)
  124. })