gitlab.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. // Capabilities return the provider supported capabilities (ReadOnly, WriteOnly, ReadWrite).
  101. func (g *Gitlab) Capabilities() esv1beta1.SecretStoreCapabilities {
  102. return esv1beta1.SecretStoreReadOnly
  103. }
  104. // Method on Gitlab Provider to set up client with credentials and populate projectID.
  105. func (g *Gitlab) NewClient(ctx context.Context, store esv1beta1.GenericStore, kube kclient.Client, namespace string) (esv1beta1.SecretsClient, error) {
  106. storeSpec := store.GetSpec()
  107. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  108. return nil, fmt.Errorf("no store type or wrong store type")
  109. }
  110. storeSpecGitlab := storeSpec.Provider.Gitlab
  111. cliStore := gClient{
  112. kube: kube,
  113. store: storeSpecGitlab,
  114. namespace: namespace,
  115. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  116. }
  117. if err := cliStore.setAuth(ctx); err != nil {
  118. return nil, err
  119. }
  120. var err error
  121. // Create client options
  122. var opts []gitlab.ClientOptionFunc
  123. if cliStore.store.URL != "" {
  124. opts = append(opts, gitlab.WithBaseURL(cliStore.store.URL))
  125. }
  126. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  127. // in a similar way to extend functionality of the provider
  128. // Create a new Gitlab client using credentials and options
  129. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), opts...)
  130. if err != nil {
  131. log.Logf("Failed to create client: %v", err)
  132. }
  133. g.client = gitlabClient.ProjectVariables
  134. g.projectID = cliStore.store.ProjectID
  135. g.url = cliStore.store.URL
  136. return g, nil
  137. }
  138. // Not Implemented SetSecret.
  139. func (g *Gitlab) SetSecret(ctx context.Context, value []byte, remoteRef esv1beta1.PushRemoteRef) error {
  140. return fmt.Errorf("not implemented")
  141. }
  142. // Empty GetAllSecrets.
  143. func (g *Gitlab) GetAllSecrets(ctx context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  144. // TO be implemented
  145. return nil, fmt.Errorf("GetAllSecrets not implemented")
  146. }
  147. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  148. if utils.IsNil(g.client) {
  149. return nil, fmt.Errorf(errUninitalizedGitlabProvider)
  150. }
  151. // Need to replace hyphens with underscores to work with Gitlab API
  152. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  153. // Retrieves a gitlab variable in the form
  154. // {
  155. // "key": "TEST_VARIABLE_1",
  156. // "variable_type": "env_var",
  157. // "value": "TEST_1",
  158. // "protected": false,
  159. // "masked": true
  160. data, _, err := g.client.GetVariable(g.projectID, ref.Key, nil) // Optional 'filter' parameter could be added later
  161. if err != nil {
  162. return nil, err
  163. }
  164. if ref.Property == "" {
  165. if data.Value != "" {
  166. return []byte(data.Value), nil
  167. }
  168. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  169. }
  170. var payload string
  171. if data.Value != "" {
  172. payload = data.Value
  173. }
  174. val := gjson.Get(payload, ref.Property)
  175. if !val.Exists() {
  176. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  177. }
  178. return []byte(val.String()), nil
  179. }
  180. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  181. // Gets a secret as normal, expecting secret value to be a json object
  182. data, err := g.GetSecret(ctx, ref)
  183. if err != nil {
  184. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  185. }
  186. // Maps the json data to a string:string map
  187. kv := make(map[string]string)
  188. err = json.Unmarshal(data, &kv)
  189. if err != nil {
  190. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  191. }
  192. // Converts values in K:V pairs into bytes, while leaving keys as strings
  193. secretData := make(map[string][]byte)
  194. for k, v := range kv {
  195. secretData[k] = []byte(v)
  196. }
  197. return secretData, nil
  198. }
  199. func (g *Gitlab) Close(ctx context.Context) error {
  200. return nil
  201. }
  202. // Validate will use the gitlab client to validate the gitlab provider using the ListVariable call to ensure get permissions without needing a specific key.
  203. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  204. _, resp, err := g.client.ListVariables(g.projectID, nil)
  205. if err != nil {
  206. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  207. } else if resp == nil || resp.StatusCode != http.StatusOK {
  208. return esv1beta1.ValidationResultError, fmt.Errorf(errAuth)
  209. }
  210. return esv1beta1.ValidationResultReady, nil
  211. }
  212. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  213. storeSpec := store.GetSpec()
  214. gitlabSpec := storeSpec.Provider.Gitlab
  215. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  216. err := utils.ValidateSecretSelector(store, accessToken)
  217. if err != nil {
  218. return err
  219. }
  220. if gitlabSpec.ProjectID == "" {
  221. return fmt.Errorf("projectID cannot be empty")
  222. }
  223. if accessToken.Key == "" {
  224. return fmt.Errorf("accessToken.key cannot be empty")
  225. }
  226. if accessToken.Name == "" {
  227. return fmt.Errorf("accessToken.name cannot be empty")
  228. }
  229. return nil
  230. }