|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { jupyterProxyContract } from '@/lib/api/contracts/tools/jupyter' |
| 5 | +import { parseRequest } from '@/lib/api/server' |
| 6 | +import { checkInternalAuth } from '@/lib/auth/hybrid' |
| 7 | +import { |
| 8 | + secureFetchWithPinnedIP, |
| 9 | + validateUrlWithDNS, |
| 10 | +} from '@/lib/core/security/input-validation.server' |
| 11 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 12 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 13 | +import { buildJupyterAuthHeaders, normalizeJupyterServerUrl } from '@/tools/jupyter/utils' |
| 14 | + |
| 15 | +export const dynamic = 'force-dynamic' |
| 16 | + |
| 17 | +const logger = createLogger('JupyterProxyAPI') |
| 18 | + |
| 19 | +/** |
| 20 | + * Proxies Contents/Kernels/Kernelspecs/Sessions API calls to a self-hosted |
| 21 | + * Jupyter server. Self-hosted servers have no fixed public host, so every |
| 22 | + * request is server-side (DNS-pinned, http(s) allowed, redirects disabled) |
| 23 | + * rather than going through the generic external tool executor, which blocks |
| 24 | + * plain-HTTP and private-IP hosts by default. Mirrors the upstream status |
| 25 | + * and body verbatim so callers can treat this exactly like a direct fetch. |
| 26 | + */ |
| 27 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 28 | + const requestId = generateRequestId() |
| 29 | + |
| 30 | + try { |
| 31 | + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) |
| 32 | + if (!authResult.success || !authResult.userId) { |
| 33 | + logger.warn(`[${requestId}] Unauthorized Jupyter proxy attempt: ${authResult.error}`) |
| 34 | + return NextResponse.json( |
| 35 | + { success: false, error: authResult.error || 'Authentication required' }, |
| 36 | + { status: 401 } |
| 37 | + ) |
| 38 | + } |
| 39 | + |
| 40 | + const parsed = await parseRequest(jupyterProxyContract, request, {}) |
| 41 | + if (!parsed.success) return parsed.response |
| 42 | + const data = parsed.data.body |
| 43 | + |
| 44 | + const base = normalizeJupyterServerUrl(data.serverUrl) |
| 45 | + const url = `${base}/api/${data.path}` |
| 46 | + |
| 47 | + const urlValidation = await validateUrlWithDNS(url, 'serverUrl', { allowHttp: true }) |
| 48 | + if (!urlValidation.isValid || !urlValidation.resolvedIP) { |
| 49 | + return NextResponse.json( |
| 50 | + { success: false, error: `Invalid Jupyter serverUrl: ${urlValidation.error}` }, |
| 51 | + { status: 400 } |
| 52 | + ) |
| 53 | + } |
| 54 | + |
| 55 | + const hasBody = data.body !== undefined && data.body !== null |
| 56 | + |
| 57 | + const upstream = await secureFetchWithPinnedIP(url, urlValidation.resolvedIP, { |
| 58 | + method: data.method, |
| 59 | + headers: { |
| 60 | + ...buildJupyterAuthHeaders(data.token), |
| 61 | + ...(hasBody ? { 'Content-Type': 'application/json' } : {}), |
| 62 | + }, |
| 63 | + body: hasBody ? JSON.stringify(data.body) : undefined, |
| 64 | + allowHttp: true, |
| 65 | + maxRedirects: 0, |
| 66 | + }) |
| 67 | + |
| 68 | + const text = await upstream.text() |
| 69 | + |
| 70 | + return new NextResponse(text.length > 0 ? text : null, { |
| 71 | + status: upstream.status, |
| 72 | + headers: { 'Content-Type': upstream.headers.get('content-type') || 'application/json' }, |
| 73 | + }) |
| 74 | + } catch (error) { |
| 75 | + logger.error(`[${requestId}] Unexpected error:`, error) |
| 76 | + return NextResponse.json( |
| 77 | + { success: false, error: getErrorMessage(error, 'Unknown error') }, |
| 78 | + { status: 500 } |
| 79 | + ) |
| 80 | + } |
| 81 | +}) |
0 commit comments