gitlab.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. "strings"
  18. "github.com/tidwall/gjson"
  19. gitlab "github.com/xanzy/go-gitlab"
  20. corev1 "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/types"
  22. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  23. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  24. "github.com/external-secrets/external-secrets/e2e/framework/log"
  25. "github.com/external-secrets/external-secrets/pkg/utils"
  26. )
  27. // Requires GITLAB_TOKEN and GITLAB_PROJECT_ID to be set in environment variables
  28. const (
  29. errGitlabCredSecretName = "credentials are empty"
  30. errInvalidClusterStoreMissingSAKNamespace = "invalid clusterStore missing SAK namespace"
  31. errFetchSAKSecret = "couldn't find secret on cluster: %w"
  32. errMissingSAK = "missing credentials while setting auth"
  33. errUninitalizedGitlabProvider = "provider gitlab is not initialized"
  34. errJSONSecretUnmarshal = "unable to unmarshal secret: %w"
  35. )
  36. type Client interface {
  37. GetVariable(pid interface{}, key string, opt *gitlab.GetProjectVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectVariable, *gitlab.Response, error)
  38. }
  39. // Gitlab Provider struct with reference to a GitLab client and a projectID.
  40. type Gitlab struct {
  41. client Client
  42. projectID interface{}
  43. }
  44. // Client for interacting with kubernetes cluster...?
  45. type gClient struct {
  46. kube kclient.Client
  47. store *esv1beta1.GitlabProvider
  48. namespace string
  49. storeKind string
  50. credentials []byte
  51. }
  52. func init() {
  53. esv1beta1.Register(&Gitlab{}, &esv1beta1.SecretStoreProvider{
  54. Gitlab: &esv1beta1.GitlabProvider{},
  55. })
  56. }
  57. // Set gClient credentials to Access Token.
  58. func (c *gClient) setAuth(ctx context.Context) error {
  59. credentialsSecret := &corev1.Secret{}
  60. credentialsSecretName := c.store.Auth.SecretRef.AccessToken.Name
  61. if credentialsSecretName == "" {
  62. return fmt.Errorf(errGitlabCredSecretName)
  63. }
  64. objectKey := types.NamespacedName{
  65. Name: credentialsSecretName,
  66. Namespace: c.namespace,
  67. }
  68. // only ClusterStore is allowed to set namespace (and then it's required)
  69. if c.storeKind == esv1beta1.ClusterSecretStoreKind {
  70. if c.store.Auth.SecretRef.AccessToken.Namespace == nil {
  71. return fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  72. }
  73. objectKey.Namespace = *c.store.Auth.SecretRef.AccessToken.Namespace
  74. }
  75. err := c.kube.Get(ctx, objectKey, credentialsSecret)
  76. if err != nil {
  77. return fmt.Errorf(errFetchSAKSecret, err)
  78. }
  79. c.credentials = credentialsSecret.Data[c.store.Auth.SecretRef.AccessToken.Key]
  80. if (c.credentials == nil) || (len(c.credentials) == 0) {
  81. return fmt.Errorf(errMissingSAK)
  82. }
  83. // I don't know where ProjectID is being set
  84. // This line SHOULD set it, but instead just breaks everything :)
  85. // c.store.ProjectID = string(credentialsSecret.Data[c.store.ProjectID])
  86. return nil
  87. }
  88. // Function newGitlabProvider returns a reference to a new instance of a 'Gitlab' struct.
  89. func NewGitlabProvider() *Gitlab {
  90. return &Gitlab{}
  91. }
  92. // Method on Gitlab Provider to set up client with credentials and populate projectID.
  93. func (g *Gitlab) NewClient(ctx context.Context, store esv1beta1.GenericStore, kube kclient.Client, namespace string) (esv1beta1.SecretsClient, error) {
  94. storeSpec := store.GetSpec()
  95. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  96. return nil, fmt.Errorf("no store type or wrong store type")
  97. }
  98. storeSpecGitlab := storeSpec.Provider.Gitlab
  99. cliStore := gClient{
  100. kube: kube,
  101. store: storeSpecGitlab,
  102. namespace: namespace,
  103. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  104. }
  105. if err := cliStore.setAuth(ctx); err != nil {
  106. return nil, err
  107. }
  108. var err error
  109. // Create client options
  110. var opts []gitlab.ClientOptionFunc
  111. if cliStore.store.URL != "" {
  112. opts = append(opts, gitlab.WithBaseURL(cliStore.store.URL))
  113. }
  114. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  115. // in a similar way to extend functionality of the provider
  116. // Create a new Gitlab client using credentials and options
  117. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), opts...)
  118. if err != nil {
  119. log.Logf("Failed to create client: %v", err)
  120. }
  121. g.client = gitlabClient.ProjectVariables
  122. g.projectID = cliStore.store.ProjectID
  123. return g, nil
  124. }
  125. // Empty GetAllSecrets.
  126. func (g *Gitlab) GetAllSecrets(ctx context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  127. // TO be implemented
  128. return nil, fmt.Errorf("GetAllSecrets not implemented")
  129. }
  130. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  131. if utils.IsNil(g.client) {
  132. return nil, fmt.Errorf(errUninitalizedGitlabProvider)
  133. }
  134. // Need to replace hyphens with underscores to work with Gitlab API
  135. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  136. // Retrieves a gitlab variable in the form
  137. // {
  138. // "key": "TEST_VARIABLE_1",
  139. // "variable_type": "env_var",
  140. // "value": "TEST_1",
  141. // "protected": false,
  142. // "masked": true
  143. data, _, err := g.client.GetVariable(g.projectID, ref.Key, nil) // Optional 'filter' parameter could be added later
  144. if err != nil {
  145. return nil, err
  146. }
  147. if ref.Property == "" {
  148. if data.Value != "" {
  149. return []byte(data.Value), nil
  150. }
  151. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  152. }
  153. var payload string
  154. if data.Value != "" {
  155. payload = data.Value
  156. }
  157. val := gjson.Get(payload, ref.Property)
  158. if !val.Exists() {
  159. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  160. }
  161. return []byte(val.String()), nil
  162. }
  163. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  164. // Gets a secret as normal, expecting secret value to be a json object
  165. data, err := g.GetSecret(ctx, ref)
  166. if err != nil {
  167. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  168. }
  169. // Maps the json data to a string:string map
  170. kv := make(map[string]string)
  171. err = json.Unmarshal(data, &kv)
  172. if err != nil {
  173. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  174. }
  175. // Converts values in K:V pairs into bytes, while leaving keys as strings
  176. secretData := make(map[string][]byte)
  177. for k, v := range kv {
  178. secretData[k] = []byte(v)
  179. }
  180. return secretData, nil
  181. }
  182. func (g *Gitlab) Close(ctx context.Context) error {
  183. return nil
  184. }
  185. func (g *Gitlab) Validate() error {
  186. return nil
  187. }
  188. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  189. return nil
  190. }