plugin-secrets.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // 敏感插件选项私有存储(docs/design/v2/plugin-compat.md「Sensitive Option Storage」测试 1–7)。
  2. // 每个用例都用临时目录:插件存储目录在 <root>/plugins,私有文件因此落在 <root>/plugin-secrets.json;
  3. // 协议 handler 只认 ~/.zcode,下面把 homedir 重定向到一次性目录,绝不触碰真实 HOME。
  4. import { existsSync } from "node:fs";
  5. import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
  6. import { tmpdir } from "node:os";
  7. import { dirname, join } from "node:path";
  8. import { afterAll, describe, expect, it, vi } from "vitest";
  9. const FAKE_HOME = await vi.hoisted(async () => {
  10. const [{ mkdtemp: makeTemp }, { tmpdir: osTmpdir }, { join: joinPath }] = await Promise.all([
  11. import("node:fs/promises"),
  12. import("node:os"),
  13. import("node:path"),
  14. ]);
  15. return await makeTemp(joinPath(osTmpdir(), "zcode-plugin-secrets-home-"));
  16. });
  17. vi.mock("node:os", async (importOriginal) => {
  18. const actual = await importOriginal<typeof import("node:os")>();
  19. return { ...actual, homedir: () => FAKE_HOME };
  20. });
  21. import { createConfig } from "@zcode/adapters/config";
  22. import type { Logger } from "@zcode/contracts";
  23. import { zcodePluginsListResultSchema } from "@zcode/shared";
  24. import { resolveStartupPlugins } from "../src/app/startup-marks.js";
  25. import type { ZCodeAppOptions } from "../src/app/types.js";
  26. import {
  27. configureZCodePlugin,
  28. installZCodeMarketplacePlugin,
  29. resetZCodePluginConfig,
  30. resolveZCodePlugins,
  31. uninstallZCodeMarketplacePlugin,
  32. } from "../src/plugins.js";
  33. import { StartupTimer } from "../src/startup-logging.js";
  34. import { configurePlugin, listPlugins } from "../src/zcode-protocol/plugins.js";
  35. import { readPluginUserOptions } from "../src/zcode-protocol/plugin-user-options.js";
  36. import type { ZCodeProtocolAgentServerContext } from "../src/zcode-protocol/server-types.js";
  37. const PLUGIN_NAME = "secret-plugin";
  38. const PLUGIN_ID = `${PLUGIN_NAME}@inline`;
  39. const API_SERVER = `plugin:${PLUGIN_NAME}:api`;
  40. const LEAKY_SERVER = `plugin:${PLUGIN_NAME}:leaky`;
  41. const SECRETS_FILE = "plugin-secrets.json";
  42. const PRIVATE_FILE_MODE = 0o600;
  43. const FILE_MODE_MASK = 0o777;
  44. afterAll(async () => {
  45. await rm(FAKE_HOME, { force: true, recursive: true });
  46. });
  47. describe("plugin sensitive option storage", () => {
  48. it("1. stores a configured sensitive key only in the private file", async () => {
  49. await withFixture(async (fixture) => {
  50. await configureZCodePlugin({
  51. ...fixture.userOptions(),
  52. options: { region: "eu", token: "s3cret-user" },
  53. pluginId: PLUGIN_ID,
  54. });
  55. expect(await readJson(fixture.secretsPath)).toEqual({
  56. version: 1,
  57. user: { [PLUGIN_ID]: { token: "s3cret-user" } },
  58. workspaces: {},
  59. });
  60. if (process.platform !== "win32") {
  61. expect((await stat(fixture.secretsPath)).mode & FILE_MODE_MASK).toBe(PRIVATE_FILE_MODE);
  62. }
  63. const userConfigText = await readFile(fixture.userConfigPath, "utf8");
  64. expect(userConfigText).not.toContain("s3cret-user");
  65. expect(JSON.parse(userConfigText).plugins.options[PLUGIN_ID]).toEqual({ region: "eu" });
  66. });
  67. });
  68. it("2. reads a legacy plain-text value and migrates it on the next save", async () => {
  69. await withFixture(async (fixture) => {
  70. await fixture.writeUserConfig({ [PLUGIN_ID]: { token: "legacy-secret" } });
  71. const before = await resolveZCodePlugins(fixture.userOptions());
  72. expect(authorizationHeader(before.mcpServers[API_SERVER])).toBe("Bearer legacy-secret");
  73. // 不在启动时迁移:只读解析不创建私有文件,也不改写 config.json。
  74. expect(existsSync(fixture.secretsPath)).toBe(false);
  75. expect(JSON.parse(await readFile(fixture.userConfigPath, "utf8")).plugins.options).toEqual({
  76. [PLUGIN_ID]: { token: "legacy-secret" },
  77. });
  78. // 只保存普通键:UI 不回传敏感值,旧明文仍要在这次保存里迁走。
  79. await configureZCodePlugin({
  80. ...fixture.userOptions(),
  81. options: { region: "eu" },
  82. pluginId: PLUGIN_ID,
  83. });
  84. expect((await readJson(fixture.secretsPath)).user).toEqual({
  85. [PLUGIN_ID]: { token: "legacy-secret" },
  86. });
  87. const userConfigText = await readFile(fixture.userConfigPath, "utf8");
  88. expect(userConfigText).not.toContain("legacy-secret");
  89. expect(JSON.parse(userConfigText).plugins.options[PLUGIN_ID]).toEqual({ region: "eu" });
  90. const after = await resolveZCodePlugins(fixture.userOptions());
  91. expect(authorizationHeader(after.mcpServers[API_SERVER])).toBe("Bearer legacy-secret");
  92. });
  93. });
  94. it("3. expands a private value in MCP secret sinks and still rejects other fields", async () => {
  95. await withFixture(async (fixture) => {
  96. // 值只在私有文件里,config.json 没有:证明运行时读的是私有文件。
  97. await writeTestFile(
  98. fixture.secretsPath,
  99. JSON.stringify({
  100. version: 1,
  101. user: { [PLUGIN_ID]: { token: "runtime-secret" } },
  102. workspaces: {},
  103. }),
  104. );
  105. const outcome = await resolveStartupPlugins({
  106. cliStorageRoot: fixture.root,
  107. configResult: createConfig({
  108. env: {},
  109. userConfigPath: fixture.userConfigPath,
  110. workingDirectory: fixture.root,
  111. }),
  112. env: {},
  113. options: { pluginStorageRoot: fixture.pluginStorageRoot } as ZCodeAppOptions,
  114. startupTimer: createNoopStartupTimer(),
  115. workingDirectory: fixture.root,
  116. });
  117. expect(authorizationHeader(outcome.mcpServers[API_SERVER])).toBe("Bearer runtime-secret");
  118. expect(outcome.mcpServers[LEAKY_SERVER]).toBeUndefined();
  119. expect(outcome.diagnostics).toContainEqual(
  120. expect.objectContaining({ code: "plugin_variable_missing", pluginId: PLUGIN_ID }),
  121. );
  122. expect(JSON.stringify(outcome.diagnostics)).not.toContain("runtime-secret");
  123. });
  124. });
  125. it("4. keys workspace secrets by workspace root and keeps the innermost workspace first", async () => {
  126. await withFixture(async (fixture) => {
  127. const repositoryRoot = join(fixture.root, "repository");
  128. const nestedRoot = join(repositoryRoot, "packages", "app");
  129. await mkdir(join(repositoryRoot, ".git"), { recursive: true });
  130. await mkdir(nestedRoot, { recursive: true });
  131. await configureZCodePlugin({
  132. ...fixture.userOptions(repositoryRoot),
  133. options: { token: "outer-secret" },
  134. pluginId: PLUGIN_ID,
  135. scope: "workspace",
  136. });
  137. await configureZCodePlugin({
  138. ...fixture.userOptions(nestedRoot),
  139. options: { token: "inner-secret" },
  140. pluginId: PLUGIN_ID,
  141. scope: "workspace",
  142. });
  143. expect((await readJson(fixture.secretsPath)).workspaces).toEqual({
  144. [repositoryRoot]: { [PLUGIN_ID]: { token: "outer-secret" } },
  145. [nestedRoot]: { [PLUGIN_ID]: { token: "inner-secret" } },
  146. });
  147. for (const workspaceRoot of [repositoryRoot, nestedRoot]) {
  148. const workspaceConfig = await readFile(
  149. join(workspaceRoot, ".zcode", "config.json"),
  150. "utf8",
  151. );
  152. expect(workspaceConfig).not.toMatch(/(outer|inner)-secret/u);
  153. expect(JSON.parse(workspaceConfig).plugins.options[PLUGIN_ID]).toEqual({});
  154. }
  155. const nested = await resolveZCodePlugins(fixture.userOptions(nestedRoot));
  156. expect(authorizationHeader(nested.mcpServers[API_SERVER])).toBe("Bearer inner-secret");
  157. const outer = await resolveZCodePlugins(fixture.userOptions(repositoryRoot));
  158. expect(authorizationHeader(outer.mcpServers[API_SERVER])).toBe("Bearer outer-secret");
  159. // 清掉最内层的值后回落到外层 workspace 的私有值。
  160. await configureZCodePlugin({
  161. ...fixture.userOptions(nestedRoot),
  162. clearOptionKeys: ["token"],
  163. options: {},
  164. pluginId: PLUGIN_ID,
  165. scope: "workspace",
  166. });
  167. const fallback = await resolveZCodePlugins(fixture.userOptions(nestedRoot));
  168. expect(authorizationHeader(fallback.mcpServers[API_SERVER])).toBe("Bearer outer-secret");
  169. expect((await readJson(fixture.secretsPath)).workspaces).toEqual({
  170. [repositoryRoot]: { [PLUGIN_ID]: { token: "outer-secret" } },
  171. });
  172. });
  173. });
  174. it("5. keeps plugins/list filtered and returns user values from plugins/readUserOptions", async () => {
  175. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-secrets-protocol-"));
  176. const userConfigPath = join(FAKE_HOME, ".zcode", "cli", "config.json");
  177. const secretsPath = join(FAKE_HOME, ".zcode", "cli", SECRETS_FILE);
  178. const pluginRoot = join(root, PLUGIN_NAME);
  179. const context = {} as ZCodeProtocolAgentServerContext;
  180. const workspace = { workspacePath: root, workspaceKey: root };
  181. try {
  182. await writePluginManifest(pluginRoot);
  183. await writeTestFile(userConfigPath, JSON.stringify({ plugins: { dirs: [pluginRoot] } }));
  184. await configurePlugin(context, {
  185. workspace,
  186. pluginId: PLUGIN_ID,
  187. options: { token: "protocol-secret" },
  188. });
  189. expect((await readJson(secretsPath)).user).toEqual({
  190. [PLUGIN_ID]: { token: "protocol-secret" },
  191. });
  192. const listed = zcodePluginsListResultSchema.parse(
  193. await listPlugins(context, { workspace, configScope: "user" }),
  194. );
  195. expect(JSON.stringify(listed)).not.toContain("protocol-secret");
  196. const plugin = listed.plugins.find((item) => item.id === PLUGIN_ID);
  197. // 迁进私有文件的键仍要报 scope,设置页的标记与清除按钮依赖它。
  198. expect(plugin?.optionSources).toMatchObject({ token: "user" });
  199. expect(plugin?.configuredOptions?.token).toBeUndefined();
  200. expect(await readPluginUserOptions(context, { pluginId: PLUGIN_ID })).toEqual({
  201. values: { region: "us", token: "protocol-secret" },
  202. });
  203. await expect(
  204. readPluginUserOptions(context, { pluginId: "missing@inline" }),
  205. ).rejects.toMatchObject({ code: -32602, data: { code: "plugin_not_found" } });
  206. } finally {
  207. await rm(join(FAKE_HOME, ".zcode"), { force: true, recursive: true });
  208. await rm(root, { force: true, recursive: true });
  209. }
  210. });
  211. it("6. removes private entries on reset and on uninstall", async () => {
  212. await withFixture(async (fixture) => {
  213. await configureZCodePlugin({
  214. ...fixture.userOptions(),
  215. options: { token: "user-secret" },
  216. pluginId: PLUGIN_ID,
  217. });
  218. await configureZCodePlugin({
  219. ...fixture.userOptions(),
  220. options: { token: "workspace-secret" },
  221. pluginId: PLUGIN_ID,
  222. scope: "workspace",
  223. });
  224. // workspace「恢复继承」只删启用覆盖,与 config.json 同语义:workspace 私有值保留。
  225. await resetZCodePluginConfig({
  226. ...fixture.userOptions(),
  227. pluginId: PLUGIN_ID,
  228. scope: "workspace",
  229. });
  230. expect((await readJson(fixture.secretsPath)).workspaces).toEqual({
  231. [fixture.root]: { [PLUGIN_ID]: { token: "workspace-secret" } },
  232. });
  233. await resetZCodePluginConfig({ ...fixture.userOptions(), pluginId: PLUGIN_ID });
  234. expect((await readJson(fixture.secretsPath)).user).toEqual({});
  235. const marketplacePluginId = "hello@lazy-market";
  236. await installMarketplacePlugin(fixture);
  237. await writeTestFile(
  238. fixture.secretsPath,
  239. JSON.stringify({
  240. version: 1,
  241. user: { [marketplacePluginId]: { token: "a" }, [PLUGIN_ID]: { token: "keep" } },
  242. workspaces: {
  243. [fixture.root]: { [marketplacePluginId]: { token: "b" } },
  244. [join(fixture.root, "other")]: {
  245. [marketplacePluginId]: { token: "c" },
  246. [PLUGIN_ID]: { token: "keep-too" },
  247. },
  248. },
  249. }),
  250. );
  251. const removed = await uninstallZCodeMarketplacePlugin({
  252. ...fixture.userOptions(),
  253. pluginId: marketplacePluginId,
  254. });
  255. expect(removed?.id).toBe(marketplacePluginId);
  256. expect(await readJson(fixture.secretsPath)).toEqual({
  257. version: 1,
  258. user: { [PLUGIN_ID]: { token: "keep" } },
  259. workspaces: { [join(fixture.root, "other")]: { [PLUGIN_ID]: { token: "keep-too" } } },
  260. });
  261. });
  262. });
  263. it("7. backs up a corrupt private file, treats it as empty and reports a value-free diagnostic", async () => {
  264. await withFixture(async (fixture) => {
  265. const corrupt = '{"version":1,"user":{"secret-plugin@inline":{"token":"corrupt-secret"';
  266. await writeTestFile(fixture.secretsPath, corrupt);
  267. const outcome = await resolveZCodePlugins(fixture.userOptions());
  268. const diagnostic = outcome.diagnostics.find(
  269. (item) => item.code === "plugin_secrets_unreadable",
  270. );
  271. expect(diagnostic).toMatchObject({ severity: "error" });
  272. expect(JSON.stringify(outcome.diagnostics)).not.toContain("corrupt-secret");
  273. // 按空处理:需要 token 的 server 按现有规则报缺值。
  274. expect(outcome.mcpServers[API_SERVER]).toBeUndefined();
  275. expect(outcome.diagnostics).toContainEqual(
  276. expect.objectContaining({ code: "plugin_variable_missing", pluginId: PLUGIN_ID }),
  277. );
  278. const backups = (await readdir(fixture.root)).filter((name) =>
  279. name.startsWith(`${SECRETS_FILE}.corrupt-`),
  280. );
  281. expect(backups).toHaveLength(1);
  282. expect(await readFile(join(fixture.root, backups[0] ?? ""), "utf8")).toBe(corrupt);
  283. // 下一次保存把损坏文件替换成有效内容,备份留着。
  284. await configureZCodePlugin({
  285. ...fixture.userOptions(),
  286. options: { token: "fresh-secret" },
  287. pluginId: PLUGIN_ID,
  288. });
  289. expect(await readJson(fixture.secretsPath)).toEqual({
  290. version: 1,
  291. user: { [PLUGIN_ID]: { token: "fresh-secret" } },
  292. workspaces: {},
  293. });
  294. expect(existsSync(join(fixture.root, backups[0] ?? ""))).toBe(true);
  295. const healed = await resolveZCodePlugins(fixture.userOptions());
  296. expect(healed.diagnostics.some((item) => item.code === "plugin_secrets_unreadable")).toBe(
  297. false,
  298. );
  299. });
  300. });
  301. });
  302. interface Fixture {
  303. root: string;
  304. pluginStorageRoot: string;
  305. secretsPath: string;
  306. userConfigPath: string;
  307. userOptions(workingDirectory?: string): {
  308. env: NodeJS.ProcessEnv;
  309. pluginStorageRoot: string;
  310. userConfigPath: string;
  311. workingDirectory: string;
  312. };
  313. writeUserConfig(options?: Record<string, Record<string, unknown>>): Promise<void>;
  314. }
  315. async function withFixture(run: (fixture: Fixture) => Promise<void>): Promise<void> {
  316. const root = await mkdtemp(join(tmpdir(), "zcode-plugin-secrets-"));
  317. const pluginRoot = join(root, PLUGIN_NAME);
  318. const userConfigPath = join(root, "user-config.json");
  319. const writeUserConfig = async (options?: Record<string, Record<string, unknown>>) =>
  320. writeTestFile(
  321. userConfigPath,
  322. JSON.stringify({ plugins: { dirs: [pluginRoot], ...(options ? { options } : {}) } }),
  323. );
  324. const fixture: Fixture = {
  325. root,
  326. pluginStorageRoot: join(root, "plugins"),
  327. secretsPath: join(root, SECRETS_FILE),
  328. userConfigPath,
  329. userOptions: (workingDirectory = root) => ({
  330. env: {},
  331. pluginStorageRoot: join(root, "plugins"),
  332. userConfigPath,
  333. workingDirectory,
  334. }),
  335. writeUserConfig,
  336. };
  337. try {
  338. await writePluginManifest(pluginRoot);
  339. await writeUserConfig();
  340. await run(fixture);
  341. } finally {
  342. await rm(root, { force: true, recursive: true });
  343. }
  344. }
  345. async function writePluginManifest(pluginRoot: string): Promise<void> {
  346. await writeTestFile(
  347. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  348. JSON.stringify({
  349. name: PLUGIN_NAME,
  350. userConfig: {
  351. token: { sensitive: true, type: "string" },
  352. region: { type: "string", default: "us" },
  353. },
  354. mcpServers: {
  355. // headers 是 secret sink:敏感值可以展开。
  356. api: {
  357. type: "http",
  358. url: "https://mcp.example.com/api",
  359. headers: { Authorization: "Bearer ${user_config.token}" },
  360. },
  361. // url 不是 secret sink:敏感值必须被拒绝,server 被单独禁用。
  362. leaky: { type: "http", url: "https://mcp.example.com/${user_config.token}" },
  363. },
  364. }),
  365. );
  366. }
  367. async function installMarketplacePlugin(fixture: Fixture): Promise<void> {
  368. const marketplaceRoot = join(fixture.root, "marketplace");
  369. await writeTestFile(
  370. join(fixture.pluginStorageRoot, "known_marketplaces.json"),
  371. JSON.stringify({
  372. version: 1,
  373. marketplaces: [
  374. {
  375. id: "lazy-market",
  376. source: { source: "directory", path: marketplaceRoot },
  377. name: "lazy-market",
  378. addedAt: "2026-01-01T00:00:00.000Z",
  379. pluginCount: 0,
  380. },
  381. ],
  382. }),
  383. );
  384. await writeTestFile(
  385. join(marketplaceRoot, ".claude-plugin", "marketplace.json"),
  386. JSON.stringify({
  387. name: "lazy-market",
  388. plugins: [{ name: "hello", source: "./plugins/hello" }],
  389. }),
  390. );
  391. await writeTestFile(
  392. join(marketplaceRoot, "plugins", "hello", ".claude-plugin", "plugin.json"),
  393. JSON.stringify({ name: "hello", userConfig: { token: { sensitive: true } } }),
  394. );
  395. await installZCodeMarketplacePlugin({
  396. ...fixture.userOptions(),
  397. marketplace: "lazy-market",
  398. pluginName: "hello",
  399. });
  400. }
  401. function authorizationHeader(server: unknown): string | undefined {
  402. if (!server || typeof server !== "object" || !("headers" in server)) return undefined;
  403. return (server as { headers?: Record<string, string> }).headers?.Authorization;
  404. }
  405. async function readJson(path: string): Promise<Record<string, unknown>> {
  406. return JSON.parse(await readFile(path, "utf8")) as Record<string, unknown>;
  407. }
  408. async function writeTestFile(path: string, contents: string): Promise<void> {
  409. await mkdir(dirname(path), { recursive: true });
  410. await writeFile(path, contents);
  411. }
  412. function createNoopStartupTimer(): StartupTimer {
  413. const noop = () => {};
  414. const logger: Logger = {
  415. debug: noop,
  416. info: noop,
  417. warn: noop,
  418. error: noop,
  419. child: () => logger,
  420. };
  421. return new StartupTimer(logger, {});
  422. }