credential-access-lifecycle.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. createSystemCredentialCipher,
  7. createCredentialCipherBridge,
  8. executeCredentialCipherRequest,
  9. } from "@zcode/shared/credential-security";
  10. import {
  11. credentialCipherRequestSchema,
  12. credentialCipherReplySchema,
  13. isCredentialDecryptError,
  14. type CredentialCipherRequest,
  15. } from "@zcode/shared";
  16. import { createSharedZCodeCredentialStore } from "../src/auth/shared-credentials.js";
  17. const backend = vi.hoisted(() => ({ reads: 0, fail: false }));
  18. vi.mock("@napi-rs/keyring", () => ({
  19. AsyncEntry: class {
  20. async getPassword() {
  21. backend.reads++;
  22. if (backend.fail) throw new Error("synthetic access denied");
  23. return Buffer.alloc(32, 7).toString("base64url");
  24. }
  25. },
  26. }));
  27. const dirs: string[] = [];
  28. beforeEach(() => {
  29. backend.reads = 0;
  30. backend.fail = false;
  31. });
  32. afterEach(async () => {
  33. await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  34. });
  35. async function fixture() {
  36. const dir = await mkdtemp(join(tmpdir(), "credential-access-lifecycle-"));
  37. dirs.push(dir);
  38. const filePath = join(dir, "credentials.json");
  39. const cipher = createSystemCredentialCipher({
  40. filePath,
  41. env: {},
  42. keyStore: {
  43. get: async () => Buffer.alloc(32, 7).toString("base64url"),
  44. set: async () => {
  45. throw new Error("unexpected synthetic key write");
  46. },
  47. },
  48. });
  49. const value = await cipher.encrypt("first-token");
  50. await writeFile(filePath, JSON.stringify({ zcodejwttoken: value }));
  51. return { filePath, cipher, value };
  52. }
  53. describe("system credential access lifecycle", () => {
  54. it("roundtrips the exact UTF-8 boundary for ASCII and multibyte plaintext", async () => {
  55. const { cipher } = await fixture();
  56. for (const value of ["a".repeat(1048576), "界".repeat(349525), "😀".repeat(262144)]) {
  57. const encrypted = await executeCredentialCipherRequest(cipher, {
  58. requestId: "7a648738-5de1-4b7d-a26e-2b6e6d91d174",
  59. operation: "encrypt",
  60. value,
  61. });
  62. expect(credentialCipherReplySchema.safeParse(encrypted).success).toBe(true);
  63. if (!encrypted.result.ok) throw new Error("Expected successful boundary encryption");
  64. const decrypted = await executeCredentialCipherRequest(cipher, {
  65. requestId: "7a648738-5de1-4b7d-a26e-2b6e6d91d174",
  66. operation: "decrypt",
  67. value: encrypted.result.value,
  68. });
  69. expect(decrypted.result).toEqual({ ok: true, value });
  70. }
  71. });
  72. it("migrates a large legacy value through the real bridge and releases its lock", async () => {
  73. const { filePath, cipher } = await fixture();
  74. const bridge = createCredentialCipherBridge((request) => {
  75. void executeCredentialCipherRequest(cipher, request).then((reply) => {
  76. // 与 Host 的接收路径相同;超限回复不能被静默丢弃后挂起迁移。
  77. if (credentialCipherReplySchema.safeParse(reply).success) bridge.receive(reply);
  78. });
  79. });
  80. try {
  81. const value = "a".repeat(800000);
  82. await writeFile(filePath, JSON.stringify({ profile: value }));
  83. const store = createSharedZCodeCredentialStore({ filePath, cipher: bridge.cipher });
  84. expect(await store.load("profile")).toBe(value);
  85. await store.save("later", "still-available");
  86. expect(await store.load("later")).toBe("still-available");
  87. } finally {
  88. bridge.dispose();
  89. }
  90. });
  91. it("rejects a malformed correlated reply and releases the migration lock", async () => {
  92. const { filePath } = await fixture();
  93. const bridge = createCredentialCipherBridge((request) => {
  94. bridge.receive({ requestId: request.requestId, result: { ok: true, value: 42 } } as never);
  95. });
  96. try {
  97. await writeFile(filePath, JSON.stringify({ profile: "legacy" }));
  98. const store = createSharedZCodeCredentialStore({ filePath, cipher: bridge.cipher });
  99. await expect(store.load("profile")).rejects.toHaveProperty(
  100. "code",
  101. "CREDENTIAL_CIPHER_INVALID_PAYLOAD",
  102. );
  103. await expect(store.load("profile")).rejects.toHaveProperty(
  104. "code",
  105. "CREDENTIAL_CIPHER_INVALID_PAYLOAD",
  106. );
  107. } finally {
  108. bridge.dispose();
  109. }
  110. });
  111. it("rejects oversized output with a valid error and bounds UTF-8 input", async () => {
  112. const request = {
  113. requestId: "7a648738-5de1-4b7d-a26e-2b6e6d91d174",
  114. operation: "encrypt" as const,
  115. value: "valid",
  116. };
  117. const reply = await executeCredentialCipherRequest(
  118. { encrypt: () => "a".repeat(2_000_000), decrypt: () => "" },
  119. request,
  120. );
  121. expect(credentialCipherReplySchema.safeParse(reply).success).toBe(true);
  122. expect(reply.result.ok).toBe(false);
  123. expect(
  124. credentialCipherRequestSchema.safeParse({ ...request, value: "界".repeat(400000) }).success,
  125. ).toBe(false);
  126. expect(
  127. credentialCipherRequestSchema.safeParse({ ...request, value: "a".repeat(1048576) }).success,
  128. ).toBe(true);
  129. expect(
  130. credentialCipherRequestSchema.safeParse({ ...request, value: "a".repeat(1048577) }).success,
  131. ).toBe(false);
  132. expect(
  133. credentialCipherRequestSchema.safeParse({ ...request, value: "界".repeat(349525) }).success,
  134. ).toBe(true);
  135. expect(
  136. credentialCipherRequestSchema.safeParse({ ...request, value: "😀".repeat(262144) }).success,
  137. ).toBe(true);
  138. expect(
  139. credentialCipherRequestSchema.safeParse({ ...request, value: "😀".repeat(262145) }).success,
  140. ).toBe(false);
  141. });
  142. it("correlates delegated crypto replies and rejects pending work on disconnect", async () => {
  143. const sent: CredentialCipherRequest[] = [];
  144. const bridge = createCredentialCipherBridge((request) => sent.push(request));
  145. const first = bridge.cipher.encrypt("first");
  146. const second = bridge.cipher.decrypt("second");
  147. bridge.receive({ requestId: sent[1]!.requestId, result: { ok: true, value: "decoded" } });
  148. bridge.receive({ requestId: sent[0]!.requestId, result: { ok: true, value: "encoded" } });
  149. expect(await first).toBe("encoded");
  150. expect(await second).toBe("decoded");
  151. const interrupted = bridge.cipher.decrypt("pending");
  152. const rejection = expect(interrupted).rejects.toThrow("closed");
  153. bridge.dispose();
  154. await rejection;
  155. bridge.receive({ requestId: sent[2]!.requestId, result: { ok: true, value: "late" } });
  156. await expect(bridge.cipher.encrypt("closed")).rejects.toThrow("closed");
  157. expect(sent).toHaveLength(3);
  158. });
  159. it("limits the delegated API and preserves error classification without native details", async () => {
  160. const request = {
  161. requestId: "7a648738-5de1-4b7d-a26e-2b6e6d91d174",
  162. operation: "decrypt" as const,
  163. value: "invalid",
  164. };
  165. expect(
  166. credentialCipherRequestSchema.safeParse({ ...request, filePath: "/another-account" }).success,
  167. ).toBe(false);
  168. const result = await executeCredentialCipherRequest(
  169. {
  170. encrypt: () => "",
  171. decrypt: () => {
  172. throw Object.assign(new Error("private native detail"), {
  173. code: "ZCODE_CREDENTIAL_DECRYPT_FAILED",
  174. });
  175. },
  176. },
  177. request,
  178. );
  179. expect(result.result.ok).toBe(false);
  180. if (result.result.ok) throw new Error("Expected failure");
  181. expect(result.result.error.message).not.toContain("private native detail");
  182. expect(
  183. isCredentialDecryptError(
  184. Object.assign(new Error(result.result.error.message), { code: result.result.error.code }),
  185. ),
  186. ).toBe(true);
  187. });
  188. it("shares one system lookup across sequential and concurrent default cipher instances", async () => {
  189. const { filePath, value } = await fixture();
  190. for (let i = 0; i < 3; i++) {
  191. const cipher = createSystemCredentialCipher({ filePath, env: {} });
  192. expect(await cipher.decrypt(value)).toBe("first-token");
  193. }
  194. await Promise.all(
  195. Array.from({ length: 8 }, () =>
  196. createSystemCredentialCipher({ filePath, env: {} }).decrypt(value),
  197. ),
  198. );
  199. expect(backend.reads).toBe(1);
  200. });
  201. it("uses the canonical path to share access and keeps different directories isolated", async () => {
  202. const first = await fixture();
  203. const second = await fixture();
  204. const alias = join(first.filePath, "..", "credentials.json");
  205. await createSystemCredentialCipher({ filePath: first.filePath, env: {} }).decrypt(first.value);
  206. await createSystemCredentialCipher({ filePath: alias, env: {} }).decrypt(first.value);
  207. await createSystemCredentialCipher({ filePath: second.filePath, env: {} }).decrypt(
  208. second.value,
  209. );
  210. expect(backend.reads).toBe(2);
  211. });
  212. it("retains denied access across instances without retrying or clearing credential data", async () => {
  213. const { filePath, value } = await fixture();
  214. backend.fail = true;
  215. for (let i = 0; i < 3; i++) {
  216. const store = createSharedZCodeCredentialStore({ filePath, env: {} });
  217. await expect(store.load("zcodejwttoken")).rejects.toHaveProperty(
  218. "code",
  219. "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE",
  220. );
  221. }
  222. backend.fail = false;
  223. await expect(
  224. createSystemCredentialCipher({ filePath, env: {} }).decrypt(value),
  225. ).rejects.toHaveProperty("code", "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE");
  226. expect(backend.reads).toBe(1);
  227. const { readFile } = await import("node:fs/promises");
  228. expect(JSON.parse(await readFile(filePath, "utf8")).zcodejwttoken).toBe(value);
  229. });
  230. it("reads current tokens from disk while reusing only the system key", async () => {
  231. const { filePath, cipher } = await fixture();
  232. const first = createSharedZCodeCredentialStore({ filePath, env: {} });
  233. expect(await first.load("zcodejwttoken")).toBe("first-token");
  234. await writeFile(
  235. filePath,
  236. JSON.stringify({ zcodejwttoken: await cipher.encrypt("replacement-token") }),
  237. );
  238. const second = createSharedZCodeCredentialStore({ filePath, env: {} });
  239. expect(await second.load("zcodejwttoken")).toBe("replacement-token");
  240. expect(backend.reads).toBe(1);
  241. });
  242. it("shares an injected adapter within its scope without poisoning another adapter", async () => {
  243. const { filePath, value } = await fixture();
  244. let reads = 0;
  245. const denied = {
  246. get: async (): Promise<string | null> => {
  247. reads++;
  248. throw new Error("synthetic access denied");
  249. },
  250. set: async () => {},
  251. };
  252. for (let i = 0; i < 2; i++) {
  253. await expect(
  254. createSystemCredentialCipher({ filePath, env: {}, keyStore: denied }).decrypt(value),
  255. ).rejects.toHaveProperty("code", "CREDENTIAL_SECURE_STORAGE_UNAVAILABLE");
  256. }
  257. expect(reads).toBe(1);
  258. const available = {
  259. get: async () => Buffer.alloc(32, 7).toString("base64url"),
  260. set: async () => {},
  261. };
  262. expect(
  263. await createSystemCredentialCipher({ filePath, env: {}, keyStore: available }).decrypt(value),
  264. ).toBe("first-token");
  265. });
  266. });