credential-key-failure-diagnostics.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
  5. import {
  6. createLegacyCredentialCipher,
  7. createSystemCredentialCipher,
  8. migrateCredentialRecord,
  9. observeCredentialKeyFailures,
  10. type CredentialKeyFailureDiagnostic,
  11. } from "@zcode/shared/credential-security";
  12. // 3.18.2 Windows 用户一直登录失败:Credential Manager 已满时 CredWrite 返回
  13. // ERROR_NOT_ENOUGH_MEMORY,但日志只有统一的“System credential storage is unavailable”,
  14. // 排查用了多轮用户侧探针。这里固定每个失败点的受控诊断。
  15. // 默认路径(不注入 KeyStore)才是 Desktop Main 实际走的路径;用 mock 替换原生模块。
  16. const VALID_KEY = Buffer.alloc(32, 7).toString("base64url");
  17. const backend = vi.hoisted(() => ({
  18. get: async (): Promise<string | null> => null,
  19. set: async (_value: string): Promise<void> => {},
  20. }));
  21. vi.mock("@napi-rs/keyring", () => ({
  22. AsyncEntry: class {
  23. getPassword() {
  24. return backend.get();
  25. }
  26. setPassword(value: string) {
  27. return backend.set(value);
  28. }
  29. },
  30. }));
  31. // 观察者是进程级的:本文件独立运行(vitest 按文件隔离),模拟 Desktop Main 启动时注册。
  32. const failures: CredentialKeyFailureDiagnostic[] = [];
  33. let registered = false;
  34. beforeAll(() => {
  35. registered = observeCredentialKeyFailures((diagnostic) => failures.push(diagnostic));
  36. });
  37. const dirs: string[] = [];
  38. beforeEach(() => {
  39. failures.length = 0;
  40. backend.get = async () => null;
  41. backend.set = async () => {};
  42. });
  43. afterEach(async () => {
  44. await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
  45. });
  46. async function credentialFile(content?: string) {
  47. const dir = await mkdtemp(join(tmpdir(), "zcode-credential-diagnostics-"));
  48. dirs.push(dir);
  49. const file = join(dir, "credentials.json");
  50. if (content !== undefined) await writeFile(file, content);
  51. return file;
  52. }
  53. // keyring-core 对 Windows 平台错误的固定格式(windows-native-keyring-store PlatformError)。
  54. const windowsWriteFailure = () =>
  55. new Error("Platform failure: Windows error code 8") as Error & { code?: string };
  56. const failureOf = (promise: Promise<unknown>) =>
  57. promise.then(
  58. () => {
  59. throw new Error("expected credential storage failure");
  60. },
  61. (error: { code?: string; diagnostic?: unknown; message?: string }) => error,
  62. );
  63. describe("system credential key failure diagnostics", () => {
  64. it("registers the process observer once", () => {
  65. expect(registered).toBe(true);
  66. expect(observeCredentialKeyFailures(() => {})).toBe(false);
  67. });
  68. it("reports a Credential Manager write failure with the Windows error number", async () => {
  69. // 与事故相同:3.17.2 留下 v1 凭据,升级后首次迁移需要创建系统密钥。
  70. const v1 = createLegacyCredentialCipher({}).encrypt("legacy-login");
  71. const file = await credentialFile(JSON.stringify({ zcodejwttoken: v1 }));
  72. backend.set = async () => {
  73. throw windowsWriteFailure();
  74. };
  75. const cipher = createSystemCredentialCipher({ filePath: file, env: {} });
  76. const error = await failureOf(migrateCredentialRecord({ zcodejwttoken: v1 }, cipher));
  77. expect(error.code).toBe("CREDENTIAL_SECURE_STORAGE_UNAVAILABLE");
  78. expect(error.diagnostic).toEqual({ stage: "create", osCode: 8 });
  79. expect(failures).toEqual([{ stage: "create", osCode: 8 }]);
  80. // 失败按进程缓存:后续请求不再访问系统库,也不重复通知。
  81. await failureOf(cipher.encrypt("next"));
  82. await failureOf(createSystemCredentialCipher({ filePath: file, env: {} }).encrypt("other"));
  83. expect(failures).toHaveLength(1);
  84. });
  85. it("distinguishes read, read-back and malformed entries", async () => {
  86. backend.get = async () => {
  87. throw new Error("Couldn't access platform storage: Windows ERROR_NO_SUCH_LOGON_SESSION");
  88. };
  89. const read = await failureOf(
  90. createSystemCredentialCipher({ filePath: await credentialFile(), env: {} }).encrypt("x"),
  91. );
  92. expect(read.diagnostic).toEqual({ stage: "read", osCode: 1312 });
  93. let stored: string | null = null;
  94. backend.get = async () => (stored === null ? null : "different-value");
  95. backend.set = async (value) => {
  96. stored = value;
  97. };
  98. const verify = await failureOf(
  99. createSystemCredentialCipher({ filePath: await credentialFile(), env: {} }).encrypt("x"),
  100. );
  101. expect(verify.diagnostic).toEqual({ stage: "verify" });
  102. backend.get = async () => "not-a-valid-key";
  103. const invalid = await failureOf(
  104. createSystemCredentialCipher({ filePath: await credentialFile(), env: {} }).encrypt("x"),
  105. );
  106. expect(invalid.diagnostic).toEqual({ stage: "invalid" });
  107. expect(failures.map((failure) => failure.stage)).toEqual(["read", "verify", "invalid"]);
  108. });
  109. it("reports a missing key for an os-bound directory without creating a replacement", async () => {
  110. const file = await credentialFile("{}\n");
  111. await writeFile(join(file, "..", "credential-source"), "os\n");
  112. let writes = 0;
  113. backend.set = async () => {
  114. writes++;
  115. };
  116. const error = await failureOf(
  117. createSystemCredentialCipher({ filePath: file, env: {} }).encrypt("x"),
  118. );
  119. expect(error.diagnostic).toEqual({ stage: "missing" });
  120. expect(writes).toBe(0);
  121. });
  122. it("reports an unknown source marker and an unreadable credential file", async () => {
  123. const marked = await credentialFile("{}\n");
  124. await writeFile(join(marked, "..", "credential-source"), "unknown\n");
  125. const source = await failureOf(
  126. createSystemCredentialCipher({ filePath: marked, env: {} }).encrypt("x"),
  127. );
  128. expect(source.diagnostic).toEqual({ stage: "source" });
  129. // 凭据文件位置被同名目录占用:读取得到 EISDIR,属于文件层错误而不是系统库错误。
  130. const occupied = await credentialFile();
  131. await mkdir(occupied);
  132. const file = await failureOf(
  133. createSystemCredentialCipher({ filePath: occupied, env: {} }).encrypt("x"),
  134. );
  135. expect(file.diagnostic).toEqual({ stage: "file", errorCode: "EISDIR" });
  136. });
  137. it("reports conflicting explicit configuration once per cipher", async () => {
  138. const cipher = createSystemCredentialCipher({
  139. filePath: await credentialFile(),
  140. env: {
  141. ZCODE_CREDENTIAL_SECRET: "explicit-secret-0123456789-0123456789",
  142. ZCODE_CREDENTIAL_SECRET_FILE: "credential-secret-file",
  143. },
  144. });
  145. expect((await failureOf(cipher.encrypt("x"))).diagnostic).toEqual({ stage: "config" });
  146. await failureOf(cipher.encrypt("y"));
  147. expect(failures).toEqual([{ stage: "config" }]);
  148. });
  149. it("never exposes key material, paths or native error text in diagnostics", async () => {
  150. const file = await credentialFile();
  151. // 原生错误正文与错误码字段都混入密钥和路径;诊断只能保留固定格式的数字错误号。
  152. backend.get = async () => {
  153. throw Object.assign(new Error(`os error 5 at ${file} key=${VALID_KEY}`), {
  154. code: `${VALID_KEY}`,
  155. });
  156. };
  157. const error = await failureOf(
  158. createSystemCredentialCipher({ filePath: file, env: {} }).encrypt("x"),
  159. );
  160. expect(error.diagnostic).toEqual({ stage: "read", osCode: 5 });
  161. const serialized = JSON.stringify(failures) + JSON.stringify(error.diagnostic) + error.message;
  162. expect(serialized).not.toContain(VALID_KEY);
  163. expect(serialized).not.toContain(file);
  164. });
  165. it("does not notify when the key loads and keeps the success path unchanged", async () => {
  166. const file = await credentialFile();
  167. backend.get = async () => VALID_KEY;
  168. const cipher = createSystemCredentialCipher({ filePath: file, env: {} });
  169. expect(await cipher.decrypt(await cipher.encrypt("ok"))).toBe("ok");
  170. expect(await readFile(join(file, "..", "credential-source"), "utf8")).toBe("os\n");
  171. expect(failures).toEqual([]);
  172. });
  173. it("isolates observer exceptions from the credential result", async () => {
  174. // 观察者已注册为本文件的 collector;用会抛错的 get 验证错误仍是受控存储错误。
  175. backend.get = async () => {
  176. throw new Error("Platform failure: Windows error code 1312");
  177. };
  178. const original = failures.push.bind(failures);
  179. failures.push = () => {
  180. throw new Error("observer failed");
  181. };
  182. try {
  183. const error = await failureOf(
  184. createSystemCredentialCipher({ filePath: await credentialFile(), env: {} }).encrypt("x"),
  185. );
  186. expect(error.code).toBe("CREDENTIAL_SECURE_STORAGE_UNAVAILABLE");
  187. expect(error.diagnostic).toEqual({ stage: "read", osCode: 1312 });
  188. } finally {
  189. failures.push = original;
  190. }
  191. });
  192. });