-
Notifications
You must be signed in to change notification settings - Fork 90
/
clone_test.go
1611 lines (1440 loc) · 46.8 KB
/
clone_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
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2022 The Flux authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gogit
import (
"context"
"errors"
"fmt"
iofs "io/fs"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"github.com/elazarl/goproxy"
"github.com/go-git/go-billy/v5/memfs"
extgogit "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/cache"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/storage/filesystem"
. "github.com/onsi/gomega"
cryptossh "golang.org/x/crypto/ssh"
"github.com/fluxcd/gitkit"
"github.com/fluxcd/pkg/git"
"github.com/fluxcd/pkg/git/gogit/fs"
"github.com/fluxcd/pkg/git/repository"
"github.com/fluxcd/pkg/gittestserver"
"github.com/fluxcd/pkg/ssh"
)
const testRepositoryPath = "../testdata/git/repo"
func TestClone_cloneBranch(t *testing.T) {
repo, repoPath, err := initRepo(t.TempDir())
if err != nil {
t.Fatal(err)
}
firstCommit, err := commitFile(repo, "branch", "init", time.Now())
if err != nil {
t.Fatal(err)
}
if err = createBranch(repo, "test"); err != nil {
t.Fatal(err)
}
secondCommit, err := commitFile(repo, "branch", "second", time.Now())
if err != nil {
t.Fatal(err)
}
_, emptyRepoPath, err := initRepo(t.TempDir())
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
branch string
filesCreated map[string]string
lastRevision string
expectedCommit string
expectedConcreteCommit bool
expectedErr string
expectedEmpty bool
}{
{
name: "Default branch",
branch: "master",
filesCreated: map[string]string{"branch": "init"},
expectedCommit: firstCommit.String(),
expectedConcreteCommit: true,
},
{
name: "skip clone if LastRevision hasn't changed",
branch: "master",
filesCreated: map[string]string{"branch": "init"},
lastRevision: fmt.Sprintf("master@%s", git.Hash(firstCommit.String()).Digest()),
expectedCommit: firstCommit.String(),
expectedConcreteCommit: false,
},
{
name: "skip clone if LastRevision hasn't changed (legacy)",
branch: "master",
filesCreated: map[string]string{"branch": "init"},
lastRevision: fmt.Sprintf("master/%s", firstCommit.String()),
expectedCommit: firstCommit.String(),
expectedConcreteCommit: false,
},
{
name: "Other branch - revision has changed",
branch: "test",
filesCreated: map[string]string{"branch": "second"},
lastRevision: fmt.Sprintf("master@%s", git.Hash(firstCommit.String()).Digest()),
expectedCommit: secondCommit.String(),
expectedConcreteCommit: true,
},
{
name: "Other branch - revision has changed (legacy)",
branch: "test",
filesCreated: map[string]string{"branch": "second"},
lastRevision: fmt.Sprintf("master/%s", firstCommit.String()),
expectedCommit: secondCommit.String(),
expectedConcreteCommit: true,
},
{
name: "Non existing branch",
branch: "invalid",
expectedErr: "couldn't find remote ref \"refs/heads/invalid\"",
},
{
name: "empty repo",
branch: "master",
expectedEmpty: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
tmpDir := t.TempDir()
ggc, err := NewClient(tmpDir, &git.AuthOptions{Transport: git.HTTP})
g.Expect(err).ToNot(HaveOccurred())
var upstreamPath string
if tt.expectedEmpty {
upstreamPath = emptyRepoPath
} else {
upstreamPath = repoPath
}
cc, err := ggc.Clone(context.TODO(), upstreamPath, repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Branch: tt.branch,
},
ShallowClone: true,
LastObservedCommit: tt.lastRevision,
})
if tt.expectedErr != "" {
g.Expect(err).To(HaveOccurred())
g.Expect(err.Error()).To(ContainSubstring(tt.expectedErr))
g.Expect(cc).To(BeNil())
return
}
if tt.expectedEmpty {
g.Expect(cc).To(BeNil())
g.Expect(err).ToNot(HaveOccurred())
g.Expect(filepath.Join(ggc.path, ".git")).To(BeADirectory())
return
}
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc.String()).To(Equal(tt.branch + "@" + git.HashTypeSHA1 + ":" + tt.expectedCommit))
g.Expect(git.IsConcreteCommit(*cc)).To(Equal(tt.expectedConcreteCommit))
if tt.expectedConcreteCommit {
for k, v := range tt.filesCreated {
g.Expect(filepath.Join(tmpDir, k)).To(BeARegularFile())
g.Expect(os.ReadFile(filepath.Join(tmpDir, k))).To(BeEquivalentTo(v))
}
}
})
}
}
func TestClone_cloneTag(t *testing.T) {
type testTag struct {
name string
annotated bool
}
tests := []struct {
name string
tagsInRepo []testTag
checkoutTag string
lastRevTag string
expectConcreteCommit bool
expectErr string
}{
{
name: "Tag",
tagsInRepo: []testTag{{"tag-1", false}},
checkoutTag: "tag-1",
expectConcreteCommit: true,
},
{
name: "Annotated",
tagsInRepo: []testTag{{"annotated", true}},
checkoutTag: "annotated",
expectConcreteCommit: true,
},
{
name: "Non existing tag",
// Without this go-git returns error "remote repository is empty".
tagsInRepo: []testTag{{"tag-1", false}},
checkoutTag: "invalid",
expectErr: "couldn't find remote ref \"refs/tags/invalid\"",
},
{
name: "Skip clone - last revision unchanged",
tagsInRepo: []testTag{{"tag-1", false}},
checkoutTag: "tag-1",
lastRevTag: "tag-1",
expectConcreteCommit: false,
},
{
name: "Last revision changed",
tagsInRepo: []testTag{{"tag-1", false}, {"tag-2", false}},
checkoutTag: "tag-2",
lastRevTag: "tag-1",
expectConcreteCommit: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
repo, path, err := initRepo(t.TempDir())
g.Expect(err).ToNot(HaveOccurred())
// Collect tags and their associated commit hash for later
// reference.
tagCommits := map[string]string{}
// Populate the repo with commits and tags.
if tt.tagsInRepo != nil {
for _, tr := range tt.tagsInRepo {
h, err := commitFile(repo, "tag", tr.name, time.Now())
if err != nil {
t.Fatal(err)
}
_, err = tag(repo, h, tr.annotated, tr.name, time.Now())
if err != nil {
t.Fatal(err)
}
tagCommits[tr.name] = h.String()
}
}
tmpDir := t.TempDir()
ggc, err := NewClient(tmpDir, &git.AuthOptions{Transport: git.HTTP})
g.Expect(err).ToNot(HaveOccurred())
opts := repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Tag: tt.checkoutTag,
},
ShallowClone: true,
}
// If last revision is provided, configure it.
if tt.lastRevTag != "" {
lc := tagCommits[tt.lastRevTag]
opts.LastObservedCommit = fmt.Sprintf("%s@%s", tt.lastRevTag, git.Hash(lc).Digest())
}
cc, err := ggc.Clone(context.TODO(), path, opts)
if tt.expectErr != "" {
g.Expect(err).ToNot(BeNil())
g.Expect(err.Error()).To(ContainSubstring(tt.expectErr))
g.Expect(cc).To(BeNil())
return
}
// Check successful checkout results.
g.Expect(git.IsConcreteCommit(*cc)).To(Equal(tt.expectConcreteCommit))
targetTagHash := tagCommits[tt.checkoutTag]
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc.String()).To(Equal(tt.checkoutTag + "@" + git.HashTypeSHA1 + ":" + targetTagHash))
// Check file content only when there's an actual checkout.
if tt.lastRevTag != tt.checkoutTag {
g.Expect(filepath.Join(tmpDir, "tag")).To(BeARegularFile())
g.Expect(os.ReadFile(filepath.Join(tmpDir, "tag"))).To(BeEquivalentTo(tt.checkoutTag))
}
})
}
}
func TestClone_cloneCommit(t *testing.T) {
repo, path, err := initRepo(t.TempDir())
if err != nil {
t.Fatal(err)
}
firstCommit, err := commitFile(repo, "commit", "init", time.Now())
if err != nil {
t.Fatal(err)
}
if err = createBranch(repo, "other-branch"); err != nil {
t.Fatal(err)
}
secondCommit, err := commitFile(repo, "commit", "second", time.Now())
if err != nil {
t.Fatal(err)
}
tests := []struct {
name string
commit string
branch string
expectCommit string
expectFile string
expectError string
}{
{
name: "Commit",
commit: firstCommit.String(),
expectCommit: git.HashTypeSHA1 + ":" + firstCommit.String(),
expectFile: "init",
},
{
name: "Commit in specific branch",
commit: secondCommit.String(),
branch: "other-branch",
expectCommit: "other-branch@" + git.HashTypeSHA1 + ":" + secondCommit.String(),
expectFile: "second",
},
{
name: "Non existing commit",
commit: "a-random-invalid-commit",
expectError: "unable to resolve commit object for 'a-random-invalid-commit': object not found",
},
{
name: "Non existing commit in specific branch",
commit: secondCommit.String(),
branch: "master",
expectError: "object not found",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
tmpDir := t.TempDir()
opts := repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Branch: tt.branch,
Commit: tt.commit,
},
ShallowClone: true,
}
ggc, err := NewClient(tmpDir, nil)
g.Expect(err).ToNot(HaveOccurred())
cc, err := ggc.Clone(context.TODO(), path, opts)
if tt.expectError != "" {
g.Expect(err).To(HaveOccurred())
g.Expect(err.Error()).To(ContainSubstring(tt.expectError))
g.Expect(cc).To(BeNil())
return
}
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc).ToNot(BeNil())
g.Expect(cc.String()).To(Equal(tt.expectCommit))
g.Expect(filepath.Join(tmpDir, "commit")).To(BeARegularFile())
g.Expect(os.ReadFile(filepath.Join(tmpDir, "commit"))).To(BeEquivalentTo(tt.expectFile))
})
}
}
func TestClone_cloneSemVer(t *testing.T) {
now := time.Now()
tags := []struct {
tag string
annotated bool
commitTime time.Time
tagTime time.Time
}{
{
tag: "v0.0.1",
annotated: false,
commitTime: now,
},
{
tag: "v0.1.0+build-1",
annotated: true,
commitTime: now.Add(10 * time.Minute),
tagTime: now.Add(2 * time.Hour), // This should be ignored during TS comparisons
},
{
tag: "v0.1.0+build-2",
annotated: false,
commitTime: now.Add(30 * time.Minute),
},
{
tag: "v0.1.0+build-3",
annotated: true,
commitTime: now.Add(1 * time.Hour),
tagTime: now.Add(1 * time.Hour), // This should be ignored during TS comparisons
},
{
tag: "0.2.0",
annotated: true,
commitTime: now,
tagTime: now,
},
}
tests := []struct {
name string
constraint string
expectErr error
expectTag string
}{
{
name: "Orders by SemVer",
constraint: ">0.1.0",
expectTag: "0.2.0",
},
{
name: "Orders by SemVer and timestamp",
constraint: "<0.2.0",
expectTag: "v0.1.0+build-3",
},
{
name: "Errors without match",
constraint: ">=1.0.0",
expectErr: errors.New("no match found for semver: >=1.0.0"),
},
}
repo, path, err := initRepo(t.TempDir())
if err != nil {
t.Fatal(err)
}
refs := make(map[string]string, len(tags))
for _, tt := range tags {
ref, err := commitFile(repo, "tag", tt.tag, tt.commitTime)
if err != nil {
t.Fatal(err)
}
_, err = tag(repo, ref, tt.annotated, tt.tag, tt.tagTime)
if err != nil {
t.Fatal(err)
}
refs[tt.tag] = ref.String()
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
tmpDir := t.TempDir()
ggc, err := NewClient(tmpDir, nil)
g.Expect(err).ToNot(HaveOccurred())
opts := repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
SemVer: tt.constraint,
},
ShallowClone: true,
}
cc, err := ggc.Clone(context.TODO(), path, opts)
if tt.expectErr != nil {
g.Expect(err).To(Equal(tt.expectErr))
g.Expect(cc).To(BeNil())
return
}
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc.String()).To(Equal(tt.expectTag + "@" + git.HashTypeSHA1 + ":" + refs[tt.expectTag]))
g.Expect(filepath.Join(tmpDir, "tag")).To(BeARegularFile())
g.Expect(os.ReadFile(filepath.Join(tmpDir, "tag"))).To(BeEquivalentTo(tt.expectTag))
})
}
}
func TestClone_cloneRefName(t *testing.T) {
g := NewWithT(t)
server, err := gittestserver.NewTempGitServer()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(server.Root())
err = server.StartHTTP()
g.Expect(err).ToNot(HaveOccurred())
defer server.StopHTTP()
repoPath := "test.git"
err = server.InitRepo("../testdata/git/repo", git.DefaultBranch, repoPath)
g.Expect(err).ToNot(HaveOccurred())
repoURL := server.HTTPAddress() + "/" + repoPath
repo, err := extgogit.PlainClone(t.TempDir(), false, &extgogit.CloneOptions{
URL: repoURL,
})
g.Expect(err).ToNot(HaveOccurred())
// head is the current HEAD on master
head, err := repo.Head()
g.Expect(err).ToNot(HaveOccurred())
err = createBranch(repo, "test")
g.Expect(err).ToNot(HaveOccurred())
err = repo.Push(&extgogit.PushOptions{})
g.Expect(err).ToNot(HaveOccurred())
// create a new branch for testing tags in order to avoid disturbing the state
// of the current branch that's used for testing branches later.
err = createBranch(repo, "tag-testing")
g.Expect(err).ToNot(HaveOccurred())
hash, err := commitFile(repo, "bar.txt", "this is the way", time.Now())
g.Expect(err).ToNot(HaveOccurred())
err = repo.Push(&extgogit.PushOptions{})
g.Expect(err).ToNot(HaveOccurred())
_, err = tag(repo, hash, true, "v0.1.0", time.Now())
g.Expect(err).ToNot(HaveOccurred())
err = repo.Push(&extgogit.PushOptions{
RefSpecs: []config.RefSpec{
config.RefSpec("+refs/tags/v0.1.0" + ":refs/tags/v0.1.0"),
},
})
g.Expect(err).ToNot(HaveOccurred())
// set a custom reference, in the format of GitHub PRs.
err = repo.Storer.SetReference(plumbing.NewHashReference(plumbing.ReferenceName("/refs/pull/1/head"), hash))
g.Expect(err).ToNot(HaveOccurred())
err = repo.Push(&extgogit.PushOptions{
RefSpecs: []config.RefSpec{
config.RefSpec("+refs/pull/1/head" + ":refs/pull/1/head"),
},
})
g.Expect(err).ToNot(HaveOccurred())
tests := []struct {
name string
refName string
filesCreated map[string]string
lastRevision string
expectedCommit string
expectedConcreteCommit bool
expectedErr string
}{
{
name: "ref name pointing to a branch",
refName: "refs/heads/master",
filesCreated: map[string]string{"foo.txt": "test file\n"},
expectedCommit: head.Hash().String(),
expectedConcreteCommit: true,
},
{
name: "skip clone if LastRevision is unchanged",
refName: "refs/heads/master",
lastRevision: "refs/heads/master" + "@" + git.HashTypeSHA1 + ":" + head.Hash().String(),
expectedCommit: head.Hash().String(),
expectedConcreteCommit: false,
},
{
name: "skip clone if LastRevision is unchanged even if the reference changes",
refName: "refs/heads/test",
lastRevision: "refs/heads/test" + "@" + git.HashTypeSHA1 + ":" + head.Hash().String(),
expectedCommit: head.Hash().String(),
expectedConcreteCommit: false,
},
{
name: "ref name pointing to a tag",
refName: "refs/tags/v0.1.0",
filesCreated: map[string]string{"bar.txt": "this is the way"},
lastRevision: "refs/heads/test" + "@" + git.HashTypeSHA1 + ":" + head.Hash().String(),
expectedCommit: hash.String(),
expectedConcreteCommit: true,
},
{
name: "ref name with dereference suffix pointing to a tag",
refName: "refs/tags/v0.1.0" + tagDereferenceSuffix,
filesCreated: map[string]string{"bar.txt": "this is the way"},
lastRevision: "refs/heads/test" + "@" + git.HashTypeSHA1 + ":" + head.Hash().String(),
expectedCommit: hash.String(),
expectedConcreteCommit: true,
},
{
name: "ref name pointing to a pull request",
refName: "refs/pull/1/head",
filesCreated: map[string]string{"bar.txt": "this is the way"},
expectedCommit: hash.String(),
expectedConcreteCommit: true,
},
{
name: "non existing ref",
refName: "refs/tags/v0.2.0",
expectedErr: "unable to resolve ref 'refs/tags/v0.2.0' to a specific commit",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
tmpDir := t.TempDir()
ggc, err := NewClient(tmpDir, &git.AuthOptions{Transport: git.HTTP})
g.Expect(err).ToNot(HaveOccurred())
cc, err := ggc.Clone(context.TODO(), repoURL, repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
RefName: tt.refName,
},
LastObservedCommit: tt.lastRevision,
})
if tt.expectedErr != "" {
g.Expect(err).To(HaveOccurred())
g.Expect(err.Error()).To(ContainSubstring(tt.expectedErr))
g.Expect(cc).To(BeNil())
return
}
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc.AbsoluteReference()).To(Equal(tt.refName + "@" + git.HashTypeSHA1 + ":" + tt.expectedCommit))
g.Expect(git.IsConcreteCommit(*cc)).To(Equal(tt.expectedConcreteCommit))
for k, v := range tt.filesCreated {
g.Expect(filepath.Join(tmpDir, k)).To(BeARegularFile())
content, err := os.ReadFile(filepath.Join(tmpDir, k))
g.Expect(err).ToNot(HaveOccurred())
g.Expect(string(content)).To(Equal(v))
}
})
}
}
func Test_cloneSubmodule(t *testing.T) {
g := NewWithT(t)
server, err := gittestserver.NewTempGitServer()
g.Expect(err).ToNot(HaveOccurred())
defer os.RemoveAll(server.Root())
err = server.StartHTTP()
g.Expect(err).ToNot(HaveOccurred())
defer server.StopHTTP()
baseRepoPath := "base.git"
err = server.InitRepo("../testdata/git/repo", git.DefaultBranch, baseRepoPath)
g.Expect(err).ToNot(HaveOccurred())
icingRepoPath := "icing.git"
err = server.InitRepo("../testdata/git/repo2", git.DefaultBranch, icingRepoPath)
g.Expect(err).ToNot(HaveOccurred())
tmp := t.TempDir()
icingRepo, err := extgogit.PlainClone(tmp, false, &extgogit.CloneOptions{
URL: server.HTTPAddress() + "/" + icingRepoPath,
ReferenceName: plumbing.NewBranchReferenceName(git.DefaultBranch),
Tags: extgogit.NoTags,
})
g.Expect(err).ToNot(HaveOccurred())
cmd := exec.Command("git", "submodule", "add", fmt.Sprintf("%s/%s", server.HTTPAddress(), baseRepoPath))
cmd.Dir = tmp
_, err = cmd.Output()
g.Expect(err).ToNot(HaveOccurred())
wt, err := icingRepo.Worktree()
g.Expect(err).ToNot(HaveOccurred())
_, err = wt.Add(".gitmodules")
g.Expect(err).ToNot(HaveOccurred())
_, err = wt.Commit("submod", &extgogit.CommitOptions{
Author: &object.Signature{
Name: "test user",
},
})
g.Expect(err).ToNot(HaveOccurred())
err = icingRepo.Push(&extgogit.PushOptions{})
g.Expect(err).ToNot(HaveOccurred())
tmpDir := t.TempDir()
ggc, err := NewClient(tmpDir, &git.AuthOptions{
Transport: git.HTTP,
})
g.Expect(err).ToNot(HaveOccurred())
_, err = ggc.Clone(context.TODO(), server.HTTPAddress()+"/"+icingRepoPath, repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Branch: "master",
},
ShallowClone: true,
RecurseSubmodules: true,
})
expectedPaths := []string{"base", "base/foo.txt", "bar.txt", "."}
var c int
filepath.Walk(tmpDir, func(path string, d iofs.FileInfo, err error) error {
if err != nil {
return err
}
if strings.Contains(path, ".git") {
return nil
}
rel, err := filepath.Rel(tmpDir, path)
if err != nil {
return err
}
for _, expectedPath := range expectedPaths {
if rel == expectedPath {
c += 1
}
}
return nil
})
g.Expect(c).To(Equal(len(expectedPaths)))
}
// Test_ssh_KeyTypes assures support for the different types of keys
// for SSH Authentication supported by Flux.
func Test_ssh_KeyTypes(t *testing.T) {
tests := []struct {
name string
keyType ssh.KeyPairType
authorized bool
wantErr string
}{
{name: "RSA 4096", keyType: ssh.RSA_4096, authorized: true},
{name: "ECDSA P256", keyType: ssh.ECDSA_P256, authorized: true},
{name: "ECDSA P384", keyType: ssh.ECDSA_P384, authorized: true},
{name: "ECDSA P521", keyType: ssh.ECDSA_P521, authorized: true},
{name: "ED25519", keyType: ssh.ED25519, authorized: true},
{name: "unauthorized key", keyType: ssh.RSA_4096, wantErr: "unable to authenticate, attempted methods [none publickey], no supported methods remain"},
}
serverRootDir := t.TempDir()
server := gittestserver.NewGitServer(serverRootDir)
// Auth needs to be called, for authentication to be enabled.
server.Auth("", "")
var authorizedPublicKey string
server.PublicKeyLookupFunc(func(content string) (*gitkit.PublicKey, error) {
authedKey := strings.TrimSuffix(string(authorizedPublicKey), "\n")
if authedKey == content {
return &gitkit.PublicKey{Content: content}, nil
}
return nil, fmt.Errorf("pubkey provided '%s' does not match %s", content, authedKey)
})
g := NewWithT(t)
timeout := 5 * time.Second
server.KeyDir(filepath.Join(server.Root(), "keys"))
g.Expect(server.ListenSSH()).To(Succeed())
go func() {
server.StartSSH()
}()
defer server.StopSSH()
repoPath := "test.git"
err := server.InitRepo(testRepositoryPath, git.DefaultBranch, repoPath)
g.Expect(err).NotTo(HaveOccurred())
sshURL := server.SSHAddress()
repoURL := sshURL + "/" + repoPath
// Fetch host key.
u, err := url.Parse(sshURL)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(u.Host).ToNot(BeEmpty())
knownHosts, err := ssh.ScanHostKey(u.Host, timeout, git.HostKeyAlgos, false)
g.Expect(err).ToNot(HaveOccurred())
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
// Generate ssh keys based on key type.
kp, err := ssh.GenerateKeyPair(tt.keyType)
g.Expect(err).ToNot(HaveOccurred())
// Update authorized key to ensure only the new key is valid on the server.
if tt.authorized {
authorizedPublicKey = string(kp.PublicKey)
}
authOpts := git.AuthOptions{
Transport: git.SSH,
Identity: kp.PrivateKey,
KnownHosts: knownHosts,
}
tmpDir := t.TempDir()
ctx, cancel := context.WithTimeout(context.TODO(), timeout)
defer cancel()
// Checkout the repo.
ggc, err := NewClient(tmpDir, &authOpts)
g.Expect(err).ToNot(HaveOccurred())
cc, err := ggc.Clone(ctx, repoURL, repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Branch: git.DefaultBranch,
},
ShallowClone: true,
})
if tt.wantErr == "" {
g.Expect(err).ToNot(HaveOccurred())
g.Expect(cc).ToNot(BeNil())
// Confirm checkout actually happened.
d, err := os.ReadDir(tmpDir)
g.Expect(err).ToNot(HaveOccurred())
g.Expect(d).To(HaveLen(2)) // .git and foo.txt
} else {
g.Expect(err).To(HaveOccurred())
g.Expect(err.Error()).Should(ContainSubstring(tt.wantErr))
}
})
}
}
// Test_ssh_KeyExchangeAlgos assures support for the different
// types of SSH key exchange algorithms supported by Flux.
func Test_ssh_KeyExchangeAlgos(t *testing.T) {
tests := []struct {
name string
ClientKex []string
ServerKex []string
wantErr string
}{
{
name: "support for kex: diffie-hellman-group14-sha1",
ClientKex: []string{"diffie-hellman-group14-sha1"},
ServerKex: []string{"diffie-hellman-group14-sha1"},
},
{
name: "support for kex: diffie-hellman-group14-sha256",
ClientKex: []string{"diffie-hellman-group14-sha256"},
ServerKex: []string{"diffie-hellman-group14-sha256"},
},
{
name: "support for kex: curve25519-sha256",
ClientKex: []string{"curve25519-sha256"},
ServerKex: []string{"curve25519-sha256"},
},
{
name: "support for kex: ecdh-sha2-nistp256",
ClientKex: []string{"ecdh-sha2-nistp256"},
ServerKex: []string{"ecdh-sha2-nistp256"},
},
{
name: "support for kex: ecdh-sha2-nistp384",
ClientKex: []string{"ecdh-sha2-nistp384"},
ServerKex: []string{"ecdh-sha2-nistp384"},
},
{
name: "support for kex: ecdh-sha2-nistp521",
ClientKex: []string{"ecdh-sha2-nistp521"},
ServerKex: []string{"ecdh-sha2-nistp521"},
},
{
name: "support for kex: curve25519-sha256@libssh.org",
ClientKex: []string{"curve25519-sha256@libssh.org"},
ServerKex: []string{"curve25519-sha256@libssh.org"},
},
{
name: "non-matching kex",
ClientKex: []string{"ecdh-sha2-nistp521"},
ServerKex: []string{"curve25519-sha256@libssh.org"},
wantErr: "ssh: no common algorithm for key exchange; client offered: [ecdh-sha2-nistp521 ext-info-c], server offered: [curve25519-sha256@libssh.org]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := NewWithT(t)
timeout := 5 * time.Second
serverRootDir := t.TempDir()
server := gittestserver.NewGitServer(serverRootDir).WithSSHConfig(&cryptossh.ServerConfig{
Config: cryptossh.Config{
KeyExchanges: tt.ServerKex,
},
})
// Set what Client Key Exchange Algos to send
git.KexAlgos = tt.ClientKex
server.KeyDir(filepath.Join(server.Root(), "keys"))
g.Expect(server.ListenSSH()).To(Succeed())
go func() {
server.StartSSH()
}()
defer server.StopSSH()
repoPath := "test.git"
err := server.InitRepo(testRepositoryPath, git.DefaultBranch, repoPath)
g.Expect(err).NotTo(HaveOccurred())
sshURL := server.SSHAddress()
repoURL := sshURL + "/" + repoPath
// Fetch host key.
u, err := url.Parse(sshURL)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(u.Host).ToNot(BeEmpty())
knownHosts, err := ssh.ScanHostKey(u.Host, timeout, git.HostKeyAlgos, false)
g.Expect(err).ToNot(HaveOccurred())
// No authentication is required for this test, but it is
// used here to make the Checkout logic happy.
kp, err := ssh.GenerateKeyPair(ssh.ED25519)
g.Expect(err).ToNot(HaveOccurred())
authOpts := git.AuthOptions{
Transport: git.SSH,
Identity: kp.PrivateKey,
KnownHosts: knownHosts,
}
tmpDir := t.TempDir()
ctx, cancel := context.WithTimeout(context.TODO(), timeout)
defer cancel()
ggc, err := NewClient(tmpDir, &authOpts)
g.Expect(err).ToNot(HaveOccurred())
_, err = ggc.Clone(ctx, repoURL, repository.CloneConfig{
CheckoutStrategy: repository.CheckoutStrategy{
Branch: git.DefaultBranch,
},
ShallowClone: true,
})
if tt.wantErr != "" {
g.Expect(err).Error().Should(HaveOccurred())
g.Expect(err.Error()).Should(ContainSubstring(tt.wantErr))
} else {
g.Expect(err).Error().ShouldNot(HaveOccurred())
}
})
}
}
// Test_ssh_HostKeyAlgos assures support for the different
// types of SSH Host Key algorithms supported by Flux.
func Test_ssh_HostKeyAlgos(t *testing.T) {
tests := []struct {
name string
keyType ssh.KeyPairType
ClientHostKeyAlgos []string
hashHostNames bool
}{
{
name: "support for hostkey: ssh-rsa",
keyType: ssh.RSA_4096,
ClientHostKeyAlgos: []string{"ssh-rsa"},
},
{
name: "support for hostkey: rsa-sha2-256",
keyType: ssh.RSA_4096,
ClientHostKeyAlgos: []string{"rsa-sha2-256"},
},
{
name: "support for hostkey: rsa-sha2-512",
keyType: ssh.RSA_4096,
ClientHostKeyAlgos: []string{"rsa-sha2-512"},
},
{
name: "support for hostkey: ecdsa-sha2-nistp256",
keyType: ssh.ECDSA_P256,
ClientHostKeyAlgos: []string{"ecdsa-sha2-nistp256"},
},
{
name: "support for hostkey: ecdsa-sha2-nistp384",
keyType: ssh.ECDSA_P384,
ClientHostKeyAlgos: []string{"ecdsa-sha2-nistp384"},
},
{
name: "support for hostkey: ecdsa-sha2-nistp521",
keyType: ssh.ECDSA_P521,