gitlab.go 7.2 KB

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