gitlab.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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/find"
  26. "github.com/external-secrets/external-secrets/pkg/utils"
  27. )
  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. errUninitializedGitlabProvider = "provider gitlab is not initialized"
  36. errNameNotDefined = "'find.name' is mandatory"
  37. errTagsNotImplemented = "'find.tags' is not currently supported by Gitlab provider"
  38. errPathNotImplemented = "'find.path' is not implemented in the Gitlab provider"
  39. errJSONSecretUnmarshal = "unable to unmarshal secret: %w"
  40. )
  41. // https://github.com/external-secrets/external-secrets/issues/644
  42. var _ esv1beta1.SecretsClient = &Gitlab{}
  43. var _ esv1beta1.Provider = &Gitlab{}
  44. type Client interface {
  45. GetVariable(pid interface{}, key string, opt *gitlab.GetProjectVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectVariable, *gitlab.Response, error)
  46. ListVariables(pid interface{}, opt *gitlab.ListProjectVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectVariable, *gitlab.Response, error)
  47. }
  48. // Gitlab Provider struct with reference to a GitLab client and a projectID.
  49. type Gitlab struct {
  50. client Client
  51. url string
  52. projectID interface{}
  53. environment string
  54. }
  55. // Client for interacting with kubernetes cluster...?
  56. type gClient struct {
  57. kube kclient.Client
  58. store *esv1beta1.GitlabProvider
  59. namespace string
  60. storeKind string
  61. credentials []byte
  62. }
  63. func init() {
  64. esv1beta1.Register(&Gitlab{}, &esv1beta1.SecretStoreProvider{
  65. Gitlab: &esv1beta1.GitlabProvider{},
  66. })
  67. }
  68. // Set gClient credentials to Access Token.
  69. func (c *gClient) setAuth(ctx context.Context) error {
  70. credentialsSecret := &corev1.Secret{}
  71. credentialsSecretName := c.store.Auth.SecretRef.AccessToken.Name
  72. if credentialsSecretName == "" {
  73. return fmt.Errorf(errGitlabCredSecretName)
  74. }
  75. objectKey := types.NamespacedName{
  76. Name: credentialsSecretName,
  77. Namespace: c.namespace,
  78. }
  79. // only ClusterStore is allowed to set namespace (and then it's required)
  80. if c.storeKind == esv1beta1.ClusterSecretStoreKind {
  81. if c.store.Auth.SecretRef.AccessToken.Namespace == nil {
  82. return fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  83. }
  84. objectKey.Namespace = *c.store.Auth.SecretRef.AccessToken.Namespace
  85. }
  86. err := c.kube.Get(ctx, objectKey, credentialsSecret)
  87. if err != nil {
  88. return fmt.Errorf(errFetchSAKSecret, err)
  89. }
  90. c.credentials = credentialsSecret.Data[c.store.Auth.SecretRef.AccessToken.Key]
  91. if c.credentials == nil || len(c.credentials) == 0 {
  92. return fmt.Errorf(errMissingSAK)
  93. }
  94. // I don't know where ProjectID is being set
  95. // This line SHOULD set it, but instead just breaks everything :)
  96. // c.store.ProjectID = string(credentialsSecret.Data[c.store.ProjectID])
  97. return nil
  98. }
  99. // Function newGitlabProvider returns a reference to a new instance of a 'Gitlab' struct.
  100. func NewGitlabProvider() *Gitlab {
  101. return &Gitlab{}
  102. }
  103. // Method on Gitlab Provider to set up client with credentials, populate projectID and environment.
  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.environment = cliStore.store.Environment
  135. g.url = cliStore.store.URL
  136. return g, nil
  137. }
  138. // GetAllSecrets syncs all gitlab project variables into a single Kubernetes Secret.
  139. func (g *Gitlab) GetAllSecrets(ctx context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  140. if utils.IsNil(g.client) {
  141. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  142. }
  143. if ref.Tags != nil {
  144. return nil, fmt.Errorf(errTagsNotImplemented)
  145. }
  146. if ref.Path != nil {
  147. return nil, fmt.Errorf(errPathNotImplemented)
  148. }
  149. if ref.Name == nil {
  150. return nil, fmt.Errorf(errNameNotDefined)
  151. }
  152. allData, _, err := g.client.ListVariables(g.projectID, nil)
  153. if err != nil {
  154. return nil, err
  155. }
  156. var matcher *find.Matcher
  157. if ref.Name != nil {
  158. m, err := find.New(*ref.Name)
  159. if err != nil {
  160. return nil, err
  161. }
  162. matcher = m
  163. }
  164. secretData := make(map[string][]byte)
  165. for _, data := range allData {
  166. matching, key := matchesFilter(g.environment, data, matcher)
  167. if !matching {
  168. continue
  169. }
  170. secretData[key] = []byte(data.Value)
  171. }
  172. return secretData, nil
  173. }
  174. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  175. if utils.IsNil(g.client) {
  176. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  177. }
  178. // Need to replace hyphens with underscores to work with Gitlab API
  179. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  180. // Retrieves a gitlab variable in the form
  181. // {
  182. // "key": "TEST_VARIABLE_1",
  183. // "variable_type": "env_var",
  184. // "value": "TEST_1",
  185. // "protected": false,
  186. // "masked": true,
  187. // "environment_scope": "*"
  188. // }
  189. var vopts *gitlab.GetProjectVariableOptions
  190. if g.environment != "" {
  191. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.environment}}
  192. }
  193. data, _, err := g.client.GetVariable(g.projectID, ref.Key, vopts)
  194. if err != nil {
  195. return nil, err
  196. }
  197. if ref.Property == "" {
  198. if data.Value != "" {
  199. return []byte(data.Value), nil
  200. }
  201. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  202. }
  203. var payload string
  204. if data.Value != "" {
  205. payload = data.Value
  206. }
  207. val := gjson.Get(payload, ref.Property)
  208. if !val.Exists() {
  209. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  210. }
  211. return []byte(val.String()), nil
  212. }
  213. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  214. // Gets a secret as normal, expecting secret value to be a json object
  215. data, err := g.GetSecret(ctx, ref)
  216. if err != nil {
  217. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  218. }
  219. // Maps the json data to a string:string map
  220. kv := make(map[string]string)
  221. err = json.Unmarshal(data, &kv)
  222. if err != nil {
  223. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  224. }
  225. // Converts values in K:V pairs into bytes, while leaving keys as strings
  226. secretData := make(map[string][]byte)
  227. for k, v := range kv {
  228. secretData[k] = []byte(v)
  229. }
  230. return secretData, nil
  231. }
  232. func matchesFilter(environment string, data *gitlab.ProjectVariable, matcher *find.Matcher) (bool, string) {
  233. if environment != "" && environment != "*" {
  234. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  235. if data.EnvironmentScope != environment {
  236. return false, ""
  237. }
  238. }
  239. key := data.Key
  240. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  241. return false, ""
  242. }
  243. return true, key
  244. }
  245. func (g *Gitlab) Close(ctx context.Context) error {
  246. return nil
  247. }
  248. // Validate will use the gitlab client to validate the gitlab provider using the ListVariable call to ensure get permissions without needing a specific key.
  249. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  250. _, resp, err := g.client.ListVariables(g.projectID, nil)
  251. if err != nil {
  252. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  253. } else if resp == nil || resp.StatusCode != http.StatusOK {
  254. return esv1beta1.ValidationResultError, fmt.Errorf(errAuth)
  255. }
  256. return esv1beta1.ValidationResultReady, nil
  257. }
  258. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  259. storeSpec := store.GetSpec()
  260. gitlabSpec := storeSpec.Provider.Gitlab
  261. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  262. err := utils.ValidateSecretSelector(store, accessToken)
  263. if err != nil {
  264. return err
  265. }
  266. if gitlabSpec.ProjectID == "" {
  267. return fmt.Errorf("projectID cannot be empty")
  268. }
  269. if accessToken.Key == "" {
  270. return fmt.Errorf("accessToken.key cannot be empty")
  271. }
  272. if accessToken.Name == "" {
  273. return fmt.Errorf("accessToken.name cannot be empty")
  274. }
  275. return nil
  276. }