Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions apps/local/src/lib/objects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" });
});
});
6 changes: 4 additions & 2 deletions apps/local/src/lib/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ export type WithoutUndefined<T> = {
/**
* 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<T extends object>(
export function withoutUndefined<T extends Record<string, unknown>>(
value: T,
): WithoutUndefined<T> {
return Object.fromEntries(
Expand Down
4 changes: 1 addition & 3 deletions packages/cli/src/commands/alert/metrics/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
28 changes: 0 additions & 28 deletions packages/cli/test/commands/alert/metrics/list.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
30 changes: 30 additions & 0 deletions packages/mcp-cloudflare/src/server/lib/approval-dialog.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("@sentry/mcp-core/telem/logging")>()),
logError,
logWarn,
}));

function skillInputAttributes(html: string, skillId: string): string {
const match = html.match(
new RegExp(
Expand Down Expand Up @@ -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 = {
Expand Down
Original file line number Diff line number Diff line change
@@ -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<typeof import("@sentry/mcp-core/telem/logging")>()),
logIssue,
}));

vi.mock("@ai-sdk/mcp", () => ({
experimental_createMCPClient: vi.fn(async () => ({
tools: async () => ({}),
close: async () => {},
})),
}));

vi.mock("ai", async (importOriginal) => ({
...(await importOriginal<typeof import("ai")>()),
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");
});
});
35 changes: 27 additions & 8 deletions scripts/tsconfig-policy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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,
Expand Down
16 changes: 16 additions & 0 deletions scripts/tsconfig-policy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
policyOptions,
ROOT,
trackedTypeScriptFiles,
typecheckCommandConfigs,
workspacePackages,
} from "./tsconfig-policy.mjs";

Expand Down Expand Up @@ -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) {
Expand Down
Loading