gitlab.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. "github.com/external-secrets/external-secrets/e2e/framework/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. // I don't know where ProjectID is being set, but this line breaks it :)
  87. // c.store.ProjectID = string(credentialsSecret.Data[c.store.ProjectID])
  88. log.Logf("\n Set auth with projectID: %s and token: %s \n", c.store.ProjectID, c.store.Auth.SecretRef.AccessToken.Key)
  89. return nil
  90. }
  91. // Function newGitlabProvider returns a reference to a new instance of a 'Gitlab' struct
  92. func NewGitlabProvider() *Gitlab {
  93. return &Gitlab{}
  94. }
  95. // Method on Gitlab Provider to set up client with credentials and populate projectID
  96. func (g *Gitlab) NewClient(ctx context.Context, store esv1alpha1.GenericStore, kube kclient.Client, namespace string) (provider.SecretsClient, error) {
  97. storeSpec := store.GetSpec()
  98. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  99. return nil, fmt.Errorf("no store type or wrong store type")
  100. }
  101. storeSpecGitlab := storeSpec.Provider.Gitlab
  102. cliStore := gClient{
  103. kube: kube,
  104. store: storeSpecGitlab,
  105. namespace: namespace,
  106. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  107. }
  108. if err := cliStore.setAuth(ctx); err != nil {
  109. return nil, err
  110. }
  111. var err error
  112. // Create a new Gitlab client with credentials
  113. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), nil)
  114. if err != nil {
  115. log.Logf("Failed to create client: %v", err)
  116. }
  117. g.client = gitlabClient
  118. g.projectID = cliStore.store.ProjectID
  119. return g, nil
  120. }
  121. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1alpha1.ExternalSecretDataRemoteRef) ([]byte, error) {
  122. // Retrieves a gitlab variable in the form
  123. // {
  124. // "key": "TEST_VARIABLE_1",
  125. // "variable_type": "env_var",
  126. // "value": "TEST_1",
  127. // "protected": false,
  128. // "masked": true
  129. // }
  130. log.Logf("\n Getting variable with projectID: %s and key: %s \n", g.projectID, ref.Key)
  131. data, _, err := g.client.ProjectVariables.GetVariable(g.projectID, ref.Key, nil) //Optional 'filter' parameter could be added later
  132. if err != nil {
  133. return nil, err
  134. }
  135. // Return only the variable's 'value'
  136. return []byte(data.Value), nil
  137. }
  138. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1alpha1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  139. // Gets a secret as normal, expecting secret value to be a json object
  140. data, err := g.GetSecret(ctx, ref)
  141. if err != nil {
  142. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  143. }
  144. // Maps the json data to a string:string map
  145. kv := make(map[string]string)
  146. err = json.Unmarshal(data, &kv)
  147. if err != nil {
  148. fmt.Printf("unable to unmarshal secret %v: %v", ref.Key, err)
  149. return nil, err
  150. }
  151. // Converts values in K:V pairs into bytes, while leaving keys as strings
  152. secretData := make(map[string][]byte)
  153. for k, v := range kv {
  154. secretData[k] = []byte(v)
  155. }
  156. return secretData, nil
  157. }
  158. func (g *Gitlab) Close() error {
  159. return nil
  160. }