computerProvider.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // @vitest-environment node
  2. import {afterEach,expect,it,vi} from 'vitest'
  3. import {randomUUID} from 'node:crypto'
  4. import {mkdtemp,rm,symlink,mkdir,rename,writeFile,realpath} from 'node:fs/promises'
  5. import {tmpdir} from 'node:os'
  6. import {join} from 'node:path'
  7. import {ContainerComputerProvider,CUA_DRIVER,type ContainerCommand,type ComputerSpecification} from '../../src/runner/computers/container'
  8. import {COMMAND_ROOT,GUEST_COMMAND} from '../../src/runner/computers/commandProcess'
  9. const homes:string[]=[]
  10. afterEach(async()=>{await Promise.all(homes.splice(0).map(home=>rm(home,{recursive:true,force:true})))})
  11. async function fixture(runtime:'docker'|'podman'='docker',onCommand?:(args:string[])=>Promise<void>){
  12. const home=await realpath(await mkdtemp(join(tmpdir(),'yaoyao-computer-unit-')));homes.push(home)
  13. const spec:ComputerSpecification={id:randomUUID(),ownerKey:randomUUID(),imageId:`sha256:${'a'.repeat(64)}`}
  14. let detail:any
  15. const calls:string[][]=[]
  16. const run:ContainerCommand=async(_runtime,args)=>{
  17. if(onCommand)await onCommand(args)
  18. calls.push(args)
  19. if(args[0]==='context')return {stdout:JSON.stringify('unix:///tmp/fixture-engine.sock'),stderr:''}
  20. if(args[0]==='system')return {stdout:'[]',stderr:''}
  21. if(args[0]==='image')return {stdout:JSON.stringify([{Id:spec.imageId,Config:{Labels:{'com.openmausbot.cua-driver':'0.20.0','com.openmausbot.image-layer':'5'}}}]),stderr:''}
  22. if(args[0]==='inspect'){
  23. if(!detail)throw Object.assign(new Error('missing'),{stderr:'No such object'})
  24. return {stdout:JSON.stringify([detail]),stderr:''}
  25. }
  26. if(args[0]==='create'){
  27. const value=(flag:string)=>args[args.indexOf(flag)+1]!
  28. const values=(flag:string)=>args.flatMap((arg,i)=>arg===flag?[args[i+1]!]:[])
  29. const workspace=/source=([^,]+)/.exec(value('--mount'))![1]
  30. detail={Id:'b'.repeat(64),Image:spec.imageId,Config:{Labels:Object.fromEntries(values('--label').map(label=>label.split('=')))},State:{Running:false},
  31. HostConfig:{Memory:4096*1024*1024,MemorySwap:4096*1024*1024,NanoCpus:2e9,PidsLimit:512,Privileged:false,IpcMode:'private',CgroupnsMode:'private',NetworkMode:'none',RestartPolicy:{Name:'no'},CapAdd:values('--cap-add'),CapDrop:values('--cap-drop'),SecurityOpt:values('--security-opt'),PortBindings:{}},
  32. Mounts:[{Type:'bind',Source:workspace,Destination:'/home/cua/workspace',RW:true}],NetworkSettings:{Ports:{}}}
  33. return {stdout:detail.Id,stderr:''}
  34. }
  35. if(args[0]==='start')detail.State.Running=true
  36. if(args[0]==='stop')detail.State.Running=false
  37. if(args[0]==='rm')detail=undefined
  38. return {stdout:'fixture',stderr:''}
  39. }
  40. const provider=new ContainerComputerProvider(runtime,randomUUID(),home,run,{})
  41. return {provider,spec,calls,home,run,get detail(){return detail}}
  42. }
  43. it.each(['docker','podman'] as const)('uses the same private ownership and execution boundary for %s',async runtime=>{
  44. const f=await fixture(runtime),state=await f.provider.ensure(f.spec,()=>{})
  45. expect(state).toMatchObject({running:true,isolation:'container'})
  46. await f.provider.execute(f.spec,['/bin/sh','-c','echo hello'],{authorize:()=>{}})
  47. expect(f.calls.find(args=>args[0]==='exec')).toEqual(['exec','--user','0:0','--env','HOME=/home/cua','--env','USER=cua','--workdir','/home/cua/workspace','--',state.containerId,'python3','-u','-c',GUEST_COMMAND,'run',COMMAND_ROOT,expect.any(String),'cua','30','/bin/sh','-c','echo hello'])
  48. await f.provider.execute(f.spec,['/bin/sh','-c','id -u'],{authorize:()=>{},user:'root'})
  49. expect(f.calls.find(args=>args.includes('HOME=/root'))).toEqual(['exec','--user','0:0','--env','HOME=/root','--env','USER=root','--workdir','/home/cua/workspace','--',state.containerId,'python3','-u','-c',GUEST_COMMAND,'run',COMMAND_ROOT,expect.any(String),'root','30','/bin/sh','-c','id -u'])
  50. await expect(f.provider.ensure({...f.spec,ownerKey:'different-account'},()=>{})).rejects.toMatchObject({code:'computer_owner_mismatch'})
  51. await f.provider.remove(f.spec)
  52. expect(f.calls.find(args=>args[0]==='rm')).toEqual(['rm','--',state.containerId])
  53. })
  54. it('waits for the desktop driver on a cold start before sending a GUI command',async()=>{
  55. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  56. let checks=0
  57. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,f.home,async(runtime,args,options)=>{
  58. if(args.includes('health_report')){
  59. checks++
  60. if(checks<3)throw Object.assign(new Error('driver starting'),{stderr:'Cua Driver daemon is not running on /run/user/1000/openmausbot-cua.sock.'})
  61. }
  62. return f.run(runtime,args,options)
  63. },{})
  64. await provider.execute(f.spec,[CUA_DRIVER,'call','get_desktop_state','{}'],{authorize:()=>{},lane:'gui'})
  65. expect(checks).toBe(3)
  66. expect(f.calls.filter(args=>args.includes('health_report'))).toHaveLength(1)
  67. expect(f.calls.some(args=>args.includes('get_desktop_state'))).toBe(true)
  68. })
  69. it.each([
  70. (d:any)=>{d.HostConfig.Privileged=true},
  71. (d:any)=>{d.HostConfig.CapAdd.push('SYS_ADMIN')},
  72. (d:any)=>{d.HostConfig.Memory=0},
  73. (d:any)=>{d.HostConfig.NetworkMode='host'},
  74. (d:any)=>{d.HostConfig.PidMode='host'},
  75. (d:any)=>{d.HostConfig.SecurityOpt=['seccomp=unconfined']},
  76. (d:any)=>{d.Mounts[0].Source='/Users/private'},
  77. (d:any)=>{d.Mounts.push({Source:'/var/run/docker.sock'})},
  78. (d:any)=>{d.HostConfig.PortBindings['6901/tcp']=[{HostIp:'127.0.0.1',HostPort:'12345'}]},
  79. (d:any)=>{d.Image=`sha256:${'c'.repeat(64)}`},
  80. ])('refuses execution when an existing container no longer matches its constraints (%#)',async mutate=>{
  81. const f=await fixture();await f.provider.ensure(f.spec,()=>{});mutate(f.detail)
  82. await expect(f.provider.execute(f.spec,['true'],{authorize:()=>{}})).rejects.toMatchObject({code:'computer_configuration_unsafe'})
  83. expect(f.calls.some(args=>args[0]==='exec')).toBe(false)
  84. await f.provider.stop(f.spec)
  85. expect(f.detail.State.Running).toBe(false)
  86. })
  87. it('replaces an existing desktop created with the old no-new-privileges flag',async()=>{
  88. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  89. f.detail.HostConfig.SecurityOpt=['no-new-privileges:true'];f.detail.State.Running=true
  90. const state=await f.provider.ensure(f.spec,()=>{})
  91. expect(state.running).toBe(true)
  92. expect(f.detail.HostConfig.SecurityOpt).toEqual([])
  93. expect(f.calls.filter(args=>args[0]==='create')).toHaveLength(2)
  94. expect(f.calls.some(args=>args[0]==='rm')).toBe(true)
  95. expect(f.calls.flat().includes('no-new-privileges:true')).toBe(false)
  96. })
  97. it('does not stop or remove an identically named container belonging to another node',async()=>{
  98. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  99. f.detail.Config.Labels['cn.samien.yaoyao.runner']=randomUUID()
  100. await expect(f.provider.stop(f.spec)).rejects.toMatchObject({code:'computer_owner_mismatch'})
  101. await expect(f.provider.remove(f.spec)).rejects.toMatchObject({code:'computer_owner_mismatch'})
  102. expect(f.calls.some(args=>['stop','rm'].includes(args[0]!))).toBe(false)
  103. })
  104. it('rejects workspace links and remote engine contexts before creating a computer',async()=>{
  105. const f=await fixture(),outside=await mkdtemp(join(tmpdir(),'yaoyao-computer-outside-'));homes.push(outside)
  106. await mkdir(join(f.home,'computer-workspaces'));await symlink(outside,join(f.home,'computer-workspaces',f.spec.id))
  107. await expect(f.provider.ensure(f.spec,()=>{})).rejects.toMatchObject({code:'computer_path_unsafe'})
  108. const remote=new ContainerComputerProvider('docker',randomUUID(),f.home,f.run,{DOCKER_HOST:'tcp://remote.invalid:2375'})
  109. await expect(remote.ensure(f.spec,()=>{})).rejects.toMatchObject({code:'computer_remote_engine'})
  110. expect(f.calls.some(args=>args[0]==='create')).toBe(false)
  111. })
  112. it('checks authority again after asynchronous inspection, before a guest command starts',async()=>{
  113. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  114. let active=true
  115. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,f.home,async(runtime,args,options)=>{
  116. const result=await f.run(runtime,args,options);if(args[0]==='inspect')active=false;return result
  117. },{})
  118. await expect(provider.execute(f.spec,['true'],{authorize:()=>{if(!active)throw new Error('revoked')}})).rejects.toThrow('revoked')
  119. expect(f.calls.some(args=>args[0]==='exec')).toBe(false)
  120. })
  121. it('recreates a migrated mount while retaining the stopped original container and persistent workspace',async()=>{
  122. const f=await fixture(),oldRoot=join(f.home,'.hermes-yaoyao'),newRoot=join(f.home,'.yaoyao')
  123. const oldHome=join(oldRoot,'runner-state/r1'),newHome=join(newRoot,'runner-state/r1')
  124. await mkdir(oldHome,{recursive:true})
  125. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,oldHome,f.run,{})
  126. await provider.ensure(f.spec,()=>{});await provider.stop(f.spec)
  127. await writeFile(join(oldHome,'computer-workspaces',f.spec.id,'keep.txt'),'keep workspace')
  128. await rename(oldRoot,newRoot)
  129. await writeFile(join(newRoot,'.data-home-migration.json'),JSON.stringify({source:oldRoot,target:newRoot,phase:'complete'}))
  130. let renamed=false
  131. const next=new ContainerComputerProvider('docker',f.provider.runnerId,newHome,async(runtime,args,options)=>{
  132. if(args[0]==='rename'){renamed=true;expect(args[1]).toBe(f.detail.Id);expect(args[2]).toContain('-before-data-move-');return {stdout:'',stderr:''}}
  133. if(args[0]==='inspect'&&renamed&&args[1]!==f.detail.Id)throw Object.assign(new Error('missing'),{stderr:'No such object'})
  134. if(args[0]==='create')renamed=false
  135. return f.run(runtime,args,options)
  136. },{})
  137. const state=await next.ensure(f.spec,()=>{})
  138. expect(state.workspace).toContain('/.yaoyao/')
  139. await expect((await import('node:fs/promises')).readFile(join(state.workspace,'keep.txt'),'utf8')).resolves.toBe('keep workspace')
  140. expect(f.calls.filter(args=>args[0]==='rm')).toHaveLength(0)
  141. })
  142. it('runs command lanes concurrently, serializes desktop input and drains every lane before lifecycle operations',async()=>{
  143. const order:string[]=[],held:Array<()=>void>=[]
  144. let active=0,peak=0
  145. const f=await fixture('docker',async args=>{
  146. if(args[0]==='exec'){
  147. const marker=String(args.at(-1))
  148. active++;peak=Math.max(peak,active)
  149. try{
  150. if(marker.startsWith('hold'))await new Promise<void>(resolve=>held.push(resolve))
  151. order.push(`exec:${marker}`)
  152. }finally{active--}
  153. }
  154. if(args[0]==='stop'||args[0]==='rm')order.push(args[0]!)
  155. })
  156. await f.provider.ensure(f.spec,()=>{})
  157. // File commands from different holders overlap on the exec lane.
  158. const slowFile=f.provider.execute(f.spec,['/bin/sh','-c','hold-a'],{authorize:()=>{}})
  159. await f.provider.execute(f.spec,['/bin/sh','-c','plain-b'],{authorize:()=>{}})
  160. expect(order).toContain('exec:plain-b')
  161. // Desktop input is serialized: the second GUI action waits for the first.
  162. const slowGui=f.provider.execute(f.spec,['driver','hold-gui-1'],{authorize:()=>{},lane:'gui'})
  163. let guiTwoDone=false
  164. const guiTwo=f.provider.execute(f.spec,['driver','plain-gui-2'],{authorize:()=>{},lane:'gui'}).then(()=>{guiTwoDone=true})
  165. await new Promise(resolve=>setTimeout(resolve,25))
  166. expect(guiTwoDone).toBe(false)
  167. // A lifecycle operation drains both lanes before touching the container.
  168. let stopped=false
  169. const stopping=f.provider.stop(f.spec).then(()=>{stopped=true})
  170. await new Promise(resolve=>setTimeout(resolve,25))
  171. expect(stopped).toBe(false)
  172. for(const release of held.splice(0))release()
  173. await Promise.all([slowFile,slowGui,guiTwo,stopping])
  174. expect(guiTwoDone).toBe(true)
  175. expect(peak).toBeGreaterThanOrEqual(2)
  176. expect(order.filter(entry=>entry.startsWith('exec:')).indexOf('exec:plain-gui-2')).toBeGreaterThan(order.indexOf('exec:hold-gui-1'))
  177. expect(order.indexOf('stop')).toBeGreaterThan(order.indexOf('exec:plain-gui-2'))
  178. })
  179. it('keeps a shared desktop alive when one holder cancels an unacknowledged operation',async()=>{
  180. let stopped=0
  181. const f=await fixture('docker',async args=>{
  182. if(args[0]==='stop')stopped++
  183. if(args[0]==='exec'&&String(args.at(-1)).startsWith('boom'))throw Object.assign(new Error('unacknowledged'),{killed:true})
  184. })
  185. await f.provider.ensure(f.spec,()=>{})
  186. // Another holder still shares the desktop: the ambiguous operation must not close it.
  187. await expect(f.provider.execute(f.spec,['/bin/sh','-c','boom-shared'],{authorize:()=>{},mayFence:()=>false})).rejects.toMatchObject({code:'computer_cancel_uncertain'})
  188. await new Promise(resolve=>setTimeout(resolve,25))
  189. expect(stopped).toBe(0)
  190. await f.provider.execute(f.spec,['/bin/sh','-c','after'],{authorize:()=>{}})
  191. // A sole holder keeps the original hard fence.
  192. await expect(f.provider.execute(f.spec,['/bin/sh','-c','boom-alone'],{authorize:()=>{}})).rejects.toMatchObject({code:'computer_cancel_uncertain'})
  193. await new Promise(resolve=>setTimeout(resolve,25))
  194. expect(stopped).toBe(1)
  195. })
  196. it('requires a guest stop acknowledgement for a cancelled command and preserves another holder',async()=>{
  197. const f=await fixture(),abort=new AbortController(),calls:string[][]=[]
  198. await f.provider.ensure(f.spec,()=>{})
  199. let acknowledge:()=>void=()=>{}
  200. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,f.home,async(runtime,args,options)=>{
  201. calls.push(args)
  202. if(args.includes(GUEST_COMMAND)&&args.includes('run')){abort.abort();return {stdout:'late',stderr:''}}
  203. if(args.includes(GUEST_COMMAND)&&args.includes('cancel')){
  204. expect(options?.signal).toBeUndefined()
  205. await new Promise<void>(resolve=>{acknowledge=resolve})
  206. return {stdout:JSON.stringify({stopped:true}),stderr:''}
  207. }
  208. return f.run(runtime,args,options)
  209. },{})
  210. let finished=false
  211. const execution=provider.execute(f.spec,['work'],{authorize:()=>{},signal:abort.signal,mayFence:()=>false}).catch(error=>{finished=true;return error})
  212. await vi.waitFor(()=>expect(calls.some(args=>args.includes('cancel'))).toBe(true))
  213. expect(finished).toBe(false)
  214. const running=calls.find(args=>args.includes('run'))!,cancelled=calls.find(args=>args.includes('cancel'))!
  215. expect(cancelled.at(-1)).toBe(running[running.indexOf(COMMAND_ROOT)+1])
  216. acknowledge()
  217. expect(await execution).toMatchObject({code:'computer_cancelled'})
  218. expect(calls.some(args=>args[0]==='stop')).toBe(false)
  219. })