From 90b6b2801b658bf29a8e1fafbf1ce42a5bad44c5 Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:01:43 +0800 Subject: [PATCH 1/2] chore: checkpoint QZa50tfK3Gq7DmsBMl5UZ --- worker/src/index.ts | 6 + worker/src/lib/__tests__/spark-access.test.ts | 95 +++- worker/src/lib/auth.ts | 40 ++ worker/src/lib/spark-access.ts | 136 ++++++ worker/src/lib/spark-worker-link.ts | 61 +++ worker/src/middleware/auth.ts | 29 +- worker/src/middleware/security.ts | 7 +- .../src/routes/__tests__/admin-spark.test.ts | 98 ++++ worker/src/routes/__tests__/databases.test.ts | 44 ++ .../routes/__tests__/spark-history.test.ts | 16 + worker/src/routes/__tests__/spark-ui.test.ts | 24 + .../src/routes/__tests__/spark-worker.test.ts | 418 ++++++++++++++++++ worker/src/routes/admin.ts | 43 +- worker/src/routes/auth.ts | 7 + worker/src/routes/databases.ts | 3 + worker/src/routes/spark-history.ts | 36 +- worker/src/routes/spark-ui.ts | 30 +- worker/src/routes/spark-worker.ts | 408 +++++++++++++++++ 18 files changed, 1479 insertions(+), 22 deletions(-) create mode 100644 worker/src/lib/spark-worker-link.ts create mode 100644 worker/src/routes/__tests__/spark-worker.test.ts create mode 100644 worker/src/routes/spark-worker.ts diff --git a/worker/src/index.ts b/worker/src/index.ts index 4b07f252..d7147b92 100644 --- a/worker/src/index.ts +++ b/worker/src/index.ts @@ -28,6 +28,7 @@ import admin from './routes/admin' import setup from './routes/setup' import sparkUi, { sparkUiApi } from './routes/spark-ui' import sparkHistory, { sparkHistoryApi } from './routes/spark-history' +import sparkWorker, { sparkWorkerApi } from './routes/spark-worker' const app = new Hono<{ Bindings: Env; Variables: Variables }>() @@ -73,6 +74,7 @@ app.route('/api/admin', admin) app.route('/api/setup', setup) app.route('/api/spark-ui', sparkUiApi) app.route('/api/spark-history', sparkHistoryApi) +app.route('/api/spark-worker', sparkWorkerApi) // ── Waker callback (periodic log-archive cleanup, frozen contract v2) ────────── @@ -206,6 +208,10 @@ app.route('/spark-ui', sparkUi) app.route('/spark-history', sparkHistory) +// ── Worker UI proxy ────────────────────────────────────────────────────────── + +app.route('/spark-worker', sparkWorker) + // ── Serve SPA (Workers Assets fallback) ────────────────────────────────────── app.all('*', async (c) => { diff --git a/worker/src/lib/__tests__/spark-access.test.ts b/worker/src/lib/__tests__/spark-access.test.ts index 56730e2e..9d70dc52 100644 --- a/worker/src/lib/__tests__/spark-access.test.ts +++ b/worker/src/lib/__tests__/spark-access.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { hasHistoryServer, hasLivyConfig, hasSparkUi, normalizeSparkAccess } from '../spark-access' +import { hasHistoryServer, hasLivyConfig, hasSparkUi, hasWorkerUi, normalizeSparkAccess } from '../spark-access' // A made-up published address: no real host or token appears here. @@ -12,6 +12,8 @@ const LIVY_URL = 'https://livy-3f9a.publish.example.dev' const LIVY_TOKEN = 'livy-token-qwe456' const HISTORY_URL = 'https://history-18080.publish.example.dev' const HISTORY_TOKEN = 'history-token-asd789' +const WORKER_URL = 'https://worker-8082.publish.example.dev' +const WORKER_TOKEN = 'worker-token-zxc456' const payload = (over: Record = {}) => ({ url: URL, @@ -345,4 +347,95 @@ describe('normalizeSparkAccess', () => { expect(hasHistoryServer({ history_url: HISTORY_URL, history_platform_token: HISTORY_TOKEN })).toBe(true) }) }) + + describe('worker ui fields', () => { + it('splits a pasted publish link into a clean address and a separate platform token', () => { + const result = normalizeSparkAccess( + payload({ + worker_ui_url: `${WORKER_URL}/worker/?_token=${WORKER_TOKEN}`, + }) + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.access.worker_url).toBe(`${WORKER_URL}/worker`) + expect(result.access.worker_platform_token).toBe(WORKER_TOKEN) + expect(hasWorkerUi(result.access)).toBe(true) + }) + + it('accepts the normalised stored shape so a sealed payload round-trips', () => { + const result = normalizeSparkAccess( + payload({ + worker_url: `${WORKER_URL}/worker`, + worker_platform_token: ` ${WORKER_TOKEN} `, + }) + ) + expect(result.ok).toBe(true) + if (!result.ok) return + expect(result.access.worker_url).toBe(`${WORKER_URL}/worker`) + expect(result.access.worker_platform_token).toBe(WORKER_TOKEN) + expect(hasWorkerUi(result.access)).toBe(true) + }) + + it('requires the publish link to carry an address token', () => { + const result = normalizeSparkAccess(payload({ worker_ui_url: WORKER_URL })) + expect(result.ok).toBe(false) + expect(!result.ok && result.error).toContain('_token') + }) + + it('rejects a publish link that is not https, has credentials, or an unsendable token', () => { + expect( + normalizeSparkAccess(payload({ worker_ui_url: `http://worker.example.com?_token=${WORKER_TOKEN}` })).ok + ).toBe(false) + expect( + normalizeSparkAccess(payload({ worker_ui_url: `https://u:p@worker.example.com?_token=${WORKER_TOKEN}` })).ok + ).toBe(false) + expect(normalizeSparkAccess(payload({ worker_ui_url: `${WORKER_URL}/?_token=bad token` })).ok).toBe(false) + }) + + it('rejects providing both the publish link and the separate stored fields', () => { + const result = normalizeSparkAccess( + payload({ + worker_ui_url: `${WORKER_URL}/?_token=${WORKER_TOKEN}`, + worker_url: WORKER_URL, + worker_platform_token: WORKER_TOKEN, + }) + ) + expect(result.ok).toBe(false) + expect(!result.ok && result.error).toContain('not both') + }) + + it('requires the separate stored fields to be paired', () => { + const onlyUrl = normalizeSparkAccess(payload({ worker_url: WORKER_URL })) + expect(onlyUrl.ok).toBe(false) + expect(!onlyUrl.ok && onlyUrl.error).toContain('together') + + const onlyToken = normalizeSparkAccess(payload({ worker_platform_token: WORKER_TOKEN })) + expect(onlyToken.ok).toBe(false) + expect(!onlyToken.ok && onlyToken.error).toContain('together') + }) + + it('never echoes the Worker UI link or token in errors', () => { + const cases = [ + payload({ worker_ui_url: `http://worker.example.com?_token=${WORKER_TOKEN}` }), + payload({ worker_ui_url: `${WORKER_URL}/?_token=bad token` }), + payload({ worker_url: WORKER_URL }), + ] + for (const input of cases) { + const result = normalizeSparkAccess(input) + expect(result.ok).toBe(false) + const error = (result as { error: string }).error + expect(error).not.toContain(WORKER_URL) + expect(error).not.toContain(WORKER_TOKEN) + } + }) + + it('hasWorkerUi correctly evaluates payloads', () => { + expect(hasWorkerUi(null)).toBe(false) + expect(hasWorkerUi({})).toBe(false) + expect(hasWorkerUi({ worker_url: WORKER_URL })).toBe(false) + expect(hasWorkerUi({ worker_platform_token: WORKER_TOKEN })).toBe(false) + expect(hasWorkerUi({ worker_url: '', worker_platform_token: WORKER_TOKEN })).toBe(false) + expect(hasWorkerUi({ worker_url: WORKER_URL, worker_platform_token: WORKER_TOKEN })).toBe(true) + }) + }) }) diff --git a/worker/src/lib/auth.ts b/worker/src/lib/auth.ts index 3e653a2a..62a1e59d 100644 --- a/worker/src/lib/auth.ts +++ b/worker/src/lib/auth.ts @@ -114,11 +114,22 @@ export interface HistoryServerSessionPayload extends RegisteredClaims { type: 'history_server' } +export interface WorkerUiSessionPayload extends RegisteredClaims { + sub: string + role: 'admin' | 'member' + db: string + jti: string + iat: number + exp: number + type: 'worker_ui' +} + const ACCESS_TTL = 15 * 60 // 15 min const REFRESH_TTL = 7 * 24 * 3600 // 7 days const PENDING_TTL = 10 * 60 // 10 min export const SPARK_UI_SESSION_TTL = 24 * 3600 // 24 hours export const HISTORY_SERVER_SESSION_TTL = 24 * 3600 // 24 hours +export const WORKER_UI_SESSION_TTL = 24 * 3600 // 24 hours async function hmacKey(secret: string): Promise { return crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [ @@ -310,6 +321,35 @@ export async function verifyHistoryServerSessionToken( return payload } +export async function createWorkerUiSessionToken( + args: { userId: string; role: 'admin' | 'member'; databaseId: string }, + env: JwtEnv +): Promise { + const now = Math.floor(Date.now() / 1000) + return signJwt( + { + sub: args.userId, + role: args.role, + db: args.databaseId, + jti: crypto.randomUUID(), + iat: now, + exp: now + WORKER_UI_SESSION_TTL, + type: 'worker_ui', + }, + env + ) +} + +export async function verifyWorkerUiSessionToken( + token: string | undefined, + env: JwtEnv +): Promise { + if (!token) return null + const payload = await verifyJwt(token, env) + if (payload?.type !== 'worker_ui') return null + return payload +} + export async function revokeRefreshToken(env: Env, jti: string): Promise { await env.KV.put(KV.jtiDeny(jti), '1', { expirationTtl: REFRESH_TTL }) } diff --git a/worker/src/lib/spark-access.ts b/worker/src/lib/spark-access.ts index 58183093..f94993f1 100644 --- a/worker/src/lib/spark-access.ts +++ b/worker/src/lib/spark-access.ts @@ -22,6 +22,8 @@ export interface SparkAccess { livy_platform_token?: string history_url?: string history_platform_token?: string + worker_url?: string + worker_platform_token?: string } export interface SparkAccessOk { @@ -66,6 +68,74 @@ function readToken(value: unknown, label: string): { ok: true; token: string } | return { ok: true, token } } +// A Worker UI publish link is the single field an admin pastes: the full published address that +// carries the platform token as `?_token=`. The normaliser splits the token out and stores the +// clean address, so the token only ever travels as a `Authorization: Bearer` header. +function splitWorkerPublishLink( + raw: string, + label: string +): { ok: true; url: string; token: string } | { ok: false; error: string } { + if (raw.length > MAX_URL_LENGTH) return { ok: false, error: `The ${label} publish link is too long.` } + + let parsed: URL + try { + parsed = new URL(raw) + } catch { + return { ok: false, error: `That is not a valid ${label} publish link.` } + } + if (parsed.protocol !== 'https:') return { ok: false, error: `The ${label} publish link must start with https://.` } + if (!parsed.hostname) return { ok: false, error: `The ${label} publish link is missing a host.` } + if (parsed.username || parsed.password) { + return { ok: false, error: `The ${label} publish link must not carry a username or password.` } + } + + let token = '' + for (const [key, value] of parsed.searchParams.entries()) { + if (URL_TOKEN_PARAMETERS.has(key.toLowerCase())) { + token = value + break + } + } + if (!token.trim()) { + return { ok: false, error: `The ${label} publish link must carry an address token (?_token=).` } + } + const tokenResult = readToken(token, `${label} address token`) + if (!tokenResult.ok) return tokenResult + + return { + ok: true, + url: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}`, + token: tokenResult.token, + } +} + +// The stored, normalised shape (`worker_url` + `worker_platform_token`) must round-trip through +// this same normaliser, so an old or hand-edited row can never smuggle a different URL shape in. +function validateWorkerPublishUrl( + raw: string, + label: string +): { ok: true; url: string } | { ok: false; error: string } { + if (raw.length > MAX_URL_LENGTH) return { ok: false, error: `The ${label} publish URL is too long.` } + + let parsed: URL + try { + parsed = new URL(raw) + } catch { + return { ok: false, error: `That is not a valid ${label} publish URL.` } + } + if (parsed.protocol !== 'https:') return { ok: false, error: `The ${label} publish URL must start with https://.` } + if (!parsed.hostname) return { ok: false, error: `The ${label} publish URL is missing a host.` } + if (parsed.username || parsed.password) { + return { ok: false, error: `The ${label} publish URL must not carry a username or password.` } + } + for (const key of parsed.searchParams.keys()) { + if (URL_TOKEN_PARAMETERS.has(key.toLowerCase())) { + return { ok: false, error: `The ${label} publish URL carries an address token; it must not.` } + } + } + return { ok: true, url: `${parsed.origin}${parsed.pathname.replace(/\/+$/, '')}` } +} + // Validates one payload — a pasted registration or a stored, unsealed one — and rewrites it into the // exact form that is sealed and handed to the executor. Errors are deliberately generic: the input // carries both tokens. @@ -268,6 +338,46 @@ export function normalizeSparkAccess(input: unknown): SparkAccessResult { history_platform_token = historyToken.token } + // Worker UI publish configuration. Unlike the other Spark ports it is registered from a single + // pasted publish link (`worker_ui_url`) whose token rides in `?_token=`; the stored, normalised + // shape (`worker_url` + `worker_platform_token`) is also accepted so the sealed payload + // round-trips here. + const rawWorkerPublish = typeof payload.worker_ui_url === 'string' ? payload.worker_ui_url.trim() : '' + const rawWorkerUrl = typeof payload.worker_url === 'string' ? payload.worker_url.trim() : '' + const rawWorkerToken = typeof payload.worker_platform_token === 'string' ? payload.worker_platform_token.trim() : '' + const hasWorkerPublish = rawWorkerPublish.length > 0 + const hasWorkerUrl = rawWorkerUrl.length > 0 + const hasWorkerToken = rawWorkerToken.length > 0 + + if (hasWorkerPublish && (hasWorkerUrl || hasWorkerToken)) { + return { + ok: false, + error: 'Provide the Worker UI either as a publish link or as separate url and token fields, not both.', + } + } + + let worker_url: string | undefined + let worker_platform_token: string | undefined + + if (hasWorkerPublish) { + const link = splitWorkerPublishLink(rawWorkerPublish, 'Worker UI') + if (!link.ok) return link + worker_url = link.url + worker_platform_token = link.token + } else if (hasWorkerUrl !== hasWorkerToken) { + return { + ok: false, + error: 'worker_url and worker_platform_token must be provided together, or both omitted.', + } + } else if (hasWorkerUrl && hasWorkerToken) { + const workerToken = readToken(payload.worker_platform_token, 'Worker UI platform token') + if (!workerToken.ok) return workerToken + const workerUrl = validateWorkerPublishUrl(rawWorkerUrl, 'Worker UI') + if (!workerUrl.ok) return workerUrl + worker_url = workerUrl.url + worker_platform_token = workerToken.token + } + return { ok: true, access: { @@ -277,6 +387,7 @@ export function normalizeSparkAccess(input: unknown): SparkAccessResult { ...(ui_url && ui_platform_token ? { ui_url, ui_platform_token } : {}), ...(livy_url && livy_platform_token ? { livy_url, livy_platform_token } : {}), ...(history_url && history_platform_token ? { history_url, history_platform_token } : {}), + ...(worker_url && worker_platform_token ? { worker_url, worker_platform_token } : {}), }, host: parsed.hostname, } @@ -315,6 +426,17 @@ export function hasHistoryServer(access: unknown): boolean { ) } +export function hasWorkerUi(access: unknown): boolean { + if (!access || typeof access !== 'object') return false + const a = access as Record + return ( + typeof a.worker_url === 'string' && + a.worker_url.trim().length > 0 && + typeof a.worker_platform_token === 'string' && + a.worker_platform_token.trim().length > 0 + ) +} + export async function checkDatabaseHasSparkUi( env: Env, row: { kind?: string | null; connection_secret?: string | null } @@ -356,3 +478,17 @@ export async function checkDatabaseHasHistoryServer( return false } } + +export async function checkDatabaseHasWorkerUi( + env: Env, + row: { kind?: string | null; connection_secret?: string | null } +): Promise { + if (row.kind !== 'spark' || !row.connection_secret) return false + try { + const raw = await openSecret(env, row.connection_secret) + const payload = JSON.parse(raw) + return hasWorkerUi(payload) + } catch { + return false + } +} diff --git a/worker/src/lib/spark-worker-link.ts b/worker/src/lib/spark-worker-link.ts new file mode 100644 index 00000000..2e234bae --- /dev/null +++ b/worker/src/lib/spark-worker-link.ts @@ -0,0 +1,61 @@ +// ── Spark Worker UI link rewriting ────────────────────────────────────────────────────────────── +// Spark's application UI and History Server emit executor log links that point straight at the +// Worker UI host Spark runs on, e.g. `spark:8082/logPage/?appId=…&executorId=…&logType=…`. That +// host is a container-internal name the browser cannot resolve, so the two proxies rewrite those +// links into Zeta's Worker UI reverse proxy mount, carrying the database context through the same +// `?db=` first-hit mechanism `/spark-ui` uses. + +export const SPARK_WORKER_MOUNT = '/spark-worker' + +// Fixed by the apollo deployment's entrypoint: Master is 8081, the query service 8080, and the +// Worker UI 8082. The rewrite target is therefore the fixed host `spark:8082`, never discovered. +const SPARK_WORKER_UI_HOST = 'spark' +const SPARK_WORKER_UI_PORT = '8082' +const SPARK_WORKER_HOST_PORT = `${SPARK_WORKER_UI_HOST}:${SPARK_WORKER_UI_PORT}` + +// Spark emits the Worker UI address as a bare `host:port` (parsed by a browser as a `spark:` URL +// scheme), but tolerate the absolute and protocol-relative spellings too. +function stripScheme(value: string): string { + const lower = value.toLowerCase() + if (lower.startsWith('http://')) return value.slice('http://'.length) + if (lower.startsWith('https://')) return value.slice('https://'.length) + if (lower.startsWith('//')) return value.slice(2) + return value +} + +/** + * Rewrites a value that points at the fixed Worker UI host (`spark:8082`) into the Worker UI + * reverse proxy mount with the database context attached as `?db=`. Returns null for anything + * else, so callers can fall through to their normal rewriting. + */ +export function rewriteSparkWorkerLink(val: string, databaseId: string): string | null { + if (!val || typeof val !== 'string') return null + const trimmed = val.trim() + if (!trimmed) return null + + const body = stripScheme(trimmed) + if (!body.toLowerCase().startsWith(SPARK_WORKER_HOST_PORT)) return null + let rest = body.slice(SPARK_WORKER_HOST_PORT.length) + if (rest.length > 0 && !rest.startsWith('/') && !rest.startsWith('?') && !rest.startsWith('#')) { + return null + } + + let hash = '' + const hashIdx = rest.indexOf('#') + if (hashIdx >= 0) { + hash = rest.slice(hashIdx) + rest = rest.slice(0, hashIdx) + } + let query = '' + const queryIdx = rest.indexOf('?') + if (queryIdx >= 0) { + query = rest.slice(queryIdx) + rest = rest.slice(0, queryIdx) + } + const path = rest.startsWith('/') ? rest : `/${rest}` + + const search = new URLSearchParams(query) + search.set('db', databaseId) + const searchString = search.toString() + return `${SPARK_WORKER_MOUNT}${path}${searchString ? `?${searchString}` : ''}${hash}` +} diff --git a/worker/src/middleware/auth.ts b/worker/src/middleware/auth.ts index be057ad0..6c4b9fdc 100644 --- a/worker/src/middleware/auth.ts +++ b/worker/src/middleware/auth.ts @@ -1,8 +1,14 @@ import type { Context, MiddlewareHandler } from 'hono' import { getCookie } from 'hono/cookie' import type { Env, Variables } from '../types' -import { verifyAccessToken, verifyHistoryServerSessionToken, verifySparkUiSessionToken } from '../lib/auth' +import { + verifyAccessToken, + verifyHistoryServerSessionToken, + verifySparkUiSessionToken, + verifyWorkerUiSessionToken, +} from '../lib/auth' import { KV } from '../lib/kv' +import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' type Ctx = Context<{ Bindings: Env; Variables: Variables }> @@ -51,6 +57,27 @@ async function authenticate(c: Ctx) { } } + const isSparkWorker = c.req.path.startsWith(SPARK_WORKER_MOUNT) + if (isSparkWorker) { + const cookie = getCookie(c, 'spark_worker_session') + if (cookie) { + const session = await verifyWorkerUiSessionToken(cookie, c.env) + if (session) { + const invalidatedAt = await c.env.KV.get(KV.sessionInvalidatedAt(session.sub)) + if (!invalidatedAt || session.iat > parseInt(invalidatedAt, 10)) { + return { + sub: session.sub, + role: session.role, + iat: session.iat, + exp: session.exp, + type: 'access' as const, + jti: session.jti, + } + } + } + } + } + const authHeader = c.req.header('Authorization')?.replace(/^Bearer\s+/i, '') if (authHeader) { const payload = await verifyAccessToken(authHeader, c.env) diff --git a/worker/src/middleware/security.ts b/worker/src/middleware/security.ts index 36ea9e28..57cd2167 100644 --- a/worker/src/middleware/security.ts +++ b/worker/src/middleware/security.ts @@ -1,5 +1,6 @@ import type { MiddlewareHandler } from 'hono' import type { Env, Variables } from '../types' +import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' // Secure whenever the app is configured for HTTPS *or* this request actually arrived over HTTPS, // so a mistyped http:// APP_URL behind TLS cannot strip the refresh cookie's Secure flag or HSTS. @@ -12,7 +13,11 @@ export const securityHeaders: MiddlewareHandler<{ Bindings: Env; Variables: Vari c.header('X-Content-Type-Options', 'nosniff') c.header('Referrer-Policy', 'strict-origin-when-cross-origin') c.header('Permissions-Policy', 'camera=(), microphone=(), geolocation=()') - if (c.req.path.startsWith('/spark-ui') || c.req.path.startsWith('/spark-history')) { + if ( + c.req.path.startsWith('/spark-ui') || + c.req.path.startsWith('/spark-history') || + c.req.path.startsWith(SPARK_WORKER_MOUNT) + ) { c.header('X-Frame-Options', 'SAMEORIGIN') c.header( 'Content-Security-Policy', diff --git a/worker/src/routes/__tests__/admin-spark.test.ts b/worker/src/routes/__tests__/admin-spark.test.ts index 2f1004b1..1b60c105 100644 --- a/worker/src/routes/__tests__/admin-spark.test.ts +++ b/worker/src/routes/__tests__/admin-spark.test.ts @@ -191,6 +191,34 @@ describe('POST /api/admin/databases (kind=spark)', () => { expect(await listRows(e)).toEqual([]) expect(spark.calls).toEqual([]) }) + + it('stores the Worker UI publish link as a clean address plus a separate platform token', async () => { + const e = env() + spark.queue.push({ kind: 'ok' }) + const workerUrl = 'https://worker-8082.publish.example.dev' + const workerToken = 'worker-token-secret' + const res = await callWorker( + e, + '/api/admin/databases', + postJson(body({ worker_ui_url: `${workerUrl}/worker/?_token=${workerToken}` }), { + headers: await adminHeaders(e), + }) + ) + expect(res.status).toBe(201) + + const row = (await listRows(e))[0]! + const sealed = row.connection_secret as string + expect(JSON.parse(await openSecret(e, sealed))).toMatchObject({ + url: URL, + platform_token: PLATFORM, + app_token: APP, + worker_url: `${workerUrl}/worker`, + worker_platform_token: workerToken, + }) + // The pasted link with its token never lands verbatim in the stored payload. + expect(JSON.stringify(row)).not.toContain(workerToken) + expect(JSON.stringify(row)).not.toContain('_token') + }) }) describe('GET /api/admin/databases (kind=spark)', () => { @@ -632,6 +660,76 @@ describe('PATCH /api/admin/databases/:id (kind=spark)', () => { 'History Server is only available for Spark databases' ) }) + + it('updates Worker UI fields on an existing spark row without re-testing or re-entering connection_url', async () => { + const e = env() + const id = await seed(e) + const workerUrl = 'https://worker-8082.publish.example.dev' + const workerToken = 'worker-tok-123' + const res = await callWorker(e, `/api/admin/databases/${id}`, { + ...postJson({ worker_ui_url: `${workerUrl}/?_token=${workerToken}` }, { headers: await adminHeaders(e) }), + method: 'PATCH', + }) + expect(res.status).toBe(200) + const json = (await res.json()) as { database: Record } + expect(json.database).toMatchObject({ has_worker_ui: true }) + expect(spark.calls).toEqual([]) // Did not invoke Spark health check + + const sealed = (await listRows(e))[0]!.connection_secret as string + expect(JSON.parse(await openSecret(e, sealed))).toMatchObject({ + url: URL, + platform_token: PLATFORM, + app_token: APP, + worker_url: workerUrl, + worker_platform_token: workerToken, + }) + }) + + it('clears Worker UI fields when worker_ui_url is set to empty string', async () => { + const e = env() + const sealed = await sealSecret( + e, + JSON.stringify({ + url: URL, + platform_token: PLATFORM, + app_token: APP, + worker_url: 'https://worker-8082.publish.example.dev', + worker_platform_token: 'tok', + }) + ) + await e.DB.prepare( + `INSERT INTO d1_databases (id, name, binding_name, cf_database_id, kind, connection_secret, is_active, created_at) + VALUES ('sp4', 'spark4', 'spark:sp4', NULL, 'spark', ?1, 1, 0)` + ) + .bind(sealed) + .run() + + const res = await callWorker(e, '/api/admin/databases/sp4', { + ...postJson({ worker_ui_url: '' }, { headers: await adminHeaders(e) }), + method: 'PATCH', + }) + expect(res.status).toBe(200) + const json = (await res.json()) as { database: Record } + expect(json.database).toMatchObject({ has_worker_ui: false }) + + const unsealed = JSON.parse(await openSecret(e, (await listRows(e))[0]!.connection_secret as string)) + expect(unsealed.worker_url).toBeUndefined() + expect(unsealed.worker_platform_token).toBeUndefined() + }) + + it('rejects Worker UI fields on PATCH for non-spark targets with 400', async () => { + const e = env() + await e.DB.prepare( + `INSERT INTO d1_databases (id, name, binding_name, cf_database_id, kind, connection_secret, is_active, created_at) + VALUES ('pg3', 'pg-test', 'pg:pg3', NULL, 'postgres', NULL, 1, 0)` + ).run() + const res = await callWorker(e, '/api/admin/databases/pg3', { + ...postJson({ worker_ui_url: 'https://worker.example.dev?_token=tok' }, { headers: await adminHeaders(e) }), + method: 'PATCH', + }) + expect(res.status).toBe(400) + expect(((await res.json()) as { error: string }).error).toContain('Worker UI is only available for Spark databases') + }) }) describe('DELETE /api/admin/databases/:id', () => { diff --git a/worker/src/routes/__tests__/databases.test.ts b/worker/src/routes/__tests__/databases.test.ts index bdacc003..75250f13 100644 --- a/worker/src/routes/__tests__/databases.test.ts +++ b/worker/src/routes/__tests__/databases.test.ts @@ -199,4 +199,48 @@ describe('GET /api/databases (provider label)', () => { expect(byId.get('sp2')?.has_history_server).toBe(false) expect(byId.get('d1_1')?.has_history_server).toBe(false) }) + + it('annotates rows with has_worker_ui: true/false appropriately', async () => { + const dummyEnv = fakeEnv() + const sparkWithWorker = await sealSecret( + dummyEnv, + JSON.stringify({ + url: 'https://spark.dev', + platform_token: 'p', + app_token: 'a', + worker_url: 'https://worker-8082.publish.example.dev', + worker_platform_token: 'wt', + }) + ) + const sparkWithoutWorker = await sealSecret( + dummyEnv, + JSON.stringify({ + url: 'https://spark.dev', + platform_token: 'p', + app_token: 'a', + }) + ) + + const sampleRows = [ + { ...rows[1], id: 'sp1', kind: 'spark', connection_secret: sparkWithWorker }, + { ...rows[1], id: 'sp2', kind: 'spark', connection_secret: sparkWithoutWorker }, + { ...rows[1], id: 'd1_1', kind: 'sqlite', connection_secret: null }, + ] + + const { db } = fakeD1((sql) => { + if (sql.includes('FROM d1_databases')) return sampleRows + if (sql.startsWith('SELECT database_id, permission')) { + return sampleRows.map((r) => ({ database_id: r.id, permission: 'read' })) + } + return null + }) + const env = fakeEnv({ DB: db, ZETA_APP_DB_ID: APP_DB }) + const res = await callWorker(env, '/api/databases', { headers: await bearer(env, 'u1') }) + expect(res.status).toBe(200) + const body = (await res.json()) as Array<{ id: string; has_worker_ui: boolean }> + const byId = new Map(body.map((r) => [r.id, r])) + expect(byId.get('sp1')?.has_worker_ui).toBe(true) + expect(byId.get('sp2')?.has_worker_ui).toBe(false) + expect(byId.get('d1_1')?.has_worker_ui).toBe(false) + }) }) diff --git a/worker/src/routes/__tests__/spark-history.test.ts b/worker/src/routes/__tests__/spark-history.test.ts index 9f651a6e..da8d7aa6 100644 --- a/worker/src/routes/__tests__/spark-history.test.ts +++ b/worker/src/routes/__tests__/spark-history.test.ts @@ -437,6 +437,22 @@ describe('rewriteHistoryUrl', () => { ) expect(rewriteHistoryUrl('jobs/', HISTORY_URL)).toBe('/spark-history/jobs/') }) + + it('rewrites spark:8082 worker log links into /spark-worker with the database context', () => { + const db = 'sp1' + expect( + rewriteHistoryUrl( + 'spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', + HISTORY_URL, + undefined, + undefined, + db + ) + ).toBe('/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1') + expect(rewriteHistoryUrl('http://spark:8082/logPage/?appId=app-1', HISTORY_URL, undefined, undefined, db)).toBe( + '/spark-worker/logPage/?appId=app-1&db=sp1' + ) + }) }) describe('rewriteHistoryLocation', () => { diff --git a/worker/src/routes/__tests__/spark-ui.test.ts b/worker/src/routes/__tests__/spark-ui.test.ts index 34922f43..d8994adf 100644 --- a/worker/src/routes/__tests__/spark-ui.test.ts +++ b/worker/src/routes/__tests__/spark-ui.test.ts @@ -640,6 +640,19 @@ describe('/spark-ui proxying with signed cookie', () => { expect(rewriteSparkUiUrl('/proxy/local-1/jobs/', UI_URL)).toBe('/spark-ui/jobs/') expect(rewriteSparkUiUrl('/spark-ui/proxy/local-1?sort=id', UI_URL)).toBe('/spark-ui?sort=id') }) + + it('rewrites spark:8082 worker log links into /spark-worker with the database context', () => { + const db = 'sp1' + expect( + rewriteSparkUiUrl('spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', UI_URL, undefined, db) + ).toBe('/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1') + expect(rewriteSparkUiUrl('http://spark:8082/logPage/?appId=app-1', UI_URL, undefined, db)).toBe( + '/spark-worker/logPage/?appId=app-1&db=sp1' + ) + expect(rewriteSparkUiUrl('//spark:8082/logPage/?appId=app-1', UI_URL, undefined, db)).toBe( + '/spark-worker/logPage/?appId=app-1&db=sp1' + ) + }) }) describe('rewriteSparkUiLocation', () => { @@ -758,6 +771,17 @@ describe('/spark-ui proxying with signed cookie', () => { expect(rewritten).toContain('src="/spark-ui/static/spark-logo.svg"') expect(rewritten).toContain('href="/spark-ui/stages/"') }) + + it('rewrites executor stdout/stderr links that point at spark:8082 to the Worker UI route', () => { + const raw = ` + stdout + stderr + ` + const rewritten = rewriteSparkUiHtml(raw, UI_URL, undefined, 'sp1') + expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1"') + expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stderr&db=sp1"') + expect(rewritten).not.toContain('spark:8082') + }) }) describe('proxy response rewriting and header forwarding', () => { diff --git a/worker/src/routes/__tests__/spark-worker.test.ts b/worker/src/routes/__tests__/spark-worker.test.ts new file mode 100644 index 00000000..733e9f2d --- /dev/null +++ b/worker/src/routes/__tests__/spark-worker.test.ts @@ -0,0 +1,418 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { getMigrations } from '../../lib/migrations' +import { sealSecret } from '../../lib/secrets' +import type { Env } from '../../types' +import { rewriteWorkerLocation, rewriteWorkerUrl } from '../spark-worker' +import { bearer, callWorker, fakeEnv, postJson } from './fakes' +import { sqliteD1 } from './sqlite-d1' + +const WORKER_URL = 'https://worker-8082.publish.example.dev' +const WORKER_TOKEN = 'worker-platform-token-secret' + +function env(): Env { + const app = sqliteD1() + for (const migration of getMigrations({ TABLE_PREFIX: '' })) app.sqlite.exec(migration.sql) + app.sqlite.exec( + `INSERT INTO users (id, email, name, role, created_at, updated_at) + VALUES ('a1', 'admin@example.com', 'Admin', 'admin', 0, 0), + ('u1', 'member@example.com', 'Member', 'member', 0, 0), + ('u2', 'stranger@example.com', 'Stranger', 'member', 0, 0)` + ) + return fakeEnv({ DB: app.db }) +} + +async function seedSparkDatabase( + e: Env, + opts: { id?: string; withWorker?: boolean; kind?: string } = {} +): Promise { + const id = opts.id ?? 'sp1' + const kind = opts.kind ?? 'spark' + const payload: Record = { + url: 'https://spark-8080.publish.example.dev', + platform_token: 'p-token', + app_token: 'a-token', + } + if (opts.withWorker !== false) { + payload.worker_url = WORKER_URL + payload.worker_platform_token = WORKER_TOKEN + } + const sealed = await sealSecret(e, JSON.stringify(payload)) + await e.DB.prepare( + `INSERT INTO d1_databases (id, name, binding_name, cf_database_id, kind, connection_secret, is_active, created_at) + VALUES (?1, ?2, ?3, NULL, ?4, ?5, 1, 0)` + ) + .bind(id, `db-${id}`, `spark:${id}`, kind, sealed) + .run() + return id +} + +async function grantPermission(e: Env, userId: string, databaseId: string, permission = 'read'): Promise { + await e.DB.prepare( + `INSERT INTO user_database_permissions (id, user_id, database_id, permission, granted_at) + VALUES (?1, ?2, ?3, ?4, 0)` + ) + .bind(`p-${userId}-${databaseId}`, userId, databaseId, permission) + .run() +} + +describe('/spark-worker access control', () => { + let fetchMock: ReturnType + const originalFetch = globalThis.fetch + + beforeEach(() => { + fetchMock = vi.fn() + globalThis.fetch = fetchMock as unknown as typeof fetch + }) + + afterEach(() => { + globalThis.fetch = originalFetch + }) + + it('blocks unauthenticated visits with 401', async () => { + const e = env() + const res = await callWorker(e, '/spark-worker/') + expect(res.status).toBe(401) + expect(await res.json()).toEqual({ error: 'Unauthorized' }) + }) + + it('rejects /spark-worker/?db=missing with 404', async () => { + const e = env() + const headers = await bearer(e, 'a1', 'admin') + const res = await callWorker(e, '/spark-worker/?db=nonexistent', { headers }) + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Database not found' }) + }) + + it('rejects non-spark databases with 404', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'pg1', kind: 'postgres' }) + const headers = await bearer(e, 'a1', 'admin') + const res = await callWorker(e, '/spark-worker/?db=pg1', { headers }) + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Database is not a Spark database' }) + }) + + it('rejects spark databases without Worker UI configured with 404', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'sp_no_worker', withWorker: false }) + const headers = await bearer(e, 'a1', 'admin') + const res = await callWorker(e, '/spark-worker/?db=sp_no_worker', { headers }) + expect(res.status).toBe(404) + expect(await res.json()).toEqual({ error: 'Worker UI not configured' }) + }) + + it('rejects users without permission with 403', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'sp1' }) + const headers = await bearer(e, 'u2', 'member') + const res = await callWorker(e, '/spark-worker/?db=sp1', { headers }) + expect(res.status).toBe(403) + expect(await res.json()).toEqual({ error: 'Forbidden' }) + }) + + it('first hit (?db=) sets a signed HttpOnly cookie and 302 redirects to the same path without db', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'sp1' }) + await grantPermission(e, 'u1', 'sp1', 'read') + + const headers = await bearer(e, 'u1', 'member') + const res = await callWorker(e, '/spark-worker/logPage/?db=sp1&appId=app-1&logType=stdout', { headers }) + expect(res.status).toBe(302) + expect(res.headers.get('Location')).toBe('/spark-worker/logPage/?appId=app-1&logType=stdout') + + const setCookie = res.headers.get('Set-Cookie') ?? '' + expect(setCookie).toContain('spark_worker_session=') + expect(setCookie).toContain('HttpOnly') + expect(setCookie).toContain('Path=/spark-worker') + expect(setCookie).toContain('SameSite=Lax') + }) + + it('serves /spark-worker with the relaxed inline-script CSP', async () => { + const e = env() + const res = await callWorker(e, '/spark-worker/') + expect(res.status).toBe(401) + const csp = res.headers.get('Content-Security-Policy') ?? '' + expect(csp).toContain("script-src 'self' 'unsafe-inline' 'unsafe-eval'") + }) + + it('POST /api/auth/logout clears the spark_worker_session cookie', async () => { + const e = env() + const res = await callWorker(e, '/api/auth/logout', { method: 'POST' }) + expect(res.status).toBe(200) + const setCookie = res.headers.get('Set-Cookie') ?? '' + expect(setCookie).toContain('spark_worker_session=;') + expect(setCookie).toContain('Max-Age=0') + expect(setCookie).toContain('Path=/spark-worker') + }) +}) + +describe('POST /api/spark-worker/session', () => { + let fetchMock: ReturnType + const originalFetch = globalThis.fetch + + beforeEach(() => { + fetchMock = vi.fn() + globalThis.fetch = fetchMock as unknown as typeof fetch + }) + + afterEach(() => { + globalThis.fetch = originalFetch + }) + + it('allows admin to create session and sets signed HttpOnly cookie with 204', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'sp1' }) + const headers = await bearer(e, 'a1', 'admin') + const res = await callWorker(e, '/api/spark-worker/session', postJson({ db: 'sp1' }, { headers })) + expect(res.status).toBe(204) + expect(await res.text()).toBe('') + + const setCookie = res.headers.get('Set-Cookie') ?? '' + expect(setCookie).toContain('spark_worker_session=') + expect(setCookie).toContain('HttpOnly') + expect(setCookie).toContain('Path=/spark-worker') + expect(setCookie).toContain('Max-Age=86400') + }) + + it('allows member with read permission to create session with 204', async () => { + const e = env() + await seedSparkDatabase(e, { id: 'sp1' }) + await grantPermission(e, 'u1', 'sp1', 'read') + + const headers = await bearer(e, 'u1', 'member') + const res = await callWorker(e, '/api/spark-worker/session', postJson({ db: 'sp1' }, { headers })) + expect(res.status).toBe(204) + expect(res.headers.get('Set-Cookie')).toContain('spark_worker_session=') + }) +}) + +describe('/spark-worker proxying with signed cookie', () => { + let fetchMock: ReturnType + const originalFetch = globalThis.fetch + + beforeEach(() => { + fetchMock = vi.fn() + globalThis.fetch = fetchMock as unknown as typeof fetch + }) + + afterEach(() => { + globalThis.fetch = originalFetch + }) + + async function setupSession(e: Env, userId = 'u1', role: 'admin' | 'member' = 'member'): Promise { + await seedSparkDatabase(e, { id: 'sp1' }) + if (role !== 'admin') await grantPermission(e, userId, 'sp1', 'read') + const headers = await bearer(e, userId, role) + const res = await callWorker(e, '/spark-worker/?db=sp1', { headers }) + const cookieHeader = res.headers.get('Set-Cookie') ?? '' + const match = cookieHeader.match(/spark_worker_session=([^;]+)/) + expect(match).not.toBeNull() + return match![1]! + } + + it('proxies /spark-worker/ to upstream root with the Worker UI platform token', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce( + new Response('Worker Home', { + status: 200, + headers: { 'Content-Type': 'text/html' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toBe('Worker Home') + + expect(fetchMock).toHaveBeenCalledTimes(1) + const [calledUrl, init] = fetchMock.mock.calls[0] as [string, RequestInit] + expect(calledUrl).toBe(`${WORKER_URL}/`) + const headers = new Headers(init.headers) + expect(headers.get('Authorization')).toBe(`Bearer ${WORKER_TOKEN}`) + }) + + it('forwards /spark-worker/logPage/?appId=… to upstream /logPage/?appId=…', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce( + new Response('Log page', { + status: 200, + headers: { 'Content-Type': 'text/html' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + expect(fetchMock).toHaveBeenCalledTimes(1) + const [calledUrl] = fetchMock.mock.calls[0] as [string, RequestInit] + expect(calledUrl).toBe(`${WORKER_URL}/logPage/?appId=app-1&executorId=0&logType=stdout`) + }) + + it('proxies static assets and passes through Content-Type', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce( + new Response(new Uint8Array([1, 2, 3, 4]), { + status: 200, + headers: { 'Content-Type': 'image/png' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/static/spark-logo.png', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + expect(res.headers.get('Content-Type')).toBe('image/png') + expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3, 4])) + }) + + it('rewrites relative and absolute Location headers back into /spark-worker prefix', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce(new Response(null, { status: 302, headers: { Location: '/logPage/?appId=app-1' } })) + const res1 = await callWorker(e, '/spark-worker/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res1.status).toBe(302) + expect(res1.headers.get('Location')).toBe('/spark-worker/logPage/?appId=app-1') + + fetchMock.mockResolvedValueOnce( + new Response(null, { status: 302, headers: { Location: `${WORKER_URL}/logPage/?appId=app-2` } }) + ) + const res2 = await callWorker(e, '/spark-worker/logPage/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res2.status).toBe(302) + expect(res2.headers.get('Location')).toBe('/spark-worker/logPage/?appId=app-2') + expect(res2.headers.get('Location')).not.toContain(WORKER_URL) + }) + + it('rewrites HTML resource paths into /spark-worker prefix', async () => { + const e = env() + const cookie = await setupSession(e) + + const upstreamHtml = ` + + + + + + + + stdout + + + + ` + fetchMock.mockResolvedValueOnce( + new Response(upstreamHtml, { + status: 200, + headers: { 'Content-Type': 'text/html; charset=utf-8' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + const body = await res.text() + expect(body).toContain('href="/spark-worker/static/bootstrap.min.css"') + expect(body).toContain('src="/spark-worker/static/webui.js"') + expect(body).toContain('href="/spark-worker/logPage/?appId=app-1&logType=stdout"') + expect(body).toContain('src="/spark-worker/static/spark-logo.svg"') + expect(body).not.toContain('/spark-worker/spark-worker') + }) + + it('sanitizes upstream Worker UI URL in JSON responses to prevent leak', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce( + new Response(JSON.stringify({ log_link: `${WORKER_URL}/logPage/?appId=app-1` }), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/json/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + const json = await res.json() + expect(json).toEqual({ log_link: '/spark-worker/logPage/?appId=app-1' }) + expect(JSON.stringify(json)).not.toContain(WORKER_URL) + }) + + it('returns 502 when upstream Worker UI is unreachable, without leaking tokens', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockRejectedValueOnce(new Error('Connection refused')) + + const res = await callWorker(e, '/spark-worker/logPage/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(502) + const json = (await res.json()) as { error: string } + expect(json.error).toBe('Worker UI service unreachable') + expect(JSON.stringify(json)).not.toContain(WORKER_URL) + expect(JSON.stringify(json)).not.toContain(WORKER_TOKEN) + }) + + it('forwards X-Forwarded-Context and X-Forwarded-Prefix to upstream', async () => { + const e = env() + const cookie = await setupSession(e) + + fetchMock.mockResolvedValueOnce( + new Response('
Content
', { + status: 200, + headers: { 'Content-Type': 'text/html' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/logPage/', { + headers: { Cookie: `spark_worker_session=${cookie}` }, + }) + expect(res.status).toBe(200) + const [, init] = fetchMock.mock.calls[0] as [string, RequestInit] + const headers = new Headers(init.headers) + expect(headers.get('X-Forwarded-Context')).toBe('/spark-worker') + expect(headers.get('X-Forwarded-Prefix')).toBe('/spark-worker') + }) +}) + +describe('rewriteWorkerUrl', () => { + it('leaves external absolute URLs, anchors, data and javascript URIs intact', () => { + expect(rewriteWorkerUrl('https://spark.apache.org/docs', WORKER_URL)).toBe('https://spark.apache.org/docs') + expect(rewriteWorkerUrl('//cdn.example.com/lib.css', WORKER_URL)).toBe('//cdn.example.com/lib.css') + expect(rewriteWorkerUrl('#section', WORKER_URL)).toBe('#section') + expect(rewriteWorkerUrl('javascript:void(0)', WORKER_URL)).toBe('javascript:void(0)') + expect(rewriteWorkerUrl('data:image/png;base64,...', WORKER_URL)).toBe('data:image/png;base64,...') + }) + + it('rewrites root-relative, relative, and upstream-origin URLs into /spark-worker', () => { + expect(rewriteWorkerUrl('/static/webui.css', WORKER_URL)).toBe('/spark-worker/static/webui.css') + expect(rewriteWorkerUrl('/logPage/?appId=app-1', WORKER_URL)).toBe('/spark-worker/logPage/?appId=app-1') + expect(rewriteWorkerUrl('static/webui.css', WORKER_URL)).toBe('/spark-worker/static/webui.css') + expect(rewriteWorkerUrl('../logPage/?appId=app-1', WORKER_URL)).toBe('/spark-worker/logPage/?appId=app-1') + expect(rewriteWorkerUrl(`${WORKER_URL}/logPage/?appId=app-1`, WORKER_URL)).toBe( + '/spark-worker/logPage/?appId=app-1' + ) + }) +}) + +describe('rewriteWorkerLocation', () => { + it('keeps external hosts untouched and rewrites upstream/relative Locations into /spark-worker', () => { + expect(rewriteWorkerLocation('https://spark.apache.org/docs', WORKER_URL)).toBe('https://spark.apache.org/docs') + expect(rewriteWorkerLocation('/logPage/?appId=app-1', WORKER_URL)).toBe('/spark-worker/logPage/?appId=app-1') + expect(rewriteWorkerLocation('/', WORKER_URL)).toBe('/spark-worker/') + }) +}) diff --git a/worker/src/routes/admin.ts b/worker/src/routes/admin.ts index d177240e..97f4ccfd 100644 --- a/worker/src/routes/admin.ts +++ b/worker/src/routes/admin.ts @@ -16,6 +16,7 @@ import { runSetup } from '../lib/setup' import { checkDatabaseHasHistoryServer, checkDatabaseHasSparkUi, + checkDatabaseHasWorkerUi, checkHasLivy, normalizeSparkAccess, } from '../lib/spark-access' @@ -309,6 +310,7 @@ interface ConnectionBody { livy_platform_token?: unknown history_url?: unknown history_platform_token?: unknown + worker_ui_url?: unknown } // Proves pasted credentials against the real server before anything is saved. Registration, @@ -336,6 +338,7 @@ async function verifyConnection( livy_platform_token: body.livy_platform_token, history_url: body.history_url, history_platform_token: body.history_platform_token, + worker_ui_url: body.worker_ui_url, }) if (!access.ok) return c.json({ error: access.error }, 400) try { @@ -389,6 +392,7 @@ async function adminDatabaseDto(env: Env, row: DatabaseRow) { const has_spark_ui = await checkDatabaseHasSparkUi(env, row) const has_livy = await checkHasLivy(env, row) const has_history_server = await checkDatabaseHasHistoryServer(env, row) + const has_worker_ui = await checkDatabaseHasWorkerUi(env, row) return { ...rest, kind, @@ -398,6 +402,7 @@ async function adminDatabaseDto(env: Env, row: DatabaseRow) { has_spark_ui, has_livy, has_history_server, + has_worker_ui, is_app_db: isAppDb(env, row.cf_database_id), } } @@ -492,6 +497,7 @@ admin.post('/databases', async (c) => { livy_platform_token?: unknown history_url?: unknown history_platform_token?: unknown + worker_ui_url?: unknown provider?: unknown }>() .catch(() => null) @@ -509,6 +515,9 @@ admin.post('/databases', async (c) => { if (kind !== 'spark' && (body.history_url !== undefined || body.history_platform_token !== undefined)) { return c.json({ error: 'History Server is only available for Spark databases.' }, 400) } + if (kind !== 'spark' && body.worker_ui_url !== undefined) { + return c.json({ error: 'Worker UI is only available for Spark databases.' }, 400) + } // Display-only label; a blank value keeps the engine's own provider. const provider = normalizeProvider(body.provider) @@ -623,6 +632,7 @@ admin.patch('/databases/:id', async (c) => { livy_platform_token?: unknown history_url?: unknown history_platform_token?: unknown + worker_ui_url?: unknown provider?: unknown }>() .catch(() => null) @@ -659,6 +669,9 @@ admin.patch('/databases/:id', async (c) => { if (rowKind !== 'spark' && (body.history_url !== undefined || body.history_platform_token !== undefined)) { return c.json({ error: 'History Server is only available for Spark databases.' }, 400) } + if (rowKind !== 'spark' && body.worker_ui_url !== undefined) { + return c.json({ error: 'Worker UI is only available for Spark databases.' }, 400) + } const updates: string[] = [] const bindings: unknown[] = [] @@ -674,6 +687,7 @@ admin.patch('/databases/:id', async (c) => { let livyTokenToPass = body.livy_platform_token let historyUrlToPass = body.history_url let historyTokenToPass = body.history_platform_token + let workerUiUrlToPass = body.worker_ui_url if ( rowKind === 'spark' && row.connection_secret && @@ -682,7 +696,8 @@ admin.patch('/databases/:id', async (c) => { livyUrlToPass === undefined || livyTokenToPass === undefined || historyUrlToPass === undefined || - historyTokenToPass === undefined) + historyTokenToPass === undefined || + workerUiUrlToPass === undefined) ) { try { const existing = JSON.parse(await openSecret(c.env, row.connection_secret)) @@ -692,6 +707,13 @@ admin.patch('/databases/:id', async (c) => { if (livyTokenToPass === undefined) livyTokenToPass = existing.livy_platform_token if (historyUrlToPass === undefined) historyUrlToPass = existing.history_url if (historyTokenToPass === undefined) historyTokenToPass = existing.history_platform_token + if (workerUiUrlToPass === undefined) { + const workerUrl = typeof existing.worker_url === 'string' ? existing.worker_url : '' + const workerToken = typeof existing.worker_platform_token === 'string' ? existing.worker_platform_token : '' + if (workerUrl && workerToken) { + workerUiUrlToPass = `${workerUrl}?${new URLSearchParams({ _token: workerToken }).toString()}` + } + } } catch { /* ignore */ } @@ -704,6 +726,7 @@ admin.patch('/databases/:id', async (c) => { livy_platform_token: livyTokenToPass, history_url: historyUrlToPass, history_platform_token: historyTokenToPass, + worker_ui_url: workerUiUrlToPass, }) if (verified instanceof Response) return verified updates.push(`connection_secret = ?${i++}`) @@ -715,7 +738,8 @@ admin.patch('/databases/:id', async (c) => { body.livy_url !== undefined || body.livy_platform_token !== undefined || body.history_url !== undefined || - body.history_platform_token !== undefined) + body.history_platform_token !== undefined || + body.worker_ui_url !== undefined) ) { if (!row.connection_secret) { return c.json({ error: 'Database has no connection credentials configured.' }, 400) @@ -727,7 +751,7 @@ admin.patch('/databases/:id', async (c) => { } catch { return c.json({ error: 'The stored connection for this database could not be read.' }, 500) } - const merged = { + const merged: Record = { ...storedAccess, ui_url: body.ui_url !== undefined @@ -766,6 +790,19 @@ admin.patch('/databases/:id', async (c) => { : body.history_platform_token : storedAccess.history_platform_token, } + if (body.worker_ui_url !== undefined) { + // A blank clears the Worker UI; otherwise the pasted publish link replaces the stored + // address + token pair, which normalizeSparkAccess splits back into its stored shape. + if (body.worker_ui_url === '' || body.worker_ui_url === null) { + delete merged.worker_url + delete merged.worker_platform_token + delete merged.worker_ui_url + } else { + merged.worker_ui_url = body.worker_ui_url + delete merged.worker_url + delete merged.worker_platform_token + } + } const normalized = normalizeSparkAccess(merged) if (!normalized.ok) return c.json({ error: normalized.error }, 400) updates.push(`connection_secret = ?${i++}`) diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index 64efeb7e..fffcc30b 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -6,6 +6,7 @@ import { now, getSetting, audit, tables } from '../lib/db' import { KV } from '../lib/kv' import { isSecure } from '../middleware/security' import { resolveAppOrigin, resolveRpID } from '../lib/app-url' +import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' import { hashPassword, verifyPassword, @@ -69,6 +70,11 @@ function clearSparkHistoryCookie(c: HeaderSetter, secure: boolean): void { c.header('Set-Cookie', `spark_history_session=; ${flags}`, { append: true }) } +function clearSparkWorkerCookie(c: HeaderSetter, secure: boolean): void { + const flags = `HttpOnly; Path=${SPARK_WORKER_MOUNT}; Max-Age=0; SameSite=Lax${secure ? '; Secure' : ''}` + c.header('Set-Cookie', `spark_worker_session=; ${flags}`, { append: true }) +} + // ── POST /api/auth/register ─────────────────────────────────────────────────── auth.post('/register', async (c) => { @@ -430,6 +436,7 @@ auth.post('/logout', async (c) => { clearRefreshCookie(c, isSecure(c)) clearSparkUiCookie(c, isSecure(c)) clearSparkHistoryCookie(c, isSecure(c)) + clearSparkWorkerCookie(c, isSecure(c)) return c.json({ message: 'Logged out' }) }) diff --git a/worker/src/routes/databases.ts b/worker/src/routes/databases.ts index dc94113c..25a715ae 100644 --- a/worker/src/routes/databases.ts +++ b/worker/src/routes/databases.ts @@ -9,6 +9,7 @@ import type { SparkAccess } from '../lib/spark-access' import { checkDatabaseHasHistoryServer, checkDatabaseHasSparkUi, + checkDatabaseHasWorkerUi, checkHasLivy, normalizeSparkAccess, } from '../lib/spark-access' @@ -70,6 +71,7 @@ databases.get('/', async (c) => { const has_spark_ui = await checkDatabaseHasSparkUi(c.env, db) const has_livy = await checkHasLivy(c.env, db) const has_history_server = await checkDatabaseHasHistoryServer(c.env, db) + const has_worker_ui = await checkDatabaseHasWorkerUi(c.env, db) return { id: db.id, name: db.name, @@ -85,6 +87,7 @@ databases.get('/', async (c) => { has_spark_ui, has_livy, has_history_server, + has_worker_ui, } }) ) diff --git a/worker/src/routes/spark-history.ts b/worker/src/routes/spark-history.ts index 74f4bb8a..b5fffd49 100644 --- a/worker/src/routes/spark-history.ts +++ b/worker/src/routes/spark-history.ts @@ -4,6 +4,7 @@ import { createHistoryServerSessionToken, verifyHistoryServerSessionToken } from import { tables } from '../lib/db' import { openSecret } from '../lib/secrets' import { normalizeSparkAccess } from '../lib/spark-access' +import { rewriteSparkWorkerLink } from '../lib/spark-worker-link' import { requireAuth } from '../middleware/auth' import { isSecure } from '../middleware/security' import type { DatabaseRow, Env, Variables } from '../types' @@ -33,7 +34,16 @@ function withMount(path: string): string { return `${HISTORY_MOUNT}/${trimmed}` } -export function rewriteHistoryLocation(location: string, historyUrl: string, requestUrl?: string): string { +export function rewriteHistoryLocation( + location: string, + historyUrl: string, + requestUrl?: string, + databaseId?: string +): string { + if (databaseId) { + const workerLink = rewriteSparkWorkerLink(location, databaseId) + if (workerLink) return workerLink + } try { const locUrl = new URL(location) const targetUrl = new URL(historyUrl) @@ -83,9 +93,19 @@ export function rewriteHistoryLocation(location: string, historyUrl: string, req } } -export function rewriteHistoryUrl(val: string, historyUrl: string, _requestUrl?: string, baseUrl?: string): string { +export function rewriteHistoryUrl( + val: string, + historyUrl: string, + _requestUrl?: string, + baseUrl?: string, + databaseId?: string +): string { if (!val || typeof val !== 'string') return val const trimmed = val.trim() + if (databaseId) { + const workerLink = rewriteSparkWorkerLink(trimmed, databaseId) + if (workerLink) return workerLink + } if ( !trimmed || trimmed.startsWith('#') || @@ -151,7 +171,7 @@ export function rewriteHistoryUrl(val: string, historyUrl: string, _requestUrl?: return withMount(trimmed) } -export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl?: string): string { +export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl?: string, databaseId?: string): string { if (!html || typeof html !== 'string') return html // Resolve relative hrefs/srcs against the original when the page declares one. @@ -168,7 +188,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? // 1. Rewrite let result = html.replace(/]*)?>/gi, (match) => { return match.replace(/href\s*=\s*(["'])(.*?)\1/i, (_m, quote, attrVal) => { - return `href=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl)}${quote}` + return `href=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, undefined, databaseId)}${quote}` }) }) @@ -177,7 +197,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? let updatedRest = rest.replace( /\b(href|src|action)\s*=\s*(["'])(.*?)\2/gi, (_attrMatch: string, attrName: string, quote: string, attrVal: string) => { - return `${attrName}=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, baseUrl)}${quote}` + return `${attrName}=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, baseUrl, databaseId)}${quote}` } ) updatedRest = updatedRest.replace( @@ -189,7 +209,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? const trimmed = part.trim() const [src, ...restTokens] = trimmed.split(/\s+/) if (!src) return part - return [rewriteHistoryUrl(src, historyUrl, requestUrl, baseUrl), ...restTokens].join(' ') + return [rewriteHistoryUrl(src, historyUrl, requestUrl, baseUrl, databaseId), ...restTokens].join(' ') }) .join(', ') return `srcset=${quote}${rewritten}${quote}` @@ -373,13 +393,13 @@ async function handleSparkHistory(c: Context<{ Bindings: Env; Variables: Variabl const loc = resHeaders.get('location') if (loc) { - resHeaders.set('location', rewriteHistoryLocation(loc, resolved.history_url, c.req.url)) + resHeaders.set('location', rewriteHistoryLocation(loc, resolved.history_url, c.req.url, resolved.db.id)) } const contentType = resHeaders.get('content-type') || '' if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) { const rawHtml = await proxyRes.text() - const rewrittenHtml = rewriteHistoryHtml(rawHtml, resolved.history_url, c.req.url) + const rewrittenHtml = rewriteHistoryHtml(rawHtml, resolved.history_url, c.req.url, resolved.db.id) return new Response(rewrittenHtml, { status: proxyRes.status, statusText: proxyRes.statusText, diff --git a/worker/src/routes/spark-ui.ts b/worker/src/routes/spark-ui.ts index 8914ec7c..56849793 100644 --- a/worker/src/routes/spark-ui.ts +++ b/worker/src/routes/spark-ui.ts @@ -4,6 +4,7 @@ import { createSparkUiSessionToken, verifySparkUiSessionToken } from '../lib/aut import { tables } from '../lib/db' import { openSecret } from '../lib/secrets' import { normalizeSparkAccess } from '../lib/spark-access' +import { rewriteSparkWorkerLink } from '../lib/spark-worker-link' import { requireAuth } from '../middleware/auth' import { isSecure } from '../middleware/security' import type { DatabaseRow, Env, Variables } from '../types' @@ -20,7 +21,16 @@ function stripSparkUiProxySegment(path: string): string { return path.replace(/^(\/spark-ui)?\/proxy\/[^/?#]+/, '$1') } -export function rewriteSparkUiLocation(location: string, uiUrl: string, requestUrl?: string): string { +export function rewriteSparkUiLocation( + location: string, + uiUrl: string, + requestUrl?: string, + databaseId?: string +): string { + if (databaseId) { + const workerLink = rewriteSparkWorkerLink(location, databaseId) + if (workerLink) return workerLink + } try { const locUrl = new URL(location) const targetUrl = new URL(uiUrl) @@ -80,9 +90,13 @@ export function rewriteSparkUiLocation(location: string, uiUrl: string, requestU } } -export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: string): string { +export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: string, databaseId?: string): string { if (!val || typeof val !== 'string') return val const trimmed = val.trim() + if (databaseId) { + const workerLink = rewriteSparkWorkerLink(trimmed, databaseId) + if (workerLink) return workerLink + } if ( !trimmed || trimmed.startsWith('#') || @@ -161,13 +175,13 @@ export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: stri return stripSparkUiProxySegment(`/spark-ui/${trimmed}`) } -export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: string): string { +export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: string, databaseId?: string): string { if (!html || typeof html !== 'string') return html // 1. Rewrite let result = html.replace(/]*)?>/gi, (match) => { return match.replace(/href\s*=\s*(["'])(.*?)\1/i, (_m, quote, attrVal) => { - const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl) + const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl, databaseId) return `href=${quote}${rewritten}${quote}` }) }) @@ -177,7 +191,7 @@ export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: str let updatedRest = rest.replace( /\b(href|src|action)\s*=\s*(["'])(.*?)\2/gi, (_attrMatch: string, attrName: string, quote: string, attrVal: string) => { - const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl) + const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl, databaseId) return `${attrName}=${quote}${rewritten}${quote}` } ) @@ -190,7 +204,7 @@ export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: str const trimmed = part.trim() const [src, ...restTokens] = trimmed.split(/\s+/) if (!src) return part - return [rewriteSparkUiUrl(src, uiUrl, requestUrl), ...restTokens].join(' ') + return [rewriteSparkUiUrl(src, uiUrl, requestUrl, databaseId), ...restTokens].join(' ') }) .join(', ') return `srcset=${quote}${rewritten}${quote}` @@ -382,13 +396,13 @@ async function handleSparkUi(c: Context<{ Bindings: Env; Variables: Variables }> const loc = resHeaders.get('location') if (loc) { - resHeaders.set('location', rewriteSparkUiLocation(loc, resolved.ui_url, c.req.url)) + resHeaders.set('location', rewriteSparkUiLocation(loc, resolved.ui_url, c.req.url, resolved.db.id)) } const contentType = resHeaders.get('content-type') || '' if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) { const rawHtml = await proxyRes.text() - const rewrittenHtml = rewriteSparkUiHtml(rawHtml, resolved.ui_url, c.req.url) + const rewrittenHtml = rewriteSparkUiHtml(rawHtml, resolved.ui_url, c.req.url, resolved.db.id) return new Response(rewrittenHtml, { status: proxyRes.status, statusText: proxyRes.statusText, diff --git a/worker/src/routes/spark-worker.ts b/worker/src/routes/spark-worker.ts new file mode 100644 index 00000000..eccecac1 --- /dev/null +++ b/worker/src/routes/spark-worker.ts @@ -0,0 +1,408 @@ +import { type Context, Hono } from 'hono' +import { getCookie } from 'hono/cookie' +import { createWorkerUiSessionToken, verifyWorkerUiSessionToken } from '../lib/auth' +import { tables } from '../lib/db' +import { openSecret } from '../lib/secrets' +import { normalizeSparkAccess } from '../lib/spark-access' +import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' +import { requireAuth } from '../middleware/auth' +import { isSecure } from '../middleware/security' +import type { DatabaseRow, Env, Variables } from '../types' + +// ── Worker UI reverse proxy ───────────────────────────────────────────────────────────────────── +// Mirrors /spark-ui for the Spark Worker UI: it verifies the Zeta login through a signed, HttpOnly +// session cookie scoped to this prefix, then forwards to the registered Worker UI publish address +// with the platform token as a Bearer header. The token never reaches the browser. +// +// The Worker UI has no `/proxy//` segment to strip: its pages live at /logPage/..., +// /json/... and /static/... . A request for /spark-worker/logPage/?appId=… is forwarded to +// /logPage/?appId=… . + +const WORKER_MOUNT = SPARK_WORKER_MOUNT + +const sparkWorker = new Hono<{ Bindings: Env; Variables: Variables }>() +sparkWorker.use('*', requireAuth) + +// Prefix a value that the Worker UI emitted as its own root-relative path. Empty becomes the mount +// itself; anything else gets the mount prepended exactly once. +function withMount(path: string): string { + const trimmed = path.trim() + if (!trimmed) return WORKER_MOUNT + if (trimmed === WORKER_MOUNT || trimmed.startsWith(`${WORKER_MOUNT}/`)) return trimmed + if (trimmed.startsWith('/')) return `${WORKER_MOUNT}${trimmed}` + return `${WORKER_MOUNT}/${trimmed}` +} + +export function rewriteWorkerLocation(location: string, workerUrl: string, requestUrl?: string): string { + try { + const locUrl = new URL(location) + const targetUrl = new URL(workerUrl) + const pathAndQuery = locUrl.pathname + locUrl.search + locUrl.hash + + if ( + pathAndQuery === WORKER_MOUNT || + pathAndQuery.startsWith(`${WORKER_MOUNT}/`) || + pathAndQuery.startsWith(`${WORKER_MOUNT}?`) || + pathAndQuery.startsWith(`${WORKER_MOUNT}#`) + ) { + return pathAndQuery + } + + if (locUrl.origin === targetUrl.origin) { + let p = pathAndQuery + if (targetUrl.pathname && targetUrl.pathname !== '/' && p.startsWith(targetUrl.pathname)) { + p = p.slice(targetUrl.pathname.length) + } + if (!p.startsWith('/')) p = `/${p}` + return withMount(p) + } + return location + } catch { + if ( + location === WORKER_MOUNT || + location.startsWith(`${WORKER_MOUNT}/`) || + location.startsWith(`${WORKER_MOUNT}?`) || + location.startsWith(`${WORKER_MOUNT}#`) + ) { + return location + } + if (location.startsWith('/')) return withMount(location) + if (requestUrl) { + try { + const resolved = new URL(location, requestUrl) + const pathAndQuery = `${resolved.pathname}${resolved.search}${resolved.hash}` + if (pathAndQuery.startsWith(WORKER_MOUNT)) return pathAndQuery + return withMount(pathAndQuery) + } catch { + // Fall back + } + } + return withMount(location.replace(/^(\.\.\/)+/, '')) + } +} + +export function rewriteWorkerUrl(val: string, workerUrl: string, _requestUrl?: string, baseUrl?: string): string { + if (!val || typeof val !== 'string') return val + const trimmed = val.trim() + if ( + !trimmed || + trimmed.startsWith('#') || + trimmed.startsWith('//') || + trimmed.startsWith('data:') || + trimmed.startsWith('javascript:') || + trimmed.startsWith('mailto:') + ) { + return val + } + + try { + const parsed = new URL(trimmed) + const target = new URL(workerUrl) + const pathAndQuery = parsed.pathname + parsed.search + parsed.hash + + if ( + pathAndQuery === WORKER_MOUNT || + pathAndQuery.startsWith(`${WORKER_MOUNT}/`) || + pathAndQuery.startsWith(`${WORKER_MOUNT}?`) || + pathAndQuery.startsWith(`${WORKER_MOUNT}#`) + ) { + return pathAndQuery + } + + if (parsed.origin === target.origin) { + let p = pathAndQuery + if (target.pathname && target.pathname !== '/' && p.startsWith(target.pathname)) { + p = p.slice(target.pathname.length) + } + if (!p.startsWith('/')) p = `/${p}` + return withMount(p) + } + return val + } catch { + // Relative or domain-relative URL + } + + if ( + trimmed === WORKER_MOUNT || + trimmed.startsWith(`${WORKER_MOUNT}/`) || + trimmed.startsWith(`${WORKER_MOUNT}?`) || + trimmed.startsWith(`${WORKER_MOUNT}#`) + ) { + return trimmed + } + if (trimmed.startsWith('/')) return withMount(trimmed) + if (baseUrl) { + try { + const resolved = new URL(trimmed, baseUrl) + return withMount(`${resolved.pathname}${resolved.search}${resolved.hash}`) + } catch { + // Fall back + } + } + if (trimmed.startsWith('./')) return withMount(trimmed.slice(2)) + if (trimmed.startsWith('../')) return withMount(trimmed.replace(/^(\.\.\/)+/, '')) + return withMount(trimmed) +} + +export function rewriteWorkerHtml(html: string, workerUrl: string, requestUrl?: string): string { + if (!html || typeof html !== 'string') return html + + let baseUrl: string | undefined + const baseMatch = html.match(/]*href\s*=\s*(["'])(.*?)\1[^>]*>/i) + if (baseMatch?.[2]) { + try { + baseUrl = new URL(baseMatch[2], workerUrl).toString() + } catch { + baseUrl = undefined + } + } + + // 1. Rewrite + let result = html.replace(/]*)?>/gi, (match) => { + return match.replace(/href\s*=\s*(["'])(.*?)\1/i, (_m, quote, attrVal) => { + return `href=${quote}${rewriteWorkerUrl(attrVal, workerUrl, requestUrl)}${quote}` + }) + }) + + // 2. Rewrite HTML attributes (href, src, action, srcset) + result = result.replace(/<(link|script|img|a|form|source|iframe)\b([^>]*)>/gi, (_match, _tag, rest) => { + let updatedRest = rest.replace( + /\b(href|src|action)\s*=\s*(["'])(.*?)\2/gi, + (_attrMatch: string, attrName: string, quote: string, attrVal: string) => { + return `${attrName}=${quote}${rewriteWorkerUrl(attrVal, workerUrl, requestUrl, baseUrl)}${quote}` + } + ) + updatedRest = updatedRest.replace( + /\bsrcset\s*=\s*(["'])(.*?)\1/gi, + (_attrMatch: string, quote: string, attrVal: string) => { + const rewritten = attrVal + .split(',') + .map((part) => { + const trimmed = part.trim() + const [src, ...restTokens] = trimmed.split(/\s+/) + if (!src) return part + return [rewriteWorkerUrl(src, workerUrl, requestUrl, baseUrl), ...restTokens].join(' ') + }) + .join(', ') + return `srcset=${quote}${rewritten}${quote}` + } + ) + return `<${_tag}${updatedRest}>` + }) + + // 3. Any direct mention of the private Worker UI origin/base (prevent leakage). + try { + const parsedTarget = new URL(workerUrl) + const fullBase = `${parsedTarget.origin}${parsedTarget.pathname.replace(/\/+$/, '')}` + if (result.includes(fullBase)) result = result.replaceAll(fullBase, WORKER_MOUNT) + if (result.includes(parsedTarget.origin)) result = result.replaceAll(parsedTarget.origin, WORKER_MOUNT) + result = result.replaceAll(`${WORKER_MOUNT}${WORKER_MOUNT}`, WORKER_MOUNT) + } catch {} + + return result +} + +async function resolveTargetDatabase( + c: Context<{ Bindings: Env; Variables: Variables }>, + databaseId: string +): Promise<{ db: DatabaseRow; worker_url: string; worker_platform_token: string } | Response> { + const T = tables(c.env) + const db = await c.env.DB.prepare(`SELECT * FROM ${T.d1_databases} WHERE id = ?1 AND is_active = 1`) + .bind(databaseId) + .first() + if (!db) return c.json({ error: 'Database not found' }, 404) + if (db.kind !== 'spark') return c.json({ error: 'Database is not a Spark database' }, 404) + if (!db.connection_secret) return c.json({ error: 'Worker UI not configured' }, 404) + + let parsed: unknown + try { + const raw = await openSecret(c.env, db.connection_secret) + parsed = JSON.parse(raw) + } catch { + return c.json({ error: 'Worker UI not configured' }, 404) + } + const accessResult = normalizeSparkAccess(parsed) + if (!accessResult.ok || !accessResult.access.worker_url || !accessResult.access.worker_platform_token) { + return c.json({ error: 'Worker UI not configured' }, 404) + } + + const userId = c.get('userId') + const role = c.get('userRole') + if (role !== 'admin') { + const permRow = await c.env.DB.prepare( + `SELECT permission FROM ${T.user_database_permissions} WHERE user_id = ?1 AND database_id = ?2` + ) + .bind(userId, db.id) + .first<{ permission: string }>() + if (!permRow || !['read', 'write', 'write_drop', 'manage'].includes(permRow.permission)) { + return c.json({ error: 'Forbidden' }, 403) + } + } + + return { + db, + worker_url: accessResult.access.worker_url, + worker_platform_token: accessResult.access.worker_platform_token, + } +} + +async function setWorkerSessionCookie( + c: Context<{ Bindings: Env; Variables: Variables }>, + databaseId: string +): Promise { + const sessionToken = await createWorkerUiSessionToken( + { + userId: c.get('userId'), + role: c.get('userRole'), + databaseId, + }, + c.env + ) + const secure = isSecure(c) + const flags = `HttpOnly; Path=${WORKER_MOUNT}; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` + c.header('Set-Cookie', `spark_worker_session=${sessionToken}; ${flags}`) +} + +export const sparkWorkerApi = new Hono<{ Bindings: Env; Variables: Variables }>() +sparkWorkerApi.use('*', requireAuth) + +sparkWorkerApi.post('/session', async (c) => { + const body = await c.req.json<{ db?: unknown }>().catch(() => null) + if (!body || typeof body.db !== 'string' || !body.db.trim()) { + return c.json({ error: 'db is required' }, 400) + } + + const resolved = await resolveTargetDatabase(c, body.db.trim()) + if (resolved instanceof Response) return resolved + + await setWorkerSessionCookie(c, resolved.db.id) + return c.body(null, 204) +}) + +async function handleSparkWorker(c: Context<{ Bindings: Env; Variables: Variables }>) { + const dbParam = c.req.query('db') + + // First hit: ?db=. Establish the scoped cookie, then redirect back to the same path without + // the db parameter so a rewritten deep link (e.g. /spark-worker/logPage/?db=…&appId=…) lands on + // the right Worker UI page instead of being sent to the mount root. + if (dbParam) { + const resolved = await resolveTargetDatabase(c, dbParam) + if (resolved instanceof Response) return resolved + + await setWorkerSessionCookie(c, resolved.db.id) + + const reqUrl = new URL(c.req.url) + let remainder = reqUrl.pathname.slice(WORKER_MOUNT.length) + if (!remainder || remainder === '/') { + remainder = '/' + } else if (!remainder.startsWith('/')) { + remainder = `/${remainder}` + } + reqUrl.searchParams.delete('db') + const searchString = reqUrl.searchParams.toString() + return c.redirect(`${WORKER_MOUNT}${remainder}${searchString ? `?${searchString}` : ''}`, 302) + } + + // Subsequent requests: parse databaseId from the signed cookie. + const cookie = getCookie(c, 'spark_worker_session') + if (!cookie) { + return c.json({ error: 'Unauthorized' }, 401) + } + const session = await verifyWorkerUiSessionToken(cookie, c.env) + if (!session) { + return c.json({ error: 'Unauthorized' }, 401) + } + + const resolved = await resolveTargetDatabase(c, session.db) + if (resolved instanceof Response) return resolved + + const reqUrl = new URL(c.req.url) + let remainder = reqUrl.pathname.slice(WORKER_MOUNT.length) + if (!remainder || remainder === '/') { + remainder = '/' + } else if (!remainder.startsWith('/')) { + remainder = `/${remainder}` + } + const targetUrl = `${resolved.worker_url}${remainder}${reqUrl.search}` + + // Forward headers (excluding the caller's Authorization, Cookies, Host). + const forwardHeaders = new Headers() + for (const [key, value] of c.req.raw.headers.entries()) { + const k = key.toLowerCase() + if (k === 'authorization' || k === 'cookie' || k === 'host' || k === 'connection' || k === 'keep-alive') { + continue + } + forwardHeaders.set(key, value) + } + forwardHeaders.set('Authorization', `Bearer ${resolved.worker_platform_token}`) + forwardHeaders.set('X-Forwarded-Context', WORKER_MOUNT) + forwardHeaders.set('X-Forwarded-Prefix', WORKER_MOUNT) + forwardHeaders.set('X-Forwarded-Proto', reqUrl.protocol.replace(':', '')) + forwardHeaders.set('X-Forwarded-Host', reqUrl.host) + + const fetchInit: RequestInit = { + method: c.req.method, + headers: forwardHeaders, + redirect: 'manual', + } + if (c.req.method !== 'GET' && c.req.method !== 'HEAD') { + fetchInit.body = c.req.raw.body + ;(fetchInit as RequestInit & { duplex?: string }).duplex = 'half' + } + + let proxyRes: Response + try { + proxyRes = await fetch(targetUrl, fetchInit) + } catch (err) { + console.error('Worker UI proxy request failed:', err instanceof Error ? err.message : String(err)) + return c.json({ error: 'Worker UI service unreachable' }, 502) + } + + const resHeaders = new Headers(proxyRes.headers) + resHeaders.delete('content-encoding') + resHeaders.delete('content-length') + + const loc = resHeaders.get('location') + if (loc) { + resHeaders.set('location', rewriteWorkerLocation(loc, resolved.worker_url, c.req.url)) + } + + const contentType = resHeaders.get('content-type') || '' + if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) { + const rawHtml = await proxyRes.text() + const rewrittenHtml = rewriteWorkerHtml(rawHtml, resolved.worker_url, c.req.url) + return new Response(rewrittenHtml, { + status: proxyRes.status, + statusText: proxyRes.statusText, + headers: resHeaders, + }) + } + + if (contentType.includes('application/json')) { + const rawJson = await proxyRes.text() + let sanitizedJson = rawJson + try { + const parsedTarget = new URL(resolved.worker_url) + const fullBase = `${parsedTarget.origin}${parsedTarget.pathname.replace(/\/+$/, '')}` + if (sanitizedJson.includes(fullBase)) sanitizedJson = sanitizedJson.replaceAll(fullBase, WORKER_MOUNT) + if (sanitizedJson.includes(parsedTarget.origin)) { + sanitizedJson = sanitizedJson.replaceAll(parsedTarget.origin, WORKER_MOUNT) + } + } catch {} + return new Response(sanitizedJson, { + status: proxyRes.status, + statusText: proxyRes.statusText, + headers: resHeaders, + }) + } + + return new Response(proxyRes.body, { + status: proxyRes.status, + statusText: proxyRes.statusText, + headers: resHeaders, + }) +} + +sparkWorker.all('*', handleSparkWorker) + +export default sparkWorker From 13b54181f30dc34cbcb76f7f6796b18e169b1a0b Mon Sep 17 00:00:00 2001 From: mapxn <16299874+mapxn@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:20:39 +0800 Subject: [PATCH 2/2] chore: checkpoint hvcsPXBZgJsCUihBjHaMj --- worker/src/lib/spark-worker-link.ts | 17 +++--- worker/src/middleware/auth.ts | 4 +- .../routes/__tests__/spark-history.test.ts | 20 +++---- worker/src/routes/__tests__/spark-ui.test.ts | 22 ++++--- .../src/routes/__tests__/spark-worker.test.ts | 53 ++++++++++++++++ worker/src/routes/auth.ts | 4 +- worker/src/routes/spark-history.ts | 60 ++++++++++--------- worker/src/routes/spark-ui.ts | 51 +++++++++------- worker/src/routes/spark-worker.ts | 6 +- 9 files changed, 144 insertions(+), 93 deletions(-) diff --git a/worker/src/lib/spark-worker-link.ts b/worker/src/lib/spark-worker-link.ts index 2e234bae..4b6dd78b 100644 --- a/worker/src/lib/spark-worker-link.ts +++ b/worker/src/lib/spark-worker-link.ts @@ -2,10 +2,11 @@ // Spark's application UI and History Server emit executor log links that point straight at the // Worker UI host Spark runs on, e.g. `spark:8082/logPage/?appId=…&executorId=…&logType=…`. That // host is a container-internal name the browser cannot resolve, so the two proxies rewrite those -// links into Zeta's Worker UI reverse proxy mount, carrying the database context through the same -// `?db=` first-hit mechanism `/spark-ui` uses. +// links into Zeta's Worker UI reverse proxy mount. The database context rides in the Worker UI +// session cookie, which the Spark UI / History Server session bootstrap mints alongside its own. export const SPARK_WORKER_MOUNT = '/spark-worker' +export const SPARK_WORKER_SESSION_COOKIE = 'spark_worker_session' // Fixed by the apollo deployment's entrypoint: Master is 8081, the query service 8080, and the // Worker UI 8082. The rewrite target is therefore the fixed host `spark:8082`, never discovered. @@ -25,10 +26,11 @@ function stripScheme(value: string): string { /** * Rewrites a value that points at the fixed Worker UI host (`spark:8082`) into the Worker UI - * reverse proxy mount with the database context attached as `?db=`. Returns null for anything - * else, so callers can fall through to their normal rewriting. + * reverse proxy mount. The data-source context rides in the Worker UI session cookie, established + * together with the Spark UI / History Server session, so it never has to appear in a URL. Returns + * null for anything else, so callers can fall through to their normal rewriting. */ -export function rewriteSparkWorkerLink(val: string, databaseId: string): string | null { +export function rewriteSparkWorkerLink(val: string): string | null { if (!val || typeof val !== 'string') return null const trimmed = val.trim() if (!trimmed) return null @@ -54,8 +56,5 @@ export function rewriteSparkWorkerLink(val: string, databaseId: string): string } const path = rest.startsWith('/') ? rest : `/${rest}` - const search = new URLSearchParams(query) - search.set('db', databaseId) - const searchString = search.toString() - return `${SPARK_WORKER_MOUNT}${path}${searchString ? `?${searchString}` : ''}${hash}` + return `${SPARK_WORKER_MOUNT}${path}${query}${hash}` } diff --git a/worker/src/middleware/auth.ts b/worker/src/middleware/auth.ts index 6c4b9fdc..2e11ff55 100644 --- a/worker/src/middleware/auth.ts +++ b/worker/src/middleware/auth.ts @@ -8,7 +8,7 @@ import { verifyWorkerUiSessionToken, } from '../lib/auth' import { KV } from '../lib/kv' -import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' +import { SPARK_WORKER_MOUNT, SPARK_WORKER_SESSION_COOKIE } from '../lib/spark-worker-link' type Ctx = Context<{ Bindings: Env; Variables: Variables }> @@ -59,7 +59,7 @@ async function authenticate(c: Ctx) { const isSparkWorker = c.req.path.startsWith(SPARK_WORKER_MOUNT) if (isSparkWorker) { - const cookie = getCookie(c, 'spark_worker_session') + const cookie = getCookie(c, SPARK_WORKER_SESSION_COOKIE) if (cookie) { const session = await verifyWorkerUiSessionToken(cookie, c.env) if (session) { diff --git a/worker/src/routes/__tests__/spark-history.test.ts b/worker/src/routes/__tests__/spark-history.test.ts index da8d7aa6..90c06f1a 100644 --- a/worker/src/routes/__tests__/spark-history.test.ts +++ b/worker/src/routes/__tests__/spark-history.test.ts @@ -122,6 +122,7 @@ describe('/spark-history access control', () => { const setCookie = res.headers.get('Set-Cookie') ?? '' expect(setCookie).toContain('spark_history_session=') + expect(setCookie).toContain('spark_worker_session=') expect(setCookie).toContain('HttpOnly') expect(setCookie).toContain('Path=/spark-history') expect(setCookie).toContain('SameSite=Lax') @@ -438,19 +439,12 @@ describe('rewriteHistoryUrl', () => { expect(rewriteHistoryUrl('jobs/', HISTORY_URL)).toBe('/spark-history/jobs/') }) - it('rewrites spark:8082 worker log links into /spark-worker with the database context', () => { - const db = 'sp1' - expect( - rewriteHistoryUrl( - 'spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', - HISTORY_URL, - undefined, - undefined, - db - ) - ).toBe('/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1') - expect(rewriteHistoryUrl('http://spark:8082/logPage/?appId=app-1', HISTORY_URL, undefined, undefined, db)).toBe( - '/spark-worker/logPage/?appId=app-1&db=sp1' + it('rewrites spark:8082 worker log links into the /spark-worker mount', () => { + expect(rewriteHistoryUrl('spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', HISTORY_URL)).toBe( + '/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout' + ) + expect(rewriteHistoryUrl('http://spark:8082/logPage/?appId=app-1', HISTORY_URL)).toBe( + '/spark-worker/logPage/?appId=app-1' ) }) }) diff --git a/worker/src/routes/__tests__/spark-ui.test.ts b/worker/src/routes/__tests__/spark-ui.test.ts index d8994adf..420f02a1 100644 --- a/worker/src/routes/__tests__/spark-ui.test.ts +++ b/worker/src/routes/__tests__/spark-ui.test.ts @@ -128,6 +128,7 @@ describe('/spark-ui access control', () => { const setCookie = res.headers.get('Set-Cookie') ?? '' expect(setCookie).toContain('spark_ui_session=') + expect(setCookie).toContain('spark_worker_session=') expect(setCookie).toContain('HttpOnly') expect(setCookie).toContain('Path=/spark-ui') expect(setCookie).toContain('SameSite=Lax') @@ -641,17 +642,14 @@ describe('/spark-ui proxying with signed cookie', () => { expect(rewriteSparkUiUrl('/spark-ui/proxy/local-1?sort=id', UI_URL)).toBe('/spark-ui?sort=id') }) - it('rewrites spark:8082 worker log links into /spark-worker with the database context', () => { - const db = 'sp1' - expect( - rewriteSparkUiUrl('spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', UI_URL, undefined, db) - ).toBe('/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1') - expect(rewriteSparkUiUrl('http://spark:8082/logPage/?appId=app-1', UI_URL, undefined, db)).toBe( - '/spark-worker/logPage/?appId=app-1&db=sp1' + it('rewrites spark:8082 worker log links into the /spark-worker mount', () => { + expect(rewriteSparkUiUrl('spark:8082/logPage/?appId=app-1&executorId=0&logType=stdout', UI_URL)).toBe( + '/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout' ) - expect(rewriteSparkUiUrl('//spark:8082/logPage/?appId=app-1', UI_URL, undefined, db)).toBe( - '/spark-worker/logPage/?appId=app-1&db=sp1' + expect(rewriteSparkUiUrl('http://spark:8082/logPage/?appId=app-1', UI_URL)).toBe( + '/spark-worker/logPage/?appId=app-1' ) + expect(rewriteSparkUiUrl('//spark:8082/logPage/?appId=app-1', UI_URL)).toBe('/spark-worker/logPage/?appId=app-1') }) }) @@ -777,9 +775,9 @@ describe('/spark-ui proxying with signed cookie', () => { stdout stderr ` - const rewritten = rewriteSparkUiHtml(raw, UI_URL, undefined, 'sp1') - expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout&db=sp1"') - expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stderr&db=sp1"') + const rewritten = rewriteSparkUiHtml(raw, UI_URL) + expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout"') + expect(rewritten).toContain('href="/spark-worker/logPage/?appId=app-1&executorId=0&logType=stderr"') expect(rewritten).not.toContain('spark:8082') }) }) diff --git a/worker/src/routes/__tests__/spark-worker.test.ts b/worker/src/routes/__tests__/spark-worker.test.ts index 733e9f2d..aaeb2878 100644 --- a/worker/src/routes/__tests__/spark-worker.test.ts +++ b/worker/src/routes/__tests__/spark-worker.test.ts @@ -387,6 +387,59 @@ describe('/spark-worker proxying with signed cookie', () => { expect(headers.get('X-Forwarded-Context')).toBe('/spark-worker') expect(headers.get('X-Forwarded-Prefix')).toBe('/spark-worker') }) + + it('a Spark UI session bootstrap also establishes the Worker UI session cookie, so a bare executor-log link is authenticated', async () => { + const e = env() + const sealed = await sealSecret( + e, + JSON.stringify({ + url: 'https://spark-8080.publish.example.dev', + platform_token: 'p-token', + app_token: 'a-token', + ui_url: 'https://spark-ui-4040.publish.example.dev', + ui_platform_token: 'ui-token', + worker_url: WORKER_URL, + worker_platform_token: WORKER_TOKEN, + }) + ) + await e.DB.prepare( + `INSERT INTO d1_databases (id, name, binding_name, cf_database_id, kind, connection_secret, is_active, created_at) + VALUES ('sp1', 'spark', 'spark:sp1', NULL, 'spark', ?1, 1, 0)` + ) + .bind(sealed) + .run() + await grantPermission(e, 'u1', 'sp1', 'read') + + // The Spark UI menu link bootstraps the Spark UI session; the same response must also mint the + // Worker UI session cookie so a later click carries a + // credential on that bare navigation (no ?db=, no Authorization header). + const headers = await bearer(e, 'u1', 'member') + const sessionRes = await callWorker(e, '/api/spark-ui/session', postJson({ db: 'sp1' }, { headers })) + expect(sessionRes.status).toBe(204) + const setCookie = sessionRes.headers.get('Set-Cookie') ?? '' + expect(setCookie).toContain('spark_ui_session=') + expect(setCookie).toContain('spark_worker_session=') + const match = setCookie.match(/spark_worker_session=([^;]+)/) + expect(match).not.toBeNull() + const workerCookie = match![1]! + + fetchMock.mockResolvedValueOnce( + new Response('Log page', { + status: 200, + headers: { 'Content-Type': 'text/html' }, + }) + ) + + const res = await callWorker(e, '/spark-worker/logPage/?appId=app-1&executorId=0&logType=stdout', { + headers: { Cookie: `spark_worker_session=${workerCookie}` }, + }) + expect(res.status).toBe(200) + expect(await res.text()).toBe('Log page') + const [calledUrl, init] = fetchMock.mock.calls[0] as [string, RequestInit] + expect(calledUrl).toBe(`${WORKER_URL}/logPage/?appId=app-1&executorId=0&logType=stdout`) + const forwardedHeaders = new Headers(init.headers) + expect(forwardedHeaders.get('Authorization')).toBe(`Bearer ${WORKER_TOKEN}`) + }) }) describe('rewriteWorkerUrl', () => { diff --git a/worker/src/routes/auth.ts b/worker/src/routes/auth.ts index fffcc30b..7a0cefae 100644 --- a/worker/src/routes/auth.ts +++ b/worker/src/routes/auth.ts @@ -6,7 +6,7 @@ import { now, getSetting, audit, tables } from '../lib/db' import { KV } from '../lib/kv' import { isSecure } from '../middleware/security' import { resolveAppOrigin, resolveRpID } from '../lib/app-url' -import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' +import { SPARK_WORKER_MOUNT, SPARK_WORKER_SESSION_COOKIE } from '../lib/spark-worker-link' import { hashPassword, verifyPassword, @@ -72,7 +72,7 @@ function clearSparkHistoryCookie(c: HeaderSetter, secure: boolean): void { function clearSparkWorkerCookie(c: HeaderSetter, secure: boolean): void { const flags = `HttpOnly; Path=${SPARK_WORKER_MOUNT}; Max-Age=0; SameSite=Lax${secure ? '; Secure' : ''}` - c.header('Set-Cookie', `spark_worker_session=; ${flags}`, { append: true }) + c.header('Set-Cookie', `${SPARK_WORKER_SESSION_COOKIE}=; ${flags}`, { append: true }) } // ── POST /api/auth/register ─────────────────────────────────────────────────── diff --git a/worker/src/routes/spark-history.ts b/worker/src/routes/spark-history.ts index b5fffd49..5a123fb3 100644 --- a/worker/src/routes/spark-history.ts +++ b/worker/src/routes/spark-history.ts @@ -1,10 +1,14 @@ import { type Context, Hono } from 'hono' import { getCookie } from 'hono/cookie' -import { createHistoryServerSessionToken, verifyHistoryServerSessionToken } from '../lib/auth' +import { + createHistoryServerSessionToken, + createWorkerUiSessionToken, + verifyHistoryServerSessionToken, +} from '../lib/auth' import { tables } from '../lib/db' import { openSecret } from '../lib/secrets' import { normalizeSparkAccess } from '../lib/spark-access' -import { rewriteSparkWorkerLink } from '../lib/spark-worker-link' +import { rewriteSparkWorkerLink, SPARK_WORKER_MOUNT, SPARK_WORKER_SESSION_COOKIE } from '../lib/spark-worker-link' import { requireAuth } from '../middleware/auth' import { isSecure } from '../middleware/security' import type { DatabaseRow, Env, Variables } from '../types' @@ -34,16 +38,9 @@ function withMount(path: string): string { return `${HISTORY_MOUNT}/${trimmed}` } -export function rewriteHistoryLocation( - location: string, - historyUrl: string, - requestUrl?: string, - databaseId?: string -): string { - if (databaseId) { - const workerLink = rewriteSparkWorkerLink(location, databaseId) - if (workerLink) return workerLink - } +export function rewriteHistoryLocation(location: string, historyUrl: string, requestUrl?: string): string { + const workerLink = rewriteSparkWorkerLink(location) + if (workerLink) return workerLink try { const locUrl = new URL(location) const targetUrl = new URL(historyUrl) @@ -93,19 +90,11 @@ export function rewriteHistoryLocation( } } -export function rewriteHistoryUrl( - val: string, - historyUrl: string, - _requestUrl?: string, - baseUrl?: string, - databaseId?: string -): string { +export function rewriteHistoryUrl(val: string, historyUrl: string, _requestUrl?: string, baseUrl?: string): string { if (!val || typeof val !== 'string') return val const trimmed = val.trim() - if (databaseId) { - const workerLink = rewriteSparkWorkerLink(trimmed, databaseId) - if (workerLink) return workerLink - } + const workerLink = rewriteSparkWorkerLink(trimmed) + if (workerLink) return workerLink if ( !trimmed || trimmed.startsWith('#') || @@ -171,7 +160,7 @@ export function rewriteHistoryUrl( return withMount(trimmed) } -export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl?: string, databaseId?: string): string { +export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl?: string): string { if (!html || typeof html !== 'string') return html // Resolve relative hrefs/srcs against the original when the page declares one. @@ -188,7 +177,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? // 1. Rewrite let result = html.replace(/]*)?>/gi, (match) => { return match.replace(/href\s*=\s*(["'])(.*?)\1/i, (_m, quote, attrVal) => { - return `href=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, undefined, databaseId)}${quote}` + return `href=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl)}${quote}` }) }) @@ -197,7 +186,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? let updatedRest = rest.replace( /\b(href|src|action)\s*=\s*(["'])(.*?)\2/gi, (_attrMatch: string, attrName: string, quote: string, attrVal: string) => { - return `${attrName}=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, baseUrl, databaseId)}${quote}` + return `${attrName}=${quote}${rewriteHistoryUrl(attrVal, historyUrl, requestUrl, baseUrl)}${quote}` } ) updatedRest = updatedRest.replace( @@ -209,7 +198,7 @@ export function rewriteHistoryHtml(html: string, historyUrl: string, requestUrl? const trimmed = part.trim() const [src, ...restTokens] = trimmed.split(/\s+/) if (!src) return part - return [rewriteHistoryUrl(src, historyUrl, requestUrl, baseUrl, databaseId), ...restTokens].join(' ') + return [rewriteHistoryUrl(src, historyUrl, requestUrl, baseUrl), ...restTokens].join(' ') }) .join(', ') return `srcset=${quote}${rewritten}${quote}` @@ -302,6 +291,19 @@ async function setHistoryServerSessionCookie( const secure = isSecure(c) const flags = `HttpOnly; Path=${HISTORY_MOUNT}; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` c.header('Set-Cookie', `spark_history_session=${sessionToken}; ${flags}`) + + // The History Server page emits the same executor log links into the Worker UI. Establish the + // Worker UI session cookie now so a later bare-navigation click on those links is authenticated. + const workerSessionToken = await createWorkerUiSessionToken( + { + userId: c.get('userId'), + role: c.get('userRole'), + databaseId, + }, + c.env + ) + const workerFlags = `HttpOnly; Path=${SPARK_WORKER_MOUNT}; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` + c.header('Set-Cookie', `${SPARK_WORKER_SESSION_COOKIE}=${workerSessionToken}; ${workerFlags}`, { append: true }) } export const sparkHistoryApi = new Hono<{ Bindings: Env; Variables: Variables }>() @@ -393,13 +395,13 @@ async function handleSparkHistory(c: Context<{ Bindings: Env; Variables: Variabl const loc = resHeaders.get('location') if (loc) { - resHeaders.set('location', rewriteHistoryLocation(loc, resolved.history_url, c.req.url, resolved.db.id)) + resHeaders.set('location', rewriteHistoryLocation(loc, resolved.history_url, c.req.url)) } const contentType = resHeaders.get('content-type') || '' if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) { const rawHtml = await proxyRes.text() - const rewrittenHtml = rewriteHistoryHtml(rawHtml, resolved.history_url, c.req.url, resolved.db.id) + const rewrittenHtml = rewriteHistoryHtml(rawHtml, resolved.history_url, c.req.url) return new Response(rewrittenHtml, { status: proxyRes.status, statusText: proxyRes.statusText, diff --git a/worker/src/routes/spark-ui.ts b/worker/src/routes/spark-ui.ts index 56849793..8a39974e 100644 --- a/worker/src/routes/spark-ui.ts +++ b/worker/src/routes/spark-ui.ts @@ -1,10 +1,10 @@ import { type Context, Hono } from 'hono' import { getCookie } from 'hono/cookie' -import { createSparkUiSessionToken, verifySparkUiSessionToken } from '../lib/auth' +import { createSparkUiSessionToken, createWorkerUiSessionToken, verifySparkUiSessionToken } from '../lib/auth' import { tables } from '../lib/db' import { openSecret } from '../lib/secrets' import { normalizeSparkAccess } from '../lib/spark-access' -import { rewriteSparkWorkerLink } from '../lib/spark-worker-link' +import { rewriteSparkWorkerLink, SPARK_WORKER_MOUNT, SPARK_WORKER_SESSION_COOKIE } from '../lib/spark-worker-link' import { requireAuth } from '../middleware/auth' import { isSecure } from '../middleware/security' import type { DatabaseRow, Env, Variables } from '../types' @@ -21,16 +21,9 @@ function stripSparkUiProxySegment(path: string): string { return path.replace(/^(\/spark-ui)?\/proxy\/[^/?#]+/, '$1') } -export function rewriteSparkUiLocation( - location: string, - uiUrl: string, - requestUrl?: string, - databaseId?: string -): string { - if (databaseId) { - const workerLink = rewriteSparkWorkerLink(location, databaseId) - if (workerLink) return workerLink - } +export function rewriteSparkUiLocation(location: string, uiUrl: string, requestUrl?: string): string { + const workerLink = rewriteSparkWorkerLink(location) + if (workerLink) return workerLink try { const locUrl = new URL(location) const targetUrl = new URL(uiUrl) @@ -90,13 +83,11 @@ export function rewriteSparkUiLocation( } } -export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: string, databaseId?: string): string { +export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: string): string { if (!val || typeof val !== 'string') return val const trimmed = val.trim() - if (databaseId) { - const workerLink = rewriteSparkWorkerLink(trimmed, databaseId) - if (workerLink) return workerLink - } + const workerLink = rewriteSparkWorkerLink(trimmed) + if (workerLink) return workerLink if ( !trimmed || trimmed.startsWith('#') || @@ -175,13 +166,13 @@ export function rewriteSparkUiUrl(val: string, uiUrl: string, _requestUrl?: stri return stripSparkUiProxySegment(`/spark-ui/${trimmed}`) } -export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: string, databaseId?: string): string { +export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: string): string { if (!html || typeof html !== 'string') return html // 1. Rewrite let result = html.replace(/]*)?>/gi, (match) => { return match.replace(/href\s*=\s*(["'])(.*?)\1/i, (_m, quote, attrVal) => { - const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl, databaseId) + const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl) return `href=${quote}${rewritten}${quote}` }) }) @@ -191,7 +182,7 @@ export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: str let updatedRest = rest.replace( /\b(href|src|action)\s*=\s*(["'])(.*?)\2/gi, (_attrMatch: string, attrName: string, quote: string, attrVal: string) => { - const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl, databaseId) + const rewritten = rewriteSparkUiUrl(attrVal, uiUrl, requestUrl) return `${attrName}=${quote}${rewritten}${quote}` } ) @@ -204,7 +195,7 @@ export function rewriteSparkUiHtml(html: string, uiUrl: string, requestUrl?: str const trimmed = part.trim() const [src, ...restTokens] = trimmed.split(/\s+/) if (!src) return part - return [rewriteSparkUiUrl(src, uiUrl, requestUrl, databaseId), ...restTokens].join(' ') + return [rewriteSparkUiUrl(src, uiUrl, requestUrl), ...restTokens].join(' ') }) .join(', ') return `srcset=${quote}${rewritten}${quote}` @@ -301,6 +292,20 @@ async function setSparkUiSessionCookie( const secure = isSecure(c) const flags = `HttpOnly; Path=/spark-ui; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` c.header('Set-Cookie', `spark_ui_session=${sessionToken}; ${flags}`) + + // The Spark UI page emits executor log links that point at the Worker UI. Establish the Worker UI + // session cookie now (same data source, scoped to /spark-worker) so a later click on those links + // is already authenticated — a bare navigation cannot carry the ?db= first-hit bearer. + const workerSessionToken = await createWorkerUiSessionToken( + { + userId: c.get('userId'), + role: c.get('userRole'), + databaseId, + }, + c.env + ) + const workerFlags = `HttpOnly; Path=${SPARK_WORKER_MOUNT}; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` + c.header('Set-Cookie', `${SPARK_WORKER_SESSION_COOKIE}=${workerSessionToken}; ${workerFlags}`, { append: true }) } export const sparkUiApi = new Hono<{ Bindings: Env; Variables: Variables }>() @@ -396,13 +401,13 @@ async function handleSparkUi(c: Context<{ Bindings: Env; Variables: Variables }> const loc = resHeaders.get('location') if (loc) { - resHeaders.set('location', rewriteSparkUiLocation(loc, resolved.ui_url, c.req.url, resolved.db.id)) + resHeaders.set('location', rewriteSparkUiLocation(loc, resolved.ui_url, c.req.url)) } const contentType = resHeaders.get('content-type') || '' if (contentType.includes('text/html') || contentType.includes('application/xhtml+xml')) { const rawHtml = await proxyRes.text() - const rewrittenHtml = rewriteSparkUiHtml(rawHtml, resolved.ui_url, c.req.url, resolved.db.id) + const rewrittenHtml = rewriteSparkUiHtml(rawHtml, resolved.ui_url, c.req.url) return new Response(rewrittenHtml, { status: proxyRes.status, statusText: proxyRes.statusText, diff --git a/worker/src/routes/spark-worker.ts b/worker/src/routes/spark-worker.ts index eccecac1..2a1a48a6 100644 --- a/worker/src/routes/spark-worker.ts +++ b/worker/src/routes/spark-worker.ts @@ -4,7 +4,7 @@ import { createWorkerUiSessionToken, verifyWorkerUiSessionToken } from '../lib/a import { tables } from '../lib/db' import { openSecret } from '../lib/secrets' import { normalizeSparkAccess } from '../lib/spark-access' -import { SPARK_WORKER_MOUNT } from '../lib/spark-worker-link' +import { SPARK_WORKER_MOUNT, SPARK_WORKER_SESSION_COOKIE } from '../lib/spark-worker-link' import { requireAuth } from '../middleware/auth' import { isSecure } from '../middleware/security' import type { DatabaseRow, Env, Variables } from '../types' @@ -260,7 +260,7 @@ async function setWorkerSessionCookie( ) const secure = isSecure(c) const flags = `HttpOnly; Path=${WORKER_MOUNT}; Max-Age=86400; SameSite=Lax${secure ? '; Secure' : ''}` - c.header('Set-Cookie', `spark_worker_session=${sessionToken}; ${flags}`) + c.header('Set-Cookie', `${SPARK_WORKER_SESSION_COOKIE}=${sessionToken}; ${flags}`) } export const sparkWorkerApi = new Hono<{ Bindings: Env; Variables: Variables }>() @@ -304,7 +304,7 @@ async function handleSparkWorker(c: Context<{ Bindings: Env; Variables: Variable } // Subsequent requests: parse databaseId from the signed cookie. - const cookie = getCookie(c, 'spark_worker_session') + const cookie = getCookie(c, SPARK_WORKER_SESSION_COOKIE) if (!cookie) { return c.json({ error: 'Unauthorized' }, 401) }