provider.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  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/constants"
  27. "github.com/external-secrets/external-secrets/runtime/esutils"
  28. "github.com/external-secrets/external-secrets/runtime/metrics"
  29. )
  30. // Provider satisfies the provider interface.
  31. type Provider struct{}
  32. // gitlabBase satisfies the provider.SecretsClient interface.
  33. type gitlabBase struct {
  34. kube kclient.Client
  35. store *esv1.GitlabProvider
  36. storeKind string
  37. namespace string
  38. projectsClient ProjectsClient
  39. projectVariablesClient ProjectVariablesClient
  40. groupVariablesClient GroupVariablesClient
  41. }
  42. // Capabilities returns the provider supported capabilities (ReadOnly, WriteOnly, ReadWrite).
  43. func (g *Provider) Capabilities() esv1.SecretStoreCapabilities {
  44. return esv1.SecretStoreReadOnly
  45. }
  46. // NewClient creates a new GitLab client with the given store configuration.
  47. // It sets up the project variables client with credentials and populates projectID and environment.
  48. func (g *Provider) NewClient(ctx context.Context, store esv1.GenericStore, kube kclient.Client, namespace string) (esv1.SecretsClient, error) {
  49. storeSpec := store.GetSpec()
  50. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  51. return nil, errors.New("no store type or wrong store type")
  52. }
  53. storeSpecGitlab := storeSpec.Provider.Gitlab
  54. gl := &gitlabBase{
  55. kube: kube,
  56. store: storeSpecGitlab,
  57. namespace: namespace,
  58. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  59. }
  60. client, err := gl.getClient(ctx, storeSpecGitlab)
  61. if err != nil {
  62. return nil, err
  63. }
  64. gl.projectsClient = client.Projects
  65. gl.projectVariablesClient = client.ProjectVariables
  66. gl.groupVariablesClient = client.GroupVariables
  67. return gl, nil
  68. }
  69. func (g *gitlabBase) getClient(ctx context.Context, provider *esv1.GitlabProvider) (*gitlab.Client, error) {
  70. credentials, err := g.getAuth(ctx)
  71. if err != nil {
  72. return nil, err
  73. }
  74. // Create projectVariablesClient options
  75. var opts []gitlab.ClientOptionFunc
  76. if provider.URL != "" {
  77. opts = append(opts, gitlab.WithBaseURL(provider.URL))
  78. }
  79. if len(provider.CABundle) > 0 || provider.CAProvider != nil {
  80. caCertPool := x509.NewCertPool()
  81. ca, err := esutils.FetchCACertFromSource(ctx, esutils.CreateCertOpts{
  82. CABundle: provider.CABundle,
  83. CAProvider: provider.CAProvider,
  84. StoreKind: g.storeKind,
  85. Namespace: g.namespace,
  86. Client: g.kube,
  87. })
  88. if err != nil {
  89. return nil, fmt.Errorf("failed to read ca bundle: %w", err)
  90. }
  91. if ok := caCertPool.AppendCertsFromPEM(ca); !ok {
  92. return nil, errors.New("failed to append ca bundle")
  93. }
  94. transport := &http.Transport{
  95. TLSClientConfig: &tls.Config{
  96. RootCAs: caCertPool,
  97. MinVersion: tls.VersionTLS12,
  98. },
  99. }
  100. httpClient := &http.Client{Transport: transport}
  101. opts = append(opts, gitlab.WithHTTPClient(httpClient))
  102. }
  103. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  104. // in a similar way to extend functionality of the provider
  105. // Create a new GitLab Client using credentials and options
  106. client, err := gitlab.NewClient(credentials, opts...)
  107. if err != nil {
  108. return nil, err
  109. }
  110. return client, nil
  111. }
  112. func (g *gitlabBase) getVariables(ref esv1.ExternalSecretDataRemoteRef, vopts *gitlab.GetProjectVariableOptions) (*gitlab.ProjectVariable, error) {
  113. // First attempt to get the variable
  114. data, _, err := g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, vopts)
  115. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectVariableGet, err)
  116. // If successful, return immediately
  117. if err == nil {
  118. return data, nil
  119. }
  120. // If not a "not found" error or environment is already wildcard, return the error
  121. if !errors.Is(err, gitlab.ErrNotFound) || isEmptyOrWildcard(g.store.Environment) {
  122. return nil, err
  123. }
  124. // Retry with wildcard environment scope
  125. opts := &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: "*"}}
  126. data, _, err = g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, opts)
  127. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectVariableGet, err)
  128. if err != nil {
  129. return nil, fmt.Errorf("error getting variable %s from GitLab (including wildcard retry): %w", ref.Key, err)
  130. }
  131. return data, nil
  132. }
  133. // ValidateStore validates the GitLab store configuration.
  134. func (g *Provider) ValidateStore(store esv1.GenericStore) (admission.Warnings, error) {
  135. storeSpec := store.GetSpec()
  136. gitlabSpec := storeSpec.Provider.Gitlab
  137. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  138. err := esutils.ValidateSecretSelector(store, accessToken)
  139. if err != nil {
  140. return nil, err
  141. }
  142. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  143. return nil, errors.New("projectID and groupIDs must not both be empty")
  144. }
  145. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  146. return nil, errors.New("defining groupIDs and inheritFromGroups = true is not allowed")
  147. }
  148. if accessToken.Key == "" {
  149. return nil, errors.New("accessToken.key cannot be empty")
  150. }
  151. if accessToken.Name == "" {
  152. return nil, errors.New("accessToken.name cannot be empty")
  153. }
  154. return nil, nil
  155. }
  156. // NewProvider creates a new Provider instance.
  157. func NewProvider() esv1.Provider {
  158. return &Provider{}
  159. }
  160. // ProviderSpec returns the provider specification for registration.
  161. func ProviderSpec() *esv1.SecretStoreProvider {
  162. return &esv1.SecretStoreProvider{
  163. Gitlab: &esv1.GitlabProvider{},
  164. }
  165. }
  166. // MaintenanceStatus returns the maintenance status of the provider.
  167. func MaintenanceStatus() esv1.MaintenanceStatus {
  168. return esv1.MaintenanceStatusMaintained
  169. }