/
repository_test.go
1997 lines (1729 loc) · 70.6 KB
/
repository_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
package repository
import (
"context"
"encoding/json"
"errors"
"fmt"
goio "io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/ghodss/yaml"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
argoappv1 "github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/reposerver/apiclient"
"github.com/argoproj/argo-cd/v2/reposerver/cache"
"github.com/argoproj/argo-cd/v2/reposerver/metrics"
fileutil "github.com/argoproj/argo-cd/v2/test/fixture/path"
"github.com/argoproj/argo-cd/v2/util/argo"
cacheutil "github.com/argoproj/argo-cd/v2/util/cache"
"github.com/argoproj/argo-cd/v2/util/git"
gitmocks "github.com/argoproj/argo-cd/v2/util/git/mocks"
"github.com/argoproj/argo-cd/v2/util/helm"
helmmocks "github.com/argoproj/argo-cd/v2/util/helm/mocks"
"github.com/argoproj/argo-cd/v2/util/io"
)
const testSignature = `gpg: Signature made Wed Feb 26 23:22:34 2020 CET
gpg: using RSA key 4AEE18F83AFDEB23
gpg: Good signature from "GitHub (web-flow commit signing) <noreply@github.com>" [ultimate]
`
type clientFunc func(*gitmocks.Client)
func newServiceWithMocks(root string, signed bool) (*Service, *gitmocks.Client) {
root, err := filepath.Abs(root)
if err != nil {
panic(err)
}
return newServiceWithOpt(func(gitClient *gitmocks.Client) {
gitClient.On("Init").Return(nil)
gitClient.On("Fetch", mock.Anything).Return(nil)
gitClient.On("Checkout", mock.Anything, mock.Anything).Return(nil)
gitClient.On("LsRemote", mock.Anything).Return(mock.Anything, nil)
gitClient.On("CommitSHA").Return(mock.Anything, nil)
gitClient.On("Root").Return(root)
if signed {
gitClient.On("VerifyCommitSignature", mock.Anything).Return(testSignature, nil)
} else {
gitClient.On("VerifyCommitSignature", mock.Anything).Return("", nil)
}
})
}
func newServiceWithOpt(cf clientFunc) (*Service, *gitmocks.Client) {
helmClient := &helmmocks.Client{}
gitClient := &gitmocks.Client{}
cf(gitClient)
service := NewService(metrics.NewMetricsServer(), cache.NewCache(
cacheutil.NewCache(cacheutil.NewInMemoryCache(1*time.Minute)),
1*time.Minute,
1*time.Minute,
), RepoServerInitConstants{ParallelismLimit: 1}, argo.NewResourceTracking(), &git.NoopCredsStore{}, os.TempDir())
chart := "my-chart"
version := "1.1.0"
helmClient.On("GetIndex", true).Return(&helm.Index{Entries: map[string]helm.Entries{
chart: {{Version: "1.0.0"}, {Version: version}},
}}, nil)
helmClient.On("ExtractChart", chart, version).Return("./testdata/my-chart", io.NopCloser, nil)
helmClient.On("CleanChartCache", chart, version).Return(nil)
service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, prosy string, opts ...git.ClientOpts) (client git.Client, e error) {
return gitClient, nil
}
service.newHelmClient = func(repoURL string, creds helm.Creds, enableOci bool, proxy string, opts ...helm.ClientOpts) helm.Client {
return helmClient
}
service.gitRepoInitializer = func(rootPath string) goio.Closer {
return io.NopCloser
}
return service, gitClient
}
func newService(root string) *Service {
service, _ := newServiceWithMocks(root, false)
return service
}
func newServiceWithSignature(root string) *Service {
service, _ := newServiceWithMocks(root, true)
return service
}
func newServiceWithCommitSHA(root, revision string) *Service {
var revisionErr error
commitSHARegex := regexp.MustCompile("^[0-9A-Fa-f]{40}$")
if !commitSHARegex.MatchString(revision) {
revisionErr = errors.New("not a commit SHA")
}
service, gitClient := newServiceWithOpt(func(gitClient *gitmocks.Client) {
gitClient.On("Init").Return(nil)
gitClient.On("Fetch", mock.Anything).Return(nil)
gitClient.On("Checkout", mock.Anything, mock.Anything).Return(nil)
gitClient.On("LsRemote", revision).Return(revision, revisionErr)
gitClient.On("CommitSHA").Return("632039659e542ed7de0c170a4fcc1c571b288fc0", nil)
gitClient.On("Root").Return(root)
})
service.newGitClient = func(rawRepoURL string, root string, creds git.Creds, insecure bool, enableLfs bool, proxy string, opts ...git.ClientOpts) (client git.Client, e error) {
return gitClient, nil
}
return service
}
func TestGenerateYamlManifestInDir(t *testing.T) {
service := newService("../..")
src := argoappv1.ApplicationSource{Path: "manifests/base"}
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src}
// update this value if we add/remove manifests
const countOfManifests = 47
res1, err := service.GenerateManifest(context.Background(), &q)
assert.NoError(t, err)
assert.Equal(t, countOfManifests, len(res1.Manifests))
// this will test concatenated manifests to verify we split YAMLs correctly
res2, err := GenerateManifests(context.Background(), "./testdata/concatenated", "/", "", &q, false, &git.NoopCredsStore{})
assert.NoError(t, err)
assert.Equal(t, 3, len(res2.Manifests))
}
func Test_GenerateManifests_NoOutOfBoundsAccess(t *testing.T) {
testCases := []struct {
name string
outOfBoundsFilename string
outOfBoundsFileContents string
mustNotContain string // Optional string that must not appear in error or manifest output. If empty, use outOfBoundsFileContents.
}{
{
name: "out of bounds JSON file should not appear in error output",
outOfBoundsFilename: "test.json",
outOfBoundsFileContents: `{"some": "json"}`,
},
{
name: "malformed JSON file contents should not appear in error output",
outOfBoundsFilename: "test.json",
outOfBoundsFileContents: "$",
},
{
name: "out of bounds JSON manifest should not appear in manifest output",
outOfBoundsFilename: "test.json",
// JSON marshalling is deterministic. So if there's a leak, exactly this should appear in the manifests.
outOfBoundsFileContents: `{"apiVersion":"v1","kind":"Secret","metadata":{"name":"test","namespace":"default"},"type":"Opaque"}`,
},
{
name: "out of bounds YAML manifest should not appear in manifest output",
outOfBoundsFilename: "test.yaml",
outOfBoundsFileContents: "apiVersion: v1\nkind: Secret\nmetadata:\n name: test\n namespace: default\ntype: Opaque",
mustNotContain: `{"apiVersion":"v1","kind":"Secret","metadata":{"name":"test","namespace":"default"},"type":"Opaque"}`,
},
}
for _, testCase := range testCases {
testCaseCopy := testCase
t.Run(testCaseCopy.name, func(t *testing.T) {
t.Parallel()
outOfBoundsDir := t.TempDir()
outOfBoundsFile := path.Join(outOfBoundsDir, testCaseCopy.outOfBoundsFilename)
err := os.WriteFile(outOfBoundsFile, []byte(testCaseCopy.outOfBoundsFileContents), os.FileMode(0444))
require.NoError(t, err)
repoDir := t.TempDir()
err = os.Symlink(outOfBoundsFile, path.Join(repoDir, testCaseCopy.outOfBoundsFilename))
require.NoError(t, err)
var mustNotContain = testCaseCopy.outOfBoundsFileContents
if testCaseCopy.mustNotContain != "" {
mustNotContain = testCaseCopy.mustNotContain
}
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &argoappv1.ApplicationSource{}}
res, err := GenerateManifests(context.Background(), repoDir, "", "", &q, false, &git.NoopCredsStore{})
require.Error(t, err)
assert.NotContains(t, err.Error(), mustNotContain)
assert.Contains(t, err.Error(), "illegal filepath")
assert.Nil(t, res)
})
}
}
func TestGenerateManifests_MissingSymlinkDestination(t *testing.T) {
repoDir := t.TempDir()
err := os.Symlink("/obviously/does/not/exist", path.Join(repoDir, "test.yaml"))
require.NoError(t, err)
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &argoappv1.ApplicationSource{}}
_, err = GenerateManifests(context.Background(), repoDir, "", "", &q, false, &git.NoopCredsStore{})
require.NoError(t, err)
}
func TestGenerateManifests_K8SAPIResetCache(t *testing.T) {
service := newService("../..")
src := argoappv1.ApplicationSource{Path: "manifests/base"}
q := apiclient.ManifestRequest{
KubeVersion: "v1.16.0",
Repo: &argoappv1.Repository{}, ApplicationSource: &src,
}
cachedFakeResponse := &apiclient.ManifestResponse{Manifests: []string{"Fake"}}
err := service.cache.SetManifests(mock.Anything, &src, &q, "", "", "", "", &cache.CachedManifestResponse{ManifestResponse: cachedFakeResponse})
assert.NoError(t, err)
res, err := service.GenerateManifest(context.Background(), &q)
assert.NoError(t, err)
assert.Equal(t, cachedFakeResponse, res)
q.KubeVersion = "v1.17.0"
res, err = service.GenerateManifest(context.Background(), &q)
assert.NoError(t, err)
assert.NotEqual(t, cachedFakeResponse, res)
assert.True(t, len(res.Manifests) > 1)
}
func TestGenerateManifests_EmptyCache(t *testing.T) {
service := newService("../..")
src := argoappv1.ApplicationSource{Path: "manifests/base"}
q := apiclient.ManifestRequest{
Repo: &argoappv1.Repository{}, ApplicationSource: &src,
}
err := service.cache.SetManifests(mock.Anything, &src, &q, "", "", "", "", &cache.CachedManifestResponse{ManifestResponse: nil})
assert.NoError(t, err)
res, err := service.GenerateManifest(context.Background(), &q)
assert.NoError(t, err)
assert.True(t, len(res.Manifests) > 0)
}
// ensure we can use a semver constraint range (>= 1.0.0) and get back the correct chart (1.0.0)
func TestHelmManifestFromChartRepo(t *testing.T) {
service := newService(".")
source := &argoappv1.ApplicationSource{Chart: "my-chart", TargetRevision: ">= 1.0.0"}
request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true}
response, err := service.GenerateManifest(context.Background(), request)
assert.NoError(t, err)
assert.NotNil(t, response)
assert.Equal(t, &apiclient.ManifestResponse{
Manifests: []string{"{\"apiVersion\":\"v1\",\"kind\":\"ConfigMap\",\"metadata\":{\"name\":\"my-map\"}}"},
Namespace: "",
Server: "",
Revision: "1.1.0",
SourceType: "Helm",
}, response)
}
func TestGenerateManifestsUseExactRevision(t *testing.T) {
service, gitClient := newServiceWithMocks(".", false)
src := argoappv1.ApplicationSource{Path: "./testdata/recurse", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}}
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src, Revision: "abc"}
res1, err := service.GenerateManifest(context.Background(), &q)
assert.Nil(t, err)
assert.Equal(t, 2, len(res1.Manifests))
assert.Equal(t, gitClient.Calls[0].Arguments[0], "abc")
}
func TestRecurseManifestsInDir(t *testing.T) {
service := newService(".")
src := argoappv1.ApplicationSource{Path: "./testdata/recurse", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}}
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src}
res1, err := service.GenerateManifest(context.Background(), &q)
assert.Nil(t, err)
assert.Equal(t, 2, len(res1.Manifests))
}
func TestInvalidManifestsInDir(t *testing.T) {
service := newService(".")
src := argoappv1.ApplicationSource{Path: "./testdata/invalid-manifests", Directory: &argoappv1.ApplicationSourceDirectory{Recurse: true}}
q := apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: &src}
_, err := service.GenerateManifest(context.Background(), &q)
assert.NotNil(t, err)
}
func TestGenerateJsonnetManifestInDir(t *testing.T) {
service := newService(".")
q := apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/jsonnet",
Directory: &argoappv1.ApplicationSourceDirectory{
Jsonnet: argoappv1.ApplicationSourceJsonnet{
ExtVars: []argoappv1.JsonnetVar{{Name: "extVarString", Value: "extVarString"}, {Name: "extVarCode", Value: "\"extVarCode\"", Code: true}},
TLAs: []argoappv1.JsonnetVar{{Name: "tlaString", Value: "tlaString"}, {Name: "tlaCode", Value: "\"tlaCode\"", Code: true}},
Libs: []string{"testdata/jsonnet/vendor"},
},
},
},
}
res1, err := service.GenerateManifest(context.Background(), &q)
assert.Nil(t, err)
assert.Equal(t, 2, len(res1.Manifests))
}
func TestGenerateJsonnetLibOutside(t *testing.T) {
service := newService(".")
q := apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/jsonnet",
Directory: &argoappv1.ApplicationSourceDirectory{
Jsonnet: argoappv1.ApplicationSourceJsonnet{
Libs: []string{"../../../testdata/jsonnet/vendor"},
},
},
},
}
_, err := service.GenerateManifest(context.Background(), &q)
require.Error(t, err)
require.Contains(t, err.Error(), "value file '../../../testdata/jsonnet/vendor' resolved to outside repository root")
}
func TestManifestGenErrorCacheByNumRequests(t *testing.T) {
// Returns the state of the manifest generation cache, by querying the cache for the previously set result
getRecentCachedEntry := func(service *Service, manifestRequest *apiclient.ManifestRequest) *cache.CachedManifestResponse {
assert.NotNil(t, service)
assert.NotNil(t, manifestRequest)
cachedManifestResponse := &cache.CachedManifestResponse{}
err := service.cache.GetManifests(mock.Anything, manifestRequest.ApplicationSource, manifestRequest, manifestRequest.Namespace, "", manifestRequest.AppLabelKey, manifestRequest.AppName, cachedManifestResponse)
assert.Nil(t, err)
return cachedManifestResponse
}
// Example:
// With repo server (test) parameters:
// - PauseGenerationAfterFailedGenerationAttempts: 2
// - PauseGenerationOnFailureForRequests: 4
// - TotalCacheInvocations: 10
//
// After 2 manifest generation failures in a row, the next 4 manifest generation requests should be cached,
// with the next 2 after that being uncached. Here's how it looks...
//
// request count) result
// --------------------------
// 1) Attempt to generate manifest, fails.
// 2) Second attempt to generate manifest, fails.
// 3) Return cached error attempt from #2
// 4) Return cached error attempt from #2
// 5) Return cached error attempt from #2
// 6) Return cached error attempt from #2. Max response limit hit, so reset cache entry.
// 7) Attempt to generate manifest, fails.
// 8) Attempt to generate manifest, fails.
// 9) Return cached error attempt from #8
// 10) Return cached error attempt from #8
// The same pattern PauseGenerationAfterFailedGenerationAttempts generation attempts, followed by
// PauseGenerationOnFailureForRequests cached responses, should apply for various combinations of
// both parameters.
tests := []struct {
PauseGenerationAfterFailedGenerationAttempts int
PauseGenerationOnFailureForRequests int
TotalCacheInvocations int
}{
{2, 4, 10},
{3, 5, 10},
{1, 2, 5},
}
for _, tt := range tests {
testName := fmt.Sprintf("gen-attempts-%d-pause-%d-total-%d", tt.PauseGenerationAfterFailedGenerationAttempts, tt.PauseGenerationOnFailureForRequests, tt.TotalCacheInvocations)
t.Run(testName, func(t *testing.T) {
service := newService(".")
service.initConstants = RepoServerInitConstants{
ParallelismLimit: 1,
PauseGenerationAfterFailedGenerationAttempts: tt.PauseGenerationAfterFailedGenerationAttempts,
PauseGenerationOnFailureForMinutes: 0,
PauseGenerationOnFailureForRequests: tt.PauseGenerationOnFailureForRequests,
}
totalAttempts := service.initConstants.PauseGenerationAfterFailedGenerationAttempts + service.initConstants.PauseGenerationOnFailureForRequests
for invocationCount := 0; invocationCount < tt.TotalCacheInvocations; invocationCount++ {
adjustedInvocation := invocationCount % totalAttempts
fmt.Printf("%d )-------------------------------------------\n", invocationCount)
manifestRequest := &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
}
res, err := service.GenerateManifest(context.Background(), manifestRequest)
// Verify invariant: res != nil xor err != nil
if err != nil {
assert.True(t, res == nil, "both err and res are non-nil res: %v err: %v", res, err)
} else {
assert.True(t, res != nil, "both err and res are nil")
}
cachedManifestResponse := getRecentCachedEntry(service, manifestRequest)
isCachedError := err != nil && strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix)
if adjustedInvocation < service.initConstants.PauseGenerationAfterFailedGenerationAttempts {
// GenerateManifest should not return cached errors for the first X responses, where X is the FailGenAttempts constants
require.False(t, isCachedError)
require.NotNil(t, cachedManifestResponse)
// nolint:staticcheck
assert.Nil(t, cachedManifestResponse.ManifestResponse)
// nolint:staticcheck
assert.True(t, cachedManifestResponse.FirstFailureTimestamp != 0)
// Internal cache consec failures value should increase with invocations, cached response should stay the same,
// nolint:staticcheck
assert.True(t, cachedManifestResponse.NumberOfConsecutiveFailures == adjustedInvocation+1)
// nolint:staticcheck
assert.True(t, cachedManifestResponse.NumberOfCachedResponsesReturned == 0)
} else {
// GenerateManifest SHOULD return cached errors for the next X responses, where X is the
// PauseGenerationOnFailureForRequests constant
assert.True(t, isCachedError)
require.NotNil(t, cachedManifestResponse)
// nolint:staticcheck
assert.Nil(t, cachedManifestResponse.ManifestResponse)
// nolint:staticcheck
assert.True(t, cachedManifestResponse.FirstFailureTimestamp != 0)
// Internal cache values should update correctly based on number of return cache entries, consecutive failures should stay the same
// nolint:staticcheck
assert.True(t, cachedManifestResponse.NumberOfConsecutiveFailures == service.initConstants.PauseGenerationAfterFailedGenerationAttempts)
// nolint:staticcheck
assert.True(t, cachedManifestResponse.NumberOfCachedResponsesReturned == (adjustedInvocation-service.initConstants.PauseGenerationAfterFailedGenerationAttempts+1))
}
}
})
}
}
func TestManifestGenErrorCacheFileContentsChange(t *testing.T) {
tmpDir := t.TempDir()
service := newService(tmpDir)
service.initConstants = RepoServerInitConstants{
ParallelismLimit: 1,
PauseGenerationAfterFailedGenerationAttempts: 2,
PauseGenerationOnFailureForMinutes: 0,
PauseGenerationOnFailureForRequests: 4,
}
for step := 0; step < 3; step++ {
// step 1) Attempt to generate manifests against invalid helm chart (should return uncached error)
// step 2) Attempt to generate manifest against valid helm chart (should succeed and return valid response)
// step 3) Attempt to generate manifest against invalid helm chart (should return cached value from step 2)
errorExpected := step%2 == 0
// Ensure that the target directory will succeed or fail, so we can verify the cache correctly handles it
err := os.RemoveAll(tmpDir)
assert.NoError(t, err)
err = os.MkdirAll(tmpDir, 0777)
assert.NoError(t, err)
if errorExpected {
// Copy invalid helm chart into temporary directory, ensuring manifest generation will fail
err = fileutil.CopyDir("./testdata/invalid-helm", tmpDir)
assert.NoError(t, err)
} else {
// Copy valid helm chart into temporary directory, ensuring generation will succeed
err = fileutil.CopyDir("./testdata/my-chart", tmpDir)
assert.NoError(t, err)
}
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
},
})
fmt.Println("-", step, "-", res != nil, err != nil, errorExpected)
fmt.Println(" err: ", err)
fmt.Println(" res: ", res)
if step < 2 {
assert.True(t, (err != nil) == errorExpected, "error return value and error expected did not match")
assert.True(t, (res != nil) == !errorExpected, "GenerateManifest return value and expected value did not match")
}
if step == 2 {
assert.NoError(t, err, "error ret val was non-nil on step 3")
assert.NotNil(t, res, "GenerateManifest ret val was nil on step 3")
}
}
}
func TestManifestGenErrorCacheByMinutesElapsed(t *testing.T) {
tests := []struct {
// Test with a range of pause expiration thresholds
PauseGenerationOnFailureForMinutes int
}{
{1}, {2}, {10}, {24 * 60},
}
for _, tt := range tests {
testName := fmt.Sprintf("pause-time-%d", tt.PauseGenerationOnFailureForMinutes)
t.Run(testName, func(t *testing.T) {
service := newService(".")
// Here we simulate the passage of time by overriding the now() function of Service
currentTime := time.Now()
service.now = func() time.Time {
return currentTime
}
service.initConstants = RepoServerInitConstants{
ParallelismLimit: 1,
PauseGenerationAfterFailedGenerationAttempts: 1,
PauseGenerationOnFailureForMinutes: tt.PauseGenerationOnFailureForMinutes,
PauseGenerationOnFailureForRequests: 0,
}
// 1) Put the cache into the failure state
for x := 0; x < 2; x++ {
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
})
assert.True(t, err != nil && res == nil)
// Ensure that the second invocation triggers the cached error state
if x == 1 {
assert.True(t, strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
}
}
// 2) Jump forward X-1 minutes in time, where X is the expiration boundary
currentTime = currentTime.Add(time.Duration(tt.PauseGenerationOnFailureForMinutes-1) * time.Minute)
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
})
// 3) Ensure that the cache still returns a cached copy of the last error
assert.True(t, err != nil && res == nil)
assert.True(t, strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
// 4) Jump forward 2 minutes in time, such that the pause generation time has elapsed and we should return to normal state
currentTime = currentTime.Add(2 * time.Minute)
res, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
})
// 5) Ensure that the service no longer returns a cached copy of the last error
assert.True(t, err != nil && res == nil)
assert.True(t, !strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
})
}
}
func TestManifestGenErrorCacheRespectsNoCache(t *testing.T) {
service := newService(".")
service.initConstants = RepoServerInitConstants{
ParallelismLimit: 1,
PauseGenerationAfterFailedGenerationAttempts: 1,
PauseGenerationOnFailureForMinutes: 0,
PauseGenerationOnFailureForRequests: 4,
}
// 1) Put the cache into the failure state
for x := 0; x < 2; x++ {
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
})
assert.True(t, err != nil && res == nil)
// Ensure that the second invocation is cached
if x == 1 {
assert.True(t, strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
}
}
// 2) Call generateManifest with NoCache enabled
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
NoCache: true,
})
// 3) Ensure that the cache returns a new generation attempt, rather than a previous cached error
assert.True(t, err != nil && res == nil)
assert.True(t, !strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
// 4) Call generateManifest
res, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./testdata/invalid-helm",
},
})
// 5) Ensure that the subsequent invocation, after nocache, is cached
assert.True(t, err != nil && res == nil)
assert.True(t, strings.HasPrefix(err.Error(), cachedManifestGenerationPrefix))
}
func TestGenerateHelmWithValues(t *testing.T) {
service := newService("../..")
res, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"values-production.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.NoError(t, err)
replicasVerified := false
for _, src := range res.Manifests {
obj := unstructured.Unstructured{}
err = json.Unmarshal([]byte(src), &obj)
assert.NoError(t, err)
if obj.GetKind() == "Deployment" && obj.GetName() == "test-redis-slave" {
var dep v1.Deployment
err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &dep)
assert.NoError(t, err)
assert.Equal(t, int32(2), *dep.Spec.Replicas)
replicasVerified = true
}
}
assert.True(t, replicasVerified)
}
func TestHelmWithMissingValueFiles(t *testing.T) {
service := newService("../..")
missingValuesFile := "values-prod-overrides.yaml"
req := &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"values-production.yaml", missingValuesFile},
},
},
}
// Should fail since we're passing a non-existent values file, and error should indicate that
_, err := service.GenerateManifest(context.Background(), req)
assert.Error(t, err)
assert.Contains(t, err.Error(), fmt.Sprintf("%s: no such file or directory", missingValuesFile))
// Should template without error even if defining a non-existent values file
req.ApplicationSource.Helm.IgnoreMissingValueFiles = true
_, err = service.GenerateManifest(context.Background(), req)
assert.NoError(t, err)
}
// The requested value file (`../minio/values.yaml`) is outside the app path (`./util/helm/testdata/redis`), however
// since the requested value is sill under the repo directory (`~/go/src/github.com/argoproj/argo-cd`), it is allowed
func TestGenerateHelmWithValuesDirectoryTraversal(t *testing.T) {
service := newService("../..")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"../minio/values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.NoError(t, err)
// Test the case where the path is "."
service = newService("./testdata/my-chart")
_, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
},
})
assert.NoError(t, err)
}
// This is a Helm first-class app with a values file inside the repo directory
// (`~/go/src/github.com/argoproj/argo-cd/reposerver/repository`), so it is allowed
func TestHelmManifestFromChartRepoWithValueFile(t *testing.T) {
service := newService(".")
source := &argoappv1.ApplicationSource{
Chart: "my-chart",
TargetRevision: ">= 1.0.0",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"./my-chart-values.yaml"},
},
}
request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true}
response, err := service.GenerateManifest(context.Background(), request)
assert.NoError(t, err)
assert.NotNil(t, response)
assert.Equal(t, &apiclient.ManifestResponse{
Manifests: []string{"{\"apiVersion\":\"v1\",\"kind\":\"ConfigMap\",\"metadata\":{\"name\":\"my-map\"}}"},
Namespace: "",
Server: "",
Revision: "1.1.0",
SourceType: "Helm",
}, response)
}
// This is a Helm first-class app with a values file outside the repo directory
// (`~/go/src/github.com/argoproj/argo-cd/reposerver/repository`), so it is not allowed
func TestHelmManifestFromChartRepoWithValueFileOutsideRepo(t *testing.T) {
service := newService(".")
source := &argoappv1.ApplicationSource{
Chart: "my-chart",
TargetRevision: ">= 1.0.0",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"../my-chart-2/my-chart-2-values.yaml"},
},
}
request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true}
_, err := service.GenerateManifest(context.Background(), request)
assert.Error(t, err)
}
func TestHelmManifestFromChartRepoWithValueFileLinks(t *testing.T) {
t.Run("Valid symlink", func(t *testing.T) {
service := newService("../..")
source := &argoappv1.ApplicationSource{
Chart: "my-chart",
TargetRevision: ">= 1.0.0",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"my-chart-link.yaml"},
},
}
request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true}
_, err := service.GenerateManifest(context.Background(), request)
assert.NoError(t, err)
})
t.Run("Symlink pointing to outside", func(t *testing.T) {
service := newService("../..")
source := &argoappv1.ApplicationSource{
Chart: "my-chart",
TargetRevision: ">= 1.0.0",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"my-chart-outside-link.yaml"},
},
}
request := &apiclient.ManifestRequest{Repo: &argoappv1.Repository{}, ApplicationSource: source, NoCache: true}
_, err := service.GenerateManifest(context.Background(), request)
assert.Error(t, err)
assert.Contains(t, err.Error(), "outside repository root")
})
}
func TestGenerateHelmWithURL(t *testing.T) {
service := newService("../..")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"https://raw.githubusercontent.com/argoproj/argocd-example-apps/master/helm-guestbook/values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
HelmOptions: &argoappv1.HelmOptions{ValuesFileSchemes: []string{"https"}},
})
assert.NoError(t, err)
}
// The requested value file (`../../../../../minio/values.yaml`) is outside the repo directory
// (`~/go/src/github.com/argoproj/argo-cd`), so it is blocked
func TestGenerateHelmWithValuesDirectoryTraversalOutsideRepo(t *testing.T) {
t.Run("Values file with relative path pointing outside repo root", func(t *testing.T) {
service := newService("../..")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"../../../../../minio/values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "outside repository root")
})
t.Run("Values file with relative path pointing inside repo root", func(t *testing.T) {
service := newService("./testdata/my-chart")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"../my-chart/my-chart-values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.NoError(t, err)
})
t.Run("Values file with absolute path stays within repo root", func(t *testing.T) {
service := newService("./testdata/my-chart")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"/my-chart-values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.NoError(t, err)
})
t.Run("Values file with absolute path using back-references outside repo root", func(t *testing.T) {
service := newService("./testdata/my-chart")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"/../../../my-chart-values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "outside repository root")
})
t.Run("Remote values file from forbidden protocol", func(t *testing.T) {
service := newService("./testdata/my-chart")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"file://../../../../my-chart-values.yaml"},
Values: `cluster: {slaveCount: 2}`,
},
},
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "is not allowed")
})
t.Run("Remote values file from custom allowed protocol", func(t *testing.T) {
service := newService("./testdata/my-chart")
_, err := service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: ".",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"s3://my-bucket/my-chart-values.yaml"},
},
},
HelmOptions: &argoappv1.HelmOptions{ValuesFileSchemes: []string{"s3"}},
})
assert.Error(t, err)
assert.Contains(t, err.Error(), "s3://my-bucket/my-chart-values.yaml: no such file or directory")
})
}
// File parameter should not allow traversal outside of the repository root
func TestGenerateHelmWithAbsoluteFileParameter(t *testing.T) {
service := newService("../..")
file, err := ioutil.TempFile("", "external-secret.txt")
assert.NoError(t, err)
externalSecretPath := file.Name()
defer func() { _ = os.RemoveAll(externalSecretPath) }()
expectedFileContent, err := ioutil.ReadFile("../../util/helm/testdata/external/external-secret.txt")
assert.NoError(t, err)
err = ioutil.WriteFile(externalSecretPath, expectedFileContent, 0644)
assert.NoError(t, err)
defer file.Close()
_, err = service.GenerateManifest(context.Background(), &apiclient.ManifestRequest{
Repo: &argoappv1.Repository{},
AppName: "test",
ApplicationSource: &argoappv1.ApplicationSource{
Path: "./util/helm/testdata/redis",
Helm: &argoappv1.ApplicationSourceHelm{
ValueFiles: []string{"values-production.yaml"},
Values: `cluster: {slaveCount: 2}`,
FileParameters: []argoappv1.HelmFileParameter{{
Name: "passwordContent",
Path: externalSecretPath,
}},
},
},
})
assert.Error(t, err)
}
// The requested file parameter (`../external/external-secret.txt`) is outside the app path
// (`./util/helm/testdata/redis`), however since the requested value is sill under the repo
// directory (`~/go/src/github.com/argoproj/argo-cd`), it is allowed. It is used as a means of
// providing direct content to a helm chart via a specific key.
func TestGenerateHelmWithFileParameter(t *testing.T) {
service := newService("../..")