Skip to content

Commit a1c0f95

Browse files
committed
test(chutes): prove OAuth refresh load ordering
1 parent a9e2411 commit a1c0f95

1 file changed

Lines changed: 199 additions & 0 deletions

File tree

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4+
import type { OpenClawConfig } from "../config/types.openclaw.js";
5+
import { resetFileLockStateForTest } from "../infra/file-lock.js";
6+
import { isPluginRegistryLoadInFlight } from "../plugins/loader-cache.js";
7+
import {
8+
cleanupPluginLoaderFixturesForTest,
9+
loadOpenClawPlugins,
10+
resetPluginLoaderTestStateForTest,
11+
useNoBundledPlugins,
12+
writePlugin,
13+
} from "../plugins/loader.test-fixtures.js";
14+
import { resolveProviderOAuthCredentialWithPlugin } from "../plugins/provider-runtime.runtime.js";
15+
import { resolveProviderRefOwnership } from "../plugins/providers.js";
16+
import { withOpenClawTestState } from "../test-utils/openclaw-test-state.js";
17+
import {
18+
clearRuntimeAuthProfileStoreSnapshots,
19+
ensureAuthProfileStore,
20+
resolveApiKeyForProfile,
21+
type AuthProfileStore,
22+
} from "./auth-profiles.js";
23+
import { loadPersistedAuthProfileStore } from "./auth-profiles/persisted.js";
24+
25+
const START_AUTH_CALLBACK = "__openclawChutesLifecycleStart";
26+
const DISABLED_REGISTER_CALLBACK = "__openclawDisabledChutesRegister";
27+
28+
function writeChutesPlugin(params: { id: string; registerBody: string }) {
29+
useNoBundledPlugins();
30+
const plugin = writePlugin({
31+
id: params.id,
32+
body: `module.exports = {
33+
id: ${JSON.stringify(params.id)},
34+
register(api) {
35+
${params.registerBody}
36+
},
37+
};`,
38+
});
39+
fs.writeFileSync(
40+
path.join(plugin.dir, "openclaw.plugin.json"),
41+
JSON.stringify(
42+
{
43+
id: params.id,
44+
providers: ["chutes"],
45+
configSchema: { type: "object", additionalProperties: false, properties: {} },
46+
},
47+
null,
48+
2,
49+
),
50+
"utf8",
51+
);
52+
return plugin;
53+
}
54+
55+
function createPluginConfig(params: { id: string; file: string; enabled: boolean }) {
56+
return {
57+
plugins: {
58+
allow: [params.id],
59+
load: { paths: [params.file] },
60+
entries: { [params.id]: { enabled: params.enabled } },
61+
},
62+
} satisfies OpenClawConfig;
63+
}
64+
65+
beforeEach(() => {
66+
clearRuntimeAuthProfileStoreSnapshots();
67+
resetFileLockStateForTest();
68+
resetPluginLoaderTestStateForTest();
69+
});
70+
71+
afterEach(() => {
72+
vi.unstubAllGlobals();
73+
clearRuntimeAuthProfileStoreSnapshots();
74+
resetFileLockStateForTest();
75+
resetPluginLoaderTestStateForTest();
76+
});
77+
78+
afterAll(cleanupPluginLoaderFixturesForTest);
79+
80+
describe("Chutes auth-profile plugin lifecycle", () => {
81+
it("resumes an expired OAuth refresh after synchronous provider registration completes", async () => {
82+
await withOpenClawTestState(
83+
{ layout: "state-only", prefix: "openclaw-chutes-lifecycle-", agentEnv: "main" },
84+
async (state) => {
85+
const expiredCredential = {
86+
type: "oauth" as const,
87+
provider: "chutes",
88+
access: "at_old",
89+
refresh: "rt_old",
90+
expires: 1,
91+
clientId: "cid_test",
92+
};
93+
const refreshedCredential = {
94+
...expiredCredential,
95+
access: "at_new",
96+
refresh: "rt_new",
97+
expires: 4_102_444_800_000,
98+
};
99+
const initialStore: AuthProfileStore = {
100+
version: 1,
101+
profiles: { "chutes:default": expiredCredential },
102+
};
103+
await state.writeAuthProfiles(initialStore);
104+
const store = ensureAuthProfileStore();
105+
const plugin = writeChutesPlugin({
106+
id: "chutes-lifecycle",
107+
registerBody: `
108+
globalThis[${JSON.stringify(START_AUTH_CALLBACK)}]();
109+
api.registerProvider({
110+
id: "chutes",
111+
label: "Chutes",
112+
auth: [],
113+
async refreshOAuth(credential) {
114+
return {
115+
...credential,
116+
access: "at_new",
117+
refresh: "rt_new",
118+
expires: 4102444800000,
119+
};
120+
},
121+
});
122+
`,
123+
});
124+
const config = createPluginConfig({ id: plugin.id, file: plugin.file, enabled: true });
125+
const loadOptions: NonNullable<Parameters<typeof loadOpenClawPlugins>[0]> = {
126+
cache: false,
127+
workspaceDir: plugin.dir,
128+
config,
129+
onlyPluginIds: [plugin.id],
130+
};
131+
let authResolution: ReturnType<typeof resolveApiKeyForProfile> | undefined;
132+
const startAuthDuringRegister = vi.fn(() => {
133+
if (authResolution) {
134+
throw new Error("Chutes lifecycle fixture registered more than once");
135+
}
136+
expect(isPluginRegistryLoadInFlight(loadOptions)).toBe(true);
137+
authResolution = resolveApiKeyForProfile({
138+
cfg: config,
139+
store,
140+
profileId: "chutes:default",
141+
});
142+
});
143+
vi.stubGlobal(START_AUTH_CALLBACK, startAuthDuringRegister);
144+
145+
loadOpenClawPlugins(loadOptions);
146+
147+
expect(isPluginRegistryLoadInFlight(loadOptions)).toBe(false);
148+
if (!authResolution) {
149+
throw new Error("Chutes lifecycle fixture did not start auth resolution");
150+
}
151+
await expect(authResolution).resolves.toMatchObject({ apiKey: "at_new" });
152+
expect(loadPersistedAuthProfileStore(state.agentDir())?.profiles["chutes:default"]).toEqual(
153+
refreshedCredential,
154+
);
155+
expect(startAuthDuringRegister).toHaveBeenCalledOnce();
156+
},
157+
);
158+
});
159+
160+
it("distinguishes an explicitly disabled owner from an unowned provider", async () => {
161+
const disabledRegister = vi.fn();
162+
vi.stubGlobal(DISABLED_REGISTER_CALLBACK, disabledRegister);
163+
const plugin = writeChutesPlugin({
164+
id: "disabled-chutes",
165+
registerBody: `globalThis[${JSON.stringify(DISABLED_REGISTER_CALLBACK)}]();`,
166+
});
167+
const config = createPluginConfig({ id: plugin.id, file: plugin.file, enabled: false });
168+
const credential = {
169+
type: "oauth" as const,
170+
provider: "chutes",
171+
access: "at_old",
172+
refresh: "rt_old",
173+
expires: 1,
174+
};
175+
176+
expect(
177+
resolveProviderRefOwnership({ provider: "chutes", config, workspaceDir: plugin.dir }),
178+
).toEqual({ status: "owned", pluginIds: [plugin.id] });
179+
await expect(
180+
resolveProviderOAuthCredentialWithPlugin({
181+
provider: "chutes",
182+
config,
183+
workspaceDir: plugin.dir,
184+
credential,
185+
refresh: true,
186+
}),
187+
).resolves.toEqual({ status: "configured-unavailable" });
188+
await expect(
189+
resolveProviderOAuthCredentialWithPlugin({
190+
provider: "not-owned",
191+
config,
192+
workspaceDir: plugin.dir,
193+
credential: { ...credential, provider: "not-owned" },
194+
refresh: true,
195+
}),
196+
).resolves.toEqual({ status: "unowned" });
197+
expect(disabledRegister).not.toHaveBeenCalled();
198+
});
199+
});

0 commit comments

Comments
 (0)