-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathgit_test.go
429 lines (389 loc) · 12.3 KB
/
git_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package envbuilder_test
import (
"context"
"crypto/ed25519"
"fmt"
"io"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"regexp"
"testing"
"github.com/coder/envbuilder"
"github.com/coder/envbuilder/internal/notcodersdk"
"github.com/coder/envbuilder/testutil/gittest"
"github.com/coder/envbuilder/testutil/mwtest"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-billy/v5/osfs"
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"
gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/stretchr/testify/require"
gossh "golang.org/x/crypto/ssh"
)
func TestCloneRepo(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
srvUsername string
srvPassword string
username string
password string
mungeURL func(*string)
expectError string
expectClone bool
}{
{
name: "no auth",
expectClone: true,
},
{
name: "auth",
srvUsername: "user",
srvPassword: "password",
username: "user",
password: "password",
expectClone: true,
},
{
name: "auth but no creds",
srvUsername: "user",
srvPassword: "password",
expectClone: false,
expectError: "authentication required",
},
{
name: "invalid auth",
srvUsername: "user",
srvPassword: "password",
username: "notuser",
password: "notpassword",
expectClone: false,
expectError: "authentication required",
},
{
name: "tokenish username",
srvUsername: "tokentokentoken",
srvPassword: "",
username: "tokentokentoken",
password: "",
expectClone: true,
},
} {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
// We do not overwrite a repo if one is already present.
t.Run("AlreadyCloned", func(t *testing.T) {
srvFS := memfs.New()
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
authMW := mwtest.BasicAuthMW(tc.srvUsername, tc.srvPassword)
srv := httptest.NewServer(authMW(gittest.NewServer(srvFS)))
clientFS := memfs.New()
// A repo already exists!
_ = gittest.NewRepo(t, clientFS)
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/",
RepoURL: srv.URL,
Storage: clientFS,
})
require.NoError(t, err)
require.False(t, cloned)
})
// Basic Auth
t.Run("BasicAuth", func(t *testing.T) {
t.Parallel()
srvFS := memfs.New()
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
authMW := mwtest.BasicAuthMW(tc.srvUsername, tc.srvPassword)
srv := httptest.NewServer(authMW(gittest.NewServer(srvFS)))
clientFS := memfs.New()
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/workspace",
RepoURL: srv.URL,
Storage: clientFS,
RepoAuth: &githttp.BasicAuth{
Username: tc.username,
Password: tc.password,
},
})
require.Equal(t, tc.expectClone, cloned)
if tc.expectError != "" {
require.ErrorContains(t, err, tc.expectError)
return
}
require.NoError(t, err)
require.True(t, cloned)
readme := mustRead(t, clientFS, "/workspace/README.md")
require.Equal(t, "Hello, world!", readme)
gitConfig := mustRead(t, clientFS, "/workspace/.git/config")
// Ensure we do not modify the git URL that folks pass in.
require.Regexp(t, fmt.Sprintf(`(?m)^\s+url\s+=\s+%s\s*$`, regexp.QuoteMeta(srv.URL)), gitConfig)
})
// In-URL-style auth e.g. http://user:password@host:port
t.Run("InURL", func(t *testing.T) {
t.Parallel()
srvFS := memfs.New()
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
authMW := mwtest.BasicAuthMW(tc.srvUsername, tc.srvPassword)
srv := httptest.NewServer(authMW(gittest.NewServer(srvFS)))
authURL, err := url.Parse(srv.URL)
require.NoError(t, err)
authURL.User = url.UserPassword(tc.username, tc.password)
clientFS := memfs.New()
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/workspace",
RepoURL: authURL.String(),
Storage: clientFS,
})
require.Equal(t, tc.expectClone, cloned)
if tc.expectError != "" {
require.ErrorContains(t, err, tc.expectError)
return
}
require.NoError(t, err)
require.True(t, cloned)
readme := mustRead(t, clientFS, "/workspace/README.md")
require.Equal(t, "Hello, world!", readme)
gitConfig := mustRead(t, clientFS, "/workspace/.git/config")
// Ensure we do not modify the git URL that folks pass in.
require.Regexp(t, fmt.Sprintf(`(?m)^\s+url\s+=\s+%s\s*$`, regexp.QuoteMeta(authURL.String())), gitConfig)
})
})
}
}
func TestCloneRepoSSH(t *testing.T) {
t.Parallel()
t.Run("AuthSuccess", func(t *testing.T) {
t.Parallel()
// TODO: test the rest of the cloning flow. This just tests successful auth.
tmpDir := t.TempDir()
srvFS := osfs.New(tmpDir, osfs.WithChrootOS())
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
key := randKeygen(t)
tr := gittest.NewServerSSH(t, srvFS, key.PublicKey())
gitURL := tr.String()
clientFS := memfs.New()
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/workspace",
RepoURL: gitURL,
Storage: clientFS,
RepoAuth: &gitssh.PublicKeys{
User: "",
Signer: key,
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{
// Not testing host keys here.
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
},
},
})
// TODO: ideally, we want to test the entire cloning flow.
// For now, this indicates successful ssh key auth.
require.ErrorContains(t, err, "repository not found")
require.False(t, cloned)
})
t.Run("AuthFailure", func(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
srvFS := osfs.New(tmpDir, osfs.WithChrootOS())
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
key := randKeygen(t)
tr := gittest.NewServerSSH(t, srvFS, key.PublicKey())
gitURL := tr.String()
clientFS := memfs.New()
anotherKey := randKeygen(t)
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/workspace",
RepoURL: gitURL,
Storage: clientFS,
RepoAuth: &gitssh.PublicKeys{
User: "",
Signer: anotherKey,
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{
// Not testing host keys here.
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
},
},
})
require.ErrorContains(t, err, "handshake failed")
require.False(t, cloned)
})
// nolint: paralleltest // t.Setenv
t.Run("PrivateKeyHostKeyMismatch", func(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
srvFS := osfs.New(tmpDir, osfs.WithChrootOS())
_ = gittest.NewRepo(t, srvFS, gittest.Commit(t, "README.md", "Hello, world!", "Wow!"))
key := randKeygen(t)
tr := gittest.NewServerSSH(t, srvFS, key.PublicKey())
gitURL := tr.String()
clientFS := memfs.New()
cloned, err := envbuilder.CloneRepo(context.Background(), envbuilder.CloneRepoOptions{
Path: "/workspace",
RepoURL: gitURL,
Storage: clientFS,
RepoAuth: &gitssh.PublicKeys{
User: "",
Signer: key,
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{
HostKeyCallback: gossh.FixedHostKey(randKeygen(t).PublicKey()),
},
},
})
require.ErrorContains(t, err, "ssh: host key mismatch")
require.False(t, cloned)
})
}
// nolint:paralleltest // t.Setenv for SSH_AUTH_SOCK
func TestSetupRepoAuth(t *testing.T) {
t.Setenv("SSH_AUTH_SOCK", "")
t.Run("Empty", func(t *testing.T) {
opts := &envbuilder.Options{
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
require.Nil(t, auth)
})
t.Run("HTTP/NoAuth", func(t *testing.T) {
opts := &envbuilder.Options{
GitURL: "http://host.tld/repo",
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
require.Nil(t, auth)
})
t.Run("HTTP/BasicAuth", func(t *testing.T) {
opts := &envbuilder.Options{
GitURL: "http://host.tld/repo",
GitUsername: "user",
GitPassword: "pass",
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
ba, ok := auth.(*githttp.BasicAuth)
require.True(t, ok)
require.Equal(t, opts.GitUsername, ba.Username)
require.Equal(t, opts.GitPassword, ba.Password)
})
t.Run("HTTPS/BasicAuth", func(t *testing.T) {
opts := &envbuilder.Options{
GitURL: "https://host.tld/repo",
GitUsername: "user",
GitPassword: "pass",
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
ba, ok := auth.(*githttp.BasicAuth)
require.True(t, ok)
require.Equal(t, opts.GitUsername, ba.Username)
require.Equal(t, opts.GitPassword, ba.Password)
})
t.Run("SSH/WithScheme", func(t *testing.T) {
kPath := writeTestPrivateKey(t)
opts := &envbuilder.Options{
GitURL: "ssh://host.tld/repo",
GitSSHPrivateKeyPath: kPath,
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
_, ok := auth.(*gitssh.PublicKeys)
require.True(t, ok)
})
t.Run("SSH/NoScheme", func(t *testing.T) {
kPath := writeTestPrivateKey(t)
opts := &envbuilder.Options{
GitURL: "[email protected]:repo/path",
GitSSHPrivateKeyPath: kPath,
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
_, ok := auth.(*gitssh.PublicKeys)
require.True(t, ok)
})
t.Run("SSH/OtherScheme", func(t *testing.T) {
// Anything that is not https:// or http:// is treated as SSH.
kPath := writeTestPrivateKey(t)
opts := &envbuilder.Options{
GitURL: "git://[email protected]:repo/path",
GitSSHPrivateKeyPath: kPath,
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
_, ok := auth.(*gitssh.PublicKeys)
require.True(t, ok)
})
t.Run("SSH/GitUsername", func(t *testing.T) {
kPath := writeTestPrivateKey(t)
opts := &envbuilder.Options{
GitURL: "host.tld:12345/repo/path",
GitSSHPrivateKeyPath: kPath,
GitUsername: "user",
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
_, ok := auth.(*gitssh.PublicKeys)
require.True(t, ok)
})
t.Run("SSH/PrivateKey", func(t *testing.T) {
kPath := writeTestPrivateKey(t)
opts := &envbuilder.Options{
GitURL: "ssh://[email protected]:repo/path",
GitSSHPrivateKeyPath: kPath,
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
pk, ok := auth.(*gitssh.PublicKeys)
require.True(t, ok)
require.NotNil(t, pk.Signer)
actualSigner, err := gossh.ParsePrivateKey([]byte(testKey))
require.NoError(t, err)
require.Equal(t, actualSigner, pk.Signer)
})
t.Run("SSH/NoAuthMethods", func(t *testing.T) {
opts := &envbuilder.Options{
GitURL: "ssh://[email protected]:repo/path",
Logger: testLog(t),
}
auth := envbuilder.SetupRepoAuth(opts)
require.Nil(t, auth) // TODO: actually test SSH_AUTH_SOCK
})
}
func mustRead(t *testing.T, fs billy.Filesystem, path string) string {
t.Helper()
f, err := fs.OpenFile(path, os.O_RDONLY, 0o644)
require.NoError(t, err)
content, err := io.ReadAll(f)
require.NoError(t, err)
return string(content)
}
// generates a random ed25519 private key
func randKeygen(t *testing.T) gossh.Signer {
t.Helper()
_, key, err := ed25519.GenerateKey(nil)
require.NoError(t, err)
signer, err := gossh.NewSignerFromKey(key)
require.NoError(t, err)
return signer
}
func testLog(t *testing.T) envbuilder.LoggerFunc {
return func(_ notcodersdk.LogLevel, format string, args ...interface{}) {
t.Logf(format, args...)
}
}
// nolint:gosec // Throw-away key for testing. DO NOT REUSE.
var testKey = `-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBXOGgAge/EbcejqASqZa6s8PFXZle56DiGEt0VYnljuwAAAKgM05mUDNOZ
lAAAAAtzc2gtZWQyNTUxOQAAACBXOGgAge/EbcejqASqZa6s8PFXZle56DiGEt0VYnljuw
AAAEDCawwtjrM4AGYXD1G6uallnbsgMed4cfkFsQ+mLZtOkFc4aACB78Rtx6OoBKplrqzw
8VdmV7noOIYS3RVieWO7AAAAHmNpYW5AY2RyLW1icC1mdmZmdzBuOHEwNXAuaG9tZQECAw
QFBgc=
-----END OPENSSH PRIVATE KEY-----`
func writeTestPrivateKey(t *testing.T) string {
t.Helper()
tmpDir := t.TempDir()
kPath := filepath.Join(tmpDir, "test.key")
require.NoError(t, os.WriteFile(kPath, []byte(testKey), 0o600))
return kPath
}