From 5be5674c9161ba3554bb960377aa9c5f1cb8feb3 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:32:00 +0000 Subject: [PATCH 1/2] fix(ui): make request IDs and copying work over plain HTTP `crypto.randomUUID` and `navigator.clipboard` exist only in secure contexts (HTTPS or localhost). Served over plain HTTP behind a proxy, every action that makes an ID failed with "crypto.randomUUID is not a function": starting, cancelling and rerunning runs, acknowledging, and changing triggers. Copy buttons either threw or said "Copied" without copying. - `newRequestId()` uses `crypto.randomUUID` where it exists, and otherwise builds an RFC 4122 version 4 UUID from `crypto.getRandomValues`, which every context has. - `copyText()` uses the Clipboard API where it exists and works, and otherwise copies from a hidden textarea. Copy buttons say "Copied" only when the text was copied. - A unit check keeps `crypto.randomUUID` and `navigator.clipboard` out of everything but these two helpers. - Tests: the fallback's format, version and variant bits, and uniqueness; in a browser with both APIs removed before the app loads, a plan (which makes a request ID) opens, and Copy as sqb build copies. --- ui/e2e/insecure-context.spec.ts | 34 +++++++++++++++++++ ui/src/lib/api/http-client.ts | 23 +++++++------ ui/src/lib/api/mock/large-project.ts | 3 +- ui/src/lib/browser/clipboard.ts | 29 ++++++++++++++++ ui/src/lib/browser/request-id.test.ts | 27 +++++++++++++++ ui/src/lib/browser/request-id.ts | 14 ++++++++ .../lib/browser/secure-context-only.test.ts | 31 +++++++++++++++++ ui/src/lib/components/code/sql-viewer.svelte | 4 +-- ui/src/lib/components/copy-button.svelte | 4 +-- .../components/platform/issued-secret.svelte | 4 +-- .../components/selection/selection-bar.svelte | 4 +-- ui/src/routes/plan/+page.svelte | 4 +-- 12 files changed, 159 insertions(+), 22 deletions(-) create mode 100644 ui/e2e/insecure-context.spec.ts create mode 100644 ui/src/lib/browser/clipboard.ts create mode 100644 ui/src/lib/browser/request-id.test.ts create mode 100644 ui/src/lib/browser/request-id.ts create mode 100644 ui/src/lib/browser/secure-context-only.test.ts diff --git a/ui/e2e/insecure-context.spec.ts b/ui/e2e/insecure-context.spec.ts new file mode 100644 index 0000000000..0538ccc4d0 --- /dev/null +++ b/ui/e2e/insecure-context.spec.ts @@ -0,0 +1,34 @@ +import { expect, test } from '@playwright/test'; + +// Served over plain HTTP from a host name, a page is not a secure context: `crypto.randomUUID` and +// `navigator.clipboard` don't exist. Both are removed before the app loads, as they would be there. +test.beforeEach(async ({ page }) => { + await page.addInitScript(() => { + Object.defineProperty(Crypto.prototype, 'randomUUID', { value: undefined, configurable: true }); + Object.defineProperty(Navigator.prototype, 'clipboard', { get: () => undefined, configurable: true }); + const w = window as unknown as { copied: string[] }; + w.copied = []; + document.addEventListener('copy', () => w.copied.push(String(document.getSelection() ?? ''))); + }); +}); + +test('a plan, which makes a request ID, opens without randomUUID', async ({ page }) => { + const errors: string[] = []; + page.on('pageerror', (e) => errors.push(e.message)); + await page.goto(`/plan?mock&large&cmd=${encodeURIComponent('sqb build --changed')}`); + expect(await page.evaluate(() => typeof crypto.randomUUID)).toBe('undefined'); + await expect(page.locator('.pane .plan-row').first()).toBeVisible({ timeout: 30_000 }); + expect(errors).toEqual([]); +}); + +test('copying a selection works without navigator.clipboard', async ({ page }) => { + await page.goto('/catalog?mock'); + const name = (await page.locator('table.catalog tbody tr .cell-name a').first().innerText({ timeout: 20_000 })).trim(); + await page.goto(`/catalog?mock&select=${encodeURIComponent(name)}`); + const copy = page.getByRole('button', { name: /^Copy as/ }); + // Enabled once the selection is checked and names a node. + await expect(page.getByText(/^1 of \d+ nodes$/)).toBeVisible({ timeout: 20_000 }); + await expect(copy).toBeEnabled(); + await copy.click(); + await expect.poll(() => page.evaluate(() => (window as unknown as { copied: string[] }).copied)).toEqual([`sqb build -s ${name}`]); +}); diff --git a/ui/src/lib/api/http-client.ts b/ui/src/lib/api/http-client.ts index a75a3a54af..38ea88ac47 100644 --- a/ui/src/lib/api/http-client.ts +++ b/ui/src/lib/api/http-client.ts @@ -23,6 +23,7 @@ import type { AuthMode, Bootstrap, Capability, Location, NavCounts, PlatformEven import type { Account, AuditEntry, AuditQuery, ConnectionTest, LocationDetail, ServerSettings, WarehouseConnection, LocationSummary, PlatformEventQuery, PlatformEventRecord, PlatformHealth, MaintenanceHistory, ProviderConnection, RoleAssignment, RoleAssignmentRequest, RoleDefinition, RoleDetail } from './types/platform'; import type { Acknowledgement, CatalogNode, CatalogNodeDetail, Check, CheckDetail, CheckEvidence, CheckSql, NodeStates, NodeStatusDelta, Overview, SnapshotChange, ColumnLineage } from './types/build'; import type { AdhocRunCheck, AdhocRunRequest, BulkRunResult, SelectionEvaluation, SelectionRequest, SelectionVocabulary, PlanDiff, PlanPage, PlanPageSection, PlanResult, QueueEntry, Timeline, Job, JobDetail, JobLaunchOptions, RerunMode, SnapshotNode, Run, RunDetail, RunListQuery, RunRowPage, RunRowQuery, RunTabCounts, Trigger, TriggerDetail, TriggerState, RunEventPage, RunNodeError, RunOutputLine, RunStatement, IgnoredAuditFailure, RunCostRow, CostSummary, NodeBuildCost, StatementSql } from './types/operate'; +import { newRequestId } from '$lib/browser/request-id'; type Wire = components['schemas']; @@ -364,7 +365,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, const { rows } = runRowPageOver([await listedRuns(scope)], scope.locationId, { ...query, cursor: null, limit: RUN_WINDOW }); const result: BulkRunResult = { done: [], failed: [] }; for (const { run } of rows.filter((row) => isActiveRun(row.run.status) && !row.cancelRequestedAt)) { - const body = { run_id: run.id, event_id: crypto.randomUUID(), reason: 'Cancelled from the web UI' }; + const body = { run_id: run.id, event_id: newRequestId(), reason: 'Cancelled from the web UI' }; const { error, response } = await http.POST('/api/control/runs/cancel', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); if (response.status === 401) onUnauthorized(); if (response.ok) result.done.push(run.id); @@ -483,7 +484,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, return { nodeKey: data.node_key, errorCode: data.error_code ?? null, message: data.message ?? null, file: data.path ?? null }; }, async cancelRun(scope: Scope, runId: string): Promise { - const body = { run_id: runId, event_id: crypto.randomUUID(), reason: 'Cancelled from the web UI' }; + const body = { run_id: runId, event_id: newRequestId(), reason: 'Cancelled from the web UI' }; const { error, response } = await http.POST('/api/control/runs/cancel', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); forgetPending(); if (response.status === 401) onUnauthorized(); @@ -492,7 +493,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, }, async rerunSelectedNodes(scope: Scope, runId: string, nodes: string[]): Promise { const source = await requireRun(scope, runId); - const body = { run_id: crypto.randomUUID(), source_run_id: runId, from_failure: false, nodes, priority: source.priority, reason: 'Rerun selected nodes from the web UI' }; + const body = { run_id: newRequestId(), source_run_id: runId, from_failure: false, nodes, priority: source.priority, reason: 'Rerun selected nodes from the web UI' }; const { error, response } = await http.POST('/api/control/runs/rerun', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); forgetPending(); if (response.status === 401) onUnauthorized(); @@ -502,7 +503,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, async acknowledgeRun(scope: Scope, runId: string, acknowledged: boolean): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const { error, response } = await http.POST('/api/control/locations/{location_id}/targets/{target}/acknowledgements', { - body: { event_id: crypto.randomUUID(), run_id: runId, acknowledged }, + body: { event_id: newRequestId(), run_id: runId, acknowledged }, params: { path: { location_id: locationId, target }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); if (response.status === 401) onUnauthorized(); @@ -510,7 +511,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, }, async rerunRun(scope: Scope, runId: string, mode: Exclude): Promise { const source = await requireRun(scope, runId); - const body = { run_id: crypto.randomUUID(), source_run_id: runId, from_failure: mode === 'from_failure', priority: source.priority, reason: 'Rerun from the web UI' }; + const body = { run_id: newRequestId(), source_run_id: runId, from_failure: mode === 'from_failure', priority: source.priority, reason: 'Rerun from the web UI' }; const { error, response } = await http.POST('/api/control/runs/rerun', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); forgetPending(); if (response.status === 401) onUnauthorized(); @@ -576,7 +577,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, }, async launchAdhocRun(scope: Scope, request: AdhocRunRequest): Promise { const { locationId, target } = parseLocationKey(scope.locationId); - const body = { run_id: crypto.randomUUID(), location_id: locationId, target, command: request.command, priority: request.priority, reason: 'Started from the web UI' }; + const body = { run_id: newRequestId(), location_id: locationId, target, command: request.command, priority: request.priority, reason: 'Started from the web UI' }; const { error, response } = await http.POST('/api/control/runs/adhoc', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); forgetPending(); if (response.status === 401) onUnauthorized(); @@ -590,7 +591,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, async planBuild(scope: Scope, command: string[]): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const path = { location_id: locationId, target }; - const requestId = crypto.randomUUID(); + const requestId = newRequestId(); const asked = await http.POST('/api/control/locations/{location_id}/targets/{target}/plans', { body: { request_id: requestId, command }, params: { path, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } @@ -662,7 +663,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, async requestWarehouseSync(scope: Scope): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const { error, response } = await http.POST('/api/control/locations/{location_id}/targets/{target}/warehouse-syncs', { - body: { request_id: crypto.randomUUID(), reason: 'Requested from the web UI' }, + body: { request_id: newRequestId(), reason: 'Requested from the web UI' }, params: { path: { location_id: locationId, target }, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); if (response.status === 401) onUnauthorized(); @@ -672,7 +673,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, async testConnection(scope: Scope): Promise { const { locationId, target } = parseLocationKey(scope.locationId); const path = { location_id: locationId, target }; - const requestId = crypto.randomUUID(); + const requestId = newRequestId(); const asked = await http.POST('/api/control/locations/{location_id}/targets/{target}/connection-tests', { body: { request_id: requestId, reason: 'Tested from the web UI' }, params: { path, header: { 'x-sqb-csrf': csrfToken(document.cookie) } } @@ -1149,7 +1150,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, /** Records an operator change; the server takes the actor from the session and needs a reason. */ async function changeTrigger(triggerId: string, change: Wire['TriggerChange'], reason?: string | null) { - const body = { trigger_id: triggerId, event_id: crypto.randomUUID(), actor: '', reason: reason?.trim() || 'Changed from the web UI', change }; + const body = { trigger_id: triggerId, event_id: newRequestId(), actor: '', reason: reason?.trim() || 'Changed from the web UI', change }; const { error, response } = await http.POST('/api/control/triggers', { body, params: { header: { 'x-sqb-csrf': csrfToken(document.cookie) } } }); forgetPending(); if (response.status === 401) onUnauthorized(); @@ -1223,7 +1224,7 @@ export function createHttpClient({ baseUrl = '', onUnauthorized, fetch: answer, const narrowed = !!(options?.select?.length || options?.exclude?.length); const reason = fullRefresh ? 'Full refresh started from the web UI' : window ? 'Backfill started from the web UI' : narrowed ? 'Part of the job started from the web UI' : 'Started from the web UI'; const body = { - run_id: crypto.randomUUID(), + run_id: newRequestId(), location_id: locationId, target, job_key: key, diff --git a/ui/src/lib/api/mock/large-project.ts b/ui/src/lib/api/mock/large-project.ts index 02104efa43..835face93c 100644 --- a/ui/src/lib/api/mock/large-project.ts +++ b/ui/src/lib/api/mock/large-project.ts @@ -8,6 +8,7 @@ import type { PlanDocument, PlanPage, PlanResult } from '../types'; import { largePlanDocument, planModelDiff, planPage, planSummary } from './large-plan'; import { recordPlanDiff, recordPlanRows } from './plan-rows-log'; import type { CatalogNode } from '../types'; +import { newRequestId } from '$lib/browser/request-id'; const LAYERS = [['sources'], ['seeds', 'orders'], ['customers', 'inventory'], ['payments', 'shipping'], ['returns', 'pricing'], ['suppliers', 'regions'], ['finance', 'marketing']]; const PER_SUBFOLDER = 15; @@ -53,7 +54,7 @@ export function largeProject(client: ApiClient): ApiClient { const result = await target.planBuild(...args); if (!result.plan) return result; const doc = largePlanDocument(args[1].some((t) => t === '--changed' || t.startsWith('--changed='))); - const requestId = crypto.randomUUID(); + const requestId = newRequestId(); plans.set(requestId, doc); return { plan: { ...planSummary(doc), timings: result.plan.timings }, error: null, requestId }; }; diff --git a/ui/src/lib/browser/clipboard.ts b/ui/src/lib/browser/clipboard.ts new file mode 100644 index 0000000000..e9a2d2853e --- /dev/null +++ b/ui/src/lib/browser/clipboard.ts @@ -0,0 +1,29 @@ +// Copies text. `navigator.clipboard` exists only in secure contexts (HTTPS or localhost), and the UI is also +// served over plain HTTP behind a proxy, so without it the text is copied from a hidden textarea. + +/** Copies `text`; whether it was copied. Call it from a click, which the fallback needs. */ +export async function copyText(text: string): Promise { + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(text); + return true; + } catch { + // Denied or unavailable: try the fallback. + } + } + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', ''); + area.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0;'; + const focused = document.activeElement as HTMLElement | null; + document.body.append(area); + area.select(); + try { + return document.execCommand('copy'); + } catch { + return false; + } finally { + area.remove(); + focused?.focus?.(); + } +} diff --git a/ui/src/lib/browser/request-id.test.ts b/ui/src/lib/browser/request-id.test.ts new file mode 100644 index 0000000000..55e8c637c9 --- /dev/null +++ b/ui/src/lib/browser/request-id.test.ts @@ -0,0 +1,27 @@ +import { webcrypto } from 'node:crypto'; +import { describe, expect, it } from 'vitest'; +import { newRequestId } from './request-id'; + +const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +/** A browser page that is not a secure context: random values, but no `randomUUID`. */ +const insecure = { getRandomValues: (array: T) => webcrypto.getRandomValues(array as Uint8Array) as unknown as T }; + +describe('request IDs', () => { + it('builds RFC 4122 version 4 UUIDs from random values when randomUUID is missing', () => { + const ids = Array.from({ length: 2000 }, () => newRequestId(insecure)); + for (const id of ids) expect(id).toMatch(V4); + expect(new Set(ids).size).toBe(ids.length); + }); + + it('sets the version and variant bits whatever the random bytes are', () => { + for (const fill of [0x00, 0xff]) { + const id = newRequestId({ getRandomValues: (a: T) => ((a as Uint8Array).fill(fill), a) }); + expect(id).toMatch(V4); + } + expect(newRequestId({ getRandomValues: (a: T) => ((a as Uint8Array).fill(0), a) })).toBe('00000000-0000-4000-8000-000000000000'); + }); + + it('uses randomUUID where the page has it', () => { + expect(newRequestId({ ...insecure, randomUUID: () => 'from-randomUUID' })).toBe('from-randomUUID'); + }); +}); diff --git a/ui/src/lib/browser/request-id.ts b/ui/src/lib/browser/request-id.ts new file mode 100644 index 0000000000..32d5c50936 --- /dev/null +++ b/ui/src/lib/browser/request-id.ts @@ -0,0 +1,14 @@ +// IDs for the requests the UI makes (runs, events, plans). `crypto.randomUUID` exists only in secure +// contexts (HTTPS or localhost), and the UI is also served over plain HTTP behind a proxy, so without it +// the ID is built from `crypto.getRandomValues`, which every context has. Never `Math.random`: these IDs +// make retried requests apply once, so they must not collide. + +/** A random RFC 4122 version 4 UUID. */ +export function newRequestId(source: Pick & { randomUUID?: () => string } = crypto): string { + if (typeof source.randomUUID === 'function') return source.randomUUID(); + const bytes = source.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant 10xx + const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/ui/src/lib/browser/secure-context-only.test.ts b/ui/src/lib/browser/secure-context-only.test.ts new file mode 100644 index 0000000000..6ccb7324d8 --- /dev/null +++ b/ui/src/lib/browser/secure-context-only.test.ts @@ -0,0 +1,31 @@ +// `crypto.randomUUID` and `navigator.clipboard` exist only in secure contexts (HTTPS or localhost), and the +// UI is also served over plain HTTP behind a proxy, where calling them breaks every action that makes an +// ID or copies text. Use `newRequestId` (request-id.ts) and `copyText` (clipboard.ts), which fall back. +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const SRC = new URL('../../', import.meta.url).pathname; +const BANNED = /\bcrypto\.randomUUID\b|\bnavigator\.clipboard\b/; +const HELPERS = new Set(['lib/browser/request-id.ts', 'lib/browser/clipboard.ts']); + +function files(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return files(path); + return /\.(ts|svelte|js)$/.test(name) && !/\.test\.ts$/.test(name) ? [path] : []; + }); +} + +describe('secure-context-only browser APIs', () => { + it('are called only from the helpers that fall back without them', () => { + const found = files(SRC).flatMap((path) => { + const file = relative(SRC, path); + if (HELPERS.has(file)) return []; + return readFileSync(path, 'utf8') + .split('\n') + .flatMap((line, i) => (BANNED.test(line) ? [`${file}:${i + 1}: ${line.trim()}`] : [])); + }); + expect(found, 'use newRequestId or copyText from $lib/browser').toEqual([]); + }); +}); diff --git a/ui/src/lib/components/code/sql-viewer.svelte b/ui/src/lib/components/code/sql-viewer.svelte index 7da2b7be6b..c223a4a162 100644 --- a/ui/src/lib/components/code/sql-viewer.svelte +++ b/ui/src/lib/components/code/sql-viewer.svelte @@ -1,4 +1,5 @@ diff --git a/ui/src/lib/components/copy-button.svelte b/ui/src/lib/components/copy-button.svelte index 5b900afdbb..1db7d1c84e 100644 --- a/ui/src/lib/components/copy-button.svelte +++ b/ui/src/lib/components/copy-button.svelte @@ -1,4 +1,5 @@ diff --git a/ui/src/lib/components/selection/selection-bar.svelte b/ui/src/lib/components/selection/selection-bar.svelte index e2d35463fd..7aad319109 100644 --- a/ui/src/lib/components/selection/selection-bar.svelte +++ b/ui/src/lib/components/selection/selection-bar.svelte @@ -1,4 +1,5 @@ @@ -18,7 +23,8 @@
{label}

Copy it now: it's shown only this once and can't be retrieved later. If it's lost, rotate the token.

- {secret} + {secret} + {#if failed}{/if}
@@ -55,6 +61,10 @@ font-family: var(--font-mono); font-size: 12px; } + .manual { + margin: 6px 0 0; + color: var(--sb-warning); + } .actions { display: flex; gap: 6px;