From 425ed02aadd4d64e577187f68a820bb8a4b51931 Mon Sep 17 00:00:00 2001 From: Rubab Khan Date: Wed, 11 Nov 2026 15:56:01 -0800 Subject: [PATCH] fix: remediate CodeQL scan findings - minimatch 10.2.6 (transitive dev dependency of eslint and typescript-eslint) is affected by GHSA-g3hv-75wg-m249. No eslint or typescript-eslint release yet depends on a patched minimatch, so the fixed version is forced with an exact npm override and the lock is regenerated. Lint output is unchanged under 11.0.8. - frontend, e2e fixtures: draw session-id fallback, idempotency keys, event keys and test run ids from crypto.getRandomValues via a shared randomToken helper (one per npm project); Math.random is removed and a unit test forbids it returning. - scripts: rewrite three regexes with ambiguous whitespace into equivalent linear forms (SSE union parser, iam_roles string-list locals, route_invoke_arns contract test), each pinned by tests. - CloudFront smoke and CSP tests: accept script end tags with trailing content and any case; a guard pins index.html's literal tag forms. - tests: replace host-substring assertions with exact-output, anchored grant-line and parsed-hostname assertions. - relay tests: build the non-Bearer Basic header fixture at runtime. - test_no_math_random: run git through scripts.proc_run instead of a direct subprocess call, as check_subprocess_funnel requires. - test_e2e_browser_scaffold: apply the extractor sanity check only to sources that contain an import or re-export statement, so an import-free fixture passes while a missed import still fails. --- frontend/package-lock.json | 18 +++- frontend/package.json | 3 + frontend/src/components/forms/AccountForm.tsx | 3 +- frontend/src/components/forms/ContactForm.tsx | 3 +- .../components/timeline/LogActivityForm.tsx | 7 +- frontend/src/hooks/useAgentStream.test.ts | 14 +++ frontend/src/hooks/useAgentStream.ts | 14 +-- frontend/src/lib/randomToken.test.ts | 102 ++++++++++++++++++ frontend/src/lib/randomToken.ts | 40 +++++++ .../useActivities.transactionKey.test.ts | 49 +++++++++ .../src/pages/activities/useActivities.ts | 5 +- .../src/pages/approvals/transactionKey.ts | 10 +- .../opportunities/OpportunityCreatePage.tsx | 7 +- .../opportunities/OpportunityDetailPage.tsx | 7 +- .../src/pages/pipeline/usePipelineBoard.ts | 5 +- scripts/check_sse_schema_parity.py | 2 +- scripts/smoke/cloudfront.py | 2 +- scripts/smoke/iam_roles.py | 2 +- src/relay/tests/index.test.ts | 2 +- src/relay/tests/jwt.test.ts | 2 +- tests/e2e/browser/fixtures/pageApi.ts | 4 +- tests/e2e/browser/fixtures/randomToken.ts | 25 +++++ tests/e2e/browser/fixtures/teardown.ts | 3 +- tests/unit/test_check_sse_schema_parity.py | 76 +++++++++++++ tests/unit/test_e2e_browser_scaffold.py | 48 ++++++++- tests/unit/test_eval_run_status_contract.py | 46 ++++++-- tests/unit/test_infra_csp.py | 43 +++++++- tests/unit/test_infra_cursor_key.py | 2 +- tests/unit/test_no_math_random.py | 79 ++++++++++++++ tests/unit/test_plan_security_baseline.py | 5 +- tests/unit/test_smoke_cloudfront.py | 17 +++ tests/unit/test_smoke_iam_roles.py | 87 +++++++++++++++ tests/unit/test_token_accounting.py | 15 ++- 33 files changed, 677 insertions(+), 70 deletions(-) create mode 100644 frontend/src/lib/randomToken.test.ts create mode 100644 frontend/src/lib/randomToken.ts create mode 100644 frontend/src/pages/activities/useActivities.transactionKey.test.ts create mode 100644 tests/e2e/browser/fixtures/randomToken.ts create mode 100644 tests/unit/test_no_math_random.py diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 2404c38..cde4f4c 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1160,6 +1160,13 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -6399,16 +6406,17 @@ } }, "node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^5.0.8" + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" diff --git a/frontend/package.json b/frontend/package.json index 630e5da..d71353d 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -67,5 +67,8 @@ "typescript-eslint": "8.72.1", "vite": "8.3.6", "vitest": "5.1.0" + }, + "overrides": { + "minimatch": "11.0.8" } } diff --git a/frontend/src/components/forms/AccountForm.tsx b/frontend/src/components/forms/AccountForm.tsx index 3302ce0..0daaf09 100644 --- a/frontend/src/components/forms/AccountForm.tsx +++ b/frontend/src/components/forms/AccountForm.tsx @@ -6,6 +6,7 @@ import { useId, useState, type FormEvent, type JSX } from "react"; import { useCrmApi } from "../../api/useCrmApi"; +import { randomToken } from "../../lib/randomToken"; import type { Account } from "../../types/domain"; import { ErrorBanner } from "./ErrorBanner"; @@ -79,7 +80,7 @@ export function AccountForm({ initial, onSaved, onCancel }: AccountFormProps): J region: values.region || undefined, website: values.website || undefined, employee_count: employeeCount, - transaction_key: `create-account-${Date.now()}-${Math.random().toString(36).slice(2)}`, + transaction_key: `create-account-${Date.now()}-${randomToken(11)}`, }); const accountId = extractAccountId(response); onSaved(accountId ?? ""); diff --git a/frontend/src/components/forms/ContactForm.tsx b/frontend/src/components/forms/ContactForm.tsx index b8883ad..792b8f0 100644 --- a/frontend/src/components/forms/ContactForm.tsx +++ b/frontend/src/components/forms/ContactForm.tsx @@ -6,6 +6,7 @@ import { useId, useState, type FormEvent, type JSX } from "react"; import { useCrmApi } from "../../api/useCrmApi"; +import { randomToken } from "../../lib/randomToken"; import type { Contact, ContactStatus } from "../../types/domain"; import { ErrorBanner } from "./ErrorBanner"; @@ -86,7 +87,7 @@ export function ContactForm({ email: values.email || undefined, phone: values.phone || undefined, status: values.status, - transaction_key: `create-contact-${Date.now()}-${Math.random().toString(36).slice(2)}`, + transaction_key: `create-contact-${Date.now()}-${randomToken(11)}`, }); const contactId = extractContactId(response); onSaved(contactId ?? ""); diff --git a/frontend/src/components/timeline/LogActivityForm.tsx b/frontend/src/components/timeline/LogActivityForm.tsx index 6e4bd28..ffe41bf 100644 --- a/frontend/src/components/timeline/LogActivityForm.tsx +++ b/frontend/src/components/timeline/LogActivityForm.tsx @@ -6,18 +6,13 @@ import { useId, useState, type FormEvent, type JSX } from "react"; import { useCrmApi } from "../../api/useCrmApi"; +import { newTransactionKey } from "../../lib/randomToken"; import { ACTIVITY_KINDS, type ActivityKind } from "../../types/domain"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { cn, focusRing } from "../ui/utils"; import { ApiErrorBanner } from "../../pages/opportunities/ApiErrorBanner"; -function newTransactionKey(): string { - return typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`; -} - /** Field label styling, shared by every control on this form. */ const fieldLabel = "text-xs font-medium tracking-wide text-text-secondary"; diff --git a/frontend/src/hooks/useAgentStream.test.ts b/frontend/src/hooks/useAgentStream.test.ts index 5f9789b..19e0a95 100644 --- a/frontend/src/hooks/useAgentStream.test.ts +++ b/frontend/src/hooks/useAgentStream.test.ts @@ -414,6 +414,20 @@ describe("newSessionId satisfies the runtimeSessionId bound", () => { expect(id).not.toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-/); }); + it("pads the fallback from crypto.getRandomValues, never Math.random", () => { + const randomSpy = vi.spyOn(Math, "random"); + try { + withoutRandomUUID(() => { + const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues"); + newSessionId(); + expect(cryptoSpy).toHaveBeenCalled(); + }); + expect(randomSpy).not.toHaveBeenCalled(); + } finally { + randomSpy.mockRestore(); + } + }); + it("complies on the fallback path across many draws, not just one", () => { // The fallback's random suffix varies in length, so the bound is checked over many draws. const lengths = new Set(); diff --git a/frontend/src/hooks/useAgentStream.ts b/frontend/src/hooks/useAgentStream.ts index 2d05528..3a02ddf 100644 --- a/frontend/src/hooks/useAgentStream.ts +++ b/frontend/src/hooks/useAgentStream.ts @@ -44,6 +44,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import type { AuthContextValue } from "../auth/AuthProvider"; import { buildRelayRequest, type RelayRequest } from "../lib/agentClient"; +import { randomToken } from "../lib/randomToken"; import type { AgentEventFrame } from "../types/generated/agentEvents"; /** The closed set of event kinds this hook understands natively. */ @@ -178,15 +179,6 @@ const RECONNECT_BACKOFF_MS = 1000; export const SESSION_ID_MIN_LENGTH = 33; export const SESSION_ID_MAX_LENGTH = 256; -/** Base-36 randomness of exactly `length` characters, drawing again as needed. */ -function randomBase36(length: number): string { - let out = ""; - while (out.length < length) { - out += Math.random().toString(36).slice(2); - } - return out.slice(0, length); -} - /** * A session id within {@link SESSION_ID_MIN_LENGTH} and {@link SESSION_ID_MAX_LENGTH}. * @@ -199,7 +191,7 @@ export function newSessionId(): string { } const prefix = `session-${Date.now()}-`; const shortfall = Math.max(0, SESSION_ID_MIN_LENGTH - prefix.length); - return `${prefix}${randomBase36(Math.max(shortfall, 11))}`.slice(0, SESSION_ID_MAX_LENGTH); + return `${prefix}${randomToken(Math.max(shortfall, 11))}`.slice(0, SESSION_ID_MAX_LENGTH); } /** @@ -325,7 +317,7 @@ export function useAgentStream(options: UseAgentStreamOptions): UseAgentStreamRe ]; const unrecognised = !knownKinds.includes(event.kind as KnownEventKind); eventCountRef.current += 1; - const key = `evt-${eventCountRef.current}-${Math.random().toString(36).slice(2, 8)}`; + const key = `evt-${eventCountRef.current}-${randomToken(6)}`; setTranscript((prev) => [...prev, { key, event, unrecognised }]); if (event.kind === "completed" || event.kind === "error") { setTurnEnded(true); diff --git a/frontend/src/lib/randomToken.test.ts b/frontend/src/lib/randomToken.test.ts new file mode 100644 index 0000000..8a5fb39 --- /dev/null +++ b/frontend/src/lib/randomToken.test.ts @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: MIT +// Tests for `lib/randomToken.ts`: exact length, base-36 alphabet, crypto-only randomness with +// rejection of biased bytes, input validation, and both `newTransactionKey` branches. +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { newTransactionKey, randomToken } from "./randomToken"; + +const realCrypto = globalThis.crypto; + +/** Replace the global `crypto` with one lacking `randomUUID`, keeping `getRandomValues`. */ +function hideRandomUUID(): { getRandomValues: ReturnType } { + const getRandomValues = vi.fn(>(array: T): T => + realCrypto.getRandomValues(array), + ); + vi.stubGlobal("crypto", { getRandomValues }); + return { getRandomValues }; +} + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe("randomToken", () => { + it.each([1, 6, 11, 32, 200])("returns exactly %i characters", (length) => { + expect(randomToken(length)).toHaveLength(length); + }); + + it("uses only lowercase base-36 characters", () => { + expect(randomToken(2000)).toMatch(/^[0-9a-z]+$/); + }); + + it("produces distinct tokens across many draws", () => { + const tokens = new Set(Array.from({ length: 1000 }, () => randomToken(11))); + expect(tokens.size).toBe(1000); + }); + + it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY])( + "throws RangeError for length %s", + (length) => { + expect(() => randomToken(length)).toThrow(RangeError); + }, + ); + + it("uses crypto.getRandomValues, not Math.random", () => { + const randomSpy = vi.spyOn(Math, "random"); + const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues"); + randomToken(64); + expect(cryptoSpy).toHaveBeenCalled(); + expect(randomSpy).not.toHaveBeenCalled(); + }); + + it("rejects bytes >= 252 instead of mapping them", () => { + const batches = [ + [252, 255, 253, 254, 0], + [1, 35, 251], + ]; + const getRandomValues = vi.fn((array: T): T => { + const view = array as unknown as Uint8Array; + view.fill(252); + view.set((batches.shift() ?? []).slice(0, view.length)); + return array; + }); + vi.stubGlobal("crypto", { getRandomValues }); + expect(randomToken(4)).toBe("01zz"); + }); + + it("resolves globalThis.crypto at call time", () => { + const { getRandomValues } = hideRandomUUID(); + randomToken(8); + expect(getRandomValues).toHaveBeenCalled(); + }); + + it("throws rather than degrading when Web Crypto is absent", () => { + vi.stubGlobal("crypto", undefined); + const randomSpy = vi.spyOn(Math, "random"); + expect(() => randomToken(8)).toThrow(); + expect(randomSpy).not.toHaveBeenCalled(); + }); +}); + +describe("newTransactionKey", () => { + it("returns crypto.randomUUID() when it is available", () => { + const uuidSpy = vi.spyOn(globalThis.crypto, "randomUUID"); + const key = newTransactionKey(); + expect(uuidSpy).toHaveBeenCalledOnce(); + expect(key).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/); + }); + + it("falls back to txn--<11 base-36> by default without randomUUID", () => { + const { getRandomValues } = hideRandomUUID(); + const randomSpy = vi.spyOn(Math, "random"); + expect(newTransactionKey()).toMatch(/^txn-\d+-[0-9a-z]{11}$/); + expect(getRandomValues).toHaveBeenCalled(); + expect(randomSpy).not.toHaveBeenCalled(); + }); + + it("uses an overriding prefix in the fallback", () => { + hideRandomUUID(); + expect(newTransactionKey("tk")).toMatch(/^tk-\d+-[0-9a-z]{11}$/); + }); +}); diff --git a/frontend/src/lib/randomToken.ts b/frontend/src/lib/randomToken.ts new file mode 100644 index 0000000..fa80b8a --- /dev/null +++ b/frontend/src/lib/randomToken.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: MIT +/** + * Cryptographically random tokens and idempotency keys for the SPA. + * + * `randomToken(length)` draws from `globalThis.crypto.getRandomValues`, resolved on every call, and + * throws when no Web Crypto is present. `newTransactionKey(prefix)` prefers `crypto.randomUUID()`. + */ + +const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz"; +const UNBIASED_LIMIT = ALPHABET.length * Math.floor(256 / ALPHABET.length); + +/** Lowercase base-36 token of exactly `length` characters from `crypto.getRandomValues`. */ +export function randomToken(length: number): string { + if (!Number.isInteger(length) || length < 1) { + throw new RangeError(`randomToken length must be a positive integer, got ${length}`); + } + const crypto = globalThis.crypto; + let out = ""; + while (out.length < length) { + const bytes = crypto.getRandomValues(new Uint8Array(length - out.length + 8)); + for (const byte of bytes) { + if (byte >= UNBIASED_LIMIT) continue; + out += ALPHABET[byte % ALPHABET.length]; + if (out.length === length) break; + } + } + return out; +} + +/** + * An idempotency `transaction_key`: `crypto.randomUUID()` when available, otherwise + * `${prefix}-${Date.now()}-${randomToken(11)}`. + */ +export function newTransactionKey(prefix: string = "txn"): string { + const crypto = globalThis.crypto; + if (typeof crypto?.randomUUID === "function") { + return crypto.randomUUID(); + } + return `${prefix}-${Date.now()}-${randomToken(11)}`; +} diff --git a/frontend/src/pages/activities/useActivities.transactionKey.test.ts b/frontend/src/pages/activities/useActivities.transactionKey.test.ts new file mode 100644 index 0000000..d224f2c --- /dev/null +++ b/frontend/src/pages/activities/useActivities.transactionKey.test.ts @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: MIT +/** + * Tests for the `transaction_key` that `useActivities` stamps on its mutating calls. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { newTransactionKey } from "./useActivities"; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; + +/** Hide `randomUUID`, the way an insecure context or an older browser does. */ +function withoutRandomUUID(body: () => T): T { + const original = globalThis.crypto; + vi.stubGlobal("crypto", { getRandomValues: original.getRandomValues.bind(original) }); + try { + return body(); + } finally { + vi.stubGlobal("crypto", original); + } +} + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("useActivities newTransactionKey", () => { + it("is a UUID when crypto.randomUUID is available", () => { + expect(newTransactionKey()).toMatch(UUID); + }); + + it("falls back to a tk-prefixed crypto token when randomUUID is hidden", () => { + const key = withoutRandomUUID(() => newTransactionKey()); + + expect(key).toMatch(/^tk-\d+-[0-9a-z]{11}$/); + }); + + it("draws the fallback from crypto.getRandomValues, never Math.random", () => { + const randomSpy = vi.spyOn(Math, "random"); + const keys = withoutRandomUUID(() => { + const cryptoSpy = vi.spyOn(globalThis.crypto, "getRandomValues"); + const drawn = Array.from({ length: 50 }, () => newTransactionKey()); + expect(cryptoSpy).toHaveBeenCalled(); + return drawn; + }); + + expect(randomSpy).not.toHaveBeenCalled(); + expect(new Set(keys).size).toBe(keys.length); + }); +}); diff --git a/frontend/src/pages/activities/useActivities.ts b/frontend/src/pages/activities/useActivities.ts index 7a918f2..154a0cc 100644 --- a/frontend/src/pages/activities/useActivities.ts +++ b/frontend/src/pages/activities/useActivities.ts @@ -9,13 +9,12 @@ import { useCallback, useEffect, useState } from "react"; import { useCrmApi } from "../../api/useCrmApi"; import { CrmApiError } from "../../api/CrmApiClient"; import { useReportView } from "../../components/AssistantPanel/useReportView"; +import { newTransactionKey as transactionKeyWithPrefix } from "../../lib/randomToken"; import type { Activity, ActivityKind, Opportunity } from "../../types/domain"; import type { ListActivitiesResponse, LogActivityResponse } from "./types"; function newTransactionKey(): string { - return typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `tk-${Date.now()}-${Math.random().toString(36).slice(2)}`; + return transactionKeyWithPrefix("tk"); } export interface UseActivitiesState { diff --git a/frontend/src/pages/approvals/transactionKey.ts b/frontend/src/pages/approvals/transactionKey.ts index d410b78..990d1e2 100644 --- a/frontend/src/pages/approvals/transactionKey.ts +++ b/frontend/src/pages/approvals/transactionKey.ts @@ -1,12 +1,6 @@ // SPDX-License-Identifier: MIT /** * Generates a caller-supplied idempotency key (`transaction_key`) for a mutating call such as - * approve, reject or revert. + * approve, reject or revert: `crypto.randomUUID()`, else `txn--<11 base-36>`. */ -export function newTransactionKey(): string { - if (typeof crypto !== "undefined" && "randomUUID" in crypto) { - return crypto.randomUUID(); - } - // Fallback for a test/JSDOM environment lacking `crypto.randomUUID`. - return `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`; -} +export { newTransactionKey } from "../../lib/randomToken"; diff --git a/frontend/src/pages/opportunities/OpportunityCreatePage.tsx b/frontend/src/pages/opportunities/OpportunityCreatePage.tsx index 0b269e8..ae909b6 100644 --- a/frontend/src/pages/opportunities/OpportunityCreatePage.tsx +++ b/frontend/src/pages/opportunities/OpportunityCreatePage.tsx @@ -10,6 +10,7 @@ import { useCrmApi } from "../../api/useCrmApi"; import { Button } from "../../components/ui/button"; import { Input } from "../../components/ui/input"; import { cn, focusRing } from "../../components/ui/utils"; +import { newTransactionKey } from "../../lib/randomToken"; import { OPPORTUNITY_STAGES } from "../../types/domain"; import { ApiErrorBanner } from "./ApiErrorBanner"; import { asRecord } from "./types"; @@ -27,12 +28,6 @@ const textArea = cn( focusRing, ); -function newTransactionKey(): string { - return typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`; -} - export function OpportunityCreatePage(): JSX.Element { const api = useCrmApi(); const navigate = useNavigate(); diff --git a/frontend/src/pages/opportunities/OpportunityDetailPage.tsx b/frontend/src/pages/opportunities/OpportunityDetailPage.tsx index 414d435..78f5ba7 100644 --- a/frontend/src/pages/opportunities/OpportunityDetailPage.tsx +++ b/frontend/src/pages/opportunities/OpportunityDetailPage.tsx @@ -19,6 +19,7 @@ import { cn, focusRing } from "../../components/ui/utils"; import { OPPORTUNITY_STAGES, type OpportunityStage } from "../../types/domain"; import { ApiErrorBanner } from "./ApiErrorBanner"; import { formatCurrency, formatDate } from "../../lib/format"; +import { newTransactionKey } from "../../lib/randomToken"; import { OPPORTUNITY_HIGH_RISK_FIELDS, OPPORTUNITY_LOW_RISK_FIELDS, @@ -54,12 +55,6 @@ const selectControl = cn( focusRing, ); -function newTransactionKey(): string { - return typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `txn-${Date.now()}-${Math.random().toString(36).slice(2)}`; -} - export function OpportunityDetailPage(): JSX.Element { const { opportunityId } = useParams<{ opportunityId: string }>(); const api = useCrmApi(); diff --git a/frontend/src/pages/pipeline/usePipelineBoard.ts b/frontend/src/pages/pipeline/usePipelineBoard.ts index 9410a91..93db699 100644 --- a/frontend/src/pages/pipeline/usePipelineBoard.ts +++ b/frontend/src/pages/pipeline/usePipelineBoard.ts @@ -8,14 +8,13 @@ import { useCallback, useEffect, useMemo, useState } from "react"; import { useCrmApi } from "../../api/useCrmApi"; import { CrmApiError } from "../../api/CrmApiClient"; import { useReportView } from "../../components/AssistantPanel/useReportView"; +import { newTransactionKey as transactionKeyWithPrefix } from "../../lib/randomToken"; import { OPPORTUNITY_STAGES } from "../../types/domain"; import type { Opportunity, OpportunityStage, Proposal } from "../../types/domain"; import type { ListProposalsResponse, SearchOpportunitiesResponse, SubmitProposalResponse } from "./types"; function newTransactionKey(): string { - return typeof crypto !== "undefined" && "randomUUID" in crypto - ? crypto.randomUUID() - : `tk-${Date.now()}-${Math.random().toString(36).slice(2)}`; + return transactionKeyWithPrefix("tk"); } export interface PendingStageChange { diff --git a/scripts/check_sse_schema_parity.py b/scripts/check_sse_schema_parity.py index 804000a..7465b34 100644 --- a/scripts/check_sse_schema_parity.py +++ b/scripts/check_sse_schema_parity.py @@ -58,7 +58,7 @@ #: A TypeScript string-literal union: `type EventKind = "tool_call" | "usage";`, across lines. _TS_UNION = re.compile( - r"(?:type|enum)\s+(?P\w+)\s*=\s*(?P(?:\s*\|?\s*['\"][^'\"]+['\"])+)\s*;", + r"(?:type|enum)\s+(?P\w+)\s*=\s*(?P(?:\s*(?:\|\s*)?['\"][^'\"]+['\"])+)\s*;", re.MULTILINE, ) diff --git a/scripts/smoke/cloudfront.py b/scripts/smoke/cloudfront.py index d479d05..80cfd9f 100644 --- a/scripts/smoke/cloudfront.py +++ b/scripts/smoke/cloudfront.py @@ -800,7 +800,7 @@ def _check_api_negative_auth_preserved( #: An inline `", re.DOTALL) +_INLINE_SCRIPT: Final = re.compile(r"`. Returns the offending tags, in document order. + """ + openings = [ + tag + for tag in _OPENING_SCRIPT_TAG.findall(html) + if tag != ""] + return openings + closings + + def _hcl_list(values: tuple[str, ...] | list[str]) -> str: return "[" + ", ".join(f'"{value}"' for value in values) + "]" @@ -233,6 +251,29 @@ def test_index_html_carries_exactly_one_inline_script() -> None: assert all(re.search(r"\bsrc=", tag) for tag in attributed), attributed +def test_index_html_script_tags_use_only_the_forms_terraform_hashes() -> None: + """Every script tag in `index.html` is one the case-sensitive Terraform regex reads alike.""" + html = INDEX_HTML.read_text(encoding="utf-8") + assert _OPENING_SCRIPT_TAG.findall(html), "the guard found no script tags to check" + assert _script_tag_form_violations(html) == [] + + +@pytest.mark.parametrize( + ("planted", "offending"), + [ + ("", "", ""), + ("", ""), + ("", "", INDEX_HTML.read_text("utf-8"), re.S) + scripts = re.findall(r"', "", '', ], ids=[ "plain", @@ -1811,6 +1814,8 @@ def test_an_unhashed_inline_script_in_any_spelling_fails(tag: str) -> None: "module-attribute", "space-before-close", "mixed-case-attribute-tab", + "whitespace-and-junk-before-close", + "uppercase-close-with-attribute", ], ) def test_the_inline_script_pattern_captures_exactly_the_body(tag: str) -> None: @@ -1818,6 +1823,18 @@ def test_the_inline_script_pattern_captures_exactly_the_body(tag: str) -> None: assert _INLINE_SCRIPT.findall(document) == ["window.x = 1;"] +def test_the_inline_script_pattern_extracts_the_real_index_html_theme_script_unchanged() -> None: + """On the shipped `frontend/index.html`, the one inline body is the literal-tag slice.""" + html = (Path(__file__).resolve().parents[2] / "frontend" / "index.html").read_text( + encoding="utf-8" + ) + open_tag, close_tag = "" + start = html.index(open_tag) + len(open_tag) + expected = html[start : html.index(close_tag, start)] + assert expected.strip(), "the real index.html must carry a non-empty inline script" + assert _INLINE_SCRIPT.findall(html) == [expected] + + @pytest.mark.parametrize( "tag", [ diff --git a/tests/unit/test_smoke_iam_roles.py b/tests/unit/test_smoke_iam_roles.py index 84023b2..1c6a04c 100644 --- a/tests/unit/test_smoke_iam_roles.py +++ b/tests/unit/test_smoke_iam_roles.py @@ -1965,6 +1965,93 @@ def _index_only_main_tf( return path +def _string_list_locals(text: str) -> dict[str, list[str]]: + return { + match.group("name"): re.findall(r'"([^"]*)"', match.group("items")) + for match in iam_roles._STRING_LIST_LOCAL_RE.finditer(text) + } + + +class TestStringListLocalPattern: + """`_STRING_LIST_LOCAL_RE` reads one-line string-list locals, and only those.""" + + def test_the_root_composition_string_list_locals_are_read(self) -> None: + """The real root composition yields exactly the known string-list locals.""" + lists = _string_list_locals(iam_roles._root_composition_text()) + assert set(lists) == { + "agent_only_tools", + "cognito_required_custom_claims", + "cursor_tools", + "default", + "dynamodb_grants", + "gateway_endpoint_service_names", + "sfn_vended_log_delivery_actions", + "sfn_xray_tracing_actions", + "spa_callback_urls", + "spa_connect_src_extra", + "spa_logout_urls", + "sweep_control_demo_select", + "sweep_control_tenant_query_keys", + "sweep_task_tenant_tables", + "sweep_task_unconditioned_read_tables", + } + assert lists["sweep_task_tenant_tables"] == [ + "accounts", + "contacts", + "opportunities", + "activities", + "notes", + ] + assert lists["sweep_control_tenant_query_keys"] == ["eval-*", "canary"] + assert lists["sweep_task_unconditioned_read_tables"] == ["proposals"] + + def test_the_sweep_task_comprehension_expands_to_its_five_tables(self) -> None: + """The real sweep-task comprehension is rewritten with each listed table quoted.""" + text = iam_roles._root_composition_text() + assert "local.sweep_task_tenant_tables :" not in text + for table in ("accounts", "contacts", "opportunities", "activities", "notes"): + assert f'table = "{table}"' in text, table + + @pytest.mark.parametrize( + ("line", "items"), + [ + (" t = []", []), + (" t = [ ]", []), + (' t = ["a"]', ["a"]), + (' t = ["a", "b"]', ["a", "b"]), + (' t = ["a", "b",]', ["a", "b"]), + (' t = ["a" "b"]', ["a", "b"]), + (' t = [ "a" , "b" , ] ', ["a", "b"]), + (' t = ["", "x y"]', ["", "x y"]), + ], + ) + def test_string_list_forms_are_read(self, line: str, items: list[str]) -> None: + """Empty, trailing-comma, comma-less and multi-space lists are read item for item.""" + assert _string_list_locals(f"locals {{\n{line}\n}}\n") == {"t": items} + + @pytest.mark.parametrize( + "line", + [ + ' t = ["a", b]', + ' t = ["a",, "b"]', + ' t = ["a"', + ' t = ["a"]', + ' t = ["a"] # note', + " t = [for x in local.y : x]", + ], + ) + def test_non_string_lists_are_not_read(self, line: str) -> None: + """Bare words, doubled commas, unterminated, nested and annotated lines are not read.""" + assert _string_list_locals(f"locals {{\n{line}\n}}\n") == {} + + def test_a_pathological_unterminated_list_completes_quickly(self) -> None: + """A long unterminated list is rejected in well under two seconds.""" + source = ' 0=[""' + ' ""' * 5000 + started = time.perf_counter() + assert iam_roles._STRING_LIST_LOCAL_RE.search(source) is None + assert time.perf_counter() - started < 2.0 + + class TestIndexOnlyGrantReader: """`_terraform_index_only_grants` reads which grants cover only an index, never the table.""" diff --git a/tests/unit/test_token_accounting.py b/tests/unit/test_token_accounting.py index ade4d8e..7412f83 100644 --- a/tests/unit/test_token_accounting.py +++ b/tests/unit/test_token_accounting.py @@ -7,8 +7,10 @@ from __future__ import annotations +import re from pathlib import Path from typing import Any, Final, get_args +from urllib.parse import urlparse import pytest import yaml @@ -30,6 +32,16 @@ _REPO_ROOT: Final[Path] = Path(__file__).resolve().parents[2] _PRICING_PATH: Final[Path] = _REPO_ROOT / "config" / "pricing.yaml" +_EVIDENCE_URL: Final[re.Pattern[str]] = re.compile(r"https?://[^\s\"')]+") + + +def _assert_every_evidence_url_is_on_aws(evidence: str) -> None: + """Assert `evidence` cites at least one URL and that every cited URL's host is AWS's.""" + urls = _EVIDENCE_URL.findall(evidence) + assert urls, "a declaration must cite its source URL" + for url in urls: + assert urlparse(url).hostname == "aws.amazon.com", url + #: Distinct non-zero per-category rates, so a wrong charge base shows in the computed cost. _INPUT_RATE: Final[float] = 3.0 @@ -111,13 +123,14 @@ def test_both_families_are_settled_from_authoritative_aws_docs() -> None: assert anthropic.cache_read_accounting == "exclusive" assert anthropic.evidence_direction == "exclusive" assert "optimizing-cost-and-latency-with-amazon-bedrock-prompt-caching" in anthropic.evidence - assert "aws.amazon.com" in anthropic.evidence + _assert_every_evidence_url_is_on_aws(anthropic.evidence) openai = token_accounting_for("openai") assert openai.cache_read_accounting == "inclusive" assert openai.evidence_direction == "inclusive" assert "input_tokens = cached_tokens + cache_write_tokens" in openai.evidence assert "introducing-explicit-prompt-caching-for-openai" in openai.evidence + _assert_every_evidence_url_is_on_aws(openai.evidence) # The OpenAI evidence carries a caveat covering the OpenAI models in the matrix. assert "CAVEAT:" in openai.evidence assert "the OpenAI models in the matrix" in openai.evidence