computerProvider.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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,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.each([
  55. (d:any)=>{d.HostConfig.Privileged=true},
  56. (d:any)=>{d.HostConfig.CapAdd.push('SYS_ADMIN')},
  57. (d:any)=>{d.HostConfig.Memory=0},
  58. (d:any)=>{d.HostConfig.NetworkMode='host'},
  59. (d:any)=>{d.HostConfig.PidMode='host'},
  60. (d:any)=>{d.HostConfig.SecurityOpt=['seccomp=unconfined']},
  61. (d:any)=>{d.Mounts[0].Source='/Users/private'},
  62. (d:any)=>{d.Mounts.push({Source:'/var/run/docker.sock'})},
  63. (d:any)=>{d.HostConfig.PortBindings['6901/tcp']=[{HostIp:'127.0.0.1',HostPort:'12345'}]},
  64. (d:any)=>{d.Image=`sha256:${'c'.repeat(64)}`},
  65. ])('refuses execution when an existing container no longer matches its constraints (%#)',async mutate=>{
  66. const f=await fixture();await f.provider.ensure(f.spec,()=>{});mutate(f.detail)
  67. await expect(f.provider.execute(f.spec,['true'],{authorize:()=>{}})).rejects.toMatchObject({code:'computer_configuration_unsafe'})
  68. expect(f.calls.some(args=>args[0]==='exec')).toBe(false)
  69. await f.provider.stop(f.spec)
  70. expect(f.detail.State.Running).toBe(false)
  71. })
  72. it('replaces an existing desktop created with the old no-new-privileges flag',async()=>{
  73. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  74. f.detail.HostConfig.SecurityOpt=['no-new-privileges:true'];f.detail.State.Running=true
  75. const state=await f.provider.ensure(f.spec,()=>{})
  76. expect(state.running).toBe(true)
  77. expect(f.detail.HostConfig.SecurityOpt).toEqual([])
  78. expect(f.calls.filter(args=>args[0]==='create')).toHaveLength(2)
  79. expect(f.calls.some(args=>args[0]==='rm')).toBe(true)
  80. expect(f.calls.flat().includes('no-new-privileges:true')).toBe(false)
  81. })
  82. it('does not stop or remove an identically named container belonging to another node',async()=>{
  83. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  84. f.detail.Config.Labels['cn.samien.yaoyao.runner']=randomUUID()
  85. await expect(f.provider.stop(f.spec)).rejects.toMatchObject({code:'computer_owner_mismatch'})
  86. await expect(f.provider.remove(f.spec)).rejects.toMatchObject({code:'computer_owner_mismatch'})
  87. expect(f.calls.some(args=>['stop','rm'].includes(args[0]!))).toBe(false)
  88. })
  89. it('rejects workspace links and remote engine contexts before creating a computer',async()=>{
  90. const f=await fixture(),outside=await mkdtemp(join(tmpdir(),'yaoyao-computer-outside-'));homes.push(outside)
  91. await mkdir(join(f.home,'computer-workspaces'));await symlink(outside,join(f.home,'computer-workspaces',f.spec.id))
  92. await expect(f.provider.ensure(f.spec,()=>{})).rejects.toMatchObject({code:'computer_path_unsafe'})
  93. const remote=new ContainerComputerProvider('docker',randomUUID(),f.home,f.run,{DOCKER_HOST:'tcp://remote.invalid:2375'})
  94. await expect(remote.ensure(f.spec,()=>{})).rejects.toMatchObject({code:'computer_remote_engine'})
  95. expect(f.calls.some(args=>args[0]==='create')).toBe(false)
  96. })
  97. it('checks authority again after asynchronous inspection, before a guest command starts',async()=>{
  98. const f=await fixture();await f.provider.ensure(f.spec,()=>{})
  99. let active=true
  100. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,f.home,async(runtime,args,options)=>{
  101. const result=await f.run(runtime,args,options);if(args[0]==='inspect')active=false;return result
  102. },{})
  103. await expect(provider.execute(f.spec,['true'],{authorize:()=>{if(!active)throw new Error('revoked')}})).rejects.toThrow('revoked')
  104. expect(f.calls.some(args=>args[0]==='exec')).toBe(false)
  105. })
  106. it('recreates a migrated mount while retaining the stopped original container and persistent workspace',async()=>{
  107. const f=await fixture(),oldRoot=join(f.home,'.hermes-yaoyao'),newRoot=join(f.home,'.yaoyao')
  108. const oldHome=join(oldRoot,'runner-state/r1'),newHome=join(newRoot,'runner-state/r1')
  109. await mkdir(oldHome,{recursive:true})
  110. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,oldHome,f.run,{})
  111. await provider.ensure(f.spec,()=>{});await provider.stop(f.spec)
  112. await writeFile(join(oldHome,'computer-workspaces',f.spec.id,'keep.txt'),'keep workspace')
  113. await rename(oldRoot,newRoot)
  114. await writeFile(join(newRoot,'.data-home-migration.json'),JSON.stringify({source:oldRoot,target:newRoot,phase:'complete'}))
  115. let renamed=false
  116. const next=new ContainerComputerProvider('docker',f.provider.runnerId,newHome,async(runtime,args,options)=>{
  117. if(args[0]==='rename'){renamed=true;expect(args[1]).toBe(f.detail.Id);expect(args[2]).toContain('-before-data-move-');return {stdout:'',stderr:''}}
  118. if(args[0]==='inspect'&&renamed&&args[1]!==f.detail.Id)throw Object.assign(new Error('missing'),{stderr:'No such object'})
  119. if(args[0]==='create')renamed=false
  120. return f.run(runtime,args,options)
  121. },{})
  122. const state=await next.ensure(f.spec,()=>{})
  123. expect(state.workspace).toContain('/.yaoyao/')
  124. await expect((await import('node:fs/promises')).readFile(join(state.workspace,'keep.txt'),'utf8')).resolves.toBe('keep workspace')
  125. expect(f.calls.filter(args=>args[0]==='rm')).toHaveLength(0)
  126. })
  127. it('runs command lanes concurrently, serializes desktop input and drains every lane before lifecycle operations',async()=>{
  128. const order:string[]=[],held:Array<()=>void>=[]
  129. let active=0,peak=0
  130. const f=await fixture('docker',async args=>{
  131. if(args[0]==='exec'){
  132. const marker=String(args.at(-1))
  133. active++;peak=Math.max(peak,active)
  134. try{
  135. if(marker.startsWith('hold'))await new Promise<void>(resolve=>held.push(resolve))
  136. order.push(`exec:${marker}`)
  137. }finally{active--}
  138. }
  139. if(args[0]==='stop'||args[0]==='rm')order.push(args[0]!)
  140. })
  141. await f.provider.ensure(f.spec,()=>{})
  142. // File commands from different holders overlap on the exec lane.
  143. const slowFile=f.provider.execute(f.spec,['/bin/sh','-c','hold-a'],{authorize:()=>{}})
  144. await f.provider.execute(f.spec,['/bin/sh','-c','plain-b'],{authorize:()=>{}})
  145. expect(order).toContain('exec:plain-b')
  146. // Desktop input is serialized: the second GUI action waits for the first.
  147. const slowGui=f.provider.execute(f.spec,['driver','hold-gui-1'],{authorize:()=>{},lane:'gui'})
  148. let guiTwoDone=false
  149. const guiTwo=f.provider.execute(f.spec,['driver','plain-gui-2'],{authorize:()=>{},lane:'gui'}).then(()=>{guiTwoDone=true})
  150. await new Promise(resolve=>setTimeout(resolve,25))
  151. expect(guiTwoDone).toBe(false)
  152. // A lifecycle operation drains both lanes before touching the container.
  153. let stopped=false
  154. const stopping=f.provider.stop(f.spec).then(()=>{stopped=true})
  155. await new Promise(resolve=>setTimeout(resolve,25))
  156. expect(stopped).toBe(false)
  157. for(const release of held.splice(0))release()
  158. await Promise.all([slowFile,slowGui,guiTwo,stopping])
  159. expect(guiTwoDone).toBe(true)
  160. expect(peak).toBeGreaterThanOrEqual(2)
  161. expect(order.filter(entry=>entry.startsWith('exec:')).indexOf('exec:plain-gui-2')).toBeGreaterThan(order.indexOf('exec:hold-gui-1'))
  162. expect(order.indexOf('stop')).toBeGreaterThan(order.indexOf('exec:plain-gui-2'))
  163. })
  164. it('keeps a shared desktop alive when one holder cancels an unacknowledged operation',async()=>{
  165. let stopped=0
  166. const f=await fixture('docker',async args=>{
  167. if(args[0]==='stop')stopped++
  168. if(args[0]==='exec'&&String(args.at(-1)).startsWith('boom'))throw Object.assign(new Error('unacknowledged'),{killed:true})
  169. })
  170. await f.provider.ensure(f.spec,()=>{})
  171. // Another holder still shares the desktop: the ambiguous operation must not close it.
  172. await expect(f.provider.execute(f.spec,['/bin/sh','-c','boom-shared'],{authorize:()=>{},mayFence:()=>false})).rejects.toMatchObject({code:'computer_cancel_uncertain'})
  173. await new Promise(resolve=>setTimeout(resolve,25))
  174. expect(stopped).toBe(0)
  175. await f.provider.execute(f.spec,['/bin/sh','-c','after'],{authorize:()=>{}})
  176. // A sole holder keeps the original hard fence.
  177. await expect(f.provider.execute(f.spec,['/bin/sh','-c','boom-alone'],{authorize:()=>{}})).rejects.toMatchObject({code:'computer_cancel_uncertain'})
  178. await new Promise(resolve=>setTimeout(resolve,25))
  179. expect(stopped).toBe(1)
  180. })
  181. it('requires a guest stop acknowledgement for a cancelled command and preserves another holder',async()=>{
  182. const f=await fixture(),abort=new AbortController(),calls:string[][]=[]
  183. await f.provider.ensure(f.spec,()=>{})
  184. let acknowledge:()=>void=()=>{}
  185. const provider=new ContainerComputerProvider('docker',f.provider.runnerId,f.home,async(runtime,args,options)=>{
  186. calls.push(args)
  187. if(args.includes(GUEST_COMMAND)&&args.includes('run')){abort.abort();return {stdout:'late',stderr:''}}
  188. if(args.includes(GUEST_COMMAND)&&args.includes('cancel')){
  189. expect(options?.signal).toBeUndefined()
  190. await new Promise<void>(resolve=>{acknowledge=resolve})
  191. return {stdout:JSON.stringify({stopped:true}),stderr:''}
  192. }
  193. return f.run(runtime,args,options)
  194. },{})
  195. let finished=false
  196. const execution=provider.execute(f.spec,['work'],{authorize:()=>{},signal:abort.signal,mayFence:()=>false}).catch(error=>{finished=true;return error})
  197. await vi.waitFor(()=>expect(calls.some(args=>args.includes('cancel'))).toBe(true))
  198. expect(finished).toBe(false)
  199. const running=calls.find(args=>args.includes('run'))!,cancelled=calls.find(args=>args.includes('cancel'))!
  200. expect(cancelled.at(-1)).toBe(running[running.indexOf(COMMAND_ROOT)+1])
  201. acknowledge()
  202. expect(await execution).toMatchObject({code:'computer_cancelled'})
  203. expect(calls.some(args=>args[0]==='stop')).toBe(false)
  204. })