managedBrowserTransport.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // @vitest-environment node
  2. import {afterEach,describe,expect,it,vi} from 'vitest'
  3. import {createHash,randomUUID} from 'node:crypto'
  4. import {RunnerBrowser} from '../../src/runner/managedBrowser.js'
  5. import type {BrowserInstaller} from '../../src/runner/browser/installation.js'
  6. import type {BrowserRuntime,BrowserCallContext,BrowserScope} from '../../src/runner/browser/runtime.js'
  7. const scope:BrowserScope={ownerKey:'a'.repeat(64),environmentId:randomUUID(),profile:'persistent'},grantId=randomUUID()
  8. const scopes:RunnerBrowser[]=[]
  9. function fixture(config:{enabled:boolean;idleTimeoutMs?:number}={enabled:true},installer?:BrowserInstaller){
  10. const runtime={status:vi.fn(async()=>({open:false,generation:1,tabs:[],downloads:[]})),open:vi.fn(async()=>({open:true,generation:1,tabs:[],downloads:[]})),execute:vi.fn(async()=>({ok:true})),pause:vi.fn(),resume:vi.fn(),close:vi.fn(),readDownload:vi.fn(),revoke:vi.fn(async()=>{}),shutdown:vi.fn(async()=>{})}
  11. const check=vi.fn(async(_scope:BrowserScope,_grant?:string)=>{}),probe=vi.fn(async()=>true)
  12. const browser=new RunnerBrowser(config,'/unused-browser-test',check,{runtime:runtime as unknown as BrowserRuntime,probe,installer});scopes.push(browser)
  13. const profileAllowed=vi.fn((_profile:string)=>{})
  14. const invoke=(value:Record<string,unknown>,expiresAt=Date.now()+30000)=>browser.invoke({scope,profile:'default',grantId,...value},expiresAt,profileAllowed)
  15. return {browser,runtime,check,probe,profileAllowed,invoke}
  16. }
  17. afterEach(async()=>{vi.useRealTimers();for(const browser of scopes.splice(0))await browser.shutdown()})
  18. describe('managed browser Runner transport',()=>{
  19. it('keeps default-disabled and missing-browser installations unavailable',async()=>{
  20. const f=fixture({enabled:false});await f.browser.ready
  21. expect(f.browser.available).toBe(false);expect(f.probe).not.toHaveBeenCalled()
  22. await expect(f.invoke({op:'open'})).rejects.toMatchObject({code:'browser_unavailable'})
  23. expect(f.runtime.open).not.toHaveBeenCalled()
  24. const unavailable=new RunnerBrowser({enabled:true},'/unused',async()=>{}, {runtime:f.runtime as unknown as BrowserRuntime,probe:async()=>false});scopes.push(unavailable)
  25. await unavailable.ready;expect(unavailable.available).toBe(false)
  26. })
  27. it('rejects forbidden Profiles, expired commands and foreign grants before execution',async()=>{
  28. const f=fixture();f.profileAllowed.mockImplementationOnce(()=>{throw new Error('profile forbidden')})
  29. await expect(f.invoke({op:'open'})).rejects.toThrow('profile forbidden')
  30. await expect(f.invoke({op:'open'},Date.now()-1)).rejects.toMatchObject({code:'browser_command_expired'})
  31. f.check.mockRejectedValueOnce(new Error('foreign grant'))
  32. await expect(f.invoke({op:'open'})).rejects.toThrow('foreign grant')
  33. expect(f.runtime.open).not.toHaveBeenCalled()
  34. })
  35. it('retains the explicit task grant for background activity after the command deadline',async()=>{
  36. vi.useFakeTimers();const f=fixture();let context:BrowserCallContext|undefined
  37. f.runtime.open.mockImplementationOnce(async(_scope?:unknown,call?:BrowserCallContext)=>{context=call;return {open:true,generation:1,tabs:[],downloads:[]}})
  38. await f.invoke({op:'open'},Date.now()+1000)
  39. await vi.advanceTimersByTimeAsync(5000)
  40. await context!.authorize()
  41. expect(f.check).toHaveBeenLastCalledWith(scope,grantId)
  42. expect(context!.signal!.aborted).toBe(false)
  43. f.check.mockRejectedValueOnce(new Error('grant revoked'))
  44. await expect(context!.authorize()).rejects.toThrow('grant revoked')
  45. })
  46. it('aborts in-flight execution when its transport deadline expires',async()=>{
  47. vi.useFakeTimers();const f=fixture()
  48. f.runtime.execute.mockImplementationOnce(async(_scope?:unknown,_operation?:unknown,context?:BrowserCallContext)=>new Promise((_resolve,reject)=>context!.signal!.addEventListener('abort',()=>reject(context!.signal!.reason),{once:true})))
  49. const result=f.invoke({op:'execute',operation:{generation:1,operationId:'slow',action:{kind:'text',text:'test'}}},Date.now()+1000).catch(error=>error)
  50. await vi.advanceTimersByTimeAsync(2100)
  51. expect(await result).toMatchObject({code:'browser_command_expired'})
  52. expect(f.runtime.execute).toHaveBeenCalledTimes(1)
  53. })
  54. it('disconnect aborts current calls and revokes all opened scopes',async()=>{
  55. const f=fixture()
  56. f.runtime.execute.mockImplementationOnce(async(_scope?:unknown,_operation?:unknown,context?:BrowserCallContext)=>new Promise((_resolve,reject)=>context!.signal!.addEventListener('abort',()=>reject(context!.signal!.reason),{once:true})))
  57. const result=f.invoke({op:'execute',operation:{generation:1,operationId:'inflight',action:{kind:'screenshot'}}}).catch(error=>error)
  58. await vi.waitFor(()=>expect(f.runtime.execute).toHaveBeenCalled())
  59. await f.browser.disconnect();expect(await result).toBeInstanceOf(Error)
  60. expect(f.runtime.revoke).toHaveBeenCalledWith(scope)
  61. })
  62. it('serves validated 512-KiB chunks, rechecking grants even for cached files',async()=>{
  63. const f=fixture(),id=randomUUID(),buffer=Buffer.alloc(512*1024+7,97),sha256=createHash('sha256').update(buffer).digest('hex')
  64. f.runtime.readDownload.mockResolvedValue({name:'large.txt',mimeType:'text/plain',buffer,metadata:{id,name:'large.txt',mimeType:'text/plain',size:buffer.length,sha256,url:'https://example.com/file',createdAt:Date.now()}})
  65. const first=await f.invoke({op:'download',downloadId:id,offset:0}) as {data:string;offset:number;done:boolean;sha256:string}
  66. const last=await f.invoke({op:'download',downloadId:id,offset:512*1024}) as typeof first
  67. expect(Buffer.from(first.data,'base64')).toHaveLength(512*1024);expect(first.done).toBe(false)
  68. expect(Buffer.from(last.data,'base64')).toHaveLength(7);expect(last.done).toBe(true);expect(last.sha256).toBe(sha256)
  69. expect(f.runtime.readDownload).toHaveBeenCalledTimes(1)
  70. await expect(f.invoke({op:'download',downloadId:id,offset:buffer.length+1})).rejects.toMatchObject({code:'browser_download_invalid'})
  71. f.check.mockRejectedValueOnce(new Error('download grant revoked'))
  72. await expect(f.invoke({op:'download',downloadId:id,offset:0})).rejects.toThrow('download grant revoked')
  73. await f.invoke({op:'close'});await f.invoke({op:'download',downloadId:id,offset:0})
  74. expect(f.runtime.readDownload).toHaveBeenCalledTimes(2)
  75. })
  76. it('rejects invalid upload bytes and removes idle or unauthorized browser scopes',async()=>{
  77. vi.useFakeTimers();const f=fixture({enabled:true,idleTimeoutMs:60000})
  78. await expect(f.invoke({op:'execute',upload:{id:randomUUID(),name:'file',mimeType:'text/plain',data:'a'}})).rejects.toMatchObject({code:'browser_upload_limit'})
  79. expect(f.runtime.execute).not.toHaveBeenCalled()
  80. await f.invoke({op:'open'});await vi.advanceTimersByTimeAsync(61000);await f.browser.sweep()
  81. expect(f.runtime.revoke).toHaveBeenCalledWith(scope)
  82. f.runtime.revoke.mockClear();await f.invoke({op:'open'});f.check.mockRejectedValueOnce(new Error('owner disabled'));await f.browser.sweep()
  83. expect(f.runtime.revoke).toHaveBeenCalledWith(scope)
  84. })
  85. })
  86. function installationFixture(){
  87. let complete!:()=>void,fail!:(error:Error)=>void,signal!:AbortSignal
  88. const install=vi.fn(async(options:Parameters<BrowserInstaller['install']>[0])=>{
  89. signal=options.signal
  90. await new Promise<void>((resolve,reject)=>{complete=resolve;fail=reject;signal.addEventListener('abort',()=>reject(signal.reason),{once:true})})
  91. })
  92. const installer={probe:vi.fn(async()=>false),install},f=fixture({enabled:true},installer)
  93. f.probe.mockResolvedValue(false)
  94. return {...f,installer,complete:()=>complete(),fail:(error:Error)=>fail(error),signal:()=>signal}
  95. }
  96. describe('managed browser installation transport',()=>{
  97. it('returns authorized setup state when missing and keeps close idempotent',async()=>{
  98. const f=installationFixture()
  99. await expect(f.invoke({op:'status'})).resolves.toMatchObject({open:false,available:false,installation:{status:'missing'}})
  100. await expect(f.invoke({op:'close'})).resolves.toMatchObject({open:false,tabs:[],downloads:[]})
  101. await expect(f.invoke({op:'open'})).rejects.toMatchObject({code:'browser_unavailable'})
  102. expect(f.installer.install).not.toHaveBeenCalled()
  103. f.check.mockRejectedValueOnce(new Error('foreign grant'))
  104. await expect(f.invoke({op:'prepare'})).rejects.toThrow('foreign grant')
  105. expect(f.installer.install).not.toHaveBeenCalled()
  106. })
  107. it('prepares with the real Runtime after a view grant ends without authorizing a browser session',async()=>{
  108. vi.useFakeTimers()
  109. const viewGrant=randomUUID(),prepareGrant=randomUUID(),grants=new Map<string,'view'|'prepare'>([[viewGrant,'view']])
  110. const check=vi.fn(async(_scope:BrowserScope,grant?:string)=>{
  111. if(grant?grants.has(grant):[...grants.values()].some(role=>role!=='prepare'))return
  112. throw new Error('browser session has no active grant')
  113. })
  114. let complete!:()=>void,signal!:AbortSignal
  115. const installer:BrowserInstaller={probe:async()=>false,install:async options=>{
  116. signal=options.signal
  117. await new Promise<void>((resolve,reject)=>{complete=resolve;signal.addEventListener('abort',()=>reject(signal.reason),{once:true})})
  118. }}
  119. // Use the production BrowserRuntime and its default scope-only authorization.
  120. const browser=new RunnerBrowser({enabled:true},'/unused-no-browser-session',check,{installer});scopes.push(browser)
  121. const readState=vi.spyOn(browser.runtime,'status')
  122. const invoke=(op:string,grant:string)=>browser.invoke({scope,profile:'default',grantId:grant,op},Date.now()+30000,()=>{})
  123. await expect(invoke('status',viewGrant)).resolves.toMatchObject({available:false,installation:{status:'missing'}})
  124. grants.delete(viewGrant);grants.set(prepareGrant,'prepare')
  125. await expect(invoke('prepare',prepareGrant)).resolves.toMatchObject({open:false,tabs:[],downloads:[],available:false,installation:{status:'installing'}})
  126. expect(readState).not.toHaveBeenCalled()
  127. await vi.advanceTimersByTimeAsync(2100);expect(signal.aborted).toBe(false)
  128. // Installing a binary never grants permission to use or retain a page.
  129. await expect(browser.runtime.status(scope)).rejects.toThrow('no active grant')
  130. await expect(browser.runtime.open(scope)).rejects.toThrow('no active grant')
  131. complete();await vi.advanceTimersByTimeAsync(20);expect(browser.available).toBe(true)
  132. readState.mockClear()
  133. // Another holder can finish setup between the server's view and prepare RPC.
  134. await expect(invoke('prepare',prepareGrant)).resolves.toMatchObject({open:false,tabs:[],available:true,installation:{status:'ready'}})
  135. expect(readState).not.toHaveBeenCalled()
  136. await expect(invoke('status',prepareGrant)).rejects.toThrow('no active grant')
  137. grants.set(viewGrant,'view')
  138. await expect(invoke('status',viewGrant)).resolves.toMatchObject({open:false,available:true,installation:{status:'ready'}})
  139. grants.delete(viewGrant)
  140. await expect(browser.runtime.status(scope)).rejects.toThrow('no active grant')
  141. })
  142. it('does not refresh the idle lease of an existing session when prepare finds it ready',async()=>{
  143. vi.useFakeTimers();const f=fixture({enabled:true,idleTimeoutMs:60000})
  144. await f.invoke({op:'open'});await vi.advanceTimersByTimeAsync(55000)
  145. await expect(f.invoke({op:'prepare'})).resolves.toMatchObject({open:false,available:true,installation:{status:'ready'}})
  146. expect(f.runtime.status).not.toHaveBeenCalled()
  147. await vi.advanceTimersByTimeAsync(6000);await f.browser.sweep()
  148. expect(f.runtime.revoke).toHaveBeenCalledWith(scope)
  149. })
  150. it('returns checking immediately and queues one preparation behind a slow startup probe',async()=>{
  151. vi.useFakeTimers();const f=installationFixture();let finishProbe!:(value:boolean)=>void
  152. f.probe.mockImplementationOnce(()=>new Promise(resolve=>{finishProbe=resolve}))
  153. await expect(f.invoke({op:'status'},Date.now()+1000)).resolves.toMatchObject({available:false,installation:{status:'checking'}})
  154. await expect(f.invoke({op:'prepare'},Date.now()+1000)).resolves.toMatchObject({available:false,installation:{status:'checking'}})
  155. await f.invoke({op:'prepare'})
  156. await vi.advanceTimersByTimeAsync(31000)
  157. expect(f.installer.install).not.toHaveBeenCalled()
  158. await expect(f.invoke({op:'status'})).resolves.toMatchObject({installation:{status:'checking'}})
  159. finishProbe(false);await vi.advanceTimersByTimeAsync(20)
  160. expect(f.installer.install).toHaveBeenCalledTimes(1)
  161. expect(f.signal().aborted).toBe(false)
  162. f.complete();await vi.advanceTimersByTimeAsync(20);expect(f.browser.available).toBe(true)
  163. })
  164. it('does not install when a slow probe finds an existing browser or after disconnect',async()=>{
  165. const found=installationFixture();let finishFound!:(value:boolean)=>void
  166. found.probe.mockImplementationOnce(()=>new Promise(resolve=>{finishFound=resolve}))
  167. await expect(found.invoke({op:'prepare'})).resolves.toMatchObject({installation:{status:'checking'}})
  168. finishFound(true);await found.browser.ready
  169. await vi.waitFor(()=>expect(found.browser.available).toBe(true))
  170. expect(found.installer.install).not.toHaveBeenCalled()
  171. const disconnected=installationFixture();let finishDisconnected!:(value:boolean)=>void
  172. disconnected.probe.mockImplementationOnce(()=>new Promise(resolve=>{finishDisconnected=resolve}))
  173. await disconnected.invoke({op:'prepare'});await disconnected.browser.disconnect()
  174. expect(disconnected.browser.installation.status).toBe('failed')
  175. finishDisconnected(false);await disconnected.browser.ready
  176. expect(disconnected.browser.installation.status).toBe('failed')
  177. expect(disconnected.installer.install).not.toHaveBeenCalled()
  178. })
  179. it('cancels an open request that is still waiting for the startup check',async()=>{
  180. const f=installationFixture();let finishProbe!:(value:boolean)=>void
  181. f.probe.mockImplementationOnce(()=>new Promise(resolve=>{finishProbe=resolve}))
  182. const result=f.invoke({op:'open'}).catch(error=>error)
  183. await f.invoke({op:'status'});await f.browser.disconnect()
  184. expect(await result).toBeInstanceOf(Error)
  185. finishProbe(true);await f.browser.ready;expect(f.runtime.open).not.toHaveBeenCalled()
  186. })
  187. it('deduplicates preparation and retains the grant beyond an individual RPC deadline',async()=>{
  188. vi.useFakeTimers();const f=installationFixture()
  189. await expect(f.invoke({op:'prepare'},Date.now()+1000)).resolves.toMatchObject({available:false,installation:{status:'installing'}})
  190. await f.invoke({op:'prepare'})
  191. expect(f.installer.install).toHaveBeenCalledTimes(1)
  192. await vi.advanceTimersByTimeAsync(4000)
  193. expect(f.signal().aborted).toBe(false);expect(f.check).toHaveBeenLastCalledWith(scope,grantId)
  194. f.complete();await vi.advanceTimersByTimeAsync(20)
  195. await expect(f.invoke({op:'status'})).resolves.toMatchObject({available:true,installation:{status:'ready'}})
  196. })
  197. it('keeps other authorized holders when one grant is revoked',async()=>{
  198. vi.useFakeTimers();const f=installationFixture(),otherGrant=randomUUID()
  199. await f.invoke({op:'prepare'});await f.invoke({op:'prepare',grantId:otherGrant})
  200. f.check.mockImplementation(async(_scope,grant)=>{if(grant===grantId)throw new Error('revoked')})
  201. await vi.advanceTimersByTimeAsync(2100);expect(f.signal().aborted).toBe(false)
  202. f.complete();await vi.advanceTimersByTimeAsync(20)
  203. expect(f.browser.available).toBe(true)
  204. })
  205. it('cancels when all holders lose authorization and requires an explicit retry',async()=>{
  206. vi.useFakeTimers();const f=installationFixture();await f.invoke({op:'prepare'})
  207. f.check.mockRejectedValue(new Error('revoked'));await vi.advanceTimersByTimeAsync(2100)
  208. expect(f.signal().aborted).toBe(true);expect(f.browser.installation.status).toBe('failed')
  209. f.check.mockResolvedValue(undefined);await f.invoke({op:'prepare'})
  210. expect(f.installer.install).toHaveBeenCalledTimes(1)
  211. await f.invoke({op:'prepare',retry:true});expect(f.installer.install).toHaveBeenCalledTimes(2)
  212. f.complete();await vi.advanceTimersByTimeAsync(20);expect(f.browser.available).toBe(true)
  213. })
  214. it('closing one holder does not cancel another holder, while disconnect cancels the job',async()=>{
  215. const f=installationFixture(),otherGrant=randomUUID()
  216. await f.invoke({op:'prepare'});await f.invoke({op:'prepare',grantId:otherGrant});await f.invoke({op:'close'})
  217. expect(f.signal().aborted).toBe(false)
  218. await f.browser.disconnect();expect(f.signal().aborted).toBe(true);expect(f.browser.available).toBe(false)
  219. expect(f.browser.installation.status).toBe('failed')
  220. })
  221. it('does not start a late preparation after disconnect interrupts authorization',async()=>{
  222. const f=installationFixture();let authorize!:()=>void
  223. f.check.mockImplementationOnce(()=>new Promise(resolve=>{authorize=resolve}))
  224. const result=f.invoke({op:'prepare'}).catch(error=>error)
  225. await vi.waitFor(()=>expect(f.check).toHaveBeenCalled());await f.browser.disconnect()
  226. authorize();expect(await result).toBeInstanceOf(Error)
  227. expect(f.installer.install).not.toHaveBeenCalled()
  228. })
  229. it('sanitizes failure details and never runs installation while disabled',async()=>{
  230. const f=installationFixture();await f.invoke({op:'prepare'});await vi.waitFor(()=>expect(f.installer.install).toHaveBeenCalled());f.fail(new Error('token=secret /Users/personal'))
  231. await vi.waitFor(()=>expect(f.browser.installation.status).toBe('failed'))
  232. expect(JSON.stringify(f.browser.installation)).not.toMatch(/secret|personal/)
  233. const disabled=fixture({enabled:false},f.installer)
  234. await expect(disabled.invoke({op:'status'})).resolves.toMatchObject({enabled:false,available:false,installation:{status:'missing'}})
  235. await expect(disabled.invoke({op:'prepare'})).rejects.toMatchObject({code:'browser_unavailable'})
  236. expect(f.installer.install).toHaveBeenCalledTimes(1)
  237. })
  238. })