gitlab.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package gitlab
  13. import (
  14. "context"
  15. "encoding/json"
  16. "fmt"
  17. // I think I've overwritten the log package I need with the default golang one?
  18. "log"
  19. "os"
  20. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  21. gitlab "github.com/xanzy/go-gitlab"
  22. corev1 "k8s.io/api/core/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  25. "github.com/external-secrets/external-secrets/pkg/provider"
  26. "github.com/external-secrets/external-secrets/pkg/provider/schema"
  27. )
  28. // Requires a token to be set in environment variable
  29. var GITLAB_TOKEN = os.Getenv("GITLAB_TOKEN")
  30. var GITLAB_PROJECT_ID = os.Getenv("GITLAB_PROJECT_ID")
  31. const (
  32. // TODO: Make these more descriptive
  33. errGitlabCredSecretName = "error with credentials"
  34. errInvalidClusterStoreMissingSAKNamespace = "error"
  35. errFetchSAKSecret = "couldn't find secret on cluster: %w"
  36. errMissingSAK = "error"
  37. )
  38. // Probably don't need this any more
  39. type GitlabCredentials struct {
  40. Token string `json:"token"`
  41. }
  42. // Gitlab Provider struct with reference to a github client and a projectID
  43. type Gitlab struct {
  44. client *gitlab.Client
  45. projectID interface{}
  46. }
  47. // Client for interacting with kubernetes cluster...?
  48. type gClient struct {
  49. kube kclient.Client
  50. store *esv1alpha1.GitlabProvider
  51. namespace string
  52. storeKind string
  53. credentials []byte
  54. }
  55. func init() {
  56. schema.Register(&Gitlab{}, &esv1alpha1.SecretStoreProvider{
  57. Gitlab: &esv1alpha1.GitlabProvider{},
  58. })
  59. }
  60. // Set gClient credentials to Access Token
  61. func (c *gClient) setAuth(ctx context.Context) error {
  62. credentialsSecret := &corev1.Secret{}
  63. credentialsSecretName := c.store.Auth.SecretRef.AccessToken.Name
  64. if credentialsSecretName == "" {
  65. return fmt.Errorf(errGitlabCredSecretName)
  66. }
  67. objectKey := types.NamespacedName{
  68. Name: credentialsSecretName,
  69. Namespace: c.namespace,
  70. }
  71. // only ClusterStore is allowed to set namespace (and then it's required)
  72. if c.storeKind == esv1alpha1.ClusterSecretStoreKind {
  73. if c.store.Auth.SecretRef.AccessToken.Namespace == nil {
  74. return fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  75. }
  76. objectKey.Namespace = *c.store.Auth.SecretRef.AccessToken.Namespace
  77. }
  78. err := c.kube.Get(ctx, objectKey, credentialsSecret)
  79. if err != nil {
  80. return fmt.Errorf(errFetchSAKSecret, err)
  81. }
  82. c.credentials = credentialsSecret.Data[c.store.Auth.SecretRef.AccessToken.Key]
  83. if (c.credentials == nil) || (len(c.credentials) == 0) {
  84. return fmt.Errorf(errMissingSAK)
  85. }
  86. c.store.ProjectID = string(credentialsSecret.Data[c.store.ProjectID])
  87. return nil
  88. }
  89. // Function newGitlabProvider returns a reference to a new instance of a 'Gitlab' struct
  90. func NewGitlabProvider() *Gitlab {
  91. return &Gitlab{}
  92. }
  93. // Method on Gitlab Provider to set up client with credentials and populate projectID
  94. func (g *Gitlab) NewClient(ctx context.Context, store esv1alpha1.GenericStore, kube kclient.Client, namespace string) (provider.SecretsClient, error) {
  95. storeSpec := store.GetSpec()
  96. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  97. return nil, fmt.Errorf("no store type or wrong store type")
  98. }
  99. storeSpecGitlab := storeSpec.Provider.Gitlab
  100. cliStore := gClient{
  101. kube: kube,
  102. store: storeSpecGitlab,
  103. namespace: namespace,
  104. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  105. }
  106. if err := cliStore.setAuth(ctx); err != nil {
  107. return nil, err
  108. }
  109. var err error
  110. // Create a new Gitlab client with credentials
  111. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), nil)
  112. if err != nil {
  113. log.Fatalf("Failed to create client: %v", err)
  114. }
  115. g.client = gitlabClient
  116. g.projectID = cliStore.store.ProjectID
  117. return g, nil
  118. }
  119. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1alpha1.ExternalSecretDataRemoteRef) ([]byte, error) {
  120. // Retrieves a gitlab variable in the form
  121. // {
  122. // "key": "TEST_VARIABLE_1",
  123. // "variable_type": "env_var",
  124. // "value": "TEST_1",
  125. // "protected": false,
  126. // "masked": true
  127. // }
  128. data, _, err := g.client.ProjectVariables.GetVariable(g.projectID, ref.Key, nil) //Optional 'filter' parameter could be added later
  129. if err != nil {
  130. return nil, err
  131. }
  132. // Return only the variable's 'value'
  133. return []byte(data.Value), nil
  134. }
  135. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1alpha1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  136. // Gets a secret as normal, expecting secret value to be a json object
  137. data, err := g.GetSecret(ctx, ref)
  138. if err != nil {
  139. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  140. }
  141. // Maps the json data to a string:string map
  142. kv := make(map[string]string)
  143. err = json.Unmarshal(data, &kv)
  144. if err != nil {
  145. fmt.Printf("unable to unmarshal secret %v: %v", ref.Key, err)
  146. return nil, err
  147. }
  148. // Converts values in K:V pairs into bytes, while leaving keys as strings
  149. secretData := make(map[string][]byte)
  150. for k, v := range kv {
  151. secretData[k] = []byte(v)
  152. }
  153. return secretData, nil
  154. }
  155. func (g *Gitlab) Close() error {
  156. return nil
  157. }