Repository navigation
Expand file tree
/
Copy pathboxlite-proxy.controller.ts
More file actions
382 lines (354 loc) · 13.1 KB
/
Copy pathboxlite-proxy.controller.ts
File metadata and controls
382 lines (354 loc) · 13.1 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
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
* SPDX-License-Identifier: AGPL-3.0
*/
import {
Controller,
All,
Get,
Delete,
Param,
Req,
Res,
Next,
UseGuards,
Logger,
NotFoundException,
ConflictException,
ForbiddenException,
GatewayTimeoutException,
RequestTimeoutException,
HttpCode,
HttpStatus,
ParseIntPipe,
Post,
Query,
} from '@nestjs/common'
import { ApiTags, ApiBearerAuth, ApiExcludeController } from '@nestjs/swagger'
import { createProxyMiddleware, fixRequestBody, Options } from 'http-proxy-middleware'
import { Request, Response, NextFunction } from 'express'
import { CombinedAuthGuard } from '../auth/combined-auth.guard'
import { OrganizationResourceActionGuard } from '../organization/guards/organization-resource-action.guard'
import { AuthContext } from '../common/decorators/auth-context.decorator'
import { OrganizationAuthContext } from '../common/interfaces/auth-context.interface'
import { BoxService } from '../box/services/box.service'
import { RunnerService } from '../box/services/runner.service'
import { AUTO_RESUME_TIMEOUT_SECONDS, BoxAutoResumeService } from './box-auto-resume.service'
import { BoxState } from '../box/enums/box-state.enum'
type ProxyActivityPolicy = { activity: boolean; autoResume: boolean }
const USER_OPERATION: ProxyActivityPolicy = { activity: true, autoResume: true }
const OBSERVATION_ONLY: ProxyActivityPolicy = { activity: false, autoResume: false }
// States a tunnel request may wait out: either the box is stopped (or on its
// way there) and can be started again, or it is already on its way up. Every
// other non-STARTED state — ERROR, ARCHIVED/ARCHIVING, DESTROYED/DESTROYING,
// RESIZING, UNKNOWN — either never reaches STARTED on its own or needs an
// explicit operator action, so waiting 30s to time out is strictly worse for
// the caller than an immediate 409.
const TUNNEL_RESUMABLE_STATES: readonly BoxState[] = [
BoxState.STOPPED,
BoxState.STOPPING,
BoxState.STARTING,
BoxState.CREATING,
BoxState.RESTORING,
]
// Spec-first surface (openapi/box.openapi.yaml). Must stay out of the product
// spec: @All() expands to the SEARCH verb, which OpenAPI 3.0 cannot express.
@ApiExcludeController()
@ApiTags('BoxLite REST')
@Controller(['v1/boxes', 'v1/:prefix/boxes'])
@UseGuards(CombinedAuthGuard, OrganizationResourceActionGuard)
@ApiBearerAuth()
export class BoxliteProxyController {
private readonly logger = new Logger(BoxliteProxyController.name)
constructor(
private readonly boxService: BoxService,
private readonly runnerService: RunnerService,
private readonly autoResume: BoxAutoResumeService,
) {}
@All(':boxId/exec')
async proxyExec(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/exec`,
req,
res,
next,
USER_OPERATION,
)
}
@All(':boxId/executions/:execId/signal')
async proxyExecSignal(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Param('execId') execId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/executions/${execId}/signal`,
req,
res,
next,
USER_OPERATION,
)
}
@All(':boxId/executions/:execId/resize')
async proxyExecResize(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Param('execId') execId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/executions/${execId}/resize`,
req,
res,
next,
USER_OPERATION,
)
}
@Get(':boxId/executions/:execId')
async proxyExecStatus(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Param('execId') execId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/executions/${execId}`,
req,
res,
next,
USER_OPERATION,
)
}
@Delete(':boxId/executions/:execId')
async proxyExecKill(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Param('execId') execId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/executions/${execId}`,
req,
res,
next,
USER_OPERATION,
)
}
// /executions/:execId/attach is a WebSocket-only route. Real WS upgrades
// bypass Express entirely and are handled by BoxliteWsProxyService via the
// `server.on('upgrade', ...)` hook registered in main.ts. Plain HTTP GETs
// to this path (callers that forgot the Upgrade headers) fall through to
// a NestJS 404, which is the correct answer.
@All(':boxId/files')
async proxyFiles(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
const query = req.url.includes('?') ? req.url.substring(req.url.indexOf('?')) : ''
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/files${query}`,
req,
res,
next,
USER_OPERATION,
{ proxyTimeoutMs: 0 },
)
}
@All(':boxId/metrics')
async proxyMetrics(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Req() req: Request,
@Res() res: Response,
@Next() next: NextFunction,
) {
return this.proxyToRunner(
authContext,
boxId,
(runnerBoxId) => `/v1/boxes/${runnerBoxId}/metrics`,
req,
res,
next,
OBSERVATION_ONLY,
)
}
@Post(':boxId/network/tunnel')
@HttpCode(HttpStatus.OK)
async proxyNetworkTunnel(
@AuthContext() authContext: OrganizationAuthContext,
@Param('boxId') boxId: string,
@Query('port', ParseIntPipe) port: number,
@Res({ passthrough: true }) res: Response,
) {
// findOneByIdOrName already 404s for a missing/destroyed box. Unlike
// proxyToRunner's other routes, this endpoint just resolves a URL — it
// never reaches the runner, so a non-running box would otherwise hand
// back a tunnel URI that CONNECTs successfully and then goes silently
// dead. Whitelist STARTED rather than blacklist STOPPED: a box that's
// still CREATING/STARTING/ERROR/ARCHIVED/etc. isn't reachable either.
//
const box = await this.boxService.findOneByIdOrName(boxId, authContext.organizationId)
// POL-205: tunnel URLs expose the box to the public internet. Require the
// caller to have explicitly opted in by setting public: true on the box.
// A private box should be accessed via the authenticated API, not a
// tunnel. Checked before the state gate below so a private box is never
// woken (ensureReady is a real resume, not a free status read) only to
// be rejected here anyway.
if (!box.public) {
throw new ConflictException(`Box ${boxId} is not public; set public: true before opening a tunnel`)
}
// POL-326/POL-352: opening a tunnel is user activity, exactly like the
// proxyToRunner routes. Persist it before the readiness gate so the
// AutoStop sweeper cannot reap the box we are about to hand out (or just
// woke up); the sweeper rechecks this Redis-buffered timestamp after
// taking its state lock.
await this.boxService
.updateLastActivityAt(box.id, new Date())
.catch((err) => this.logger.warn(`updateLastActivityAt failed for ${box.id}: ${err}`))
// POL-352: mirror proxyToRunner's policy — a stopped box that opted into
// autoResume gets woken here rather than rejected, since minting the
// tunnel URI is the caller's only touchpoint before the CONNECT itself
// (which has no box row to check against).
if (box.state !== BoxState.STARTED) {
if (!box.autoResume || !TUNNEL_RESUMABLE_STATES.includes(box.state)) {
throw new ConflictException(`Box ${boxId} is not running (state: ${box.state})`)
}
await this.resumeForTunnel(box.id, authContext, res)
}
const uri = await this.boxService.getNetworkTunnelUrl(boxId, authContext.organizationId, port)
return { uri }
}
// A resume that outlives its window is a "come back later", not a client
// error: POL-352 asks for 504 + Retry-After so a caller (or an SDK mapping
// this to BoxResumeTimeoutError) can retry the same request instead of
// treating the box as broken. The underlying start is still in flight.
private async resumeForTunnel(boxId: string, authContext: OrganizationAuthContext, res: Response): Promise<void> {
try {
await this.autoResume.ensureReady(boxId, authContext.organization)
} catch (err) {
if (err instanceof RequestTimeoutException) {
res.setHeader('Retry-After', String(AUTO_RESUME_TIMEOUT_SECONDS))
throw new GatewayTimeoutException(`Timed out waiting to resume box ${boxId}`)
}
throw err
}
}
private async proxyToRunner(
authContext: OrganizationAuthContext,
boxId: string,
targetPathForRunnerBox: (runnerBoxId: string) => string,
req: Request,
res: Response,
next: NextFunction,
policy: ProxyActivityPolicy,
opts?: { ws?: boolean; proxyTimeoutMs?: number },
) {
const box = await this.boxService.findOneByIdOrName(boxId, authContext.organizationId)
if (!box) {
throw new NotFoundException(`Box ${boxId} not found`)
}
if (policy.activity) {
// Persist activity before the readiness gate. The lifecycle sweeper rechecks
// this Redis-buffered timestamp after taking its state lock, closing the
// request-vs-AutoStop race without holding a lock through cold start.
await this.boxService
.updateLastActivityAt(box.id, new Date())
.catch((err) => this.logger.warn(`updateLastActivityAt failed for ${box.id}: ${err}`))
}
if (policy.activity && typeof box.autoStop === 'number' && box.autoStop > 0) {
// A long-running operation (a file upload/download, a streaming exec) is
// still activity for its whole lifetime, not just its first request.
// Refresh the idle timer periodically so the AutoStop sweeper does not
// reap the box mid-transfer; stop once the response completes or errors.
const stopHeartbeat = this.startActivityHeartbeat(box.id, box.autoStop)
let stopped = false
const stop = (): void => {
if (stopped) return
stopped = true
stopHeartbeat()
}
res.once('close', stop)
res.once('finish', stop)
res.once('error', stop)
}
if (policy.autoResume && box.autoResume) {
await this.autoResume.ensureReady(box.id, authContext.organization)
}
const runner = await this.runnerService.findOne(box.runnerId)
if (!runner) {
throw new NotFoundException(`Runner for box ${boxId} not found`)
}
const targetUrl = runner.apiUrl || runner.proxyUrl
if (!targetUrl) {
throw new NotFoundException(`Runner endpoint for box ${boxId} not found`)
}
const proxyOptions: Options = {
target: targetUrl,
secure: false,
changeOrigin: true,
autoRewrite: true,
ws: opts?.ws ?? false,
pathRewrite: () => targetPathForRunnerBox(box.id),
on: {
proxyReq: (proxyReq: any, originalReq: any) => {
proxyReq.setHeader('Authorization', `Bearer ${runner.apiKey}`)
fixRequestBody(proxyReq, originalReq)
},
proxyRes: (proxyRes: any, _req: any, res: any) => {
// Carry the file-download archive-shape hint through the proxy so the
// client's copy_out can distinguish single-file vs directory streams.
const shape = proxyRes.headers?.['x-boxlite-source-is-dir']
if (shape) {
res.setHeader('x-boxlite-source-is-dir', shape)
}
},
},
proxyTimeout: opts?.proxyTimeoutMs ?? 5 * 60 * 1000,
}
return createProxyMiddleware(proxyOptions)(req, res, next)
}
private startActivityHeartbeat(boxId: string, autoStopSeconds: number): () => void {
// Half the autoStop window (in ms) so the idle deadline can never lapse
// between two beats, however the sweeper samples it. Redis writes are
// throttled by the activity service's own per-box lock.
const intervalMs = autoStopSeconds * 500
const timer = setInterval(() => {
void this.boxService
.updateLastActivityAt(boxId, new Date())
.catch((err) => this.logger.warn(`updateLastActivityAt heartbeat failed for ${boxId}: ${err}`))
}, intervalMs)
timer.unref?.()
return () => clearInterval(timer)
}
}