auth-storage.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { registerOAuthProvider } from "@earendil-works/pi-ai/oauth";
  5. import lockfile from "proper-lockfile";
  6. import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
  7. import { AuthStorage } from "../src/core/auth-storage.ts";
  8. import { clearConfigValueCache } from "../src/core/resolve-config-value.ts";
  9. describe("AuthStorage", () => {
  10. let tempDir: string;
  11. let authJsonPath: string;
  12. let authStorage: AuthStorage;
  13. beforeEach(() => {
  14. tempDir = join(tmpdir(), `pi-test-auth-storage-${Date.now()}-${Math.random().toString(36).slice(2)}`);
  15. mkdirSync(tempDir, { recursive: true });
  16. authJsonPath = join(tempDir, "auth.json");
  17. });
  18. afterEach(() => {
  19. if (tempDir && existsSync(tempDir)) {
  20. rmSync(tempDir, { recursive: true });
  21. }
  22. clearConfigValueCache();
  23. vi.restoreAllMocks();
  24. });
  25. function writeAuthJson(data: Record<string, unknown>) {
  26. writeFileSync(authJsonPath, JSON.stringify(data));
  27. }
  28. function toShPath(value: string): string {
  29. return value.replace(/\\/g, "/").replace(/"/g, '\\"');
  30. }
  31. describe("API key resolution", () => {
  32. test("literal API key is returned directly", async () => {
  33. writeAuthJson({
  34. anthropic: { type: "api_key", key: "sk-ant-literal-key" },
  35. });
  36. authStorage = AuthStorage.create(authJsonPath);
  37. const apiKey = await authStorage.getApiKey("anthropic");
  38. expect(apiKey).toBe("sk-ant-literal-key");
  39. });
  40. test("apiKey with ! prefix executes command and uses stdout", async () => {
  41. writeAuthJson({
  42. anthropic: { type: "api_key", key: "!echo test-api-key-from-command" },
  43. });
  44. authStorage = AuthStorage.create(authJsonPath);
  45. const apiKey = await authStorage.getApiKey("anthropic");
  46. expect(apiKey).toBe("test-api-key-from-command");
  47. });
  48. test("apiKey with ! prefix trims whitespace from command output", async () => {
  49. writeAuthJson({
  50. anthropic: { type: "api_key", key: "!echo ' spaced-key '" },
  51. });
  52. authStorage = AuthStorage.create(authJsonPath);
  53. const apiKey = await authStorage.getApiKey("anthropic");
  54. expect(apiKey).toBe("spaced-key");
  55. });
  56. test("apiKey with ! prefix handles multiline output (uses trimmed result)", async () => {
  57. writeAuthJson({
  58. anthropic: { type: "api_key", key: "!printf 'line1\\nline2'" },
  59. });
  60. authStorage = AuthStorage.create(authJsonPath);
  61. const apiKey = await authStorage.getApiKey("anthropic");
  62. expect(apiKey).toBe("line1\nline2");
  63. });
  64. test("apiKey with ! prefix returns undefined on command failure", async () => {
  65. writeAuthJson({
  66. anthropic: { type: "api_key", key: "!exit 1" },
  67. });
  68. authStorage = AuthStorage.create(authJsonPath);
  69. const apiKey = await authStorage.getApiKey("anthropic");
  70. expect(apiKey).toBeUndefined();
  71. });
  72. test("apiKey with ! prefix returns undefined on nonexistent command", async () => {
  73. writeAuthJson({
  74. anthropic: { type: "api_key", key: "!nonexistent-command-12345" },
  75. });
  76. authStorage = AuthStorage.create(authJsonPath);
  77. const apiKey = await authStorage.getApiKey("anthropic");
  78. expect(apiKey).toBeUndefined();
  79. });
  80. test("apiKey with ! prefix returns undefined on empty output", async () => {
  81. writeAuthJson({
  82. anthropic: { type: "api_key", key: "!printf ''" },
  83. });
  84. authStorage = AuthStorage.create(authJsonPath);
  85. const apiKey = await authStorage.getApiKey("anthropic");
  86. expect(apiKey).toBeUndefined();
  87. });
  88. test("apiKey with $ prefix resolves to env value", async () => {
  89. const originalEnv = process.env.TEST_AUTH_API_KEY_12345;
  90. process.env.TEST_AUTH_API_KEY_12345 = "env-api-key-value";
  91. try {
  92. writeAuthJson({
  93. anthropic: { type: "api_key", key: "$TEST_AUTH_API_KEY_12345" },
  94. });
  95. authStorage = AuthStorage.create(authJsonPath);
  96. const apiKey = await authStorage.getApiKey("anthropic");
  97. expect(apiKey).toBe("env-api-key-value");
  98. } finally {
  99. if (originalEnv === undefined) {
  100. delete process.env.TEST_AUTH_API_KEY_12345;
  101. } else {
  102. process.env.TEST_AUTH_API_KEY_12345 = originalEnv;
  103. }
  104. }
  105. });
  106. test("apiKey with braced env syntax resolves to env value", async () => {
  107. const originalEnv = process.env.TEST_AUTH_BRACED_API_KEY_12345;
  108. process.env.TEST_AUTH_BRACED_API_KEY_12345 = "braced-env-api-key-value";
  109. const bracedKey = "$" + "{TEST_AUTH_BRACED_API_KEY_12345}";
  110. try {
  111. writeAuthJson({
  112. anthropic: { type: "api_key", key: bracedKey },
  113. });
  114. authStorage = AuthStorage.create(authJsonPath);
  115. const apiKey = await authStorage.getApiKey("anthropic");
  116. expect(apiKey).toBe("braced-env-api-key-value");
  117. } finally {
  118. if (originalEnv === undefined) {
  119. delete process.env.TEST_AUTH_BRACED_API_KEY_12345;
  120. } else {
  121. process.env.TEST_AUTH_BRACED_API_KEY_12345 = originalEnv;
  122. }
  123. }
  124. });
  125. test("apiKey interpolates braced env references inside literals", async () => {
  126. const originalPartA = process.env.TEST_AUTH_INTERPOLATED_PART_A_12345;
  127. const originalPartB = process.env.TEST_AUTH_INTERPOLATED_PART_B_12345;
  128. process.env.TEST_AUTH_INTERPOLATED_PART_A_12345 = "left";
  129. process.env.TEST_AUTH_INTERPOLATED_PART_B_12345 = "right";
  130. const interpolatedKey = [
  131. "$",
  132. "{TEST_AUTH_INTERPOLATED_PART_A_12345}_$",
  133. "{TEST_AUTH_INTERPOLATED_PART_B_12345}",
  134. ].join("");
  135. try {
  136. writeAuthJson({
  137. anthropic: { type: "api_key", key: interpolatedKey },
  138. });
  139. authStorage = AuthStorage.create(authJsonPath);
  140. const apiKey = await authStorage.getApiKey("anthropic");
  141. expect(apiKey).toBe("left_right");
  142. } finally {
  143. if (originalPartA === undefined) {
  144. delete process.env.TEST_AUTH_INTERPOLATED_PART_A_12345;
  145. } else {
  146. process.env.TEST_AUTH_INTERPOLATED_PART_A_12345 = originalPartA;
  147. }
  148. if (originalPartB === undefined) {
  149. delete process.env.TEST_AUTH_INTERPOLATED_PART_B_12345;
  150. } else {
  151. process.env.TEST_AUTH_INTERPOLATED_PART_B_12345 = originalPartB;
  152. }
  153. }
  154. });
  155. test("apiKey with $$ prefix escapes a leading dollar", async () => {
  156. writeAuthJson({
  157. anthropic: { type: "api_key", key: "$$TEST_AUTH_API_KEY_12345" },
  158. });
  159. authStorage = AuthStorage.create(authJsonPath);
  160. const apiKey = await authStorage.getApiKey("anthropic");
  161. expect(apiKey).toBe("$TEST_AUTH_API_KEY_12345");
  162. });
  163. test("apiKey with $! escapes a literal bang and still interpolates later env refs", async () => {
  164. const originalEnv = process.env.TEST_AUTH_API_KEY_12345;
  165. process.env.TEST_AUTH_API_KEY_12345 = "env-api-key-value";
  166. try {
  167. writeAuthJson({
  168. anthropic: { type: "api_key", key: "$!literal-$TEST_AUTH_API_KEY_12345" },
  169. });
  170. authStorage = AuthStorage.create(authJsonPath);
  171. const apiKey = await authStorage.getApiKey("anthropic");
  172. expect(apiKey).toBe("!literal-env-api-key-value");
  173. } finally {
  174. if (originalEnv === undefined) {
  175. delete process.env.TEST_AUTH_API_KEY_12345;
  176. } else {
  177. process.env.TEST_AUTH_API_KEY_12345 = originalEnv;
  178. }
  179. }
  180. });
  181. test("plain API key is used directly even when it matches an env var", async () => {
  182. const originalEnv = process.env.TEST_AUTH_API_KEY_12345;
  183. process.env.TEST_AUTH_API_KEY_12345 = "env-api-key-value";
  184. try {
  185. writeAuthJson({
  186. anthropic: { type: "api_key", key: "TEST_AUTH_API_KEY_12345" },
  187. });
  188. authStorage = AuthStorage.create(authJsonPath);
  189. const apiKey = await authStorage.getApiKey("anthropic");
  190. expect(apiKey).toBe("TEST_AUTH_API_KEY_12345");
  191. } finally {
  192. if (originalEnv === undefined) {
  193. delete process.env.TEST_AUTH_API_KEY_12345;
  194. } else {
  195. process.env.TEST_AUTH_API_KEY_12345 = originalEnv;
  196. }
  197. }
  198. });
  199. test("literal public API key is not corrupted by the Windows PUBLIC env var", async () => {
  200. const originalPublic = process.env.PUBLIC;
  201. process.env.PUBLIC = "C:\\Users\\Public";
  202. try {
  203. writeAuthJson({
  204. opencode: { type: "api_key", key: "public" },
  205. });
  206. authStorage = AuthStorage.create(authJsonPath);
  207. const apiKey = await authStorage.getApiKey("opencode");
  208. expect(apiKey).toBe("public");
  209. } finally {
  210. if (originalPublic === undefined) {
  211. delete process.env.PUBLIC;
  212. } else {
  213. process.env.PUBLIC = originalPublic;
  214. }
  215. }
  216. });
  217. test("apiKey as literal value is used directly when not an env var", async () => {
  218. // Make sure this isn't an env var
  219. delete process.env.literal_api_key_value;
  220. writeAuthJson({
  221. anthropic: { type: "api_key", key: "literal_api_key_value" },
  222. });
  223. authStorage = AuthStorage.create(authJsonPath);
  224. const apiKey = await authStorage.getApiKey("anthropic");
  225. expect(apiKey).toBe("literal_api_key_value");
  226. });
  227. test("apiKey command can use shell features like pipes", async () => {
  228. writeAuthJson({
  229. anthropic: { type: "api_key", key: "!echo 'hello world' | tr ' ' '-'" },
  230. });
  231. authStorage = AuthStorage.create(authJsonPath);
  232. const apiKey = await authStorage.getApiKey("anthropic");
  233. expect(apiKey).toBe("hello-world");
  234. });
  235. describe("caching", () => {
  236. test("command is only executed once per process", async () => {
  237. // Use a command that writes to a file to count invocations
  238. const counterFile = join(tempDir, "counter");
  239. writeFileSync(counterFile, "0");
  240. const counterPath = toShPath(counterFile);
  241. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  242. writeAuthJson({
  243. anthropic: { type: "api_key", key: command },
  244. });
  245. authStorage = AuthStorage.create(authJsonPath);
  246. // Call multiple times
  247. await authStorage.getApiKey("anthropic");
  248. await authStorage.getApiKey("anthropic");
  249. await authStorage.getApiKey("anthropic");
  250. // Command should have only run once
  251. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  252. expect(count).toBe(1);
  253. });
  254. test("cache persists across AuthStorage instances", async () => {
  255. const counterFile = join(tempDir, "counter");
  256. writeFileSync(counterFile, "0");
  257. const counterPath = toShPath(counterFile);
  258. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  259. writeAuthJson({
  260. anthropic: { type: "api_key", key: command },
  261. });
  262. // Create multiple AuthStorage instances
  263. const storage1 = AuthStorage.create(authJsonPath);
  264. await storage1.getApiKey("anthropic");
  265. const storage2 = AuthStorage.create(authJsonPath);
  266. await storage2.getApiKey("anthropic");
  267. // Command should still have only run once
  268. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  269. expect(count).toBe(1);
  270. });
  271. test("clearConfigValueCache allows command to run again", async () => {
  272. const counterFile = join(tempDir, "counter");
  273. writeFileSync(counterFile, "0");
  274. const counterPath = toShPath(counterFile);
  275. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; echo "key-value"'`;
  276. writeAuthJson({
  277. anthropic: { type: "api_key", key: command },
  278. });
  279. authStorage = AuthStorage.create(authJsonPath);
  280. await authStorage.getApiKey("anthropic");
  281. // Clear cache and call again
  282. clearConfigValueCache();
  283. await authStorage.getApiKey("anthropic");
  284. // Command should have run twice
  285. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  286. expect(count).toBe(2);
  287. });
  288. test("different commands are cached separately", async () => {
  289. writeAuthJson({
  290. anthropic: { type: "api_key", key: "!echo key-anthropic" },
  291. openai: { type: "api_key", key: "!echo key-openai" },
  292. });
  293. authStorage = AuthStorage.create(authJsonPath);
  294. const keyA = await authStorage.getApiKey("anthropic");
  295. const keyB = await authStorage.getApiKey("openai");
  296. expect(keyA).toBe("key-anthropic");
  297. expect(keyB).toBe("key-openai");
  298. });
  299. test("failed commands are cached (not retried)", async () => {
  300. const counterFile = join(tempDir, "counter");
  301. writeFileSync(counterFile, "0");
  302. const counterPath = toShPath(counterFile);
  303. const command = `!sh -c 'count=$(cat "${counterPath}"); echo $((count + 1)) > "${counterPath}"; exit 1'`;
  304. writeAuthJson({
  305. anthropic: { type: "api_key", key: command },
  306. });
  307. authStorage = AuthStorage.create(authJsonPath);
  308. // Call multiple times - all should return undefined
  309. const key1 = await authStorage.getApiKey("anthropic");
  310. const key2 = await authStorage.getApiKey("anthropic");
  311. expect(key1).toBeUndefined();
  312. expect(key2).toBeUndefined();
  313. // Command should have only run once despite failures
  314. const count = parseInt(readFileSync(counterFile, "utf-8").trim(), 10);
  315. expect(count).toBe(1);
  316. });
  317. test("environment variables are not cached (changes are picked up)", async () => {
  318. const envVarName = "TEST_AUTH_KEY_CACHE_TEST_98765";
  319. const originalEnv = process.env[envVarName];
  320. try {
  321. process.env[envVarName] = "first-value";
  322. writeAuthJson({
  323. anthropic: { type: "api_key", key: `$${envVarName}` },
  324. });
  325. authStorage = AuthStorage.create(authJsonPath);
  326. const key1 = await authStorage.getApiKey("anthropic");
  327. expect(key1).toBe("first-value");
  328. // Change env var
  329. process.env[envVarName] = "second-value";
  330. const key2 = await authStorage.getApiKey("anthropic");
  331. expect(key2).toBe("second-value");
  332. } finally {
  333. if (originalEnv === undefined) {
  334. delete process.env[envVarName];
  335. } else {
  336. process.env[envVarName] = originalEnv;
  337. }
  338. }
  339. });
  340. });
  341. });
  342. describe("oauth lock compromise handling", () => {
  343. test("returns undefined on compromised lock and allows a later retry", async () => {
  344. const providerId = `test-oauth-provider-${Date.now()}-${Math.random().toString(36).slice(2)}`;
  345. registerOAuthProvider({
  346. id: providerId,
  347. name: "Test OAuth Provider",
  348. async login() {
  349. throw new Error("Not used in this test");
  350. },
  351. async refreshToken(credentials) {
  352. return {
  353. ...credentials,
  354. access: "refreshed-access-token",
  355. expires: Date.now() + 60_000,
  356. };
  357. },
  358. getApiKey(credentials) {
  359. return `Bearer ${credentials.access}`;
  360. },
  361. });
  362. writeAuthJson({
  363. [providerId]: {
  364. type: "oauth",
  365. refresh: "refresh-token",
  366. access: "expired-access-token",
  367. expires: Date.now() - 10_000,
  368. },
  369. });
  370. authStorage = AuthStorage.create(authJsonPath);
  371. const realLock = lockfile.lock.bind(lockfile);
  372. const lockSpy = vi.spyOn(lockfile, "lock");
  373. lockSpy.mockImplementationOnce(async (file, options) => {
  374. options?.onCompromised?.(new Error("Unable to update lock within the stale threshold"));
  375. return realLock(file, options);
  376. });
  377. const firstTry = await authStorage.getApiKey(providerId);
  378. expect(firstTry).toBeUndefined();
  379. lockSpy.mockRestore();
  380. const secondTry = await authStorage.getApiKey(providerId);
  381. expect(secondTry).toBe("Bearer refreshed-access-token");
  382. });
  383. });
  384. describe("persistence semantics", () => {
  385. test("set preserves unrelated external edits", () => {
  386. writeAuthJson({
  387. anthropic: { type: "api_key", key: "old-anthropic" },
  388. openai: { type: "api_key", key: "openai-key" },
  389. });
  390. authStorage = AuthStorage.create(authJsonPath);
  391. // Simulate external edit while process is running
  392. writeAuthJson({
  393. anthropic: { type: "api_key", key: "old-anthropic" },
  394. openai: { type: "api_key", key: "openai-key" },
  395. google: { type: "api_key", key: "google-key" },
  396. });
  397. authStorage.set("anthropic", { type: "api_key", key: "new-anthropic" });
  398. const updated = JSON.parse(readFileSync(authJsonPath, "utf-8")) as Record<string, { key: string }>;
  399. expect(updated.anthropic.key).toBe("new-anthropic");
  400. expect(updated.openai.key).toBe("openai-key");
  401. expect(updated.google.key).toBe("google-key");
  402. });
  403. test("remove preserves unrelated external edits", () => {
  404. writeAuthJson({
  405. anthropic: { type: "api_key", key: "anthropic-key" },
  406. openai: { type: "api_key", key: "openai-key" },
  407. });
  408. authStorage = AuthStorage.create(authJsonPath);
  409. // Simulate external edit while process is running
  410. writeAuthJson({
  411. anthropic: { type: "api_key", key: "anthropic-key" },
  412. openai: { type: "api_key", key: "openai-key" },
  413. google: { type: "api_key", key: "google-key" },
  414. });
  415. authStorage.remove("anthropic");
  416. const updated = JSON.parse(readFileSync(authJsonPath, "utf-8")) as Record<string, { key: string }>;
  417. expect(updated.anthropic).toBeUndefined();
  418. expect(updated.openai.key).toBe("openai-key");
  419. expect(updated.google.key).toBe("google-key");
  420. });
  421. test("does not overwrite malformed auth file after load error", () => {
  422. writeAuthJson({
  423. anthropic: { type: "api_key", key: "anthropic-key" },
  424. });
  425. authStorage = AuthStorage.create(authJsonPath);
  426. writeFileSync(authJsonPath, "{invalid-json", "utf-8");
  427. authStorage.reload();
  428. authStorage.set("openai", { type: "api_key", key: "openai-key" });
  429. const raw = readFileSync(authJsonPath, "utf-8");
  430. expect(raw).toBe("{invalid-json");
  431. });
  432. test("reload records parse errors and drainErrors clears buffer", () => {
  433. writeAuthJson({
  434. anthropic: { type: "api_key", key: "anthropic-key" },
  435. });
  436. authStorage = AuthStorage.create(authJsonPath);
  437. writeFileSync(authJsonPath, "{invalid-json", "utf-8");
  438. authStorage.reload();
  439. // Keeps previous in-memory data on reload failure
  440. expect(authStorage.get("anthropic")).toEqual({ type: "api_key", key: "anthropic-key" });
  441. const firstDrain = authStorage.drainErrors();
  442. expect(firstDrain.length).toBeGreaterThan(0);
  443. expect(firstDrain[0]).toBeInstanceOf(Error);
  444. const secondDrain = authStorage.drainErrors();
  445. expect(secondDrain).toHaveLength(0);
  446. });
  447. });
  448. describe("auth status", () => {
  449. test("does not expose stored API keys or OAuth tokens", () => {
  450. authStorage = AuthStorage.inMemory({
  451. anthropic: { type: "api_key", key: "secret-api-key" },
  452. openai: {
  453. type: "oauth",
  454. access: "secret-access-token",
  455. refresh: "secret-refresh-token",
  456. expires: Date.now() + 1000,
  457. },
  458. });
  459. expect(authStorage.getAuthStatus("anthropic")).toEqual({ configured: true, source: "stored" });
  460. expect(authStorage.getAuthStatus("openai")).toEqual({ configured: true, source: "stored" });
  461. expect(JSON.stringify(authStorage.getAuthStatus("anthropic"))).not.toContain("secret-api-key");
  462. expect(JSON.stringify(authStorage.getAuthStatus("openai"))).not.toContain("secret-access-token");
  463. expect(JSON.stringify(authStorage.getAuthStatus("openai"))).not.toContain("secret-refresh-token");
  464. });
  465. });
  466. describe("runtime overrides", () => {
  467. test("runtime override takes priority over auth.json", async () => {
  468. writeAuthJson({
  469. anthropic: { type: "api_key", key: "!echo stored-key" },
  470. });
  471. authStorage = AuthStorage.create(authJsonPath);
  472. authStorage.setRuntimeApiKey("anthropic", "runtime-key");
  473. const apiKey = await authStorage.getApiKey("anthropic");
  474. expect(apiKey).toBe("runtime-key");
  475. });
  476. test("removing runtime override falls back to auth.json", async () => {
  477. writeAuthJson({
  478. anthropic: { type: "api_key", key: "!echo stored-key" },
  479. });
  480. authStorage = AuthStorage.create(authJsonPath);
  481. authStorage.setRuntimeApiKey("anthropic", "runtime-key");
  482. authStorage.removeRuntimeApiKey("anthropic");
  483. const apiKey = await authStorage.getApiKey("anthropic");
  484. expect(apiKey).toBe("stored-key");
  485. });
  486. });
  487. });