embeddedMultiUser.test.ts 9.8 KB

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