返回 DeepSeek-Reasonix
sshconfig_test.go
根目录 / internal / remote / sshconfig_test.go
1 package remote
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "runtime"
10 "testing"
11
12 "reasonix/internal/config"
13 )
14
15 const sampleSSHConfig = `
16 Host gpu
17 HostName 203.0.113.9
18 User dev
19 Port 2222
20 IdentityFile ~/.ssh/gpu_ed25519
21
22 Host bastion-*
23 User jump
24
25 Host viajump
26 HostName 10.1.1.1
27 ProxyJump bastion-1
28
29 Match host somehost
30 User shouldbeignored
31 `
32
33 func writeSampleConfig(t *testing.T) string {
34 t.Helper()
35 p := filepath.Join(t.TempDir(), "config")
36 if err := os.WriteFile(p, []byte(sampleSSHConfig), 0o600); err != nil {
37 t.Fatal(err)
38 }
39 return p
40 }
41
42 func TestEffectiveSSHConfigUsesOpenSSHOutputAndKeepsAllIdentities(t *testing.T) {
43 src, err := LoadSSHConfig(writeSampleConfig(t))
44 if err != nil {
45 t.Fatal(err)
46 }
47 src.resolveOpenSSH = func(_ context.Context, path, alias string) ([]byte, error) {
48 if path != src.Path() || alias != "gpu" {
49 t.Fatalf("ssh -G request = path %q alias %q", path, alias)
50 }
51 return []byte("hostname resolved.example\nuser effective-user\nport 2207\nidentityfile ~/.ssh/first\nidentityfile ~/.ssh/second\nproxyjump jump-a,jump-b\nidentitiesonly yes\n"), nil
52 }
53
54 got := src.Effective("gpu")
55 if got.HostName != "resolved.example" || got.User != "effective-user" || got.Port != 2207 || got.ProxyJump != "jump-a,jump-b" || !got.IdentitiesOnly {
56 t.Fatalf("effective config = %+v", got)
57 }
58 home, err := os.UserHomeDir()
59 if err != nil {
60 t.Fatal(err)
61 }
62 wantIdentities := []string{filepath.Join(home, ".ssh", "first"), filepath.Join(home, ".ssh", "second")}
63 if len(got.IdentityFiles) != 2 || got.IdentityFiles[0] != wantIdentities[0] || got.IdentityFiles[1] != wantIdentities[1] {
64 t.Fatalf("identity files = %v", got.IdentityFiles)
65 }
66 }
67
68 func TestSSHConfigMatchExecUsesOpenSSHEvenWhenFallbackRejectsIt(t *testing.T) {
69 path := filepath.Join(t.TempDir(), "config")
70 contents := "Host matched-box\n HostName 192.0.2.10\nMatch exec \"true\"\n User matched-user\n"
71 if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
72 t.Fatal(err)
73 }
74 src, err := LoadSSHConfig(path)
75 if err != nil {
76 t.Fatalf("valid OpenSSH Match exec config was rejected: %v", err)
77 }
78 src.resolveOpenSSH = func(_ context.Context, gotPath, alias string) ([]byte, error) {
79 if gotPath != path || alias != "matched-box" {
80 t.Fatalf("ssh -G request = path %q alias %q", gotPath, alias)
81 }
82 return []byte("hostname 192.0.2.10\nuser matched-user\nport 22\nidentitiesonly no\n"), nil
83 }
84 aliases := src.Aliases()
85 if len(aliases) != 1 || aliases[0].Alias != "matched-box" {
86 t.Fatalf("Match exec aliases = %+v", aliases)
87 }
88 got, err := src.EffectiveWithError("matched-box")
89 if err != nil {
90 t.Fatal(err)
91 }
92 if got.User != "matched-user" {
93 t.Fatalf("Match exec effective config = %+v", got)
94 }
95 }
96
97 func TestSSHConfigMatchExecRealOpenSSH(t *testing.T) {
98 if runtime.GOOS == "windows" {
99 t.Skip("Match exec command is shell-dependent on Windows")
100 }
101 if _, err := exec.LookPath("ssh"); err != nil {
102 t.Skip("OpenSSH client is not installed")
103 }
104 path := filepath.Join(t.TempDir(), "config")
105 contents := "Host real-match-box\n HostName 192.0.2.11\nMatch exec \"true\"\n User real-match-user\n"
106 if err := os.WriteFile(path, []byte(contents), 0o600); err != nil {
107 t.Fatal(err)
108 }
109 src, err := LoadSSHConfig(path)
110 if err != nil {
111 t.Fatal(err)
112 }
113 got := src.Effective("real-match-box")
114 if got.HostName != "192.0.2.11" || got.User != "real-match-user" {
115 t.Fatalf("real ssh -G Match exec result = %+v", got)
116 }
117 }
118
119 func TestSSHConfigLookups(t *testing.T) {
120 src, err := LoadSSHConfig(writeSampleConfig(t))
121 if err != nil {
122 t.Fatal(err)
123 }
124 if got := src.HostName("gpu"); got != "203.0.113.9" {
125 t.Errorf("HostName(gpu) = %q", got)
126 }
127 if got := src.User("gpu"); got != "dev" {
128 t.Errorf("User(gpu) = %q", got)
129 }
130 if got := src.Port("gpu"); got != 2222 {
131 t.Errorf("Port(gpu) = %d", got)
132 }
133 if got := src.ProxyJump("viajump"); got != "bastion-1" {
134 t.Errorf("ProxyJump(viajump) = %q", got)
135 }
136 }
137
138 func TestSSHConfigAliasesSkipWildcards(t *testing.T) {
139 src, err := LoadSSHConfig(writeSampleConfig(t))
140 if err != nil {
141 t.Fatal(err)
142 }
143 aliases := src.Aliases()
144 names := map[string]bool{}
145 for _, a := range aliases {
146 names[a.Alias] = true
147 }
148 if !names["gpu"] || !names["viajump"] {
149 t.Fatalf("expected concrete aliases gpu/viajump, got %v", names)
150 }
151 if names["bastion-*"] {
152 t.Fatal("wildcard pattern surfaced as an importable alias")
153 }
154 }
155
156 func TestSSHConfigAliasesIncludeImportedFiles(t *testing.T) {
157 dir := t.TempDir()
158 included := filepath.Join(dir, "hosts.conf")
159 if err := os.WriteFile(included, []byte("Host included-box\n HostName 192.0.2.10\n"), 0o600); err != nil {
160 t.Fatal(err)
161 }
162 main := filepath.Join(dir, "config")
163 if err := os.WriteFile(main, []byte("Include "+included+"\nHost direct-box\n HostName 192.0.2.9\n"), 0o600); err != nil {
164 t.Fatal(err)
165 }
166 src, err := LoadSSHConfig(main)
167 if err != nil {
168 t.Fatal(err)
169 }
170 aliases := src.Aliases()
171 if len(aliases) != 2 || aliases[0].Alias != "included-box" || aliases[1].Alias != "direct-box" {
172 t.Fatalf("included aliases = %+v", aliases)
173 }
174 got, err := src.EffectiveWithError("included-box")
175 if err != nil {
176 t.Fatal(err)
177 }
178 if got.HostName != "192.0.2.10" {
179 t.Fatalf("included host was not resolved on demand: %+v", got)
180 }
181 }
182
183 func TestSSHAliasesDoNotResolveEveryHost(t *testing.T) {
184 src, err := LoadSSHConfig(writeSampleConfig(t))
185 if err != nil {
186 t.Fatal(err)
187 }
188 calls := 0
189 src.resolveOpenSSH = func(context.Context, string, string) ([]byte, error) {
190 calls++
191 return nil, nil
192 }
193 if got := src.Aliases(); len(got) != 2 {
194 t.Fatalf("aliases = %+v", got)
195 }
196 if calls != 0 {
197 t.Fatalf("alias discovery invoked ssh -G %d times", calls)
198 }
199 }
200
201 func TestEffectiveSSHConfigPreservesIdentityFileNone(t *testing.T) {
202 src, err := LoadSSHConfig(writeSampleConfig(t))
203 if err != nil {
204 t.Fatal(err)
205 }
206 src.resolveOpenSSH = func(context.Context, string, string) ([]byte, error) {
207 return []byte("hostname host.test\nidentityfile none\nidentityfile ~/.ssh/explicit\n"), nil
208 }
209 got, err := src.EffectiveWithError("gpu")
210 if err != nil {
211 t.Fatal(err)
212 }
213 if !got.IdentityFileNone || len(got.IdentityFiles) != 1 || filepath.Base(got.IdentityFiles[0]) != "explicit" {
214 t.Fatalf("identity settings = %+v", got)
215 }
216 }
217
218 func TestEmbeddedSSHConfigPreservesIdentityFileNone(t *testing.T) {
219 path := filepath.Join(t.TempDir(), "config")
220 if err := os.WriteFile(path, []byte("Host none-box\n IdentityFile none\n IdentitiesOnly yes\n"), 0o600); err != nil {
221 t.Fatal(err)
222 }
223 src, err := LoadSSHConfig(path)
224 if err != nil {
225 t.Fatal(err)
226 }
227 src.resolveOpenSSH = nil
228 got, err := src.EffectiveWithError("none-box")
229 if err != nil {
230 t.Fatal(err)
231 }
232 if !got.IdentityFileNone || len(got.IdentityFiles) != 0 || !got.IdentitiesOnly {
233 t.Fatalf("embedded identity settings = %+v", got)
234 }
235 }
236
237 func TestEffectiveSSHConfigPropagatesInstalledOpenSSHErrors(t *testing.T) {
238 src, err := LoadSSHConfig(writeSampleConfig(t))
239 if err != nil {
240 t.Fatal(err)
241 }
242 want := context.DeadlineExceeded
243 src.resolveOpenSSH = func(context.Context, string, string) ([]byte, error) { return nil, want }
244 if _, err := src.EffectiveWithError("gpu"); !errors.Is(err, want) {
245 t.Fatalf("EffectiveWithError error = %v, want %v", err, want)
246 }
247 }
248
249 func TestResolveHostPropagatesInstalledOpenSSHErrors(t *testing.T) {
250 src, err := LoadSSHConfig(writeSampleConfig(t))
251 if err != nil {
252 t.Fatal(err)
253 }
254 want := context.DeadlineExceeded
255 src.resolveOpenSSH = func(context.Context, string, string) ([]byte, error) { return nil, want }
256 cfg := config.Default()
257 if err := cfg.UpsertRemoteHost(config.RemoteHostEntry{Name: "gpu", Host: "gpu", UseSSHConfig: true}); err != nil {
258 t.Fatal(err)
259 }
260 if _, err := ResolveHost(cfg, "gpu", src); !errors.Is(err, want) {
261 t.Fatalf("ResolveHost error = %v, want %v", err, want)
262 }
263 }
264
265 func TestEffectiveSSHConfigFallsBackOnlyWhenOpenSSHUnavailable(t *testing.T) {
266 src, err := LoadSSHConfig(writeSampleConfig(t))
267 if err != nil {
268 t.Fatal(err)
269 }
270 src.resolveOpenSSH = func(context.Context, string, string) ([]byte, error) { return nil, exec.ErrNotFound }
271 got, err := src.EffectiveWithError("gpu")
272 if err != nil {
273 t.Fatal(err)
274 }
275 if got.HostName != "203.0.113.9" || got.User != "dev" {
276 t.Fatalf("embedded fallback = %+v", got)
277 }
278 }
279
280 func TestMissingOpenSSHExecutableIsDetectable(t *testing.T) {
281 t.Setenv("PATH", t.TempDir())
282 _, err := runOpenSSHEffectiveConfig(context.Background(), "", "missing-ssh-box")
283 if !errors.Is(err, exec.ErrNotFound) {
284 t.Fatalf("missing ssh error = %v, want exec.ErrNotFound", err)
285 }
286 }
287
288 func TestLoadUserSSHConfigUsesNormalOpenSSHConfigStack(t *testing.T) {
289 home := t.TempDir()
290 t.Setenv("HOME", home)
291 if runtime.GOOS == "windows" {
292 t.Setenv("USERPROFILE", home)
293 }
294 sshDir := filepath.Join(home, ".ssh")
295 if err := os.MkdirAll(sshDir, 0o700); err != nil {
296 t.Fatal(err)
297 }
298 if err := os.WriteFile(filepath.Join(sshDir, "config"), []byte("Host user-box\n HostName 192.0.2.55\n"), 0o600); err != nil {
299 t.Fatal(err)
300 }
301 src, err := LoadUserSSHConfig()
302 if err != nil {
303 t.Fatal(err)
304 }
305 src.resolveOpenSSH = func(_ context.Context, path, alias string) ([]byte, error) {
306 if path != "" || alias != "user-box" {
307 t.Fatalf("normal ssh -G request = path %q alias %q", path, alias)
308 }
309 return []byte("hostname 192.0.2.55\n"), nil
310 }
311 if _, err := src.EffectiveWithError("user-box"); err != nil {
312 t.Fatal(err)
313 }
314 }
315
316 func TestSSHConfigMissingFileIsEmpty(t *testing.T) {
317 src, err := LoadSSHConfig(filepath.Join(t.TempDir(), "does-not-exist"))
318 if err != nil {
319 t.Fatalf("missing file should not error: %v", err)
320 }
321 if len(src.Aliases()) != 0 {
322 t.Fatal("missing file yielded aliases")
323 }
324 if src.HostName("anything") != "" {
325 t.Fatal("missing file returned a hostname")
326 }
327 }
328
329 // TestResolveHostLayersSSHConfig checks the precedence: an explicit TOML field
330 // wins, but unset fields fall through to ~/.ssh/config when use_ssh_config.
331 func TestResolveHostLayersSSHConfig(t *testing.T) {
332 src, err := LoadSSHConfig(writeSampleConfig(t))
333 if err != nil {
334 t.Fatal(err)
335 }
336 cfg := config.Default()
337 if err := cfg.UpsertRemoteHost(config.RemoteHostEntry{
338 Name: "gpu",
339 Host: "gpu", // alias; ssh_config supplies the real HostName
340 User: "override",
341 UseSSHConfig: true,
342 }); err != nil {
343 t.Fatal(err)
344 }
345 h, err := ResolveHost(cfg, "gpu", src)
346 if err != nil {
347 t.Fatal(err)
348 }
349 if h.HostName != "203.0.113.9" {
350 t.Errorf("HostName not taken from ssh_config: %q", h.HostName)
351 }
352 if h.User != "override" {
353 t.Errorf("explicit TOML user should win: %q", h.User)
354 }
355 if h.Port != 2222 {
356 t.Errorf("Port not taken from ssh_config: %d", h.Port)
357 }
358 }
359
360 func TestResolveHostUsesPersistedHostAsTheSSHConfigLookupKey(t *testing.T) {
361 src, err := LoadSSHConfig(writeSampleConfig(t))
362 if err != nil {
363 t.Fatal(err)
364 }
365 // Make the test independent of the local OpenSSH executable.
366 src.resolveOpenSSH = nil
367
368 t.Run("legacy import remains a snapshot", func(t *testing.T) {
369 cfg := config.Default()
370 if err := cfg.UpsertRemoteHost(config.RemoteHostEntry{
371 Name: "gpu", Host: "203.0.113.9", User: "legacy-user", Port: 2201,
372 IdentityFile: "/legacy/id", UseSSHConfig: true,
373 }); err != nil {
374 t.Fatal(err)
375 }
376 h, err := ResolveHost(cfg, "gpu", src)
377 if err != nil {
378 t.Fatal(err)
379 }
380 if h.HostName != "203.0.113.9" || h.User != "legacy-user" || h.Port != 2201 || h.IdentityFile != "/legacy/id" {
381 t.Fatalf("legacy snapshot was redirected through its display label: %+v", h)
382 }
383 })
384
385 t.Run("display label does not replace saved lookup key", func(t *testing.T) {
386 cfg := config.Default()
387 if err := cfg.UpsertRemoteHost(config.RemoteHostEntry{
388 Name: "my-gpu-label", Host: "gpu", UseSSHConfig: true,
389 }); err != nil {
390 t.Fatal(err)
391 }
392 h, err := ResolveHost(cfg, "my-gpu-label", src)
393 if err != nil {
394 t.Fatal(err)
395 }
396 if h.HostName != "203.0.113.9" || h.User != "dev" {
397 t.Fatalf("saved Host alias was lost: %+v", h)
398 }
399 })
400
401 t.Run("display label collision cannot redirect saved alias", func(t *testing.T) {
402 cfg := config.Default()
403 if err := cfg.UpsertRemoteHost(config.RemoteHostEntry{
404 Name: "gpu", Host: "viajump", UseSSHConfig: true,
405 }); err != nil {
406 t.Fatal(err)
407 }
408 h, err := ResolveHost(cfg, "gpu", src)
409 if err != nil {
410 t.Fatal(err)
411 }
412 if h.HostName != "10.1.1.1" || h.ProxyJump[0] != "bastion-1" {
413 t.Fatalf("display label collision redirected the saved Host alias: %+v", h)
414 }
415 })
416 }
417
417 lines GO