provider.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package gitlab implements a GitLab provider for External Secrets.
  14. package gitlab
  15. import (
  16. "context"
  17. "crypto/tls"
  18. "crypto/x509"
  19. "errors"
  20. "fmt"
  21. "net/http"
  22. gitlab "gitlab.com/gitlab-org/api/client-go"
  23. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  24. "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
  25. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  26. "github.com/external-secrets/external-secrets/runtime/esutils"
  27. "github.com/external-secrets/external-secrets/runtime/metrics"
  28. )
  29. // Provider satisfies the provider interface.
  30. type Provider struct{}
  31. // gitlabBase satisfies the provider.SecretsClient interface.
  32. type gitlabBase struct {
  33. kube kclient.Client
  34. store *esv1.GitlabProvider
  35. storeKind string
  36. namespace string
  37. projectsClient ProjectsClient
  38. projectVariablesClient ProjectVariablesClient
  39. groupVariablesClient GroupVariablesClient
  40. }
  41. // Capabilities returns the provider supported capabilities (ReadOnly, WriteOnly, ReadWrite).
  42. func (g *Provider) Capabilities() esv1.SecretStoreCapabilities {
  43. return esv1.SecretStoreReadOnly
  44. }
  45. // NewClient creates a new GitLab client with the given store configuration.
  46. // It sets up the project variables client with credentials and populates projectID and environment.
  47. func (g *Provider) NewClient(ctx context.Context, store esv1.GenericStore, kube kclient.Client, namespace string) (esv1.SecretsClient, error) {
  48. storeSpec := store.GetSpec()
  49. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  50. return nil, errors.New("no store type or wrong store type")
  51. }
  52. storeSpecGitlab := storeSpec.Provider.Gitlab
  53. gl := &gitlabBase{
  54. kube: kube,
  55. store: storeSpecGitlab,
  56. namespace: namespace,
  57. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  58. }
  59. client, err := gl.getClient(ctx, storeSpecGitlab)
  60. if err != nil {
  61. return nil, err
  62. }
  63. gl.projectsClient = client.Projects
  64. gl.projectVariablesClient = client.ProjectVariables
  65. gl.groupVariablesClient = client.GroupVariables
  66. return gl, nil
  67. }
  68. func (g *gitlabBase) getClient(ctx context.Context, provider *esv1.GitlabProvider) (*gitlab.Client, error) {
  69. credentials, err := g.getAuth(ctx)
  70. if err != nil {
  71. return nil, err
  72. }
  73. // Create projectVariablesClient options
  74. var opts []gitlab.ClientOptionFunc
  75. if provider.URL != "" {
  76. opts = append(opts, gitlab.WithBaseURL(provider.URL))
  77. }
  78. if len(provider.CABundle) > 0 || provider.CAProvider != nil {
  79. caCertPool := x509.NewCertPool()
  80. ca, err := esutils.FetchCACertFromSource(ctx, esutils.CreateCertOpts{
  81. CABundle: provider.CABundle,
  82. CAProvider: provider.CAProvider,
  83. StoreKind: g.storeKind,
  84. Namespace: g.namespace,
  85. Client: g.kube,
  86. })
  87. if err != nil {
  88. return nil, fmt.Errorf("failed to read ca bundle: %w", err)
  89. }
  90. if ok := caCertPool.AppendCertsFromPEM(ca); !ok {
  91. return nil, errors.New("failed to append ca bundle")
  92. }
  93. transport := &http.Transport{
  94. TLSClientConfig: &tls.Config{
  95. RootCAs: caCertPool,
  96. MinVersion: tls.VersionTLS12,
  97. },
  98. }
  99. httpClient := &http.Client{Transport: transport}
  100. opts = append(opts, gitlab.WithHTTPClient(httpClient))
  101. }
  102. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  103. // in a similar way to extend functionality of the provider
  104. // Create a new GitLab Client using credentials and options
  105. client, err := gitlab.NewClient(credentials, opts...)
  106. if err != nil {
  107. return nil, err
  108. }
  109. return client, nil
  110. }
  111. func (g *gitlabBase) getVariables(ref esv1.ExternalSecretDataRemoteRef, vopts *gitlab.GetProjectVariableOptions) (*gitlab.ProjectVariable, error) {
  112. // First attempt to get the variable
  113. data, _, err := g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, vopts)
  114. metrics.ObserveAPICall(ProviderGitLab, CallGitLabProjectVariableGet, err)
  115. // If successful, return immediately
  116. if err == nil {
  117. return data, nil
  118. }
  119. // If not a "not found" error or environment is already wildcard, return the error
  120. if !errors.Is(err, gitlab.ErrNotFound) || isEmptyOrWildcard(g.store.Environment) {
  121. return nil, err
  122. }
  123. // Retry with wildcard environment scope
  124. opts := &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: "*"}}
  125. data, _, err = g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, opts)
  126. metrics.ObserveAPICall(ProviderGitLab, CallGitLabProjectVariableGet, err)
  127. if err != nil {
  128. return nil, fmt.Errorf("error getting variable %s from GitLab (including wildcard retry): %w", ref.Key, err)
  129. }
  130. return data, nil
  131. }
  132. // ValidateStore validates the GitLab store configuration.
  133. func (g *Provider) ValidateStore(store esv1.GenericStore) (admission.Warnings, error) {
  134. storeSpec := store.GetSpec()
  135. gitlabSpec := storeSpec.Provider.Gitlab
  136. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  137. err := esutils.ValidateSecretSelector(store, accessToken)
  138. if err != nil {
  139. return nil, err
  140. }
  141. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  142. return nil, errors.New("projectID and groupIDs must not both be empty")
  143. }
  144. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  145. return nil, errors.New("defining groupIDs and inheritFromGroups = true is not allowed")
  146. }
  147. if accessToken.Key == "" {
  148. return nil, errors.New("accessToken.key cannot be empty")
  149. }
  150. if accessToken.Name == "" {
  151. return nil, errors.New("accessToken.name cannot be empty")
  152. }
  153. return nil, nil
  154. }
  155. // NewProvider creates a new Provider instance.
  156. func NewProvider() esv1.Provider {
  157. return &Provider{}
  158. }
  159. // ProviderSpec returns the provider specification for registration.
  160. func ProviderSpec() *esv1.SecretStoreProvider {
  161. return &esv1.SecretStoreProvider{
  162. Gitlab: &esv1.GitlabProvider{},
  163. }
  164. }
  165. // MaintenanceStatus returns the maintenance status of the provider.
  166. func MaintenanceStatus() esv1.MaintenanceStatus {
  167. return esv1.MaintenanceStatusMaintained
  168. }