Repository navigation
Expand file tree
/
Copy pathboxlite-proxy.controller.spec.ts
More file actions
474 lines (397 loc) · 19.5 KB
/
Copy pathboxlite-proxy.controller.spec.ts
File metadata and controls
474 lines (397 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
* SPDX-License-Identifier: AGPL-3.0
*/
import { EventEmitter } from 'node:events'
import { ForbiddenException, HttpStatus, NotFoundException, RequestMethod } from '@nestjs/common'
import { HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants'
import { Reflector } from '@nestjs/core'
import { createProxyMiddleware } from 'http-proxy-middleware'
import { BoxliteProxyController } from './boxlite-proxy.controller'
import { RequiredOrganizationResourcePermissions } from '../organization/decorators/required-organization-resource-permissions.decorator'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
jest.mock('http-proxy-middleware', () => ({
createProxyMiddleware: jest.fn(),
fixRequestBody: jest.fn(),
}))
jest.mock('uuid', () => ({ v4: jest.fn(() => 'mock-uuid'), validate: jest.fn(() => true) }))
const activeAuth = {
organizationId: 'org-1',
organization: { id: 'org-1', suspended: false } as any,
}
function makeHarness() {
const boxService = {
findOneByIdOrName: jest.fn().mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state: 'started',
inboundEnabled: true,
}),
updateLastActivityAt: jest.fn().mockResolvedValue(undefined),
getNetworkTunnelUrl: jest.fn().mockResolvedValue('https://3000-box.proxy.test'),
}
const runnerService = {
findOne: jest.fn().mockResolvedValue({ apiUrl: 'http://runner.local', apiKey: 'runner-key' }),
}
const autoResume = { ensureReady: jest.fn().mockResolvedValue(undefined) }
const tunnelService = {
prepare: jest.fn().mockResolvedValue({ isPublic: true, token: null }),
revoke: jest.fn().mockResolvedValue(undefined),
}
const controller = new (BoxliteProxyController as any)(
boxService,
runnerService,
autoResume,
tunnelService,
) as BoxliteProxyController
return { controller, boxService, autoResume, tunnelService }
}
describe('BoxliteProxyController', () => {
it('passes the private choice and returns only the URI and access descriptor', async () => {
const { controller, tunnelService } = makeHarness()
tunnelService.prepare.mockResolvedValue({ isPublic: false, token: 'blt_first-secret' })
await expect(
controller.proxyNetworkTunnel(activeAuth as never, 'mybox', 3000, { isPublic: false }),
).resolves.toEqual({ uri: 'https://3000-box.proxy.test', isPublic: false, token: 'blt_first-secret' })
expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, false)
})
beforeEach(() => jest.clearAllMocks())
afterEach(() => jest.useRealTimers())
it('requires box write permission to declare a public port', () => {
const reflector = new Reflector()
expect(
reflector.get(RequiredOrganizationResourcePermissions, BoxliteProxyController.prototype.proxyNetworkTunnel),
).toEqual([OrganizationResourcePermission.WRITE_BOXES])
})
it('revokes a public port with DELETE, answering 204, under box write permission', () => {
const reflector = new Reflector()
const handler = BoxliteProxyController.prototype.revokeNetworkTunnel
expect(Reflect.getMetadata(METHOD_METADATA, handler)).toBe(RequestMethod.DELETE)
expect(Reflect.getMetadata(PATH_METADATA, handler)).toBe(':boxId/network/tunnel')
expect(Reflect.getMetadata(HTTP_CODE_METADATA, handler)).toBe(HttpStatus.NO_CONTENT)
expect(reflector.get(RequiredOrganizationResourcePermissions, handler)).toEqual([
OrganizationResourcePermission.WRITE_BOXES,
])
})
it('revokes the port of the box the caller names, whatever its inbound mode or state', async () => {
const { controller, boxService, tunnelService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: false,
state: 'stopped',
inboundEnabled: false,
})
await controller.revokeNetworkTunnel(activeAuth as never, 'public-box', 3000)
expect(boxService.findOneByIdOrName).toHaveBeenCalledWith('public-box', 'org-1')
expect(tunnelService.revoke).toHaveBeenCalledWith('box-uuid', 3000)
})
it('does not revoke anything for a box outside the organization', async () => {
const { controller, boxService, tunnelService } = makeHarness()
boxService.findOneByIdOrName.mockRejectedValue(new NotFoundException('Box public-box not found'))
await expect(controller.revokeNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 404,
})
expect(tunnelService.revoke).not.toHaveBeenCalled()
})
it('rewrites public box ids to internal box ids before proxying exec', async () => {
const proxyHandler = jest.fn()
jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
const { controller, boxService } = makeHarness()
const req = { url: '/api/v1/boxes/public-box/exec' }
const res = {}
const next = jest.fn()
await controller.proxyExec(activeAuth as never, 'public-box', req as never, res as never, next)
const proxyOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
const pathRewrite = proxyOptions.pathRewrite as (path: string, req: unknown) => string
expect(pathRewrite('/api/v1/boxes/public-box/exec', req)).toBe('/v1/boxes/box-uuid/exec')
expect(boxService.findOneByIdOrName).toHaveBeenCalledWith('public-box', 'org-1')
expect(proxyHandler).toHaveBeenCalledWith(req, res, next)
})
it('disables the runner timeout for files only', async () => {
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller } = makeHarness()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())
const fileOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
const execOptions = jest.mocked(createProxyMiddleware).mock.calls[1][0]
expect(fileOptions.proxyTimeout).toBe(0)
expect(execOptions.proxyTimeout).toBe(300000)
})
// This hook is the only hop carrying the archive-shape hint through the
// hosted API. If it stops forwarding, every hosted copy_out silently
// degrades to Unknown and the client re-peeks the archive instead of
// trusting the guest — a correctness loss with no error to notice.
it('forwards the archive-shape hint from the runner response', async () => {
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller } = makeHarness()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
const proxyOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
const proxyRes = proxyOptions.on?.proxyRes as (p: unknown, q: unknown, r: unknown) => void
const res = { setHeader: jest.fn() }
proxyRes({ headers: { 'x-boxlite-source-is-dir': 'true' } }, {}, res)
expect(res.setHeader).toHaveBeenCalledWith('x-boxlite-source-is-dir', 'true')
})
// A runner that predates the hint sends no header. Forwarding a fabricated
// one would tell the client "single file" for a directory stream, so absence
// must stay absence rather than become a default.
it('sets no shape header when the runner sends none', async () => {
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller } = makeHarness()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
const proxyOptions = jest.mocked(createProxyMiddleware).mock.calls[0][0]
const proxyRes = proxyOptions.on?.proxyRes as (p: unknown, q: unknown, r: unknown) => void
const res = { setHeader: jest.fn() }
proxyRes({ headers: {} }, {}, res)
expect(res.setHeader).not.toHaveBeenCalled()
})
it('returns the public endpoint for JSON tunnel requests', async () => {
const { controller, boxService, tunnelService } = makeHarness()
const result = await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)
expect(boxService.getNetworkTunnelUrl).toHaveBeenCalledWith('public-box', 'org-1', 3000)
expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, true)
expect(boxService.getNetworkTunnelUrl.mock.invocationCallOrder[0]).toBeLessThan(
tunnelService.prepare.mock.invocationCallOrder[0],
)
expect(result).toEqual({ uri: 'https://3000-box.proxy.test', isPublic: true, token: null })
})
it('does not return a tunnel URI when the declaration cannot be saved', async () => {
const { controller, boxService, tunnelService } = makeHarness()
tunnelService.prepare.mockRejectedValue(new Error('database unavailable'))
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toThrow(
'database unavailable',
)
expect(boxService.getNetworkTunnelUrl).toHaveBeenCalledWith('public-box', 'org-1', 3000)
})
it('does not declare a public port when tunnel URL resolution fails', async () => {
const { controller, boxService, tunnelService } = makeHarness()
boxService.getNetworkTunnelUrl.mockRejectedValue(new Error('region unavailable'))
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toThrow(
'region unavailable',
)
expect(tunnelService.prepare).not.toHaveBeenCalled()
})
it('rejects a tunnel request for a box with inbound access disabled with 409', async () => {
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state: 'started',
inboundEnabled: false,
})
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 409,
})
expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
})
it('rejects a tunnel request for a stopped, non-autoResume box with 409', async () => {
const { controller, boxService, autoResume } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: false,
state: 'stopped',
inboundEnabled: true,
})
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 409,
// Pin the reason: without inboundEnabled: true this 409s at the visibility
// gate instead, and the state policy under test never runs.
message: expect.stringContaining('is not running'),
})
expect(autoResume.ensureReady).not.toHaveBeenCalled()
expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
})
it('hands a stopped autoResume box its tunnel URI without waking it', async () => {
// The CONNECT on that URI wakes the box through the proxy; waking it here
// too would only hold the caller for a start the proxy already covers.
const { controller, boxService, autoResume, tunnelService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state: 'stopped',
inboundEnabled: true,
})
const result = await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)
expect(autoResume.ensureReady).not.toHaveBeenCalled()
expect(tunnelService.prepare).toHaveBeenCalledWith('box-uuid', 3000, true)
expect(result).toEqual({ uri: 'https://3000-box.proxy.test', isPublic: true, token: null })
})
it('counts a tunnel request as activity so AutoStop does not reap the box', async () => {
// POL-326: without this the box we just handed out stays
// eligible for the idle sweeper, so the caller's tunnel dies under it.
const { controller, boxService } = makeHarness()
await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)
expect(boxService.updateLastActivityAt).toHaveBeenCalledWith('box-uuid', expect.any(Date))
})
it('does not record activity for a box it refuses to expose', async () => {
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state: 'started',
inboundEnabled: false,
})
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 409,
})
expect(boxService.updateLastActivityAt).not.toHaveBeenCalled()
})
it.each(['error', 'archived', 'archiving', 'destroying', 'resizing', 'unknown'])(
'rejects state %s with 409, even with autoResume',
async (state) => {
// The proxy's wake cannot bring these to STARTED, so their URI could
// only ever fail.
const { controller, boxService, autoResume } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state,
inboundEnabled: true,
})
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 409,
})
expect(autoResume.ensureReady).not.toHaveBeenCalled()
expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
},
)
it.each(['stopping', 'starting', 'creating', 'restoring'])(
'hands out the URI without waking an autoResume box in state %s',
async (state) => {
const { controller, boxService, autoResume } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
state,
inboundEnabled: true,
})
await controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)
expect(autoResume.ensureReady).not.toHaveBeenCalled()
expect(boxService.getNetworkTunnelUrl).toHaveBeenCalled()
},
)
it.each(['creating', 'starting', 'error', 'archived', 'unknown'])(
'rejects a tunnel request for a non-started box in state %s',
async (state) => {
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: false,
state,
inboundEnabled: true,
})
await expect(controller.proxyNetworkTunnel(activeAuth as never, 'public-box', 3000)).rejects.toMatchObject({
status: 409,
message: expect.stringContaining('is not running'),
})
expect(boxService.getNetworkTunnelUrl).not.toHaveBeenCalled()
},
)
it('auto-resumes exec and files but treats metrics as observation-only', async () => {
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller, boxService, autoResume } = makeHarness()
await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, {} as never, jest.fn())
expect(autoResume.ensureReady).toHaveBeenCalledTimes(2)
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)
autoResume.ensureReady.mockClear()
boxService.updateLastActivityAt.mockClear()
await controller.proxyMetrics(
activeAuth as never,
'public-box',
{ url: '/metrics' } as never,
{} as never,
jest.fn(),
)
expect(autoResume.ensureReady).not.toHaveBeenCalled()
expect(boxService.updateLastActivityAt).not.toHaveBeenCalled()
})
it('does not proxy when the strict AutoResume gate fails', async () => {
const proxyHandler = jest.fn()
jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
const { controller, autoResume } = makeHarness()
autoResume.ensureReady.mockRejectedValue(new Error('start failed'))
await expect(
controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn()),
).rejects.toThrow('start failed')
expect(proxyHandler).not.toHaveBeenCalled()
})
it('does not auto-resume a box whose autoResume switch is off', async () => {
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller, boxService, autoResume } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({ id: 'box-uuid', runnerId: 'runner-1', autoResume: false })
await controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn())
expect(autoResume.ensureReady).not.toHaveBeenCalled()
})
it('surfaces suspended-organization failures and never proxies', async () => {
const proxyHandler = jest.fn()
jest.mocked(createProxyMiddleware).mockReturnValue(proxyHandler as never)
const { controller, autoResume } = makeHarness()
autoResume.ensureReady.mockRejectedValue(new ForbiddenException('Organization is suspended'))
await expect(
controller.proxyExec(activeAuth as never, 'public-box', { url: '/exec' } as never, {} as never, jest.fn()),
).rejects.toThrow(ForbiddenException)
expect(proxyHandler).not.toHaveBeenCalled()
})
it('refreshes activity for the whole lifetime of a file transfer', async () => {
jest.useFakeTimers()
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
autoStop: 900,
})
const res = new EventEmitter()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)
jest.advanceTimersByTime(450_000)
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)
res.emit('close')
})
it('keeps the heartbeat below half the autoStop window for a one-second setting', async () => {
jest.useFakeTimers()
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
autoStop: 1,
})
const res = new EventEmitter()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)
// autoStop=1 → the heartbeat must fire within the window, not at its end.
jest.advanceTimersByTime(500)
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(2)
res.emit('close')
})
it('stops refreshing activity once the transfer completes', async () => {
jest.useFakeTimers()
jest.mocked(createProxyMiddleware).mockReturnValue(jest.fn() as never)
const { controller, boxService } = makeHarness()
boxService.findOneByIdOrName.mockResolvedValue({
id: 'box-uuid',
runnerId: 'runner-1',
autoResume: true,
autoStop: 900,
})
const res = new EventEmitter()
await controller.proxyFiles(activeAuth as never, 'public-box', { url: '/files' } as never, res as never, jest.fn())
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)
res.emit('close')
jest.advanceTimersByTime(900_000)
expect(boxService.updateLastActivityAt).toHaveBeenCalledTimes(1)
})
})