sshConfigAlias.test.ts 9.2 KB

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