sshConfigAlias.test.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import { chmod, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { tmpdir } from "node:os";
  4. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  5. const originalHome = process.env["HOME"];
  6. const originalPath = process.env["PATH"];
  7. const tempDirs: string[] = [];
  8. beforeEach(() => {
  9. vi.resetModules();
  10. });
  11. afterEach(async () => {
  12. if (originalHome == null) {
  13. delete process.env["HOME"];
  14. } else {
  15. process.env["HOME"] = originalHome;
  16. }
  17. if (originalPath == null) {
  18. delete process.env["PATH"];
  19. } else {
  20. process.env["PATH"] = originalPath;
  21. }
  22. while (tempDirs.length > 0) {
  23. const dir = tempDirs.pop();
  24. if (dir) {
  25. await rm(dir, { recursive: true, force: true });
  26. }
  27. }
  28. });
  29. async function createTempHome(): Promise<string> {
  30. const homeDir = await mkdtemp(join(tmpdir(), "zcode-ssh-alias-test-"));
  31. tempDirs.push(homeDir);
  32. await mkdir(join(homeDir, ".ssh"), { recursive: true });
  33. return homeDir;
  34. }
  35. async function createFakeSshExecutable(homeDir: string, lines: string[]): Promise<string> {
  36. const binDir = join(homeDir, "bin");
  37. await mkdir(binDir, { recursive: true });
  38. const sshPath = join(binDir, "ssh");
  39. const output = lines.join("\n");
  40. await writeFile(
  41. sshPath,
  42. ["#!/bin/sh", "cat <<'EOF'", output, "EOF", "exit 0", ""].join("\n"),
  43. "utf8",
  44. );
  45. await chmod(sshPath, 0o755);
  46. return binDir;
  47. }
  48. async function loadAliasParser() {
  49. const { listSSHConfigAliasesFromLocalConfig } = await import("@zcode/services/node");
  50. return listSSHConfigAliasesFromLocalConfig;
  51. }
  52. describe("sshConfigAlias fallback parser", () => {
  53. // Bugfix: pre-push 全量测试并发执行时,动态导入 services/node 会受整体负载影响。
  54. // 旧的 5s 预算在本地单测能过,但全量 hook 中偶发超时;这里放宽到和 Windows 一致,
  55. // 让用例仍然捕获真正挂起的问题,同时避免环境负载导致误失败。
  56. const testTimeout = 15000;
  57. it(
  58. "读取单个 alias 并映射到连接表单字段",
  59. async () => {
  60. const homeDir = await createTempHome();
  61. process.env["HOME"] = homeDir;
  62. process.env["PATH"] = "";
  63. const configPath = join(homeDir, ".ssh", "config");
  64. await writeFile(
  65. configPath,
  66. [
  67. "Host dev",
  68. " HostName dev.internal",
  69. " User root",
  70. " Port 2222",
  71. " IdentityFile ~/.ssh/id_ed25519",
  72. "",
  73. ].join("\n"),
  74. "utf8",
  75. );
  76. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  77. const aliases = await listSSHConfigAliasesFromLocalConfig();
  78. expect(aliases).toHaveLength(1);
  79. expect(aliases[0]).toMatchObject({
  80. alias: "dev",
  81. host: "dev.internal",
  82. username: "root",
  83. port: 2222,
  84. source: configPath,
  85. });
  86. expect(aliases[0]?.privateKeyPath).toBe(join(homeDir, ".ssh", "id_ed25519"));
  87. },
  88. testTimeout,
  89. );
  90. it(
  91. "支持 Include 并过滤不可直接连接的 pattern",
  92. async () => {
  93. const homeDir = await createTempHome();
  94. process.env["HOME"] = homeDir;
  95. process.env["PATH"] = "";
  96. const includeDir = join(homeDir, ".ssh", "includes");
  97. await mkdir(includeDir, { recursive: true });
  98. await writeFile(
  99. join(includeDir, "aliases.conf"),
  100. [
  101. "Host dev",
  102. " HostName dev.example.com",
  103. " Port 2201",
  104. "Host multi one",
  105. " HostName invalid.example.com",
  106. "",
  107. ].join("\n"),
  108. "utf8",
  109. );
  110. await writeFile(
  111. join(homeDir, ".ssh", "config"),
  112. [
  113. "Include includes/*.conf",
  114. "Host *",
  115. " User default-user",
  116. "Host skip-*",
  117. " HostName wildcard.example.com",
  118. "Host prod",
  119. " HostName prod.example.com",
  120. "",
  121. ].join("\n"),
  122. "utf8",
  123. );
  124. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  125. const aliases = await listSSHConfigAliasesFromLocalConfig();
  126. const aliasNames = aliases.map((item) => item.alias);
  127. expect(aliasNames).toEqual(["dev", "prod"]);
  128. expect(aliases[0]).toMatchObject({
  129. alias: "dev",
  130. host: "dev.example.com",
  131. port: 2201,
  132. username: "default-user",
  133. source: join(includeDir, "aliases.conf"),
  134. });
  135. expect(aliases[1]).toMatchObject({
  136. alias: "prod",
  137. host: "prod.example.com",
  138. username: "default-user",
  139. source: join(homeDir, ".ssh", "config"),
  140. });
  141. },
  142. testTimeout,
  143. );
  144. it(
  145. "Teleport 通配符 Host 块不会阻断普通 alias 枚举",
  146. async () => {
  147. const homeDir = await createTempHome();
  148. process.env["HOME"] = homeDir;
  149. process.env["PATH"] = "";
  150. const configPath = join(homeDir, ".ssh", "config");
  151. await writeFile(
  152. configPath,
  153. [
  154. "Host *.teleport-*.example.com",
  155. " User root",
  156. " UserKnownHostsFile /dev/null",
  157. "",
  158. "Host *.teleport-bj03.example.com !teleport.example.net",
  159. " Port 3022",
  160. " ProxyCommand /usr/local/bin/tsh proxy ssh --cluster=teleport-bj03.example.com %r@%h:%p",
  161. "",
  162. "Host jump-120",
  163. " HostName 172.16.0.11",
  164. " User root",
  165. "",
  166. "Host ncu",
  167. " HostName 10.0.0.103",
  168. " User root",
  169. " ProxyJump jump-120",
  170. "",
  171. ].join("\n"),
  172. "utf8",
  173. );
  174. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  175. const aliases = await listSSHConfigAliasesFromLocalConfig();
  176. expect(aliases.map((item) => item.alias)).toEqual(["jump-120", "ncu"]);
  177. expect(aliases[1]).toMatchObject({
  178. alias: "ncu",
  179. host: "10.0.0.103",
  180. username: "root",
  181. source: configPath,
  182. });
  183. },
  184. testTimeout,
  185. );
  186. // Unix shell 脚本在 Windows 上无法执行(chmod 不生效,ssh 命令不可用),直接跳过
  187. if (process.platform === "win32") {
  188. return;
  189. }
  190. it("当 ssh -G 只返回默认 identityfile 时不误判为密钥登录", async () => {
  191. const homeDir = await createTempHome();
  192. process.env["HOME"] = homeDir;
  193. const configPath = join(homeDir, ".ssh", "config");
  194. await writeFile(
  195. configPath,
  196. [
  197. "Host password-host",
  198. " HostName password.example.com",
  199. " User root",
  200. " Port 22",
  201. "",
  202. ].join("\n"),
  203. "utf8",
  204. );
  205. const fakeSshPath = await createFakeSshExecutable(homeDir, [
  206. "hostname password.example.com",
  207. "port 22",
  208. "user root",
  209. "identityfile ~/.ssh/id_rsa",
  210. ]);
  211. process.env["PATH"] = fakeSshPath;
  212. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  213. const aliases = await listSSHConfigAliasesFromLocalConfig();
  214. expect(aliases).toHaveLength(1);
  215. expect(aliases[0]).toMatchObject({
  216. alias: "password-host",
  217. host: "password.example.com",
  218. username: "root",
  219. port: 22,
  220. source: configPath,
  221. });
  222. expect(aliases[0]?.privateKeyPath).toBeUndefined();
  223. });
  224. it(
  225. "保留 Windows 风格私钥路径中的反斜杠",
  226. async () => {
  227. const homeDir = await createTempHome();
  228. process.env["HOME"] = homeDir;
  229. process.env["PATH"] = "";
  230. const configPath = join(homeDir, ".ssh", "config");
  231. const windowsPrivateKeyPath = "C:\\Users\\alice\\.ssh\\id_ed25519";
  232. await writeFile(
  233. configPath,
  234. [
  235. "Host windows-host",
  236. " HostName windows.example.com",
  237. " User root",
  238. ` IdentityFile ${windowsPrivateKeyPath}`,
  239. "",
  240. ].join("\n"),
  241. "utf8",
  242. );
  243. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  244. const aliases = await listSSHConfigAliasesFromLocalConfig();
  245. expect(aliases).toHaveLength(1);
  246. expect(aliases[0]).toMatchObject({
  247. alias: "windows-host",
  248. host: "windows.example.com",
  249. username: "root",
  250. source: configPath,
  251. });
  252. expect(aliases[0]?.privateKeyPath).toBe(windowsPrivateKeyPath);
  253. },
  254. testTimeout,
  255. );
  256. it(
  257. "支持包含反斜杠的 Include 直路径",
  258. async () => {
  259. const homeDir = await createTempHome();
  260. process.env["HOME"] = homeDir;
  261. process.env["PATH"] = "";
  262. const includeToken = "includes\\alias.conf";
  263. const includeFilePath = join(homeDir, ".ssh", includeToken);
  264. if (process.platform === "win32") {
  265. await mkdir(join(homeDir, ".ssh", "includes"), { recursive: true });
  266. }
  267. await writeFile(
  268. includeFilePath,
  269. [
  270. "Host backslash-include",
  271. " HostName include.example.com",
  272. " User include-user",
  273. "",
  274. ].join("\n"),
  275. "utf8",
  276. );
  277. const rootConfigPath = join(homeDir, ".ssh", "config");
  278. await writeFile(rootConfigPath, [`Include ${includeToken}`, ""].join("\n"), "utf8");
  279. const listSSHConfigAliasesFromLocalConfig = await loadAliasParser();
  280. const aliases = await listSSHConfigAliasesFromLocalConfig();
  281. expect(aliases).toHaveLength(1);
  282. expect(aliases[0]).toMatchObject({
  283. alias: "backslash-include",
  284. host: "include.example.com",
  285. username: "include-user",
  286. source: includeFilePath,
  287. });
  288. },
  289. testTimeout,
  290. );
  291. });