/
gitrepo.go
1130 lines (877 loc) · 33.5 KB
/
gitrepo.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 2020 The Kubernetes 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 utils
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"time"
gitssh "github.com/go-git/go-git/v5/plumbing/transport/ssh"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/knownhosts"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing"
admissionv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/klog/v2"
"strings"
"github.com/google/go-github/v42/github"
gitignore "github.com/sabhiram/go-gitignore"
"github.com/ghodss/yaml"
gitclient "gopkg.in/src-d/go-git.v4/plumbing/transport/client"
githttp "gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"sigs.k8s.io/controller-runtime/pkg/client"
chnv1 "open-cluster-management.io/multicloud-operators-channel/pkg/apis/apps/v1"
appv1 "open-cluster-management.io/multicloud-operators-subscription/pkg/apis/apps/v1"
)
const (
// UserID is key of GitHub user ID in secret
UserID = "user"
// AccessToken is key of GitHub user password or personal token in secret
AccessToken = "accessToken"
// SSHKey is use to connect to the channel via SSH
SSHKey = "sshKey"
// Passphrase is used to open the SSH key
Passphrase = "passphrase"
// ClientKey is a client private key for connecting to a Git server
ClientKey = "clientKey"
// ClientCert is a client certificate for connecting to a Git server
ClientCert = "clientCert"
Error = " err: "
)
type kubeResource struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
}
// KKubeResource export the kuKubeResource for other package
type KubeResource struct {
kubeResource
}
type GitCloneOption struct {
CommitHash string
RevisionTag string
Branch plumbing.ReferenceName
DestDir string
CloneDepth int
PrimaryConnectionOption *ChannelConnectionCfg
SecondaryConnectionOption *ChannelConnectionCfg
}
type ChannelConnectionCfg struct {
RepoURL string
User string
Password string
SSHKey []byte
Passphrase []byte
InsecureSkipVerify bool
CaCerts string
ClientKey []byte
ClientCert []byte
}
// ParseKubeResoures parses a YAML content and returns kube resources in byte array from the file
func ParseKubeResoures(file []byte) [][]byte {
cond := func(t KubeResource) bool {
return t.APIVersion == "" || t.Kind == ""
}
return KubeResourceParser(file, cond)
}
type Kube func(KubeResource) bool
func KubeResourceParser(file []byte, cond Kube) [][]byte {
var ret [][]byte
items := ParseYAML(file)
for _, i := range items {
item := []byte(strings.Trim(i, "\t \n"))
t := KubeResource{}
err := yaml.Unmarshal(item, &t)
if err != nil {
// Ignore item that cannot be unmarshalled..
klog.Warning(err, "Failed to unmarshal YAML content")
continue
}
if cond(t) {
// Ignore item that does not have apiVersion or kind.
klog.Warning("Not a Kubernetes resource")
} else {
ret = append(ret, item)
}
}
return ret
}
func getCertChain(certs string) tls.Certificate {
var certChain tls.Certificate
certPEMBlock := []byte(certs)
var certDERBlock *pem.Block
for {
certDERBlock, certPEMBlock = pem.Decode(certPEMBlock)
if certDERBlock == nil {
break
}
if certDERBlock.Type == "CERTIFICATE" {
certChain.Certificate = append(certChain.Certificate, certDERBlock.Bytes)
}
}
return certChain
}
// A subscription can have secondary channel to use when it cannot connect to the primary channel
// This builds connectionOptions *git.CloneOptions based on the channel selection
func getConnectionOptions(cloneOptions *GitCloneOption, primary bool) (connectionOptions *git.CloneOptions, err error) {
channelConnOptions := cloneOptions.PrimaryConnectionOption
if !primary {
if cloneOptions.SecondaryConnectionOption == nil {
klog.Error("no secondary channel to try")
return nil, nil
}
channelConnOptions = cloneOptions.SecondaryConnectionOption
}
options := &git.CloneOptions{
URL: channelConnOptions.RepoURL,
SingleBranch: true,
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
ReferenceName: cloneOptions.Branch,
}
// The destination directory needs to be created here
err = os.RemoveAll(cloneOptions.DestDir)
if err != nil {
klog.Warning(err, "Failed to remove directory ", cloneOptions.DestDir)
}
err = os.MkdirAll(cloneOptions.DestDir, os.ModePerm)
if err != nil {
return nil, err
}
// If branch name is provided, clone the specified branch only.
if cloneOptions.Branch != "" {
options.ReferenceName = cloneOptions.Branch
options.SingleBranch = true
}
if strings.HasPrefix(options.URL, "http") {
klog.Info("Connecting to Git server via HTTP")
err := getHTTPOptions(options,
channelConnOptions.User,
channelConnOptions.Password,
channelConnOptions.CaCerts,
channelConnOptions.InsecureSkipVerify,
channelConnOptions.ClientKey,
channelConnOptions.ClientCert)
if err != nil {
klog.Error(err, "failed to prepare HTTP clone options")
return nil, err
}
} else {
klog.Info("Connecting to Git server via SSH")
knownhostsfile := filepath.Join(cloneOptions.DestDir, "known_hosts")
if !channelConnOptions.InsecureSkipVerify {
err := getKnownHostFromURL(channelConnOptions.RepoURL, knownhostsfile)
if err != nil {
return nil, err
}
}
err = getSSHOptions(options, channelConnOptions.SSHKey, channelConnOptions.Passphrase, knownhostsfile, channelConnOptions.InsecureSkipVerify)
if err != nil {
klog.Error(err, " failed to prepare SSH clone options")
return nil, err
}
}
options.Depth = 1
if cloneOptions.CommitHash != "" || cloneOptions.RevisionTag != "" {
if cloneOptions.CloneDepth > 1 {
klog.Infof("Setting clone depth to %d", cloneOptions.CloneDepth)
options.Depth = cloneOptions.CloneDepth
} else {
klog.Info("Setting clone depth to 20")
options.Depth = 20
}
}
return options, nil
}
// CloneGitRepo clones a GitHub repository
func CloneGitRepo(cloneOptions *GitCloneOption) (commitID string, err error) {
usingPrimary := true
options, err := getConnectionOptions(cloneOptions, true)
if err != nil {
klog.Errorf("Failed to get Git clone options with the primary channel. Trying the secondary channel. err: %v", err)
usingPrimary = false
}
secondaryOptions, err := getConnectionOptions(cloneOptions, false)
if err != nil {
if !usingPrimary {
// we could not get both primary and secondary Git connection options. return error
klog.Errorf("Failed to get Git clone options with the secondary channel. err: %v", err)
return "", err
}
klog.Warning("Failed to get Git clone options with the secondary channel. err: %v", err)
}
// we could not get the connection options with the primary channel but we got it with the secondary channel. Use it instead
if !usingPrimary {
if secondaryOptions == nil {
// if trying the secondary connection option but nothing there, return error
// at this point, we have no Git connection options
klog.Error("failed to build secondary git connection options")
return "", errors.New("failed to build secondary git connection options")
}
options = secondaryOptions
}
klog.Info("Cloning ", options.URL, " into ", cloneOptions.DestDir)
klog.Info("cloneOptions.DestDir = " + cloneOptions.DestDir)
klog.Info("cloneOptions.Branch = " + cloneOptions.Branch)
klog.Info("cloneOptions.CommitHash = " + cloneOptions.CommitHash)
klog.Info("cloneOptions.RevisionTag = " + cloneOptions.RevisionTag)
klog.Infof("cloneOptions.CloneDepth = %d", cloneOptions.CloneDepth)
repo, err := git.PlainClone(cloneOptions.DestDir, false, options)
if err != nil {
if usingPrimary {
klog.Error(err, " Failed to git clone with the primary channel: ", err.Error())
if secondaryOptions == nil {
return "", errors.New("Failed to clone git: " + options.URL + Error + err.Error())
}
klog.Info("Trying to clone with the secondary channel")
klog.Info("Cloning ", secondaryOptions.URL, " into ", cloneOptions.DestDir)
repo, err = git.PlainClone(cloneOptions.DestDir, false, secondaryOptions)
if err != nil {
klog.Error("Failed to clone Git with the secondary channel." + Error + err.Error())
return "", errors.New("Failed to clone git: " + secondaryOptions.URL + " branch: " + cloneOptions.Branch.String() + Error + err.Error())
}
} else {
klog.Errorf("failed to clone secondary git channel. err: %v", err)
return "", errors.New("Failed to clone git: " + options.URL + " branch: " + cloneOptions.Branch.String() + Error + err.Error())
}
}
ref, err := repo.Head()
if err != nil {
klog.Error(err, " Failed to get git repo head")
return "", errors.New("failed to get git repo head," + Error + err.Error())
}
klog.Infof("Successfully cloned the repo and the current branch is %s", ref.Name().Short())
// If both commitHash and revisionTag are provided, take commitHash.
targetCommit := cloneOptions.CommitHash
if cloneOptions.RevisionTag != "" && targetCommit == "" {
tag := "refs/tags/" + cloneOptions.RevisionTag
releasetag := plumbing.Revision(tag)
revisionHash, err := repo.ResolveRevision(releasetag)
if err != nil {
klog.Error(err, " failed to resolve revision")
return "", errors.New("failed to resolve revision tag " + cloneOptions.RevisionTag + Error + err.Error())
}
klog.Infof("Revision tag %s is resolved to %s", cloneOptions.RevisionTag, revisionHash)
targetCommit = revisionHash.String()
}
if targetCommit != "" {
workTree, err := repo.Worktree()
if err != nil {
klog.Error(err, " Failed to get work tree")
return "", err
}
klog.Infof("Checking out commit %s ", targetCommit)
err = workTree.Checkout(&git.CheckoutOptions{
Hash: plumbing.NewHash(strings.TrimSpace(targetCommit)),
Create: false,
})
if err != nil {
klog.Error(err, " Failed to checkout commit")
return "", errors.New("failed to checkout commit " + targetCommit + Error + err.Error())
}
klog.Infof("Successfully checked out commit %s ", targetCommit)
return targetCommit, nil
}
// Otherwise return the latest commit ID
commit, err := repo.CommitObject(ref.Hash())
if err != nil {
klog.Error(err, " Failed to get git repo commit")
return "", errors.New("failed to get the repo's latest commit hash," + Error + err.Error())
}
return commit.ID().String(), nil
}
func getKnownHostFromURL(sshURL string, filepath string) error {
sshhostname := ""
sshhostport := ""
if strings.HasPrefix(sshURL, "ssh:") {
u, err := url.Parse(sshURL)
if err != nil {
klog.Error("failed toparse SSH URL: ", err)
return err
}
sshhostname = u.Hostname()
sshhostport = u.Port()
} else if strings.HasPrefix(sshURL, "git@") {
sshhostname = strings.Split(strings.SplitAfter(sshURL, "@")[1], ":")[0]
}
klog.Info("sshhostname = " + sshhostname)
klog.Info("sshhostport = " + sshhostport)
klog.Info("Getting public SSH host key for " + sshhostname)
cmd := exec.Command("ssh-keyscan", sshhostname) // #nosec G204 the variable is generated within this function.
if sshhostport != "" {
cmd = exec.Command("ssh-keyscan", "-p", sshhostport, sshhostname) // #nosec G204 the variable is generated within this function.
klog.Infof("Running command ssh-keyscan -p %s %s", sshhostport, sshhostname)
}
stdout, err := cmd.Output()
if err != nil {
klog.Error("failed to get public SSH host key: ", err)
}
klog.Info("SSH host key: " + string(stdout))
if err := os.WriteFile(filepath, stdout, 0600); err != nil {
klog.Error("failed to write known_hosts file: ", err)
return err
}
return nil
}
func getSSHOptions(options *git.CloneOptions, sshKey, passphrase []byte, knownhostsfile string, insecureSkipVerify bool) error {
publicKey := &gitssh.PublicKeys{}
publicKey.User = "git"
if len(passphrase) > 0 {
klog.Info("Parsing SSH private key with passphrase")
signer, err := ssh.ParsePrivateKeyWithPassphrase(sshKey, passphrase)
if err != nil {
klog.Error("failed to parse SSH key", err.Error())
return err
}
publicKey.Signer = signer
} else {
signer, err := ssh.ParsePrivateKey(sshKey)
if err != nil {
klog.Error("failed to parse SSH key", err.Error())
return err
}
publicKey.Signer = signer
}
if insecureSkipVerify {
klog.Info("Insecure ignore SSH host key")
publicKey.HostKeyCallback = ssh.InsecureIgnoreHostKey() // #nosec G106 this is optional and used only if users specify it in channel configuration
} else {
klog.Info("Using SSH known host keys")
callback, err := knownhosts.New(knownhostsfile)
if err != nil {
klog.Error("failed to get knownhosts ", err)
return err
}
publicKey.HostKeyCallback = callback
}
options.Auth = publicKey
return nil
}
func getHTTPOptions(options *git.CloneOptions, user, password, caCerts string, insecureSkipVerify bool, clientkey, clientcert []byte) error {
if user != "" && password != "" {
options.Auth = &githttp.BasicAuth{
Username: user,
Password: password,
}
}
installProtocol := false
// #nosec G402 -- TLS 1.2 is required for FIPS
clientConfig := &tls.Config{MinVersion: appv1.TLSMinVersionInt}
// skip TLS certificate verification for Git servers with custom or self-signed certs
if insecureSkipVerify {
klog.Info("insecureSkipVerify = true, skipping Git server's certificate verification.")
clientConfig.InsecureSkipVerify = true
installProtocol = true
} else if !strings.EqualFold(caCerts, "") {
klog.Info("Adding Git server's CA certificate to trust certificate pool")
// Load the host's trusted certs into memory
certPool, _ := x509.SystemCertPool()
if certPool == nil {
certPool = x509.NewCertPool()
}
certChain := getCertChain(caCerts)
if len(certChain.Certificate) == 0 {
klog.Warning("No certificate found")
}
// Add CA certs from the channel config map to the cert pool
// It will not add duplicate certs
for _, cert := range certChain.Certificate {
x509Cert, err := x509.ParseCertificate(cert)
if err != nil {
return err
}
klog.Info("Adding certificate -->" + x509Cert.Subject.String())
certPool.AddCert(x509Cert)
}
clientConfig.RootCAs = certPool
installProtocol = true
}
// If client key pair is provided, make mTLS connection
if len(clientkey) > 0 && len(clientcert) > 0 {
klog.Info("Client certificate key pair is provieded. Making mTLS connection.")
clientCertificate, err := tls.X509KeyPair(clientcert, clientkey)
if err != nil {
klog.Error(err.Error())
return err
}
// Add the client certificate in the connection
clientConfig.Certificates = []tls.Certificate{clientCertificate}
klog.Info("Client certificate key pair added successfully")
}
if installProtocol {
klog.Info("HTTP_PROXY = " + os.Getenv("HTTP_PROXY"))
klog.Info("HTTPS_PROXY = " + os.Getenv("HTTPS_PROXY"))
klog.Info("NO_PROXY = " + os.Getenv("NO_PROXY"))
transportConfig := &http.Transport{
TLSClientConfig: clientConfig,
}
proxyURLEnv := ""
if os.Getenv("HTTPS_PROXY") != "" {
proxyURLEnv = os.Getenv("HTTPS_PROXY")
} else if os.Getenv("HTTP_PROXY") != "" {
proxyURLEnv = os.Getenv("HTTP_PROXY")
} else if os.Getenv("NO_PROXY") != "" {
proxyURLEnv = os.Getenv("NO_PROXY")
}
if proxyURLEnv != "" {
transportConfig.Proxy = http.ProxyFromEnvironment
klog.Info("HTTP transport proxy set")
}
customClient := &http.Client{
Transport: transportConfig,
// 15 second timeout
Timeout: 15 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
}
gitclient.InstallProtocol("https", githttp.NewClient(customClient))
}
return nil
}
// GetSubscriptionBranch returns GitHub repo branch for a given subscription
func GetSubscriptionBranch(sub *appv1.Subscription) plumbing.ReferenceName {
annotations := sub.GetAnnotations()
branchStr := annotations[appv1.AnnotationGitBranch]
if branchStr == "" {
branchStr = annotations[appv1.AnnotationGithubBranch] // AnnotationGithubBranch will be depricated
}
return GetSubscriptionBranchRef(branchStr)
}
func GetSubscriptionBranchRef(b string) plumbing.ReferenceName {
if b != "" {
if !strings.HasPrefix(b, "refs/heads/") {
b = "refs/heads/" + b
}
return plumbing.ReferenceName(b)
}
return ""
}
// GetChannelSecret returns username and password for channel
func GetChannelSecret(client client.Client, chn *chnv1.Channel) (string, string, []byte, []byte, []byte, []byte, error) {
username := ""
accessToken := ""
sshKey := []byte("")
passphrase := []byte("")
clientkey := []byte("")
clientcert := []byte("")
if chn.Spec.SecretRef != nil {
secret := &corev1.Secret{}
secns := chn.Spec.SecretRef.Namespace
if secns == "" {
secns = chn.Namespace
}
err := client.Get(context.TODO(), types.NamespacedName{Name: chn.Spec.SecretRef.Name, Namespace: secns}, secret)
if err != nil {
klog.Error(err, "Unable to get secret from local cluster.")
return username, accessToken, sshKey, passphrase, clientkey, clientcert, err
}
username, accessToken, sshKey, passphrase, clientkey, clientcert, err = ParseChannelSecret(secret)
if err != nil {
return username, accessToken, sshKey, passphrase, clientkey, clientcert, err
}
}
return username, accessToken, sshKey, passphrase, clientkey, clientcert, nil
}
// GetDataFromChannelConfigMap returns username and password for channel
func GetChannelConfigMap(client client.Client, chn *chnv1.Channel) *corev1.ConfigMap {
if chn.Spec.ConfigMapRef != nil {
configMapRet := &corev1.ConfigMap{}
cmns := chn.Namespace
err := client.Get(context.TODO(), types.NamespacedName{Name: chn.Spec.ConfigMapRef.Name, Namespace: cmns}, configMapRet)
if err != nil {
klog.Error(err, "Unable to get config map from local cluster.")
return nil
}
return configMapRet
}
return nil
}
func ParseChannelSecret(secret *corev1.Secret) (string, string, []byte, []byte, []byte, []byte, error) {
username := ""
accessToken := ""
sshKey := []byte("")
passphrase := []byte("")
clientKey := []byte("")
clientCert := []byte("")
err := yaml.Unmarshal(secret.Data[UserID], &username)
if err != nil {
klog.Error(err, "Failed to unmarshal username from the secret.")
return username, accessToken, sshKey, passphrase, clientKey, clientCert, err
}
err = yaml.Unmarshal(secret.Data[AccessToken], &accessToken)
if err != nil {
klog.Error(err, "Failed to unmarshal accessToken from the secret.")
return username, accessToken, sshKey, passphrase, clientKey, clientCert, err
}
sshKey = bytes.TrimSpace(secret.Data[SSHKey])
passphrase = bytes.TrimSpace(secret.Data[Passphrase])
clientKey = bytes.TrimSpace(secret.Data[ClientKey])
clientCert = bytes.TrimSpace(secret.Data[ClientCert])
if (len(clientKey) == 0 && len(clientCert) > 0) || (len(clientKey) > 0 && len(clientCert) == 0) {
klog.Error(err, "for mTLS connection to Git, both clientKey (private key) and clientCert (certificate) are required in the channel secret")
return username, accessToken, sshKey, passphrase, clientKey, clientCert,
errors.New("for mTLS connection to Git, both clientKey (private key) and clientCert (certificate) are required in the channel secret")
}
if len(sshKey) == 0 && len(clientKey) == 0 {
if username == "" || accessToken == "" {
klog.Error(err, "sshKey (and optionally passphrase) or user and accressToken need to be specified in the channel secret")
return username, accessToken, sshKey, passphrase, clientKey, clientCert,
errors.New("sshKey (and optionally passphrase) or user and accressToken need to be specified in the channel secret")
}
}
return username, accessToken, sshKey, passphrase, clientKey, clientCert, nil
}
// GetLocalGitFolder returns the local Git repo clone directory
func GetLocalGitFolder(sub *appv1.Subscription) string {
return filepath.Join(os.TempDir(), sub.Namespace, sub.Name)
}
type SkipFunc func(string, string) bool
// SortResources sorts kube resources into different arrays for processing them later.
func SortResources(repoRoot, resourcePath string, skips ...SkipFunc) (map[string]string, map[string]string, []string, []string, []string, error) {
klog.V(4).Info("Git repo subscription directory: ", resourcePath)
var skip SkipFunc
if len(skips) == 0 {
skip = func(string, string) bool { return false }
} else {
skip = skips[0]
}
// In the cloned git repo root, find all helm chart directories
chartDirs := make(map[string]string)
// In the cloned git repo root, find all kustomization directories
kustomizeDirs := make(map[string]string)
// Apply CustomResourceDefinition and Namespace Kubernetes resources first
crdsAndNamespaceFiles := []string{}
// Then apply ServiceAccount, ClusterRole and Role Kubernetes resources next
rbacFiles := []string{}
// Then apply the rest of resource
otherFiles := []string{}
currentChartDir := "NONE"
currentKustomizeDir := "NONE"
kubeIgnore := GetKubeIgnore(resourcePath)
err := filepath.Walk(resourcePath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relativePath := path
if len(strings.SplitAfter(path, repoRoot+"/")) > 1 {
relativePath = strings.SplitAfter(path, repoRoot+"/")[1]
}
if !kubeIgnore.MatchesPath(relativePath) && !skip(resourcePath, path) {
if info.IsDir() {
klog.V(4).Info("Ignoring subfolders of ", currentChartDir)
if _, err := os.Stat(path + "/Chart.yaml"); err == nil {
klog.V(4).Info("Found Chart.yaml in ", path)
if !strings.HasPrefix(path, currentChartDir) {
klog.V(4).Info("This is a helm chart folder.")
chartDirs[path+"/"] = path + "/"
currentChartDir = path + "/"
}
} else if _, err := os.Stat(path + "/kustomization.yaml"); err == nil {
// If there are nested kustomizations or any other folder structures containing kube
// resources under a kustomization, subscription should not process them and let kustomize
// build handle them based on the top-level kustomization.yaml.
if !strings.HasPrefix(path, currentKustomizeDir) {
klog.V(4).Info("Found kustomization.yaml in ", path)
currentKustomizeDir = path + "/"
kustomizeDirs[path+"/"] = path + "/"
}
} else if _, err := os.Stat(path + "/kustomization.yml"); err == nil {
// If there are nested kustomizations or any other folder structures containing kube
// resources under a kustomization, subscription should not process them and let kustomize
// build handle them based on the top-level kustomization.yaml
if !strings.HasPrefix(path, currentKustomizeDir) {
klog.V(4).Info("Found kustomization.yml in ", path)
currentKustomizeDir = path + "/"
kustomizeDirs[path+"/"] = path + "/"
}
}
} else if !strings.HasPrefix(path, currentChartDir) &&
!strings.HasPrefix(path, repoRoot+"/.git") &&
!strings.HasPrefix(path, currentKustomizeDir) {
// Do not process kubernetes YAML files under helm chart or kustomization directory
// If there are nested kustomizations or any other folder structures containing kube
// resources under a kustomization, subscription should not process them and let kustomize
// build handle them based on the top-level kustomization.yaml
crdsAndNamespaceFiles, rbacFiles, otherFiles, err = sortKubeResource(crdsAndNamespaceFiles, rbacFiles, otherFiles, path)
if err != nil {
klog.Error(err.Error())
return err
}
}
}
return nil
})
return chartDirs, kustomizeDirs, crdsAndNamespaceFiles, rbacFiles, otherFiles, err
}
func sortKubeResource(crdsAndNamespaceFiles, rbacFiles, otherFiles []string, path string) ([]string, []string, []string, error) {
if strings.EqualFold(filepath.Ext(path), ".yml") || strings.EqualFold(filepath.Ext(path), ".yaml") {
klog.V(4).Info("Reading file: ", path)
file, err := os.ReadFile(path) // #nosec G304 path is not user input
if err != nil {
klog.Error(err, "Failed to read YAML file "+path)
return crdsAndNamespaceFiles, rbacFiles, otherFiles, err
}
resources := ParseKubeResoures(file)
if len(resources) == 1 {
t := kubeResource{}
err := yaml.Unmarshal(resources[0], &t)
if err != nil {
klog.Warning("Failed to unmarshal YAML file")
// Just ignore the YAML
return crdsAndNamespaceFiles, rbacFiles, otherFiles, nil
}
if t.APIVersion != "" && t.Kind != "" {
if strings.EqualFold(t.Kind, "customresourcedefinition") {
crdsAndNamespaceFiles = append(crdsAndNamespaceFiles, path)
} else if strings.EqualFold(t.Kind, "namespace") {
crdsAndNamespaceFiles = append(crdsAndNamespaceFiles, path)
} else if strings.EqualFold(t.Kind, "serviceaccount") ||
strings.EqualFold(t.Kind, "clusterrole") ||
strings.EqualFold(t.Kind, "role") ||
strings.EqualFold(t.Kind, "clusterrolebinding") ||
strings.EqualFold(t.Kind, "rolebinding") {
rbacFiles = append(rbacFiles, path)
} else {
otherFiles = append(otherFiles, path)
}
}
} else if len(resources) > 1 {
klog.Info("Multi resource")
otherFiles = append(otherFiles, path)
}
}
return crdsAndNamespaceFiles, rbacFiles, otherFiles, nil
}
func SkipHooksOnManaged(resourcePath, curPath string) bool {
PREHOOK := "prehook"
POSTHOOK := "posthook"
// of the resource root.
pre := fmt.Sprintf("%s/%s", resourcePath, PREHOOK)
post := fmt.Sprintf("%s/%s", resourcePath, POSTHOOK)
return strings.HasPrefix(curPath, pre) || strings.HasPrefix(curPath, post)
}
// GetKubeIgnore get .kubernetesignore list
func GetKubeIgnore(resourcePath string) *gitignore.GitIgnore {
klog.V(4).Info("Git repo resource root directory: ", resourcePath)
lines := []string{""}
kubeIgnore := gitignore.CompileIgnoreLines(lines...)
if _, err := os.Stat(filepath.Join(resourcePath, ".kubernetesignore")); err == nil {
klog.V(4).Info("Found .kubernetesignore in ", resourcePath)
kubeIgnore, _ = gitignore.CompileIgnoreFile(filepath.Join(resourcePath, ".kubernetesignore"))
}
return kubeIgnore
}
// IsGitChannel returns true if channel type is github or git
func IsGitChannel(chType string) bool {
return strings.EqualFold(chType, chnv1.ChannelTypeGitHub) ||
strings.EqualFold(chType, chnv1.ChannelTypeGit)
}
func IsClusterAdmin(client client.Client, sub *appv1.Subscription, eventRecorder *EventRecorder) bool {
isClusterAdmin := false
isUserSubAdmin := false
isSubPropagatedFromHub := false
isClusterAdminAnnotationTrue := false
userIdentity := ""
userGroups := ""
annotations := sub.GetAnnotations()
if annotations != nil {
encodedUserGroup := strings.Trim(annotations[appv1.AnnotationUserGroup], "")
encodedUserIdentity := strings.Trim(annotations[appv1.AnnotationUserIdentity], "")
if encodedUserGroup != "" {
userGroups = Base64StringDecode(encodedUserGroup)
}
if encodedUserIdentity != "" {
userIdentity = Base64StringDecode(encodedUserIdentity)
}
if annotations[appv1.AnnotationHosting] != "" {
isSubPropagatedFromHub = true
}
if strings.EqualFold(annotations[appv1.AnnotationClusterAdmin], "true") {
isClusterAdminAnnotationTrue = true
}
}
doesWebhookExist := false
theWebhook := &admissionv1.MutatingWebhookConfiguration{}
if err := client.Get(context.TODO(), types.NamespacedName{Name: appv1.AcmWebhook}, theWebhook); err == nil {
doesWebhookExist = true
}
if userIdentity != "" && doesWebhookExist {
// First, check open-cluster-management:subscription-admin cluster role binding
isUserSubAdmin = matchUserSubAdmin(client, userIdentity, userGroups)
if !isUserSubAdmin {
// Check if there is any other cluster role binding with open-cluster-management:subscription-admin cluster role
isUserSubAdmin = scanUserSubAdmin(client, userIdentity, userGroups)
}
}
// When the appsub has hosting-subscription annotation, the cluster-admin: true annotation is always respected, including 3 cases:
// 1: the appsub is on the managed cluster propagated by a hub appsub, there is no ocm-mutating-webhook found in the current cluster
// 2: the appsub is on the hub containing -local name suffix, the appsub is propagated by a hub appsub.
// 3: the appsub is on the hub not containing -local name suffix, the appsub is propagated by a hub sub of sub.
isHubSubOfHubSub := isSubPropagatedFromHub && doesWebhookExist && !strings.HasSuffix(sub.GetName(), "-local")
if isClusterAdminAnnotationTrue && isSubPropagatedFromHub {
if !doesWebhookExist || // not on the hub cluster
(doesWebhookExist && strings.HasSuffix(sub.GetName(), "-local")) { // on the hub cluster and the subscription has -local suffix
if eventRecorder != nil {
eventRecorder.RecordEvent(sub, "RoleElevation",
"Role was elevated to cluster admin for subscription "+sub.Name, nil)
}
isClusterAdmin = true
} else if isHubSubOfHubSub { // hub appsub of a hub appsub
if eventRecorder != nil {
eventRecorder.RecordEvent(sub, "RoleElevation",
"Role was elevated to cluster admin for hub subscription of hub subscription "+sub.Name, nil)
}
isClusterAdmin = true
}
} else if isUserSubAdmin {
if eventRecorder != nil {
eventRecorder.RecordEvent(sub, "RoleElevation",
"Role was elevated to cluster admin for subscription "+sub.Name+" by user "+userIdentity, nil)
}
isClusterAdmin = true
}
klog.Infof("isClusterAdmin = %v", isClusterAdmin)
return isClusterAdmin
}
func matchUserSubAdmin(client client.Client, userIdentity, userGroups string) bool {
isUserSubAdmin := false
foundClusterRoleBinding := &rbacv1.ClusterRoleBinding{}
err := client.Get(context.TODO(), types.NamespacedName{Name: appv1.SubscriptionAdmin}, foundClusterRoleBinding)
if err == nil {
klog.Infof("ClusterRoleBinding %s found.", appv1.SubscriptionAdmin)
isUserSubAdmin = checkUserSubAdmin(foundClusterRoleBinding.Subjects, userIdentity, userGroups)
} else {
klog.Error(err)
}
foundClusterRoleBinding = nil
return isUserSubAdmin
}
func scanUserSubAdmin(client client.Client, userIdentity, userGroups string) bool {
isUserSubAdmin := false
bindingList := &rbacv1.ClusterRoleBindingList{}
err := client.List(context.TODO(), bindingList)
if err == nil {
for _, binding := range bindingList.Items {