-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
settings.go
2022 lines (1850 loc) · 69.3 KB
/
settings.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 settings
import (
"context"
"crypto/rand"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"math/big"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
timeutil "github.com/argoproj/pkg/time"
"github.com/ghodss/yaml"
log "github.com/sirupsen/logrus"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
v1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
v1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"github.com/argoproj/argo-cd/v2/common"
"github.com/argoproj/argo-cd/v2/pkg/apis/application/v1alpha1"
"github.com/argoproj/argo-cd/v2/server/settings/oidc"
"github.com/argoproj/argo-cd/v2/util"
"github.com/argoproj/argo-cd/v2/util/crypto"
"github.com/argoproj/argo-cd/v2/util/kube"
"github.com/argoproj/argo-cd/v2/util/password"
tlsutil "github.com/argoproj/argo-cd/v2/util/tls"
)
// ArgoCDSettings holds in-memory runtime configuration options.
type ArgoCDSettings struct {
// URL is the externally facing URL users will visit to reach Argo CD.
// The value here is used when configuring SSO. Omitting this value will disable SSO.
URL string `json:"url,omitempty"`
// Indicates if status badge is enabled or not.
StatusBadgeEnabled bool `json:"statusBadgeEnable"`
// Indicates if status badge custom root URL should be used.
StatusBadgeRootUrl string `json:"statusBadgeRootUrl,omitempty"`
// DexConfig contains portions of a dex config yaml
DexConfig string `json:"dexConfig,omitempty"`
// OIDCConfigRAW holds OIDC configuration as a raw string
OIDCConfigRAW string `json:"oidcConfig,omitempty"`
// ServerSignature holds the key used to generate JWT tokens.
ServerSignature []byte `json:"serverSignature,omitempty"`
// Certificate holds the certificate/private key for the Argo CD API server.
// If nil, will run insecure without TLS.
Certificate *tls.Certificate `json:"-"`
// CertificateIsExternal indicates whether Certificate was loaded from external secret
CertificateIsExternal bool `json:"-"`
// WebhookGitLabSecret holds the shared secret for authenticating GitHub webhook events
WebhookGitHubSecret string `json:"webhookGitHubSecret,omitempty"`
// WebhookGitLabSecret holds the shared secret for authenticating GitLab webhook events
WebhookGitLabSecret string `json:"webhookGitLabSecret,omitempty"`
// WebhookBitbucketUUID holds the UUID for authenticating Bitbucket webhook events
WebhookBitbucketUUID string `json:"webhookBitbucketUUID,omitempty"`
// WebhookBitbucketServerSecret holds the shared secret for authenticating BitbucketServer webhook events
WebhookBitbucketServerSecret string `json:"webhookBitbucketServerSecret,omitempty"`
// WebhookGogsSecret holds the shared secret for authenticating Gogs webhook events
WebhookGogsSecret string `json:"webhookGogsSecret,omitempty"`
// Secrets holds all secrets in argocd-secret as a map[string]string
Secrets map[string]string `json:"secrets,omitempty"`
// KustomizeBuildOptions is a string of kustomize build parameters
KustomizeBuildOptions string `json:"kustomizeBuildOptions,omitempty"`
// Indicates if anonymous user is enabled or not
AnonymousUserEnabled bool `json:"anonymousUserEnabled,omitempty"`
// Specifies token expiration duration
UserSessionDuration time.Duration `json:"userSessionDuration,omitempty"`
// UiCssURL local or remote path to user-defined CSS to customize ArgoCD UI
UiCssURL string `json:"uiCssURL,omitempty"`
// Content of UI Banner
UiBannerContent string `json:"uiBannerContent,omitempty"`
// URL for UI Banner
UiBannerURL string `json:"uiBannerURL,omitempty"`
// Make Banner permanent and not closeable
UiBannerPermanent bool `json:"uiBannerPermanent,omitempty"`
// Position of UI Banner
UiBannerPosition string `json:"uiBannerPosition,omitempty"`
// PasswordPattern for password regular expression
PasswordPattern string `json:"passwordPattern,omitempty"`
// BinaryUrls contains the URLs for downloading argocd binaries
BinaryUrls map[string]string `json:"binaryUrls,omitempty"`
// InClusterEnabled indicates whether to allow in-cluster server address
InClusterEnabled bool `json:"inClusterEnabled"`
// ServerRBACLogEnforceEnable temporary var indicates whether rbac will be enforced on logs
ServerRBACLogEnforceEnable bool `json:"serverRBACLogEnforceEnable"`
// ExecEnabled indicates whether the UI exec feature is enabled
ExecEnabled bool `json:"execEnabled"`
// ExecShells restricts which shells are allowed for `exec` and in which order they are tried
ExecShells []string `json:"execShells"`
// TrackingMethod defines the resource tracking method to be used
TrackingMethod string `json:"application.resourceTrackingMethod,omitempty"`
// OIDCTLSInsecureSkipVerify determines whether certificate verification is skipped when verifying tokens with the
// configured OIDC provider (either external or the bundled Dex instance). Setting this to `true` will cause JWT
// token verification to pass despite the OIDC provider having an invalid certificate. Only set to `true` if you
// understand the risks.
OIDCTLSInsecureSkipVerify bool `json:"oidcTLSInsecureSkipVerify"`
// AppsInAnyNamespaceEnabled indicates whether applications are allowed to be created in any namespace
AppsInAnyNamespaceEnabled bool `json:"appsInAnyNamespaceEnabled"`
// ExtensionConfig configurations related to ArgoCD proxy extensions. The value
// is a yaml string defined in extension.ExtensionConfigs struct.
ExtensionConfig string `json:"extensionConfig,omitempty"`
}
type GoogleAnalytics struct {
TrackingID string `json:"trackingID,omitempty"`
AnonymizeUsers bool `json:"anonymizeUsers,omitempty"`
}
type GlobalProjectSettings struct {
ProjectName string `json:"projectName,omitempty"`
LabelSelector metav1.LabelSelector `json:"labelSelector,omitempty"`
}
// Help settings
type Help struct {
// the URL for getting chat help, this will typically be your Slack channel for support
ChatURL string `json:"chatUrl,omitempty"`
// the text for getting chat help, defaults to "Chat now!"
ChatText string `json:"chatText,omitempty"`
// the URLs for downloading argocd binaries
BinaryURLs map[string]string `json:"binaryUrl,omitempty"`
}
// oidcConfig is the same as the public OIDCConfig, except the public one excludes the AllowedAudiences and the
// SkipAudienceCheckWhenTokenHasNoAudience fields.
// AllowedAudiences should be accessed via ArgoCDSettings.OAuth2AllowedAudiences.
// SkipAudienceCheckWhenTokenHasNoAudience should be accessed via ArgoCDSettings.SkipAudienceCheckWhenTokenHasNoAudience.
type oidcConfig struct {
OIDCConfig
AllowedAudiences []string `json:"allowedAudiences,omitempty"`
SkipAudienceCheckWhenTokenHasNoAudience *bool `json:"skipAudienceCheckWhenTokenHasNoAudience,omitempty"`
}
func (o *oidcConfig) toExported() *OIDCConfig {
if o == nil {
return nil
}
return &OIDCConfig{
Name: o.Name,
Issuer: o.Issuer,
ClientID: o.ClientID,
ClientSecret: o.ClientSecret,
CLIClientID: o.CLIClientID,
RequestedScopes: o.RequestedScopes,
RequestedIDTokenClaims: o.RequestedIDTokenClaims,
LogoutURL: o.LogoutURL,
RootCA: o.RootCA,
}
}
type OIDCConfig struct {
Name string `json:"name,omitempty"`
Issuer string `json:"issuer,omitempty"`
ClientID string `json:"clientID,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
CLIClientID string `json:"cliClientID,omitempty"`
RequestedScopes []string `json:"requestedScopes,omitempty"`
RequestedIDTokenClaims map[string]*oidc.Claim `json:"requestedIDTokenClaims,omitempty"`
LogoutURL string `json:"logoutURL,omitempty"`
RootCA string `json:"rootCA,omitempty"`
}
// DEPRECATED. Helm repository credentials are now managed using RepoCredentials
type HelmRepoCredentials struct {
URL string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
CertSecret *apiv1.SecretKeySelector `json:"certSecret,omitempty"`
KeySecret *apiv1.SecretKeySelector `json:"keySecret,omitempty"`
}
// KustomizeVersion holds information about additional Kustomize version
type KustomizeVersion struct {
// Name holds Kustomize version name
Name string
// Path holds corresponding binary path
Path string
// BuildOptions that are specific to Kustomize version
BuildOptions string
}
// KustomizeSettings holds kustomize settings
type KustomizeSettings struct {
BuildOptions string
Versions []KustomizeVersion
}
var (
ByClusterURLIndexer = "byClusterURL"
byClusterURLIndexerFunc = func(obj interface{}) ([]string, error) {
s, ok := obj.(*apiv1.Secret)
if !ok {
return nil, nil
}
if s.Labels == nil || s.Labels[common.LabelKeySecretType] != common.LabelValueSecretTypeCluster {
return nil, nil
}
if s.Data == nil {
return nil, nil
}
if url, ok := s.Data["server"]; ok {
return []string{strings.TrimRight(string(url), "/")}, nil
}
return nil, nil
}
ByClusterNameIndexer = "byClusterName"
byClusterNameIndexerFunc = func(obj interface{}) ([]string, error) {
s, ok := obj.(*apiv1.Secret)
if !ok {
return nil, nil
}
if s.Labels == nil || s.Labels[common.LabelKeySecretType] != common.LabelValueSecretTypeCluster {
return nil, nil
}
if s.Data == nil {
return nil, nil
}
if name, ok := s.Data["name"]; ok {
return []string{string(name)}, nil
}
return nil, nil
}
ByProjectClusterIndexer = "byProjectCluster"
ByProjectRepoIndexer = "byProjectRepo"
byProjectIndexerFunc = func(secretType string) func(obj interface{}) ([]string, error) {
return func(obj interface{}) ([]string, error) {
s, ok := obj.(*apiv1.Secret)
if !ok {
return nil, nil
}
if s.Labels == nil || s.Labels[common.LabelKeySecretType] != secretType {
return nil, nil
}
if s.Data == nil {
return nil, nil
}
if project, ok := s.Data["project"]; ok {
return []string{string(project)}, nil
}
return nil, nil
}
}
)
func (ks *KustomizeSettings) GetOptions(source v1alpha1.ApplicationSource) (*v1alpha1.KustomizeOptions, error) {
binaryPath := ""
buildOptions := ""
if source.Kustomize != nil && source.Kustomize.Version != "" {
for _, ver := range ks.Versions {
if ver.Name == source.Kustomize.Version {
// add version specific path and build options
binaryPath = ver.Path
buildOptions = ver.BuildOptions
break
}
}
if binaryPath == "" {
return nil, fmt.Errorf("kustomize version %s is not registered", source.Kustomize.Version)
}
} else {
// add build options for the default version
buildOptions = ks.BuildOptions
}
return &v1alpha1.KustomizeOptions{
BuildOptions: buildOptions,
BinaryPath: binaryPath,
}, nil
}
// Credentials for accessing a Git repository
type Repository struct {
// The URL to the repository
URL string `json:"url,omitempty"`
// the type of the repo, "git" or "helm", assumed to be "git" if empty or absent
Type string `json:"type,omitempty"`
// helm only
Name string `json:"name,omitempty"`
// Name of the secret storing the username used to access the repo
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
// Name of the secret storing the password used to access the repo
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
// Name of the secret storing the SSH private key used to access the repo. Git only
SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"`
// Whether to connect the repository in an insecure way (deprecated)
InsecureIgnoreHostKey bool `json:"insecureIgnoreHostKey,omitempty"`
// Whether to connect the repository in an insecure way
Insecure bool `json:"insecure,omitempty"`
// Whether the repo is git-lfs enabled. Git only.
EnableLFS bool `json:"enableLfs,omitempty"`
// Name of the secret storing the TLS client cert data
TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"`
// Name of the secret storing the TLS client cert's key data
TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"`
// Whether the repo is helm-oci enabled. Git only.
EnableOci bool `json:"enableOci,omitempty"`
// Github App Private Key PEM data
GithubAppPrivateKeySecret *apiv1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"`
// Github App ID of the app used to access the repo
GithubAppId int64 `json:"githubAppID,omitempty"`
// Github App Installation ID of the installed GitHub App
GithubAppInstallationId int64 `json:"githubAppInstallationID,omitempty"`
// Github App Enterprise base url if empty will default to https://api.github.com
GithubAppEnterpriseBaseURL string `json:"githubAppEnterpriseBaseUrl,omitempty"`
// Proxy specifies the HTTP/HTTPS proxy used to access the repo
Proxy string `json:"proxy,omitempty"`
// GCPServiceAccountKey specifies the service account key in JSON format to be used for getting credentials to Google Cloud Source repos
GCPServiceAccountKey *apiv1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"`
// ForceHttpBasicAuth determines whether Argo CD should force use of basic auth for HTTP connected repositories
ForceHttpBasicAuth bool `json:"forceHttpBasicAuth,omitempty"`
}
// Credential template for accessing repositories
type RepositoryCredentials struct {
// The URL pattern the repository URL has to match
URL string `json:"url,omitempty"`
// Name of the secret storing the username used to access the repo
UsernameSecret *apiv1.SecretKeySelector `json:"usernameSecret,omitempty"`
// Name of the secret storing the password used to access the repo
PasswordSecret *apiv1.SecretKeySelector `json:"passwordSecret,omitempty"`
// Name of the secret storing the SSH private key used to access the repo. Git only
SSHPrivateKeySecret *apiv1.SecretKeySelector `json:"sshPrivateKeySecret,omitempty"`
// Name of the secret storing the TLS client cert data
TLSClientCertDataSecret *apiv1.SecretKeySelector `json:"tlsClientCertDataSecret,omitempty"`
// Name of the secret storing the TLS client cert's key data
TLSClientCertKeySecret *apiv1.SecretKeySelector `json:"tlsClientCertKeySecret,omitempty"`
// Github App Private Key PEM data
GithubAppPrivateKeySecret *apiv1.SecretKeySelector `json:"githubAppPrivateKeySecret,omitempty"`
// Github App ID of the app used to access the repo
GithubAppId int64 `json:"githubAppID,omitempty"`
// Github App Installation ID of the installed GitHub App
GithubAppInstallationId int64 `json:"githubAppInstallationID,omitempty"`
// Github App Enterprise base url if empty will default to https://api.github.com
GithubAppEnterpriseBaseURL string `json:"githubAppEnterpriseBaseUrl,omitempty"`
// EnableOCI specifies whether helm-oci support should be enabled for this repo
EnableOCI bool `json:"enableOCI,omitempty"`
// the type of the repositoryCredentials, "git" or "helm", assumed to be "git" if empty or absent
Type string `json:"type,omitempty"`
// GCPServiceAccountKey specifies the service account key in JSON format to be used for getting credentials to Google Cloud Source repos
GCPServiceAccountKey *apiv1.SecretKeySelector `json:"gcpServiceAccountKey,omitempty"`
// ForceHttpBasicAuth determines whether Argo CD should force use of basic auth for HTTP connected repositories
ForceHttpBasicAuth bool `json:"forceHttpBasicAuth,omitempty"`
}
// DeepLink structure
type DeepLink struct {
// URL that the deep link will redirect to
URL string `json:"url"`
// Title that will be displayed in the UI corresponding to that link
Title string `json:"title"`
// Description (optional) a description for what the deep link is about
Description *string `json:"description,omitempty"`
// IconClass (optional) a font-awesome icon class to be used when displaying the links in dropdown menus.
IconClass *string `json:"icon.class,omitempty"`
// Condition (optional) a conditional statement depending on which the deep link shall be rendered
Condition *string `json:"if,omitempty"`
}
const (
// settingServerSignatureKey designates the key for a server secret key inside a Kubernetes secret.
settingServerSignatureKey = "server.secretkey"
// gaTrackingID holds Google Analytics tracking id
gaTrackingID = "ga.trackingid"
// the URL for getting chat help, this will typically be your Slack channel for support
helpChatURL = "help.chatUrl"
// the text for getting chat help, defaults to "Chat now!"
helpChatText = "help.chatText"
// gaAnonymizeUsers specifies if user ids should be anonymized (hashed) before sending to Google Analytics. True unless value is set to 'false'
gaAnonymizeUsers = "ga.anonymizeusers"
// settingServerCertificate designates the key for the public cert used in TLS
settingServerCertificate = "tls.crt"
// settingServerPrivateKey designates the key for the private key used in TLS
settingServerPrivateKey = "tls.key"
// settingURLKey designates the key where Argo CD's external URL is set
settingURLKey = "url"
// repositoriesKey designates the key where ArgoCDs repositories list is set
repositoriesKey = "repositories"
// repositoryCredentialsKey designates the key where ArgoCDs repositories credentials list is set
repositoryCredentialsKey = "repository.credentials"
// helmRepositoriesKey designates the key where list of helm repositories is set
helmRepositoriesKey = "helm.repositories"
// settingDexConfigKey designates the key for the dex config
settingDexConfigKey = "dex.config"
// settingsOIDCConfigKey designates the key for OIDC config
settingsOIDCConfigKey = "oidc.config"
// statusBadgeEnabledKey holds the key which enables of disables status badge feature
statusBadgeEnabledKey = "statusbadge.enabled"
// statusBadgeRootUrlKey holds the key for the root badge URL override
statusBadgeRootUrlKey = "statusbadge.url"
// settingsWebhookGitHubSecret is the key for the GitHub shared webhook secret
settingsWebhookGitHubSecretKey = "webhook.github.secret"
// settingsWebhookGitLabSecret is the key for the GitLab shared webhook secret
settingsWebhookGitLabSecretKey = "webhook.gitlab.secret"
// settingsWebhookBitbucketUUID is the key for Bitbucket webhook UUID
settingsWebhookBitbucketUUIDKey = "webhook.bitbucket.uuid"
// settingsWebhookBitbucketServerSecret is the key for BitbucketServer webhook secret
settingsWebhookBitbucketServerSecretKey = "webhook.bitbucketserver.secret"
// settingsWebhookGogsSecret is the key for Gogs webhook secret
settingsWebhookGogsSecretKey = "webhook.gogs.secret"
// settingsApplicationInstanceLabelKey is the key to configure injected app instance label key
settingsApplicationInstanceLabelKey = "application.instanceLabelKey"
// settingsResourceTrackingMethodKey is the key to configure tracking method for application resources
settingsResourceTrackingMethodKey = "application.resourceTrackingMethod"
// resourcesCustomizationsKey is the key to the map of resource overrides
resourceCustomizationsKey = "resource.customizations"
// resourceExclusions is the key to the list of excluded resources
resourceExclusionsKey = "resource.exclusions"
// resourceInclusions is the key to the list of explicitly watched resources
resourceInclusionsKey = "resource.inclusions"
// resourceCustomLabelKey is the key to a custom label to show in node info, if present
resourceCustomLabelsKey = "resource.customLabels"
// configManagementPluginsKey is the key to the list of config management plugins
configManagementPluginsKey = "configManagementPlugins"
// kustomizeBuildOptionsKey is a string of kustomize build parameters
kustomizeBuildOptionsKey = "kustomize.buildOptions"
// kustomizeVersionKeyPrefix is a kustomize version key prefix
kustomizeVersionKeyPrefix = "kustomize.version"
// kustomizePathPrefixKey is a kustomize path for a specific version
kustomizePathPrefixKey = "kustomize.path"
// anonymousUserEnabledKey is the key which enables or disables anonymous user
anonymousUserEnabledKey = "users.anonymous.enabled"
// userSessionDurationKey is the key which specifies token expiration duration
userSessionDurationKey = "users.session.duration"
// diffOptions is the key where diff options are configured
resourceCompareOptionsKey = "resource.compareoptions"
// settingUiCssURLKey designates the key for user-defined CSS URL for UI customization
settingUiCssURLKey = "ui.cssurl"
// settingUiBannerContentKey designates the key for content of user-defined info banner for UI
settingUiBannerContentKey = "ui.bannercontent"
// settingUiBannerURLKey designates the key for the link for user-defined info banner for UI
settingUiBannerURLKey = "ui.bannerurl"
// settingUiBannerPermanentKey designates the key for whether the banner is permanent and not closeable
settingUiBannerPermanentKey = "ui.bannerpermanent"
// settingUiBannerPositionKey designates the key for the position of the banner
settingUiBannerPositionKey = "ui.bannerposition"
// settingsBinaryUrlsKey designates the key for the argocd binary URLs
settingsBinaryUrlsKey = "help.download"
// globalProjectsKey designates the key for global project settings
globalProjectsKey = "globalProjects"
// initialPasswordSecretName is the name of the secret that will hold the initial admin password
initialPasswordSecretName = "argocd-initial-admin-secret"
// initialPasswordSecretField is the name of the field in initialPasswordSecretName to store the password
initialPasswordSecretField = "password"
// initialPasswordLength defines the length of the generated initial password
initialPasswordLength = 16
// externalServerTLSSecretName defines the name of the external secret holding the server's TLS certificate
externalServerTLSSecretName = "argocd-server-tls"
// partOfArgoCDSelector holds label selector that should be applied to config maps and secrets used to manage Argo CD
partOfArgoCDSelector = "app.kubernetes.io/part-of=argocd"
// settingsPasswordPatternKey is the key to configure user password regular expression
settingsPasswordPatternKey = "passwordPattern"
// inClusterEnabledKey is the key to configure whether to allow in-cluster server address
inClusterEnabledKey = "cluster.inClusterEnabled"
// settingsServerRBACLogEnforceEnable is the key to configure whether logs RBAC enforcement is enabled
settingsServerRBACLogEnforceEnableKey = "server.rbac.log.enforce.enable"
// helmValuesFileSchemesKey is the key to configure the list of supported helm values file schemas
helmValuesFileSchemesKey = "helm.valuesFileSchemes"
// execEnabledKey is the key to configure whether the UI exec feature is enabled
execEnabledKey = "exec.enabled"
// execShellsKey is the key to configure which shells are allowed for `exec` and in what order they are tried
execShellsKey = "exec.shells"
// oidcTLSInsecureSkipVerifyKey is the key to configure whether TLS cert verification is skipped for OIDC connections
oidcTLSInsecureSkipVerifyKey = "oidc.tls.insecure.skip.verify"
// ApplicationDeepLinks is the application deep link key
ApplicationDeepLinks = "application.links"
// ProjectDeepLinks is the project deep link key
ProjectDeepLinks = "project.links"
// ResourceDeepLinks is the resource deep link key
ResourceDeepLinks = "resource.links"
extensionConfig = "extension.config"
)
var (
sourceTypeToEnableGenerationKey = map[v1alpha1.ApplicationSourceType]string{
v1alpha1.ApplicationSourceTypeKustomize: "kustomize.enable",
v1alpha1.ApplicationSourceTypeHelm: "helm.enable",
v1alpha1.ApplicationSourceTypeDirectory: "jsonnet.enable",
}
)
// SettingsManager holds config info for a new manager with which to access Kubernetes ConfigMaps.
type SettingsManager struct {
ctx context.Context
clientset kubernetes.Interface
secrets v1listers.SecretLister
secretsInformer cache.SharedIndexInformer
configmaps v1listers.ConfigMapLister
namespace string
// subscribers is a list of subscribers to settings updates
subscribers []chan<- *ArgoCDSettings
// mutex protects concurrency sensitive parts of settings manager: access to subscribers list and initialization flag
mutex *sync.Mutex
initContextCancel func()
reposCache []Repository
repoCredsCache []RepositoryCredentials
reposOrClusterChanged func()
}
type incompleteSettingsError struct {
message string
}
type IgnoreStatus string
const (
// IgnoreResourceStatusInCRD ignores status changes for all CRDs
IgnoreResourceStatusInCRD IgnoreStatus = "crd"
// IgnoreResourceStatusInAll ignores status changes for all resources
IgnoreResourceStatusInAll IgnoreStatus = "all"
// IgnoreResourceStatusInNone ignores status changes for no resources
IgnoreResourceStatusInNone IgnoreStatus = "off"
)
type ArgoCDDiffOptions struct {
IgnoreAggregatedRoles bool `json:"ignoreAggregatedRoles,omitempty"`
// If set to true then differences caused by status are ignored.
IgnoreResourceStatusField IgnoreStatus `json:"ignoreResourceStatusField,omitempty"`
}
func (e *incompleteSettingsError) Error() string {
return e.message
}
func (mgr *SettingsManager) onRepoOrClusterChanged() {
if mgr.reposOrClusterChanged != nil {
go mgr.reposOrClusterChanged()
}
}
func (mgr *SettingsManager) GetSecretsLister() (v1listers.SecretLister, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
return mgr.secrets, nil
}
func (mgr *SettingsManager) GetSecretsInformer() (cache.SharedIndexInformer, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
return mgr.secretsInformer, nil
}
func (mgr *SettingsManager) updateSecret(callback func(*apiv1.Secret) error) error {
err := mgr.ensureSynced(false)
if err != nil {
return err
}
argoCDSecret, err := mgr.secrets.Secrets(mgr.namespace).Get(common.ArgoCDSecretName)
createSecret := false
if err != nil {
if !apierr.IsNotFound(err) {
return err
}
argoCDSecret = &apiv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDSecretName,
},
Data: make(map[string][]byte),
}
createSecret = true
}
if argoCDSecret.Data == nil {
argoCDSecret.Data = make(map[string][]byte)
}
updatedSecret := argoCDSecret.DeepCopy()
err = callback(updatedSecret)
if err != nil {
return err
}
if !createSecret && reflect.DeepEqual(argoCDSecret.Data, updatedSecret.Data) {
return nil
}
if createSecret {
_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Create(context.Background(), updatedSecret, metav1.CreateOptions{})
} else {
_, err = mgr.clientset.CoreV1().Secrets(mgr.namespace).Update(context.Background(), updatedSecret, metav1.UpdateOptions{})
}
if err != nil {
return err
}
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) updateConfigMap(callback func(*apiv1.ConfigMap) error) error {
argoCDCM, err := mgr.getConfigMap()
createCM := false
if err != nil {
if !apierr.IsNotFound(err) {
return err
}
argoCDCM = &apiv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: common.ArgoCDConfigMapName,
},
}
createCM = true
}
if argoCDCM.Data == nil {
argoCDCM.Data = make(map[string]string)
}
beforeUpdate := argoCDCM.DeepCopy()
err = callback(argoCDCM)
if err != nil {
return err
}
if reflect.DeepEqual(beforeUpdate.Data, argoCDCM.Data) {
return nil
}
if createCM {
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Create(context.Background(), argoCDCM, metav1.CreateOptions{})
} else {
_, err = mgr.clientset.CoreV1().ConfigMaps(mgr.namespace).Update(context.Background(), argoCDCM, metav1.UpdateOptions{})
}
if err != nil {
return err
}
mgr.invalidateCache()
return mgr.ResyncInformers()
}
func (mgr *SettingsManager) getConfigMap() (*apiv1.ConfigMap, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
argoCDCM, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(common.ArgoCDConfigMapName)
if err != nil {
return nil, err
}
if argoCDCM.Data == nil {
argoCDCM.Data = make(map[string]string)
}
return argoCDCM, err
}
// Returns the ConfigMap with the given name from the cluster.
// The ConfigMap must be labeled with "app.kubernetes.io/part-of: argocd" in
// order to be retrievable.
func (mgr *SettingsManager) GetConfigMapByName(configMapName string) (*apiv1.ConfigMap, error) {
err := mgr.ensureSynced(false)
if err != nil {
return nil, err
}
configMap, err := mgr.configmaps.ConfigMaps(mgr.namespace).Get(configMapName)
if err != nil {
return nil, err
}
return configMap, err
}
func (mgr *SettingsManager) GetResourcesFilter() (*ResourcesFilter, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
rf := &ResourcesFilter{}
if value, ok := argoCDCM.Data[resourceInclusionsKey]; ok {
includedResources := make([]FilteredResource, 0)
err := yaml.Unmarshal([]byte(value), &includedResources)
if err != nil {
return nil, err
}
rf.ResourceInclusions = includedResources
}
if value, ok := argoCDCM.Data[resourceExclusionsKey]; ok {
excludedResources := make([]FilteredResource, 0)
err := yaml.Unmarshal([]byte(value), &excludedResources)
if err != nil {
return nil, err
}
rf.ResourceExclusions = excludedResources
}
return rf, nil
}
func (mgr *SettingsManager) GetAppInstanceLabelKey() (string, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return "", err
}
label := argoCDCM.Data[settingsApplicationInstanceLabelKey]
if label == "" {
return common.LabelKeyAppInstance, nil
}
return label, nil
}
func (mgr *SettingsManager) GetTrackingMethod() (string, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return "", err
}
return argoCDCM.Data[settingsResourceTrackingMethodKey], nil
}
func (mgr *SettingsManager) GetPasswordPattern() (string, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return "", err
}
label := argoCDCM.Data[settingsPasswordPatternKey]
if label == "" {
return common.PasswordPatten, nil
}
return label, nil
}
func (mgr *SettingsManager) GetServerRBACLogEnforceEnable() (bool, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return false, err
}
if argoCDCM.Data[settingsServerRBACLogEnforceEnableKey] == "" {
return false, nil
}
return strconv.ParseBool(argoCDCM.Data[settingsServerRBACLogEnforceEnableKey])
}
func (mgr *SettingsManager) GetConfigManagementPlugins() ([]v1alpha1.ConfigManagementPlugin, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
plugins := make([]v1alpha1.ConfigManagementPlugin, 0)
if value, ok := argoCDCM.Data[configManagementPluginsKey]; ok {
err := yaml.Unmarshal([]byte(value), &plugins)
if err != nil {
return nil, err
}
}
return plugins, nil
}
func (mgr *SettingsManager) GetDeepLinks(deeplinkType string) ([]DeepLink, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
deepLinks := make([]DeepLink, 0)
if value, ok := argoCDCM.Data[deeplinkType]; ok {
err := yaml.Unmarshal([]byte(value), &deepLinks)
if err != nil {
return nil, err
}
}
return deepLinks, nil
}
func (mgr *SettingsManager) GetEnabledSourceTypes() (map[string]bool, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
res := map[string]bool{}
for sourceType := range sourceTypeToEnableGenerationKey {
res[string(sourceType)] = true
}
for sourceType, key := range sourceTypeToEnableGenerationKey {
if val, ok := argoCDCM.Data[key]; ok && val != "" {
res[string(sourceType)] = val == "true"
}
}
// plugin based manifest generation cannot be disabled
res[string(v1alpha1.ApplicationSourceTypePlugin)] = true
return res, nil
}
// GetResourceOverrides loads Resource Overrides from argocd-cm ConfigMap
func (mgr *SettingsManager) GetResourceOverrides() (map[string]v1alpha1.ResourceOverride, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
resourceOverrides := map[string]v1alpha1.ResourceOverride{}
if value, ok := argoCDCM.Data[resourceCustomizationsKey]; ok && value != "" {
err := yaml.Unmarshal([]byte(value), &resourceOverrides)
if err != nil {
return nil, err
}
}
err = mgr.appendResourceOverridesFromSplitKeys(argoCDCM.Data, resourceOverrides)
if err != nil {
return nil, err
}
var diffOptions ArgoCDDiffOptions
if value, ok := argoCDCM.Data[resourceCompareOptionsKey]; ok {
err := yaml.Unmarshal([]byte(value), &diffOptions)
if err != nil {
return nil, err
}
}
crdGK := "apiextensions.k8s.io/CustomResourceDefinition"
crdPrsvUnkn := "/spec/preserveUnknownFields"
switch diffOptions.IgnoreResourceStatusField {
case "", "crd":
addStatusOverrideToGK(resourceOverrides, crdGK)
addIgnoreDiffItemOverrideToGK(resourceOverrides, crdGK, crdPrsvUnkn)
case "all":
addStatusOverrideToGK(resourceOverrides, "*/*")
log.Info("Ignore status for all objects")
case "off", "false":
log.Info("Not ignoring status for any object")
default:
addStatusOverrideToGK(resourceOverrides, crdGK)
log.Warnf("Unrecognized value for ignoreResourceStatusField - %s, ignore status for CustomResourceDefinitions", diffOptions.IgnoreResourceStatusField)
}
return resourceOverrides, nil
}
func addStatusOverrideToGK(resourceOverrides map[string]v1alpha1.ResourceOverride, groupKind string) {
if val, ok := resourceOverrides[groupKind]; ok {
val.IgnoreDifferences.JSONPointers = append(val.IgnoreDifferences.JSONPointers, "/status")
resourceOverrides[groupKind] = val
} else {
resourceOverrides[groupKind] = v1alpha1.ResourceOverride{
IgnoreDifferences: v1alpha1.OverrideIgnoreDiff{JSONPointers: []string{"/status"}},
}
}
}
func addIgnoreDiffItemOverrideToGK(resourceOverrides map[string]v1alpha1.ResourceOverride, groupKind, ignoreItem string) {
if val, ok := resourceOverrides[groupKind]; ok {
val.IgnoreDifferences.JSONPointers = append(val.IgnoreDifferences.JSONPointers, ignoreItem)
resourceOverrides[groupKind] = val
} else {
resourceOverrides[groupKind] = v1alpha1.ResourceOverride{
IgnoreDifferences: v1alpha1.OverrideIgnoreDiff{JSONPointers: []string{ignoreItem}},
}
}
}
func (mgr *SettingsManager) appendResourceOverridesFromSplitKeys(cmData map[string]string, resourceOverrides map[string]v1alpha1.ResourceOverride) error {
for k, v := range cmData {
if !strings.HasPrefix(k, resourceCustomizationsKey) {
continue
}
// config map key should be of format resource.customizations.<type>.<group-kind>
parts := strings.SplitN(k, ".", 4)
if len(parts) < 4 {
continue
}
overrideKey, err := convertToOverrideKey(parts[3])
if err != nil {
return err
}
if overrideKey == "all" {
overrideKey = "*/*"
}
overrideVal, ok := resourceOverrides[overrideKey]
if !ok {
overrideVal = v1alpha1.ResourceOverride{}
}
customizationType := parts[2]
switch customizationType {
case "health":
overrideVal.HealthLua = v
case "useOpenLibs":
useOpenLibs, err := strconv.ParseBool(v)
if err != nil {
return err
}
overrideVal.UseOpenLibs = useOpenLibs
case "actions":
overrideVal.Actions = v
case "ignoreDifferences":
overrideIgnoreDiff := v1alpha1.OverrideIgnoreDiff{}
err := yaml.Unmarshal([]byte(v), &overrideIgnoreDiff)
if err != nil {
return err
}
overrideVal.IgnoreDifferences = overrideIgnoreDiff
case "knownTypeFields":
var knownTypeFields []v1alpha1.KnownTypeField
err := yaml.Unmarshal([]byte(v), &knownTypeFields)
if err != nil {
return err
}
overrideVal.KnownTypeFields = knownTypeFields
default:
return fmt.Errorf("resource customization type %s not supported", customizationType)
}
resourceOverrides[overrideKey] = overrideVal
}
return nil
}
// Convert group-kind format to <group/kind>, allowed key format examples
// resource.customizations.health.cert-manager.io_Certificate
// resource.customizations.health.Certificate
func convertToOverrideKey(groupKind string) (string, error) {
parts := strings.Split(groupKind, "_")
if len(parts) == 2 {
return fmt.Sprintf("%s/%s", parts[0], parts[1]), nil
} else if len(parts) == 1 && groupKind != "" {
return groupKind, nil
}
return "", fmt.Errorf("group kind should be in format `resource.customizations.<type>.<group_kind>` or resource.customizations.<type>.<kind>`, got group kind: '%s'", groupKind)
}
func GetDefaultDiffOptions() ArgoCDDiffOptions {
return ArgoCDDiffOptions{IgnoreAggregatedRoles: false}
}
// GetResourceCompareOptions loads the resource compare options settings from the ConfigMap
func (mgr *SettingsManager) GetResourceCompareOptions() (ArgoCDDiffOptions, error) {
// We have a sane set of default diff options
diffOptions := GetDefaultDiffOptions()
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return diffOptions, err
}
if value, ok := argoCDCM.Data[resourceCompareOptionsKey]; ok {
err := yaml.Unmarshal([]byte(value), &diffOptions)
if err != nil {
return diffOptions, err
}
}
return diffOptions, nil
}
// GetHelmSettings returns helm settings
func (mgr *SettingsManager) GetHelmSettings() (*v1alpha1.HelmOptions, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
helmOptions := &v1alpha1.HelmOptions{}
if value, ok := argoCDCM.Data[helmValuesFileSchemesKey]; ok {
for _, item := range strings.Split(value, ",") {
if item := strings.TrimSpace(item); item != "" {
helmOptions.ValuesFileSchemes = append(helmOptions.ValuesFileSchemes, item)
}
}
} else {
helmOptions.ValuesFileSchemes = []string{"https", "http"}
}
return helmOptions, nil
}
// GetKustomizeSettings loads the kustomize settings from argocd-cm ConfigMap
func (mgr *SettingsManager) GetKustomizeSettings() (*KustomizeSettings, error) {
argoCDCM, err := mgr.getConfigMap()
if err != nil {
return nil, err
}
kustomizeVersionsMap := map[string]KustomizeVersion{}
buildOptions := map[string]string{}
settings := &KustomizeSettings{}
// extract build options for the default version
if options, ok := argoCDCM.Data[kustomizeBuildOptionsKey]; ok {
settings.BuildOptions = options
}
// extract per-version binary paths and build options
for k, v := range argoCDCM.Data {