gitlab.go 8.0 KB

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