gitlab.go 7.0 KB

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