Debian Codegraph @

lfshttp/ssh_test.go

raw symbols SCIP
1 package lfshttp
2
3 import (
4 goerrors "errors"
5 "fmt"
6 "os/exec"
7 "sync"
8 "testing"
9 "time"
10
11 "github.com/git-lfs/git-lfs/v3/errors"
12 sshp "github.com/git-lfs/git-lfs/v3/ssh"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 )
16
17 func TestSSHCacheResolveFromCache(t *testing.T) {
18 ssh := newFakeResolver()
19 cache := withSSHCache(ssh).(*sshCache)
20 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
21 Href: "cache",
22 createdAt: time.Now(),
23 })
24 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
25
26 e := Endpoint{
27 SSHMetadata: sshp.SSHMetadata{
28 UserAndHost: "userandhost",
29 Port: "1",
30 Path: "path",
31 },
32 }
33
34 res, err := cache.Resolve(e, "post")
35 assert.Nil(t, err)
36 assert.Equal(t, "cache", res.Href)
37 }
38
39 func TestSSHCacheResolveFromCacheWithFutureExpiresAt(t *testing.T) {
40 ssh := newFakeResolver()
41 cache := withSSHCache(ssh).(*sshCache)
42 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
43 Href: "cache",
44 ExpiresAt: time.Now().Add(time.Duration(1) * time.Hour),
45 createdAt: time.Now(),
46 })
47 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
48
49 e := Endpoint{
50 SSHMetadata: sshp.SSHMetadata{
51 UserAndHost: "userandhost",
52 Port: "1",
53 Path: "path",
54 },
55 }
56
57 res, err := cache.Resolve(e, "post")
58 assert.Nil(t, err)
59 assert.Equal(t, "cache", res.Href)
60 }
61
62 func TestSSHCacheResolveFromCacheWithFutureExpiresIn(t *testing.T) {
63 ssh := newFakeResolver()
64 cache := withSSHCache(ssh).(*sshCache)
65 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
66 Href: "cache",
67 ExpiresIn: 60 * 60,
68 createdAt: time.Now(),
69 })
70 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
71
72 e := Endpoint{
73 SSHMetadata: sshp.SSHMetadata{
74 UserAndHost: "userandhost",
75 Port: "1",
76 Path: "path",
77 },
78 }
79
80 res, err := cache.Resolve(e, "post")
81 assert.Nil(t, err)
82 assert.Equal(t, "cache", res.Href)
83 }
84
85 func TestSSHCacheResolveFromCacheWithPastExpiresAt(t *testing.T) {
86 ssh := newFakeResolver()
87 cache := withSSHCache(ssh).(*sshCache)
88 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
89 Href: "cache",
90 ExpiresAt: time.Now().Add(time.Duration(-1) * time.Hour),
91 createdAt: time.Now(),
92 })
93 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
94
95 e := Endpoint{
96 SSHMetadata: sshp.SSHMetadata{
97 UserAndHost: "userandhost",
98 Port: "1",
99 Path: "path",
100 },
101 }
102
103 res, err := cache.Resolve(e, "post")
104 assert.Nil(t, err)
105 assert.Equal(t, "real", res.Href)
106 }
107
108 func TestSSHCacheResolveFromCacheWithPastExpiresIn(t *testing.T) {
109 ssh := newFakeResolver()
110 cache := withSSHCache(ssh).(*sshCache)
111 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
112 Href: "cache",
113 ExpiresIn: -60 * 60,
114 createdAt: time.Now(),
115 })
116 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
117
118 e := Endpoint{
119 SSHMetadata: sshp.SSHMetadata{
120 UserAndHost: "userandhost",
121 Port: "1",
122 Path: "path",
123 },
124 }
125
126 res, err := cache.Resolve(e, "post")
127 assert.Nil(t, err)
128 assert.Equal(t, "real", res.Href)
129 }
130
131 func TestSSHCacheResolveFromCacheWithAmbiguousExpirationInfo(t *testing.T) {
132 ssh := newFakeResolver()
133 cache := withSSHCache(ssh).(*sshCache)
134 cache.endpoints.Store("userandhost//1//path//post", &sshAuthResponse{
135 Href: "cache",
136 ExpiresIn: 60 * 60,
137 ExpiresAt: time.Now().Add(-1 * time.Hour),
138 createdAt: time.Now(),
139 })
140 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
141
142 e := Endpoint{
143 SSHMetadata: sshp.SSHMetadata{
144 UserAndHost: "userandhost",
145 Port: "1",
146 Path: "path",
147 },
148 }
149
150 res, err := cache.Resolve(e, "post")
151 assert.Nil(t, err)
152 assert.Equal(t, "cache", res.Href)
153 }
154
155 func TestSSHCacheResolveWithoutError(t *testing.T) {
156 ssh := newFakeResolver()
157 cache := withSSHCache(ssh).(*sshCache)
158
159 assertCacheLen(t, cache, 0)
160
161 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
162
163 e := Endpoint{
164 SSHMetadata: sshp.SSHMetadata{
165 UserAndHost: "userandhost",
166 Port: "1",
167 Path: "path",
168 },
169 }
170
171 res, err := cache.Resolve(e, "post")
172 assert.Nil(t, err)
173 assert.Equal(t, "real", res.Href)
174
175 assertCacheLen(t, cache, 1)
176 val, ok := cache.endpoints.Load("userandhost//1//path//post")
177 assert.True(t, ok)
178 assert.NotNil(t, val)
179 assert.Equal(t, "real", val.(*sshAuthResponse).Href)
180
181 delete(ssh.responses, "userandhost")
182 res2, err := cache.Resolve(e, "post")
183 assert.Nil(t, err)
184 assert.Equal(t, "real", res2.Href)
185 }
186
187 func TestSSHCacheResolveWithError(t *testing.T) {
188 ssh := newFakeResolver()
189 cache := withSSHCache(ssh).(*sshCache)
190
191 assertCacheLen(t, cache, 0)
192
193 ssh.responses["userandhost"] = sshAuthResponse{Message: "resolve error", Href: "real"}
194
195 e := Endpoint{
196 SSHMetadata: sshp.SSHMetadata{
197 UserAndHost: "userandhost",
198 Port: "1",
199 Path: "path",
200 },
201 }
202
203 res, err := cache.Resolve(e, "post")
204 assert.NotNil(t, err)
205 assert.Equal(t, "real", res.Href)
206
207 assertCacheLen(t, cache, 0)
208 delete(ssh.responses, "userandhost")
209 res2, err := cache.Resolve(e, "post")
210 assert.Nil(t, err)
211 assert.Equal(t, "", res2.Href)
212 }
213
214 // countingResolver always returns the configured error and records how many
215 // times Resolve was called.
216 type countingResolver struct {
217 err error
218 calls int
219 }
220
221 func (r *countingResolver) Resolve(e Endpoint, method string) (sshAuthResponse, error) {
222 r.calls++
223 return sshAuthResponse{}, r.err
224 }
225
226 func newTestClient(t *testing.T, resolver SSHResolver) *Client {
227 t.Helper()
228 c := NewClient(NewContext(nil, nil, nil))
229 c.SSH = resolver
230 c.sshTries = 5
231 return c
232 }
233
234 func testSSHEndpoint() Endpoint {
235 return Endpoint{
236 Url: "https://git-server.com/foo/bar.git/info/lfs",
237 OriginalUrl: "[email protected]:foo/bar.git",
238 SSHMetadata: sshp.SSHMetadata{
239 UserAndHost: "[email protected]",
240 Path: "foo/bar.git",
241 },
242 }
243 }
244
245 func TestSSHResolveFallsBackWhenAuthenticateUnavailable(t *testing.T) {
246 resolver := &countingResolver{
247 err: &sshAuthenticateUnavailableError{
248 err: errors.New("bash: git-lfs-authenticate: command not found"),
249 },
250 }
251 c := newTestClient(t, resolver)
252
253 res, err := c.sshResolveWithRetries(testSSHEndpoint(), "GET")
254 assert.Nil(t, err)
255 assert.NotNil(t, res)
256 assert.Equal(t, "", res.Href)
257
258 // The unavailable command should not be retried.
259 assert.Equal(t, 1, resolver.calls)
260 }
261
262 func TestSSHResolveFailsForOtherErrors(t *testing.T) {
263 resolver := &countingResolver{err: errors.New("permission denied")}
264 c := newTestClient(t, resolver)
265
266 _, err := c.sshResolveWithRetries(testSSHEndpoint(), "GET")
267 assert.NotNil(t, err)
268
269 // Non-fallback errors are retried sshTries+1 times.
270 assert.Equal(t, 6, resolver.calls)
271 }
272
273 // exitErrorWithCode runs a trivial command that exits with the given status so
274 // that tests can obtain a real *exec.ExitError.
275 func exitErrorWithCode(t *testing.T, code int) error {
276 t.Helper()
277 err := exec.Command("sh", "-c", fmt.Sprintf("exit %d", code)).Run()
278 var exitErr *exec.ExitError
279 require.True(t, goerrors.As(err, &exitErr))
280 require.Equal(t, code, exitErr.ExitCode())
281 return err
282 }
283
284 func TestIsSSHAuthenticateUnavailable(t *testing.T) {
285 for _, tc := range []struct {
286 name string
287 exitCode int
288 stderr string
289 want bool
290 }{
291 {
292 name: "command not found exit code",
293 exitCode: 127,
294 stderr: "",
295 want: true,
296 },
297 {
298 name: "gerrit generic exit code with message",
299 exitCode: 1,
300 stderr: "fatal: Gerrit Code Review: git-lfs-authenticate: not found",
301 want: true,
302 },
303 {
304 name: "bash command not found message",
305 exitCode: 1,
306 stderr: "bash: git-lfs-authenticate: command not found",
307 want: true,
308 },
309 {
310 name: "zsh command not found message",
311 exitCode: 1,
312 stderr: "zsh: command not found: git-lfs-authenticate",
313 want: true,
314 },
315 {
316 name: "no such file message",
317 exitCode: 1,
318 stderr: "git-lfs-authenticate: No such file or directory",
319 want: true,
320 },
321 {
322 name: "unrelated not found error is not a fallback",
323 exitCode: 1,
324 stderr: "Repository not found",
325 want: false,
326 },
327 {
328 name: "generic error without message is fatal",
329 exitCode: 1,
330 stderr: "",
331 want: false,
332 },
333 } {
334 t.Run(tc.name, func(t *testing.T) {
335 err := exitErrorWithCode(t, tc.exitCode)
336 assert.Equal(t, tc.want, isSSHAuthenticateUnavailable(err, tc.stderr))
337 })
338 }
339 }
340
341 func TestIsSSHAuthenticateUnavailableNonExitError(t *testing.T) {
342 // A failure to start the command (not an *exec.ExitError) is a genuine
343 // error, never an "unavailable" signal, even with a matching message.
344 err := errors.New("exec: \"ssh\": executable file not found in $PATH")
345 assert.False(t, isSSHAuthenticateUnavailable(err,
346 "git-lfs-authenticate: not found"))
347 }
348
349 func assertCacheLen(t *testing.T, cache *sshCache, expected int) {
350 t.Helper()
351 n := 0
352 cache.endpoints.Range(func(_, _ any) bool { n++; return true })
353 assert.Equal(t, expected, n)
354 }
355
356 func TestSSHCacheConcurrentResolve(t *testing.T) {
357 ssh := newFakeResolver()
358 cache := withSSHCache(ssh)
359
360 ssh.responses["userandhost"] = sshAuthResponse{Href: "real"}
361
362 e := Endpoint{
363 SSHMetadata: sshp.SSHMetadata{
364 UserAndHost: "userandhost",
365 Port: "1",
366 Path: "path",
367 },
368 }
369
370 // Two goroutines resolving the same endpoint concurrently is enough
371 // for `go test -race` to detect an unprotected map access.
372 start := make(chan struct{})
373 var wg sync.WaitGroup
374 for i := 0; i < 2; i++ {
375 wg.Add(1)
376 go func() {
377 defer wg.Done()
378 <-start
379 res, err := cache.Resolve(e, "post")
380 assert.Nil(t, err)
381 assert.Equal(t, "real", res.Href)
382 }()
383 }
384 close(start)
385 wg.Wait()
386 }
387
388 func newFakeResolver() *fakeResolver {
389 return &fakeResolver{responses: make(map[string]sshAuthResponse)}
390 }
391
392 type fakeResolver struct {
393 responses map[string]sshAuthResponse
394 }
395
396 func (r *fakeResolver) Resolve(e Endpoint, method string) (sshAuthResponse, error) {
397 res := r.responses[e.SSHMetadata.UserAndHost]
398 var err error
399 if len(res.Message) > 0 {
400 err = errors.New(res.Message)
401 }
402
403 res.createdAt = time.Now()
404
405 return res, err
406 }