Skip to content

Commit 2a39c50

Browse files
authored
fix: make full verification hermetic across local environments (#128777)
* test: harden full verification fixtures * test: resolve main fixture overlap
1 parent 9a15d4c commit 2a39c50

15 files changed

Lines changed: 274 additions & 284 deletions
Lines changed: 38 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,52 @@
11
// Brave tests cover brave web search provider.merge plugin behavior.
22
import { describe, expect, it, vi } from "vitest";
3-
import { createBraveWebSearchProvider } from "./brave-web-search-provider.js";
4-
5-
const runtimeMock = vi.hoisted(() => {
6-
const searchConfigs: Array<Record<string, unknown> | undefined> = [];
7-
return {
8-
searchConfigs,
9-
executeBraveSearch: vi.fn(async (_args: unknown, searchConfig?: Record<string, unknown>) => {
10-
searchConfigs.push(searchConfig);
11-
return { results: [] };
12-
}),
13-
};
14-
});
15-
16-
vi.mock("./brave-web-search-provider.runtime.js", () => ({
17-
executeBraveSearch: runtimeMock.executeBraveSearch,
18-
}));
193

204
describe("brave web search config merge", () => {
215
it("keeps plugin webSearch runtime-only after merging it for the tool", async () => {
22-
const provider = createBraveWebSearchProvider();
23-
const tool = provider.createTool({
24-
config: {
25-
plugins: {
26-
entries: {
27-
brave: {
28-
config: {
29-
webSearch: {
30-
apiKey: "brave-test-key",
31-
mode: "llm-context",
6+
vi.resetModules();
7+
const searchConfigs: Array<Record<string, unknown> | undefined> = [];
8+
const executeBraveSearch = vi.fn(
9+
async (_args: unknown, searchConfig?: Record<string, unknown>) => {
10+
searchConfigs.push(searchConfig);
11+
return { results: [] };
12+
},
13+
);
14+
vi.doMock("./brave-web-search-provider.runtime.js", () => ({ executeBraveSearch }));
15+
16+
try {
17+
const { createBraveWebSearchProvider } = await import("./brave-web-search-provider.js");
18+
const provider = createBraveWebSearchProvider();
19+
const tool = provider.createTool({
20+
config: {
21+
plugins: {
22+
entries: {
23+
brave: {
24+
config: {
25+
webSearch: {
26+
apiKey: "brave-test-key",
27+
mode: "llm-context",
28+
},
3229
},
3330
},
3431
},
3532
},
3633
},
37-
},
38-
searchConfig: { provider: "brave" },
39-
});
34+
searchConfig: { provider: "brave" },
35+
});
4036

41-
await tool?.execute({ query: "OpenClaw docs" });
37+
await tool?.execute({ query: "OpenClaw docs" });
4238

43-
const [searchConfig] = runtimeMock.searchConfigs;
44-
expect(searchConfig?.brave).toEqual({
45-
apiKey: "brave-test-key",
46-
mode: "llm-context",
47-
});
48-
expect(searchConfig?.apiKey).toBe("brave-test-key");
49-
expect(Object.keys(searchConfig ?? {})).toEqual(["provider", "apiKey"]);
50-
expect(Object.getOwnPropertyDescriptor(searchConfig ?? {}, "brave")?.enumerable).toBe(false);
39+
const [searchConfig] = searchConfigs;
40+
expect(searchConfig?.brave).toEqual({
41+
apiKey: "brave-test-key",
42+
mode: "llm-context",
43+
});
44+
expect(searchConfig?.apiKey).toBe("brave-test-key");
45+
expect(Object.keys(searchConfig ?? {})).toEqual(["provider", "apiKey"]);
46+
expect(Object.getOwnPropertyDescriptor(searchConfig ?? {}, "brave")?.enumerable).toBe(false);
47+
} finally {
48+
vi.doUnmock("./brave-web-search-provider.runtime.js");
49+
vi.resetModules();
50+
}
5151
});
5252
});

‎extensions/openrouter/oauth.test.ts‎

Lines changed: 36 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -137,56 +137,6 @@ function createOpenRouterOAuthContext(params: {
137137
return { ctx, progress, note, text, log, openUrl };
138138
}
139139

140-
async function startLocalOpenRouterOAuthLogin() {
141-
let markReady = () => {};
142-
const ready = new Promise<void>((resolve) => {
143-
markReady = resolve;
144-
});
145-
const controller = new AbortController();
146-
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse({ key: "sk-or-v1-test" }));
147-
const { ctx } = createOpenRouterOAuthContext({
148-
isRemote: false,
149-
onProgress: (message) => {
150-
if (message.startsWith("Waiting for OpenRouter OAuth callback")) {
151-
markReady();
152-
}
153-
},
154-
signal: controller.signal,
155-
});
156-
const login = loginOpenRouterOAuth(ctx, {
157-
createPkce: () => ({ verifier: "verifier-1", challenge: "challenge-1" }),
158-
createState: () => "state-1",
159-
fetchImpl,
160-
});
161-
login.catch(() => undefined);
162-
await Promise.race([
163-
ready,
164-
login.then(
165-
() => {
166-
throw new Error("OpenRouter OAuth completed before callback server started");
167-
},
168-
(error: unknown) => {
169-
throw error;
170-
},
171-
),
172-
]);
173-
174-
return {
175-
abort: () => controller.abort(),
176-
fetchImpl,
177-
login,
178-
request: async (pathOrQuery: string, init?: RequestInit) => {
179-
const url = pathOrQuery.startsWith("http")
180-
? pathOrQuery
181-
: `${OPENROUTER_OAUTH_REDIRECT_URI}?${pathOrQuery}`;
182-
const headers = new Headers(init?.headers);
183-
headers.set("Connection", "close");
184-
const response = await fetch(url, { ...init, headers });
185-
return { response, body: await response.text() };
186-
},
187-
};
188-
}
189-
190140
function runRemoteOpenRouterOAuthRedirect(redirectInput: string) {
191141
const { ctx } = createOpenRouterOAuthContext({ isRemote: true, redirectInput });
192142
return loginOpenRouterOAuth(ctx, {
@@ -415,7 +365,7 @@ describe("OpenRouter OAuth", () => {
415365
expect(progress.stop).toHaveBeenCalledWith("OpenRouter OAuth complete");
416366
});
417367

418-
it("binds the local callback before opening the browser", async () => {
368+
it("binds the local callback before opening the browser and exchanges its accepted code", async () => {
419369
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse({ key: "sk-or-v1-test" }));
420370
const waitForCallback = vi.fn(async () => ({
421371
type: "authorization_code" as const,
@@ -446,6 +396,41 @@ describe("OpenRouter OAuth", () => {
446396
expect(close).toHaveBeenCalledTimes(1);
447397
expect(openUrl).toHaveBeenCalledWith(expect.stringContaining("https://openrouter.ai/auth?"));
448398
expect(text).not.toHaveBeenCalled();
399+
expect(fetchImpl).toHaveBeenCalledTimes(1);
400+
expect(requestJsonBody(fetchImpl.mock.calls[0]?.[1])).toEqual({
401+
code: "AUTHCODE",
402+
code_verifier: "verifier-1",
403+
code_challenge_method: "S256",
404+
});
405+
});
406+
407+
it("closes a state-bound provider denial without exchanging a code", async () => {
408+
const fetchImpl = vi.fn<typeof fetch>(async () => jsonResponse({ key: "sk-or-v1-test" }));
409+
const waitForCallback = vi.fn(async () => ({
410+
type: "oauth_error" as const,
411+
error: "access_denied",
412+
errorDescription: "Denied",
413+
}));
414+
const close = vi.fn(async () => undefined);
415+
const startCallback = vi.fn(async () => ({ waitForCallback, close }));
416+
const { ctx, text } = createOpenRouterOAuthContext({ isRemote: false });
417+
418+
await expect(
419+
loginOpenRouterOAuth(ctx, {
420+
createPkce: () => ({ verifier: "verifier-1", challenge: "challenge-1" }),
421+
createState: () => "state-1",
422+
fetchImpl,
423+
startCallback,
424+
}),
425+
).rejects.toThrow("OpenRouter OAuth error: access_denied: Denied");
426+
427+
expect(startCallback).toHaveBeenCalledWith(
428+
expect.objectContaining({ expectedState: "state-1" }),
429+
);
430+
expect(waitForCallback).toHaveBeenCalledTimes(1);
431+
expect(close).toHaveBeenCalledTimes(1);
432+
expect(fetchImpl).not.toHaveBeenCalled();
433+
expect(text).not.toHaveBeenCalled();
449434
});
450435

451436
it("falls back to a pasted redirect when the local listener cannot start", async () => {
@@ -472,47 +457,6 @@ describe("OpenRouter OAuth", () => {
472457
expect(fetchImpl).toHaveBeenCalledTimes(1);
473458
});
474459

475-
it("keeps waiting after rejected callback candidates and exchanges one valid code", async () => {
476-
const local = await startLocalOpenRouterOAuthLogin();
477-
try {
478-
expect((await local.request("http://localhost:3000/wrong")).response.status).toBe(404);
479-
expect((await local.request("", { method: "POST" })).response.status).toBe(405);
480-
expect((await local.request("code=missing-state")).response.status).toBe(400);
481-
expect((await local.request("state=wrong&code=wrong-state")).response.status).toBe(400);
482-
expect((await local.request("state=state-1")).response.status).toBe(400);
483-
484-
const validCallbacks = await Promise.allSettled([
485-
local.request("state=state-1&code=AUTHCODE"),
486-
local.request("state=state-1&code=REPLAY"),
487-
]);
488-
const statuses = validCallbacks.flatMap((result) =>
489-
result.status === "fulfilled" ? [result.value.response.status] : [],
490-
);
491-
expect(statuses.filter((status) => status === 200)).toHaveLength(1);
492-
await expect(local.login).resolves.toMatchObject({ defaultModel: "openrouter/auto" });
493-
expect(local.fetchImpl).toHaveBeenCalledTimes(1);
494-
} finally {
495-
local.abort();
496-
await local.login.catch(() => undefined);
497-
}
498-
});
499-
500-
it("terminates a state-bound provider denial without exchanging a code", async () => {
501-
const local = await startLocalOpenRouterOAuthLogin();
502-
try {
503-
const denied = await local.request(
504-
"state=state-1&error=access_denied&error_description=Denied",
505-
);
506-
expect(denied.response.status).toBe(400);
507-
expect(denied.body).toBe("Authorization was not completed.");
508-
await expect(local.login).rejects.toThrow("OpenRouter OAuth error: access_denied: Denied");
509-
expect(local.fetchImpl).not.toHaveBeenCalled();
510-
} finally {
511-
local.abort();
512-
await local.login.catch(() => undefined);
513-
}
514-
});
515-
516460
it("exposes stable auth choice metadata", () => {
517461
expect(createOpenRouterOAuthAuthMethod().wizard?.choiceId).toBe("openrouter-oauth");
518462
});

‎extensions/telegram/src/bot.create-telegram-bot.channel-post-media.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1004,6 +1004,10 @@ describe("createTelegramBot channel_post media", () => {
10041004
it("drops the media group when a non-recoverable media error occurs", async () => {
10051005
replySpy.mockReset();
10061006
setOpenChannelPostConfig();
1007+
saveRemoteMedia.mockResolvedValueOnce({
1008+
path: "/tmp/fatal-album-first.jpg",
1009+
contentType: "image/jpeg",
1010+
});
10071011

10081012
const runtimeError = vi.fn();
10091013
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
@@ -1031,6 +1035,10 @@ describe("createTelegramBot channel_post media", () => {
10311035
expect.stringContaining("media group handler failed"),
10321036
),
10331037
);
1038+
expect(runtimeError).toHaveBeenCalledWith(
1039+
expect.stringContaining("Telegram getFile returned no file_path"),
1040+
);
1041+
expect(saveRemoteMedia).toHaveBeenCalledTimes(1);
10341042
expect(replySpy).not.toHaveBeenCalled();
10351043
} finally {
10361044
setTimeoutSpy.mockRestore();

‎src/cli/plugins-cli.install.test.ts‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import fs from "node:fs";
33
import os from "node:os";
44
import path from "node:path";
55
import { installedPluginRoot } from "openclaw/plugin-sdk/test-fixtures";
6-
import { afterEach, beforeEach, describe, expect, it } from "vitest";
6+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
77
import type { OpenClawConfig } from "../config/config.js";
88
import { hashConfigIncludeRaw } from "../config/includes.js";
99
import { recordPluginManifestInstallOwner } from "../plugins/manifest-install-owner.js";
@@ -12,6 +12,7 @@ import {
1212
resolveOfficialExternalPluginId,
1313
resolveOfficialExternalPluginInstall,
1414
} from "../plugins/official-external-plugin-catalog.js";
15+
import { withTempDir } from "../test-utils/temp-dir.js";
1516
import {
1617
applyExclusiveSlotSelectionMock,
1718
buildPluginSnapshotReportMock,
@@ -1944,20 +1945,27 @@ describe("plugins cli install", () => {
19441945
it.each(OFFICIAL_EXTERNAL_NPM_INSTALLS_WITHOUT_INTEGRITY)(
19451946
"keeps official external npm installs trusted without integrity for $pluginId",
19461947
async ({ pluginId, npmSpec }) => {
1947-
primeSuccessfulPluginPersistence(pluginId);
1948-
findBundledPluginSourceMock.mockReturnValue(undefined);
1949-
installPluginFromNpmSpecMock.mockResolvedValue(createNpmPluginInstallResult(pluginId));
1950-
1951-
await runPluginsCommand(["plugins", "install", pluginId]);
1952-
1953-
expect(findBundledPluginSourceMock).toHaveBeenCalledWith({
1954-
lookup: { kind: "pluginId", value: pluginId },
1948+
await withTempDir("openclaw-official-plugin-install-", async (cwd) => {
1949+
const cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(cwd);
1950+
try {
1951+
primeSuccessfulPluginPersistence(pluginId);
1952+
findBundledPluginSourceMock.mockReturnValue(undefined);
1953+
installPluginFromNpmSpecMock.mockResolvedValue(createNpmPluginInstallResult(pluginId));
1954+
1955+
await runPluginsCommand(["plugins", "install", pluginId]);
1956+
1957+
expect(findBundledPluginSourceMock).toHaveBeenCalledWith({
1958+
lookup: { kind: "pluginId", value: pluginId },
1959+
});
1960+
expect(installPluginFromClawHubMock).not.toHaveBeenCalled();
1961+
expect(npmInstallCall().spec).toBe(npmSpec);
1962+
expect(npmInstallCall().expectedPluginId).toBe(pluginId);
1963+
expect(npmInstallCall().trustedSourceLinkedOfficialInstall).toBe(true);
1964+
expect(npmInstallCall().expectedIntegrity).toBeUndefined();
1965+
} finally {
1966+
cwdSpy.mockRestore();
1967+
}
19551968
});
1956-
expect(installPluginFromClawHubMock).not.toHaveBeenCalled();
1957-
expect(npmInstallCall().spec).toBe(npmSpec);
1958-
expect(npmInstallCall().expectedPluginId).toBe(pluginId);
1959-
expect(npmInstallCall().trustedSourceLinkedOfficialInstall).toBe(true);
1960-
expect(npmInstallCall().expectedIntegrity).toBeUndefined();
19611969
},
19621970
);
19631971

0 commit comments

Comments
 (0)