@gen3/workspaces 0.12.71 → 0.12.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,8 @@
3
3
  var core = require('@gen3/core');
4
4
  var nodePath = require('path');
5
5
  var fs = require('fs');
6
+ var http = require('http');
7
+ var https = require('https');
6
8
  var cookiesNext = require('cookies-next');
7
9
  var server = require('@gen3/core/server');
8
10
  var server$1 = require('@gen3/frontend/server');
@@ -13,6 +15,134 @@ process.env.GEN3_KERNEL_API || `${core.GEN3_API}/lw-workspace/proxy/jeg-panel/ap
13
15
  process.env.JEG_GATEWAY_API || `${core.GEN3_API}/lw-workspace/proxy/jeg-panel/api`;
14
16
  const JEG_SERVICE_API = 'http://jupyter-enterprise-gateway.jupyter-pods.svc.cluster.local:8888';
15
17
 
18
+ /**
19
+ * Shared HTTP proxy utility for server-side proxy handlers.
20
+ * Streams request body through and forwards response status + body.
21
+ *
22
+ * Also exports two token helpers used by the proxy factories:
23
+ * - extractTokenFallback: minimal cookie/header extraction used when the host
24
+ * app has not injected its own getToken (standalone / test use).
25
+ * - decodeJwtClaims: base64url decode of the JWT payload for REMOTE_USER header.
26
+ * Crypto verification is Ambassador's job — we only need the sub/username claim.
27
+ */ /**
28
+ * Minimal JWT extraction fallback — used only when the host app does not inject
29
+ * its own getToken. Prefers Authorization: Bearer, then access_token cookie.
30
+ * In gen3-vectis production this is never reached — getAccessToken is always wired.
31
+ */ function extractTokenFallback(req) {
32
+ const auth = req.headers['authorization'];
33
+ if (typeof auth === 'string' && auth.startsWith('Bearer ')) {
34
+ return auth.slice(7).trim() || null;
35
+ }
36
+ const cookie = req.headers['cookie'] ?? '';
37
+ const m = cookie.match(/(?:^|;\s*)access_token=([^;]+)/);
38
+ return m ? decodeURIComponent(m[1]).trim() || null : null;
39
+ }
40
+ /**
41
+ * Decode JWT payload claims without cryptographic verification.
42
+ * Ambassador has already verified the RS256 signature — we just need the sub claim
43
+ * to set the REMOTE_USER header for per-user isolation enforcement downstream.
44
+ */ // Maximum JWT string length accepted before base64 decoding.
45
+ // GA4GH RAS Passport JWTs embed multiple signed Visa JWTs as claims, so the
46
+ // outer passport can easily exceed 8 KiB (50 visas × ~2 KB each ≈ 136 KB encoded).
47
+ // 512 KiB covers the most complex real-world passports while still guarding against
48
+ // crafted JWTs designed to exhaust server memory. Ambassador has already verified
49
+ // the RS256 signature — this cap only defends the local base64/JSON decode step.
50
+ const MAX_JWT_LENGTH = 524288; // 512 KiB
51
+ function decodeJwtClaims(jwt) {
52
+ if (jwt.length > MAX_JWT_LENGTH) return null;
53
+ try {
54
+ const parts = jwt.split('.');
55
+ if (parts.length < 2) return null;
56
+ const padded = parts[1].replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(parts[1].length / 4) * 4, '=');
57
+ return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+ async function createProxyRequest({ req, res, targetUrl, method, extraHeaders = {}, forwardBody = false }) {
63
+ const headers = {
64
+ ...extraHeaders
65
+ };
66
+ if (forwardBody && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
67
+ headers['Content-Type'] ??= 'application/json';
68
+ }
69
+ let body;
70
+ if (forwardBody && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
71
+ let buf;
72
+ try {
73
+ buf = await bufferBody(req);
74
+ } catch (err) {
75
+ const statusCode = err.statusCode ?? 400;
76
+ const msg = err instanceof Error ? err.message : 'Bad request';
77
+ res.status(statusCode).json({
78
+ error: msg
79
+ });
80
+ return;
81
+ }
82
+ // Node.js Buffer is a Uint8Array subclass; cast to silence DOM BodyInit mismatch
83
+ body = buf;
84
+ if (buf.length > 0) {
85
+ headers['Content-Length'] = String(buf.length);
86
+ }
87
+ }
88
+ let upRes;
89
+ try {
90
+ upRes = await fetch(targetUrl, {
91
+ method,
92
+ headers,
93
+ body,
94
+ signal: AbortSignal.timeout(30_000)
95
+ });
96
+ } catch (err) {
97
+ const msg = err instanceof Error ? err.message : String(err);
98
+ res.status(502).json({
99
+ error: `Upstream unreachable: ${msg}`
100
+ });
101
+ return;
102
+ }
103
+ // Forward status and content-type
104
+ const contentType = upRes.headers.get('content-type') || 'application/json';
105
+ res.setHeader('Content-Type', contentType);
106
+ if (upRes.status === 204 || upRes.status === 304) {
107
+ res.status(upRes.status).end();
108
+ return;
109
+ }
110
+ // Do not forward raw upstream error bodies — they may contain stack traces or
111
+ // internal hostnames. Log them server-side (CloudWatch) and return a generic message.
112
+ if (upRes.status >= 500) {
113
+ const errBody = await upRes.text().catch(()=>'');
114
+ console.error('[proxy] upstream %d from %s: %s', upRes.status, targetUrl, errBody);
115
+ res.status(502).json({
116
+ error: 'Upstream service error.'
117
+ });
118
+ return;
119
+ }
120
+ const responseBody = await upRes.text();
121
+ res.status(upRes.status).send(responseBody);
122
+ }
123
+ // Maximum request body size accepted by the proxy (1 MiB).
124
+ // Prevents memory exhaustion from oversized payloads before any business logic runs.
125
+ const MAX_BODY_BYTES = 1 * 1024 * 1024;
126
+ function bufferBody(req) {
127
+ return new Promise((resolve, reject)=>{
128
+ const chunks = [];
129
+ let total = 0;
130
+ req.on('data', (chunk)=>{
131
+ total += chunk.length;
132
+ if (total > MAX_BODY_BYTES) {
133
+ req.destroy();
134
+ reject(Object.assign(new Error('Request body too large'), {
135
+ statusCode: 413
136
+ }));
137
+ return;
138
+ }
139
+ chunks.push(chunk);
140
+ });
141
+ req.on('end', ()=>resolve(Buffer.concat(chunks)));
142
+ req.on('error', reject);
143
+ });
144
+ }
145
+
16
146
  const MAX_FILE_SIZE_BYTES = 67108864; // 64 * 1024 * 1024
17
147
  // ---------- constants ----------
18
148
  const ALLOWED_TIERS = new Set([
@@ -38,6 +168,14 @@ const MIME_TYPES = {
38
168
  '.ipynb': 'application/json; charset=utf-8'
39
169
  };
40
170
  const DEFAULT_FULL_THEMES_URL = '/workspace-api/workspace-assets/remote/build/themes';
171
+ /**
172
+ * First path segments that identify server extension REST APIs (not static assets).
173
+ * Requests whose first segment matches one of these are proxied to
174
+ * `serverExtensionProxyPath` when that option is configured for the remote tier.
175
+ */ const SERVER_EXTENSION_PREFIXES = new Set([
176
+ 'module',
177
+ 'server-proxy'
178
+ ]);
41
179
  const REMOTE_DISABLED_EXTENSIONS = [
42
180
  '@jupyterlite/services-extension:config-section-manager',
43
181
  '@jupyterlite/services-extension:default-drive',
@@ -178,6 +316,112 @@ function injectBranding(html, branding) {
178
316
  });
179
317
  return replaceTitle(result, branding);
180
318
  }
319
+ // ---------- server-extension proxy ----------
320
+ function readBody$2(req) {
321
+ return new Promise((resolve, reject)=>{
322
+ const chunks = [];
323
+ req.on('data', (chunk)=>chunks.push(chunk));
324
+ req.on('end', ()=>resolve(Buffer.concat(chunks)));
325
+ req.on('error', reject);
326
+ });
327
+ }
328
+ async function proxyServerExtension(req, res, targetUrl, getToken) {
329
+ const forwardHeaders = {};
330
+ for (const [key, value] of Object.entries(req.headers)){
331
+ if (!value) continue;
332
+ const lower = key.toLowerCase();
333
+ if (lower === 'host' || lower === 'content-length' || lower === 'transfer-encoding') continue;
334
+ forwardHeaders[key] = Array.isArray(value) ? value.join(',') : value;
335
+ }
336
+ // Inject identity headers so workspace-proxy auth passes.
337
+ // Direct server-side calls bypass nginx (which normally injects X-Gen3-User-ID /
338
+ // REMOTE_USER from the validated access_token), so we must add them explicitly.
339
+ // SECURITY: decodeJwtClaims below does not verify the JWT signature — it relies on
340
+ // Ambassador/revproxy having already done so before this code path is reached. When
341
+ // serverExtensionProxyBaseUrl (WORKSPACE_PROXY_URL) targets workspace-proxy directly,
342
+ // that verification is skipped entirely, so a caller could supply a correctly-shaped
343
+ // but unsigned/forged JWT to impersonate another user via REMOTE_USER/X-Gen3-User-ID.
344
+ // Only point serverExtensionProxyBaseUrl at a network path a user's own request cannot
345
+ // otherwise forge, or add real signature verification (e.g. against Fence's JWKS)
346
+ // here before trusting these claims.
347
+ const jwt = getToken ? getToken(req) : extractTokenFallback(req);
348
+ if (jwt) {
349
+ const claims = decodeJwtClaims(jwt);
350
+ const rawUsername = claims?.sub ?? claims?.preferred_username ?? claims?.username;
351
+ if (typeof rawUsername === 'string') {
352
+ const safeUsername = rawUsername.replace(/[\r\n]/g, '');
353
+ const safeJwt = jwt.replace(/[\r\n]/g, '');
354
+ forwardHeaders['Authorization'] = `Bearer ${safeJwt}`;
355
+ forwardHeaders['REMOTE_USER'] = safeUsername;
356
+ forwardHeaders['X-Gen3-User-ID'] = safeUsername;
357
+ }
358
+ }
359
+ const method = (req.method || 'GET').toUpperCase();
360
+ let body;
361
+ if (![
362
+ 'GET',
363
+ 'HEAD'
364
+ ].includes(method)) {
365
+ try {
366
+ body = await readBody$2(req);
367
+ } catch (error) {
368
+ const message = error instanceof Error ? error.message : String(error);
369
+ console.error(`[workspace-assets] failed to read request body for ${method} ${targetUrl}: ${message}`);
370
+ res.status(500).end('Failed to read request body');
371
+ return;
372
+ }
373
+ if (body?.length) {
374
+ forwardHeaders['content-length'] = String(body.length);
375
+ }
376
+ }
377
+ const startedAt = Date.now();
378
+ console.warn(`[workspace-assets] proxying ${method} ${targetUrl}${body?.length ? ` (body: ${body.length} bytes)` : ''}`);
379
+ await new Promise((resolve)=>{
380
+ const parsed = new URL(targetUrl);
381
+ const transport = parsed.protocol === 'https:' ? https : http;
382
+ const reqOptions = {
383
+ method,
384
+ hostname: parsed.hostname,
385
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
386
+ path: parsed.pathname + parsed.search,
387
+ headers: forwardHeaders
388
+ };
389
+ const proxyReq = transport.request(reqOptions, (proxyRes)=>{
390
+ const statusCode = proxyRes.statusCode ?? 502;
391
+ res.status(statusCode);
392
+ const skip = new Set([
393
+ 'transfer-encoding',
394
+ 'content-length'
395
+ ]);
396
+ for (const [key, value] of Object.entries(proxyRes.headers)){
397
+ if (!skip.has(key.toLowerCase()) && value !== undefined) {
398
+ res.setHeader(key, value);
399
+ }
400
+ }
401
+ const log = statusCode >= 400 ? console.error : console.warn;
402
+ log(`[workspace-assets] ${method} ${targetUrl} -> ${statusCode} (${Date.now() - startedAt}ms)`);
403
+ proxyRes.pipe(res, {
404
+ end: true
405
+ });
406
+ proxyRes.on('end', resolve);
407
+ });
408
+ proxyReq.on('error', (err)=>{
409
+ console.error(`[workspace-assets] extension proxy failed for ${method} ${targetUrl} after ${Date.now() - startedAt}ms: ${err.code ?? 'UNKNOWN'} ${err.message}`);
410
+ if (!res.headersSent) {
411
+ res.status(502).end('Extension proxy unreachable');
412
+ }
413
+ resolve();
414
+ });
415
+ proxyReq.on('timeout', ()=>{
416
+ console.error(`[workspace-assets] extension proxy timed out for ${method} ${targetUrl} after ${Date.now() - startedAt}ms`);
417
+ proxyReq.destroy();
418
+ });
419
+ if (body?.length) {
420
+ proxyReq.write(body);
421
+ }
422
+ proxyReq.end();
423
+ });
424
+ }
181
425
  // ---------- factory ----------
182
426
  function createWorkspaceAssetsHandler(options) {
183
427
  const gatewayBaseUrl = options?.gatewayBaseUrl ?? process.env.JUPYTER_GATEWAY_BASE_URL ?? '/api/workspace/gateway/';
@@ -193,6 +437,9 @@ function createWorkspaceAssetsHandler(options) {
193
437
  faviconUrl: options.faviconUrl,
194
438
  pageTitle: options.pageTitle
195
439
  } : undefined;
440
+ const serverExtensionProxyPath = options?.serverExtensionProxyPath;
441
+ const serverExtensionProxyBaseUrl = options?.serverExtensionProxyBaseUrl;
442
+ const getToken = options?.getToken;
196
443
  const remoteInjectionConfig = {
197
444
  gatewayBaseUrl,
198
445
  disabledExtensions,
@@ -251,6 +498,20 @@ function createWorkspaceAssetsHandler(options) {
251
498
  }
252
499
  safeSegments.push(nodePath.basename(seg));
253
500
  }
501
+ // Proxy server extension API calls (e.g. jupyterlmod /module/*, jupyter-server-proxy
502
+ // /server-proxy/*) to the configured upstream rather than attempting a static file
503
+ // lookup, which would always 404.
504
+ if (tier === 'remote' && serverExtensionProxyPath && safeSegments.length > 0 && SERVER_EXTENSION_PREFIXES.has(safeSegments[0])) {
505
+ const extensionPath = safeSegments.join('/');
506
+ const rawQuery = req.url?.split('?')[1];
507
+ const qs = rawQuery ? `?${rawQuery}` : '';
508
+ const proxyBase = serverExtensionProxyBaseUrl ?? (()=>{
509
+ const { proto, host } = resolveOrigin(req);
510
+ return `${proto}://${host}`;
511
+ })();
512
+ const targetUrl = `${proxyBase}${serverExtensionProxyPath}/${extensionPath}${qs}`;
513
+ return proxyServerExtension(req, res, targetUrl, getToken);
514
+ }
254
515
  const allowedFiles = allowedFilesByTier[tier];
255
516
  const candidatePath = nodePath.resolve(tierRoot, ...safeSegments);
256
517
  const candidateIndex = nodePath.join(candidatePath, 'index.html');
@@ -404,134 +665,6 @@ function withJupyterWorkspaces(nextConfig, options) {
404
665
  };
405
666
  }
406
667
 
407
- /**
408
- * Shared HTTP proxy utility for server-side proxy handlers.
409
- * Streams request body through and forwards response status + body.
410
- *
411
- * Also exports two token helpers used by the proxy factories:
412
- * - extractTokenFallback: minimal cookie/header extraction used when the host
413
- * app has not injected its own getToken (standalone / test use).
414
- * - decodeJwtClaims: base64url decode of the JWT payload for REMOTE_USER header.
415
- * Crypto verification is Ambassador's job — we only need the sub/username claim.
416
- */ /**
417
- * Minimal JWT extraction fallback — used only when the host app does not inject
418
- * its own getToken. Prefers Authorization: Bearer, then access_token cookie.
419
- * In gen3-vectis production this is never reached — getAccessToken is always wired.
420
- */ function extractTokenFallback(req) {
421
- const auth = req.headers['authorization'];
422
- if (typeof auth === 'string' && auth.startsWith('Bearer ')) {
423
- return auth.slice(7).trim() || null;
424
- }
425
- const cookie = req.headers['cookie'] ?? '';
426
- const m = cookie.match(/(?:^|;\s*)access_token=([^;]+)/);
427
- return m ? decodeURIComponent(m[1]).trim() || null : null;
428
- }
429
- /**
430
- * Decode JWT payload claims without cryptographic verification.
431
- * Ambassador has already verified the RS256 signature — we just need the sub claim
432
- * to set the REMOTE_USER header for per-user isolation enforcement downstream.
433
- */ // Maximum JWT string length accepted before base64 decoding.
434
- // GA4GH RAS Passport JWTs embed multiple signed Visa JWTs as claims, so the
435
- // outer passport can easily exceed 8 KiB (50 visas × ~2 KB each ≈ 136 KB encoded).
436
- // 512 KiB covers the most complex real-world passports while still guarding against
437
- // crafted JWTs designed to exhaust server memory. Ambassador has already verified
438
- // the RS256 signature — this cap only defends the local base64/JSON decode step.
439
- const MAX_JWT_LENGTH = 524288; // 512 KiB
440
- function decodeJwtClaims(jwt) {
441
- if (jwt.length > MAX_JWT_LENGTH) return null;
442
- try {
443
- const parts = jwt.split('.');
444
- if (parts.length < 2) return null;
445
- const padded = parts[1].replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(parts[1].length / 4) * 4, '=');
446
- return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
447
- } catch {
448
- return null;
449
- }
450
- }
451
- async function createProxyRequest({ req, res, targetUrl, method, extraHeaders = {}, forwardBody = false }) {
452
- const headers = {
453
- ...extraHeaders
454
- };
455
- if (forwardBody && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
456
- headers['Content-Type'] ??= 'application/json';
457
- }
458
- let body;
459
- if (forwardBody && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
460
- let buf;
461
- try {
462
- buf = await bufferBody(req);
463
- } catch (err) {
464
- const statusCode = err.statusCode ?? 400;
465
- const msg = err instanceof Error ? err.message : 'Bad request';
466
- res.status(statusCode).json({
467
- error: msg
468
- });
469
- return;
470
- }
471
- // Node.js Buffer is a Uint8Array subclass; cast to silence DOM BodyInit mismatch
472
- body = buf;
473
- if (buf.length > 0) {
474
- headers['Content-Length'] = String(buf.length);
475
- }
476
- }
477
- let upRes;
478
- try {
479
- upRes = await fetch(targetUrl, {
480
- method,
481
- headers,
482
- body,
483
- signal: AbortSignal.timeout(30_000)
484
- });
485
- } catch (err) {
486
- const msg = err instanceof Error ? err.message : String(err);
487
- res.status(502).json({
488
- error: `Upstream unreachable: ${msg}`
489
- });
490
- return;
491
- }
492
- // Forward status and content-type
493
- const contentType = upRes.headers.get('content-type') || 'application/json';
494
- res.setHeader('Content-Type', contentType);
495
- if (upRes.status === 204 || upRes.status === 304) {
496
- res.status(upRes.status).end();
497
- return;
498
- }
499
- // Do not forward raw upstream error bodies — they may contain stack traces or
500
- // internal hostnames. Log them server-side (CloudWatch) and return a generic message.
501
- if (upRes.status >= 500) {
502
- const errBody = await upRes.text().catch(()=>'');
503
- console.error('[proxy] upstream %d from %s: %s', upRes.status, targetUrl, errBody);
504
- res.status(502).json({
505
- error: 'Upstream service error.'
506
- });
507
- return;
508
- }
509
- const responseBody = await upRes.text();
510
- res.status(upRes.status).send(responseBody);
511
- }
512
- // Maximum request body size accepted by the proxy (1 MiB).
513
- // Prevents memory exhaustion from oversized payloads before any business logic runs.
514
- const MAX_BODY_BYTES = 1 * 1024 * 1024;
515
- function bufferBody(req) {
516
- return new Promise((resolve, reject)=>{
517
- const chunks = [];
518
- let total = 0;
519
- req.on('data', (chunk)=>{
520
- total += chunk.length;
521
- if (total > MAX_BODY_BYTES) {
522
- req.destroy();
523
- reject(Object.assign(new Error('Request body too large'), {
524
- statusCode: 413
525
- }));
526
- return;
527
- }
528
- chunks.push(chunk);
529
- });
530
- req.on('end', ()=>resolve(Buffer.concat(chunks)));
531
- req.on('error', reject);
532
- });
533
- }
534
-
535
668
  /* ------------------------------------------------------------------ */ /* Default billing sink — structured CloudWatch-compatible JSON log */ /* ------------------------------------------------------------------ */ function defaultBillingSink(event) {
536
669
  // CloudWatch Logs Insights picks up structured JSON automatically
537
670
  process.stdout.write(JSON.stringify({
@@ -1059,7 +1192,20 @@ const DEFAULT_OPTIONS = {
1059
1192
  // launches/channels to the container; GPU kernel launches are gated (403)
1060
1193
  // with a message to use the Kernel Panel.
1061
1194
  remoteKernelsPath: '/lw-workspace/proxy/jeg-proxy',
1062
- // The remote tier attaches to a real kernel gateway, so JupyterLite's
1195
+ // Proxy server extension REST calls (jupyterlmod /module/*, jupyter-server-proxy
1196
+ // /server-proxy/*) to jeg-proxy. These calls originate from JupyterLab extensions
1197
+ // in the remote build and resolve relative to the JupyterLite base URL, which points
1198
+ // at this static-file handler — without a proxy they always 404.
1199
+ serverExtensionProxyPath: '/lw-workspace/proxy',
1200
+ // Optional internal k8s service base URL for the extension proxy. When set,
1201
+ // proxy requests target this address directly instead of routing through the
1202
+ // ingress (avoiding self-signed-cert issues). Readable from the JSON config
1203
+ // file or the WORKSPACE_PROXY_URL env var.
1204
+ serverExtensionProxyBaseUrl: process.env.WORKSPACE_PROXY_URL || undefined,
1205
+ // Direct calls to serverExtensionProxyBaseUrl bypass nginx, which normally
1206
+ // injects the X-Gen3-User-ID/REMOTE_USER headers workspace-proxy requires —
1207
+ // reuse this app's cookie extraction to inject them explicitly instead.
1208
+ getToken: (req)=>server$1.getAccessToken(req.headers['cookie'] ?? '') ?? null,
1063
1209
  // in-browser Pyodide kernel must not be offered alongside it.
1064
1210
  additionalDisabledExtensions: [
1065
1211
  '@jupyterlite/pyodide-kernel-extension:kernel'
@@ -1073,7 +1219,9 @@ const STRING_OPTIONS = [
1073
1219
  'faviconUrl',
1074
1220
  'pageTitle',
1075
1221
  'remoteKernelsPath',
1076
- 'fullThemesUrl'
1222
+ 'fullThemesUrl',
1223
+ 'serverExtensionProxyPath',
1224
+ 'serverExtensionProxyBaseUrl'
1077
1225
  ];
1078
1226
  function configFilePath() {
1079
1227
  return nodePath.resolve(process.cwd(), CONFIG_ROOT, core.GEN3_COMMONS_NAME, CONFIG_FILENAME);