diff --git a/apps/local/src/lib/objects.test.ts b/apps/local/src/lib/objects.test.ts index 8246957f0..aa4622de9 100644 --- a/apps/local/src/lib/objects.test.ts +++ b/apps/local/src/lib/objects.test.ts @@ -18,4 +18,15 @@ describe("withoutUndefined", () => { }); expect("parentId" in value).toBe(false); }); + + test("accepts only plain records, whose own keys are all it copies", () => { + class Span { + id = "span"; + get label(): string { + return "inherited"; + } + } + // @ts-expect-error A class instance's prototype members would be dropped. + expect(withoutUndefined(new Span())).toStrictEqual({ id: "span" }); + }); }); diff --git a/apps/local/src/lib/objects.ts b/apps/local/src/lib/objects.ts index 8c5b14394..25f8de8a1 100644 --- a/apps/local/src/lib/objects.ts +++ b/apps/local/src/lib/objects.ts @@ -22,9 +22,11 @@ export type WithoutUndefined = { /** * A copy of `value` without its `undefined` properties, so optional fields * parsed from a payload are omitted when unset instead of present and - * `undefined`. + * `undefined`. `value` must be a plain record: the copy keeps only own + * enumerable string keys, so class instances and symbol keys are not + * accepted. */ -export function withoutUndefined( +export function withoutUndefined>( value: T, ): WithoutUndefined { return Object.fromEntries( diff --git a/packages/cli/src/commands/alert/metrics/list.ts b/packages/cli/src/commands/alert/metrics/list.ts index 839e6469b..0e1a3b6f5 100644 --- a/packages/cli/src/commands/alert/metrics/list.ts +++ b/packages/cli/src/commands/alert/metrics/list.ts @@ -340,9 +340,7 @@ async function handleResolvedOrgs( ); const filteredRows = flags.query ? allRows.filter((row) => - ((row.rule.name as string | null) ?? "") - .toLowerCase() - .includes(flags.query?.toLowerCase() ?? ""), + row.rule.name.toLowerCase().includes(flags.query?.toLowerCase() ?? ""), ) : allRows; diff --git a/packages/cli/test/commands/alert/metrics/list.test.ts b/packages/cli/test/commands/alert/metrics/list.test.ts index c20103fe7..88330ca16 100644 --- a/packages/cli/test/commands/alert/metrics/list.test.ts +++ b/packages/cli/test/commands/alert/metrics/list.test.ts @@ -203,34 +203,6 @@ describe("alert metrics list pagination", () => { expect(parsed.hasMore).toBe(true); }); - test("query filter skips rules with a null name", async () => { - globalThis.fetch = mockFetch(async (input, init) => { - const req = new Request(input, init); - if (req.url.includes("/organizations/test-org/detectors/")) { - return new Response( - JSON.stringify([ - { ...detector({ id: "1", name: "" }), name: null }, - detector({ id: "2", name: "Metric Rule Alpha" }), - ]), - { status: 200, headers: { "Content-Type": "application/json" } }, - ); - } - return new Response(JSON.stringify({ detail: "Not found" }), { - status: 404, - }); - }); - - const { context, stdout } = createContext(); - await func.call( - context, - { web: false, fresh: false, limit: 10, json: true, query: "alpha" }, - "test-org/", - ); - - const parsed = JSON.parse(stdout.output); - expect(parsed.data.map((rule: { id: string }) => rule.id)).toEqual(["2"]); - }); - test("--web with explicit org opens browser without fetching rules", async () => { globalThis.fetch = mockFetch(async () => { throw new Error("fetch should not be called for explicit --web"); diff --git a/packages/mcp-cloudflare/src/server/lib/approval-dialog.test.ts b/packages/mcp-cloudflare/src/server/lib/approval-dialog.test.ts index 1b26beea9..5c1474670 100644 --- a/packages/mcp-cloudflare/src/server/lib/approval-dialog.test.ts +++ b/packages/mcp-cloudflare/src/server/lib/approval-dialog.test.ts @@ -1,12 +1,24 @@ import { assert, beforeEach, describe, expect, it, vi } from "vitest"; import { signState } from "../oauth/state"; import { + clientIdAlreadyApproved, getRememberedSkillsForClient, parseRedirectApproval, renderApprovalDialog, SKILL_PREFERENCES_COOKIE_NAME, } from "./approval-dialog"; +const { logError, logWarn } = vi.hoisted(() => ({ + logError: vi.fn(), + logWarn: vi.fn(), +})); + +vi.mock("@sentry/mcp-core/telem/logging", async (importOriginal) => ({ + ...(await importOriginal()), + logError, + logWarn, +})); + function skillInputAttributes(html: string, skillId: string): string { const match = html.match( new RegExp( @@ -220,6 +232,24 @@ describe("approval-dialog", () => { }); }); + describe("clientIdAlreadyApproved", () => { + it("treats an approval cookie with an empty signature as unsigned, without reporting an error", async () => { + const payload = btoa(JSON.stringify(["test-client"])); + const request = new Request("https://example.com/oauth/authorize", { + headers: { Cookie: `mcp-approved-clients=.${payload}` }, + }); + + await expect( + clientIdAlreadyApproved(request, "test-client", TEST_SECRET), + ).resolves.toBe(false); + expect(logWarn).toHaveBeenCalledWith( + "Signed cookie signature verification failed", + expect.anything(), + ); + expect(logError).not.toHaveBeenCalled(); + }); + }); + describe("CSRF protection with HMAC-signed state", () => { it("should reject tampered state in form submission", async () => { const originalOauthReqInfo = { diff --git a/packages/mcp-cloudflare/src/server/routes/__tests__/api-chat.test.ts b/packages/mcp-cloudflare/src/server/routes/__tests__/api-chat.test.ts index 31ed6073c..c66af08ec 100644 --- a/packages/mcp-cloudflare/src/server/routes/__tests__/api-chat.test.ts +++ b/packages/mcp-cloudflare/src/server/routes/__tests__/api-chat.test.ts @@ -1,22 +1,80 @@ import { env } from "cloudflare:test"; -import { describe, it, expect } from "vitest"; +import { beforeEach, describe, it, expect, vi } from "vitest"; import app from "../../app"; +const { convertToModelMessages, logIssue } = vi.hoisted(() => ({ + convertToModelMessages: vi.fn(), + logIssue: vi.fn(() => "test-event-id"), +})); + +vi.mock("@sentry/mcp-core/telem/logging", async (importOriginal) => ({ + ...(await importOriginal()), + logIssue, +})); + +vi.mock("@ai-sdk/mcp", () => ({ + experimental_createMCPClient: vi.fn(async () => ({ + tools: async () => ({}), + close: async () => {}, + })), +})); + +vi.mock("ai", async (importOriginal) => ({ + ...(await importOriginal()), + convertToModelMessages, +})); + +const authData = { + access_token: "test-access-token", + refresh_token: "test-refresh-token", + expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), + token_type: "bearer", +}; + +function postChat(cookie?: string) { + return app.request( + "/api/chat", + { + method: "POST", + headers: { + "CF-Connecting-IP": "192.0.2.1", + "Content-Type": "application/json", + ...(cookie ? { Cookie: cookie } : {}), + }, + body: JSON.stringify({ messages: [] }), + }, + { ...env, OPENROUTER_API_KEY: "test-openrouter-key" }, + ); +} + describe("/api/chat", () => { + beforeEach(() => { + convertToModelMessages.mockReset(); + logIssue.mockClear(); + }); + it("should return 401 without authorization", async () => { - const res = await app.request( - "/api/chat", - { - method: "POST", - headers: { - "CF-Connecting-IP": "192.0.2.1", - "Content-Type": "application/json", - }, - body: JSON.stringify({ messages: [] }), - }, - env, - ); + const res = await postChat(); expect(res.status).toBe(401); }); + + it("returns a 500 with an event ID when the handler throws a non-Error value", async () => { + convertToModelMessages.mockImplementation(() => { + // oxlint-disable-next-line typescript/only-throw-error -- Upstream code can throw non-Error values; this is the case under test. + throw "upstream failure"; + }); + + const res = await postChat( + `sentry_auth_data=${encodeURIComponent(JSON.stringify(authData))}`, + ); + + expect(res.status).toBe(500); + await expect(res.json()).resolves.toEqual({ + error: "Internal server error", + name: "INTERNAL_ERROR", + eventId: "test-event-id", + }); + expect(logIssue).toHaveBeenCalledWith("upstream failure"); + }); }); diff --git a/scripts/tsconfig-policy.mjs b/scripts/tsconfig-policy.mjs index 4195d1f63..2c9456806 100644 --- a/scripts/tsconfig-policy.mjs +++ b/scripts/tsconfig-policy.mjs @@ -113,6 +113,32 @@ export function workspacePackages() { .filter((path) => path !== ROOT); } +/** Commands a type check script may run before its checkers, such as builds. */ +const SETUP_PROGRAMS = new Set(["pnpm", "node"]); + +/** + * The tsconfig files one `&&`-separated type check command checks: `tsc` + * programs, the package's tsconfig.json for `astro check`, and none for a + * setup command. Throws for any other command, because the policy could not + * read the options it checks with. + */ +export function typecheckCommandConfigs(packageDir, command) { + const words = command.trim().split(/\s+/); + const program = words[0]; + if (program === "tsc") { + return configsForCommand(packageDir, command); + } + if (program === "astro" && words[1] === "check") { + return [join(packageDir, "tsconfig.json")]; + } + if (program !== undefined && SETUP_PROGRAMS.has(program)) { + return []; + } + throw new Error( + `${toRepoPath(packageDir)} type check runs "${command.trim()}", which the tsconfig policy cannot read. Use tsc or astro check, or add the program to SETUP_PROGRAMS if it only prepares inputs.`, + ); +} + /** * Every program that a package type check runs, keyed by repository path. * `astro check` checks the package's tsconfig.json. @@ -129,14 +155,7 @@ export function checkedPrograms() { continue; } for (const command of scripts[name].split("&&")) { - const program = command.trim().split(/\s+/)[0]; - const configs = - program === "tsc" - ? configsForCommand(packageDir, command) - : command.trim().startsWith("astro check") - ? [join(packageDir, "tsconfig.json")] - : []; - for (const config of configs) { + for (const config of typecheckCommandConfigs(packageDir, command)) { const parsed = parseConfig(config); programs.set(toRepoPath(config), { path: config, diff --git a/scripts/tsconfig-policy.test.mjs b/scripts/tsconfig-policy.test.mjs index e7117c506..1d36a8cc5 100644 --- a/scripts/tsconfig-policy.test.mjs +++ b/scripts/tsconfig-policy.test.mjs @@ -9,6 +9,7 @@ import { policyOptions, ROOT, trackedTypeScriptFiles, + typecheckCommandConfigs, workspacePackages, } from "./tsconfig-policy.mjs"; @@ -64,6 +65,21 @@ test("every package with a tsconfig.json has a typecheck script", () => { } }); +test("a type check command the policy cannot read fails instead of being skipped", () => { + const packageDir = join(ROOT, "packages/logger"); + assert.deepEqual(typecheckCommandConfigs(packageDir, "pnpm run build"), []); + assert.deepEqual(typecheckCommandConfigs(packageDir, "astro check"), [ + join(packageDir, "tsconfig.json"), + ]); + for (const command of ["tsgo --noEmit", "vue-tsc --noEmit", "astro build"]) { + assert.throws( + () => typecheckCommandConfigs(packageDir, command), + /tsconfig policy cannot read/, + command, + ); + } +}); + test("every type check runs a program with files", () => { assert.ok(programs.size > 0); for (const [config, { files }] of programs) {