-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathservice_test.go
More file actions
630 lines (599 loc) · 15.6 KB
/
service_test.go
File metadata and controls
630 lines (599 loc) · 15.6 KB
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
package service
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sourcegraph/sourcegraph/lib/errors"
batcheslib "github.com/sourcegraph/sourcegraph/lib/batches"
"github.com/sourcegraph/src-cli/internal/batches/docker"
"github.com/sourcegraph/src-cli/internal/batches/graphql"
"github.com/sourcegraph/src-cli/internal/batches/mock"
)
func TestService_ValidateChangesetSpecs(t *testing.T) {
repo1 := &graphql.Repository{ID: "repo-graphql-id-1", Name: "github.com/sourcegraph/src-cli"}
repo2 := &graphql.Repository{ID: "repo-graphql-id-2", Name: "github.com/sourcegraph/sourcegraph"}
tests := map[string]struct {
repos []*graphql.Repository
specs []*batcheslib.ChangesetSpec
wantErrInclude string
}{
"no errors": {
repos: []*graphql.Repository{repo1, repo2},
specs: []*batcheslib.ChangesetSpec{
{
HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1",
},
{
HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2",
},
{
HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1",
},
{
HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-2",
},
},
},
"imported changeset": {
repos: []*graphql.Repository{repo1},
specs: []*batcheslib.ChangesetSpec{
{
ExternalID: "123",
},
},
// This should not fail validation ever.
},
"duplicate branches": {
repos: []*graphql.Repository{repo1, repo2},
specs: []*batcheslib.ChangesetSpec{
{
HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-1",
},
{
HeadRepository: repo1.ID, HeadRef: "refs/heads/branch-2",
},
{
HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1",
},
{
HeadRepository: repo2.ID, HeadRef: "refs/heads/branch-1",
},
},
wantErrInclude: `github.com/sourcegraph/sourcegraph: 2 changeset specs have the branch "branch-1"`,
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
svc := &Service{}
haveErr := svc.ValidateChangesetSpecs(tt.repos, tt.specs)
if tt.wantErrInclude != "" {
if haveErr == nil {
t.Fatalf("expected %q to be included in error, but got none", tt.wantErrInclude)
} else if !strings.Contains(haveErr.Error(), tt.wantErrInclude) {
t.Fatalf("expected %q to be included in error, but was not. error=%q", tt.wantErrInclude, haveErr.Error())
}
} else {
if haveErr != nil {
t.Fatalf("unexpected error: %s", haveErr)
}
}
})
}
}
func TestEnsureDockerImages(t *testing.T) {
ctx := context.Background()
parallelCases := []int{0, 1, 2, 4, 8}
svc := &Service{}
t.Run("success", func(t *testing.T) {
t.Run("single image", func(t *testing.T) {
// A zeroed mock.Image should be usable for testing purposes.
image := &mock.Image{}
images := map[string]docker.Image{
"image": image,
}
for name, steps := range map[string][]batcheslib.Step{
"single step": {{Container: "image"}},
"multiple steps": {{Container: "image"}, {Container: "image"}},
} {
t.Run(name, func(t *testing.T) {
for _, parallelism := range parallelCases {
t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) {
progress := &mock.Progress{}
have, err := svc.EnsureDockerImages(ctx, &mock.ImageCache{Images: images}, steps, parallelism, progress.Callback())
assert.Nil(t, err)
assert.Equal(t, images, have)
assert.Equal(t, []mock.ProgressCall{
{Done: 0, Total: 1},
{Done: 1, Total: 1},
}, progress.Calls)
})
}
})
}
})
t.Run("multiple images", func(t *testing.T) {
var (
imageA = &mock.Image{}
imageB = &mock.Image{}
imageC = &mock.Image{}
images = map[string]docker.Image{
"a": imageA,
"b": imageB,
"c": imageC,
}
)
for _, parallelism := range parallelCases {
t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) {
progress := &mock.Progress{}
have, err := svc.EnsureDockerImages(
ctx,
&mock.ImageCache{Images: images},
[]batcheslib.Step{
{Container: "a"},
{Container: "a"},
{Container: "a"},
{Container: "b"},
{Container: "c"},
},
parallelism,
progress.Callback(),
)
assert.Nil(t, err)
assert.Equal(t, images, have)
assert.Equal(t, []mock.ProgressCall{
{Done: 0, Total: 3},
{Done: 1, Total: 3},
{Done: 2, Total: 3},
{Done: 3, Total: 3},
}, progress.Calls)
})
}
})
})
t.Run("errors", func(t *testing.T) {
// The only really interesting case is where an image fails — we want to
// ensure that the error is propagated, and that we don't end up
// deadlocking while the context cancellation propagates. Let's set up a
// good number of images (and steps) so we can give this a good test.
wantErr := errors.New("expected error")
images := map[string]docker.Image{}
steps := []batcheslib.Step{}
total := 100
for i := range total {
name := strconv.Itoa(i)
if i%25 == 0 {
images[name] = &mock.Image{EnsureErr: wantErr}
} else {
images[name] = &mock.Image{}
}
for j := 0; j < (i%10)+1; j++ {
steps = append(steps, batcheslib.Step{Container: name})
}
}
// Just verify we did that right!
assert.Len(t, images, total)
assert.True(t, len(steps) > total)
for _, parallelism := range parallelCases {
t.Run(fmt.Sprintf("%d worker(s)", parallelism), func(t *testing.T) {
progress := &mock.Progress{}
have, err := svc.EnsureDockerImages(ctx, &mock.ImageCache{Images: images}, steps, parallelism, progress.Callback())
assert.ErrorIs(t, err, wantErr)
assert.Nil(t, have)
// Because there's no particular order the images will be fetched in,
// the number of progress calls we get is non-deterministic, other than
// that we should always get the first one.
assert.Equal(t, mock.ProgressCall{Done: 0, Total: total}, progress.Calls[0])
})
}
})
}
func TestService_ParseBatchSpec(t *testing.T) {
svc := &Service{}
tempDir := t.TempDir()
tempOutsideDir := t.TempDir()
// create temp files/dirs that can be used by the tests
_, err := os.Create(filepath.Join(tempDir, "sample.sh"))
require.NoError(t, err)
_, err = os.Create(filepath.Join(tempDir, "another.sh"))
require.NoError(t, err)
// Create a sibling directory whose name shares a prefix with tempDir (e.g. /tmp/specdir-123 vs /tmp/specdir-123-outside)
prefixBypassDir := tempDir + "-outside"
require.NoError(t, os.MkdirAll(prefixBypassDir, 0o755))
t.Cleanup(func() { os.RemoveAll(prefixBypassDir) })
secretFile := filepath.Join(prefixBypassDir, "secret.txt")
require.NoError(t, os.WriteFile(secretFile, []byte("SECRET"), 0o644))
// Create a symlink inside tempDir that points outside it
symlinkPath := filepath.Join(tempDir, "leak")
require.NoError(t, os.Symlink(secretFile, symlinkPath))
tests := []struct {
name string
batchSpecDir string
rawSpec string
expectedSpec *batcheslib.BatchSpec
expectedErr error
}{
{
name: "simple spec",
rawSpec: `
name: test-spec
description: A test spec
`,
expectedSpec: &batcheslib.BatchSpec{Name: "test-spec", Description: "A test spec"},
},
{
name: "unknown field",
rawSpec: `
name: test-spec
description: A test spec
some-new-field: Foo bar
`,
expectedErr: errors.New("parsing batch spec: Additional property some-new-field is not allowed"),
},
{
name: "supported version",
rawSpec: `
version: 2
name: test-spec
description: A test spec
`,
expectedSpec: &batcheslib.BatchSpec{Version: 2, Name: "test-spec", Description: "A test spec"},
},
{
name: "unsupported version",
rawSpec: `
version: 99
name: test-spec
description: A test spec
`,
expectedErr: errors.New("parsing batch spec: version: version must be one of the following: 1, 2"),
},
{
name: "mount absolute file",
batchSpecDir: tempDir,
rawSpec: fmt.Sprintf(`
name: test-spec
description: A test spec
steps:
- run: /tmp/sample.sh
container: alpine:3
mount:
- path: %s
mountpoint: /tmp/sample.sh
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`, filepath.Join(tempDir, "sample.sh")),
expectedSpec: &batcheslib.BatchSpec{
Name: "test-spec",
Description: "A test spec",
Steps: []batcheslib.Step{
{
Run: "/tmp/sample.sh",
Container: "alpine:3",
Mount: []batcheslib.Mount{
{
Path: filepath.Join(tempDir, "sample.sh"),
Mountpoint: "/tmp/sample.sh",
},
},
},
},
ChangesetTemplate: &batcheslib.ChangesetTemplate{
Title: "Test Mount",
Body: "Test a mounted path",
Branch: "test",
Commit: batcheslib.ExpandedGitCommitDescription{
Message: "Test",
},
},
},
},
{
name: "mount relative file",
batchSpecDir: tempDir,
rawSpec: `
name: test-spec
description: A test spec
steps:
- run: /tmp/sample.sh
container: alpine:3
mount:
- path: ./sample.sh
mountpoint: /tmp/sample.sh
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`,
expectedSpec: &batcheslib.BatchSpec{
Name: "test-spec",
Description: "A test spec",
Steps: []batcheslib.Step{
{
Run: "/tmp/sample.sh",
Container: "alpine:3",
Mount: []batcheslib.Mount{
{
Path: "./sample.sh",
Mountpoint: "/tmp/sample.sh",
},
},
},
},
ChangesetTemplate: &batcheslib.ChangesetTemplate{
Title: "Test Mount",
Body: "Test a mounted path",
Branch: "test",
Commit: batcheslib.ExpandedGitCommitDescription{
Message: "Test",
},
},
},
},
{
name: "mount absolute directory",
batchSpecDir: tempDir,
rawSpec: fmt.Sprintf(`
name: test-spec
description: A test spec
steps:
- run: /tmp/some-file.sh
container: alpine:3
mount:
- path: %s
mountpoint: /tmp
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`, tempDir),
expectedSpec: &batcheslib.BatchSpec{
Name: "test-spec",
Description: "A test spec",
Steps: []batcheslib.Step{
{
Run: "/tmp/some-file.sh",
Container: "alpine:3",
Mount: []batcheslib.Mount{
{
Path: tempDir,
Mountpoint: "/tmp",
},
},
},
},
ChangesetTemplate: &batcheslib.ChangesetTemplate{
Title: "Test Mount",
Body: "Test a mounted path",
Branch: "test",
Commit: batcheslib.ExpandedGitCommitDescription{
Message: "Test",
},
},
},
},
{
name: "mount relative directory",
batchSpecDir: tempDir,
rawSpec: `
name: test-spec
description: A test spec
steps:
- run: /tmp/some-file.sh
container: alpine:3
mount:
- path: ./
mountpoint: /tmp
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`,
expectedSpec: &batcheslib.BatchSpec{
Name: "test-spec",
Description: "A test spec",
Steps: []batcheslib.Step{
{
Run: "/tmp/some-file.sh",
Container: "alpine:3",
Mount: []batcheslib.Mount{
{
Path: "./",
Mountpoint: "/tmp",
},
},
},
},
ChangesetTemplate: &batcheslib.ChangesetTemplate{
Title: "Test Mount",
Body: "Test a mounted path",
Branch: "test",
Commit: batcheslib.ExpandedGitCommitDescription{
Message: "Test",
},
},
},
},
{
name: "mount multiple files",
batchSpecDir: tempDir,
rawSpec: `
name: test-spec
description: A test spec
steps:
- run: /tmp/sample.sh && /tmp/another.sh
container: alpine:3
mount:
- path: ./sample.sh
mountpoint: /tmp/sample.sh
- path: ./another.sh
mountpoint: /tmp/another.sh
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`,
expectedSpec: &batcheslib.BatchSpec{
Name: "test-spec",
Description: "A test spec",
Steps: []batcheslib.Step{
{
Run: "/tmp/sample.sh && /tmp/another.sh",
Container: "alpine:3",
Mount: []batcheslib.Mount{
{
Path: "./sample.sh",
Mountpoint: "/tmp/sample.sh",
},
{
Path: "./another.sh",
Mountpoint: "/tmp/another.sh",
},
},
},
},
ChangesetTemplate: &batcheslib.ChangesetTemplate{
Title: "Test Mount",
Body: "Test a mounted path",
Branch: "test",
Commit: batcheslib.ExpandedGitCommitDescription{
Message: "Test",
},
},
},
},
{
name: "mount path does not exist",
batchSpecDir: tempDir,
rawSpec: fmt.Sprintf(`
name: test-spec
description: A test spec
steps:
- run: /tmp/sample.sh
container: alpine:3
mount:
- path: %s
mountpoint: /tmp
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`, filepath.Join(tempDir, "does", "not", "exist", "sample.sh")),
expectedErr: errors.Newf("handling mount: step 1 mount path %s does not exist", filepath.Join(tempDir, "does", "not", "exist", "sample.sh")),
},
{
name: "mount path not subdirectory of spec",
batchSpecDir: tempDir,
rawSpec: fmt.Sprintf(`
name: test-spec
description: A test spec
steps:
- run: /tmp/sample.sh
container: alpine:3
mount:
- path: %s
mountpoint: /tmp
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`, tempOutsideDir),
expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"),
},
{
name: "mount path prefix confusion bypass",
batchSpecDir: tempDir,
rawSpec: fmt.Sprintf(`
name: test-spec
description: A test spec
steps:
- run: cat /tmp/mounted
container: alpine:3
mount:
- path: %s
mountpoint: /tmp/mounted
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`, secretFile),
expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"),
},
{
name: "mount path symlink escape",
batchSpecDir: tempDir,
rawSpec: `
name: test-spec
description: A test spec
steps:
- run: cat /tmp/mounted
container: alpine:3
mount:
- path: ./leak
mountpoint: /tmp/mounted
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`,
expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"),
},
{
name: "mount path dot-dot traversal",
batchSpecDir: tempDir,
rawSpec: `
name: test-spec
description: A test spec
steps:
- run: cat /tmp/mounted
container: alpine:3
mount:
- path: ../../../etc/passwd
mountpoint: /tmp/mounted
changesetTemplate:
title: Test Mount
body: Test a mounted path
branch: test
commit:
message: Test
`,
expectedErr: errors.New("handling mount: step 1 mount path is not in the same directory or subdirectory as the batch spec"),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
spec, err := svc.ParseBatchSpec(test.batchSpecDir, []byte(test.rawSpec))
if test.expectedErr != nil {
assert.Equal(t, test.expectedErr.Error(), err.Error())
} else {
assert.NoError(t, err)
assert.Equal(t, test.expectedSpec, spec)
}
})
}
}