gitlab.go 8.7 KB

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