gitlab.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. "sort"
  19. "strconv"
  20. "strings"
  21. "github.com/tidwall/gjson"
  22. "github.com/xanzy/go-gitlab"
  23. corev1 "k8s.io/api/core/v1"
  24. ctrl "sigs.k8s.io/controller-runtime"
  25. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  26. "github.com/external-secrets/external-secrets/pkg/constants"
  27. "github.com/external-secrets/external-secrets/pkg/find"
  28. "github.com/external-secrets/external-secrets/pkg/metrics"
  29. "github.com/external-secrets/external-secrets/pkg/utils"
  30. "github.com/external-secrets/external-secrets/pkg/utils/resolvers"
  31. )
  32. const (
  33. errGitlabCredSecretName = "credentials are empty"
  34. errInvalidClusterStoreMissingSAKNamespace = "invalid clusterStore missing SAK namespace"
  35. errFetchSAKSecret = "couldn't find secret on cluster: %w"
  36. errList = "could not verify whether the gitlabClient is valid: %w"
  37. errProjectAuth = "gitlabClient is not allowed to get secrets for project id [%s]"
  38. errGroupAuth = "gitlabClient is not allowed to get secrets for group id [%s]"
  39. errUninitializedGitlabProvider = "provider gitlab is not initialized"
  40. errNameNotDefined = "'find.name' is mandatory"
  41. errEnvironmentIsConstricted = "'find.tags' is constrained by 'environment_scope' of the store"
  42. errTagsOnlyEnvironmentSupported = "'find.tags' only supports 'environment_scope'"
  43. errPathNotImplemented = "'find.path' is not implemented in the GitLab provider"
  44. errJSONSecretUnmarshal = "unable to unmarshal secret: %w"
  45. errNotImplemented = "not implemented"
  46. )
  47. // https://github.com/external-secrets/external-secrets/issues/644
  48. var _ esv1beta1.SecretsClient = &gitlabBase{}
  49. var _ esv1beta1.Provider = &Provider{}
  50. type ProjectsClient interface {
  51. ListProjectsGroups(pid any, opt *gitlab.ListProjectGroupOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectGroup, *gitlab.Response, error)
  52. }
  53. type ProjectVariablesClient interface {
  54. GetVariable(pid any, key string, opt *gitlab.GetProjectVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectVariable, *gitlab.Response, error)
  55. ListVariables(pid any, opt *gitlab.ListProjectVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectVariable, *gitlab.Response, error)
  56. }
  57. type GroupVariablesClient interface {
  58. GetVariable(gid any, key string, options ...gitlab.RequestOptionFunc) (*gitlab.GroupVariable, *gitlab.Response, error)
  59. ListVariables(gid any, opt *gitlab.ListGroupVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.GroupVariable, *gitlab.Response, error)
  60. }
  61. type ProjectGroupPathSorter []*gitlab.ProjectGroup
  62. func (a ProjectGroupPathSorter) Len() int { return len(a) }
  63. func (a ProjectGroupPathSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  64. func (a ProjectGroupPathSorter) Less(i, j int) bool { return len(a[i].FullPath) < len(a[j].FullPath) }
  65. var log = ctrl.Log.WithName("provider").WithName("gitlab")
  66. // Set gitlabBase credentials to Access Token.
  67. func (g *gitlabBase) getAuth(ctx context.Context) (string, error) {
  68. return resolvers.SecretKeyRef(
  69. ctx,
  70. g.kube,
  71. g.storeKind,
  72. g.namespace,
  73. &g.store.Auth.SecretRef.AccessToken)
  74. }
  75. func (g *gitlabBase) DeleteSecret(_ context.Context, _ esv1beta1.PushSecretRemoteRef) error {
  76. return fmt.Errorf(errNotImplemented)
  77. }
  78. func (g *gitlabBase) SecretExists(_ context.Context, _ esv1beta1.PushSecretRemoteRef) (bool, error) {
  79. return false, fmt.Errorf(errNotImplemented)
  80. }
  81. func (g *gitlabBase) PushSecret(_ context.Context, _ *corev1.Secret, _ esv1beta1.PushSecretData) error {
  82. return fmt.Errorf(errNotImplemented)
  83. }
  84. // GetAllSecrets syncs all gitlab project and group variables into a single Kubernetes Secret.
  85. func (g *gitlabBase) GetAllSecrets(_ context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  86. if utils.IsNil(g.projectVariablesClient) {
  87. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  88. }
  89. var effectiveEnvironment = g.store.Environment
  90. if ref.Tags != nil {
  91. environment, err := ExtractTag(ref.Tags)
  92. if err != nil {
  93. return nil, err
  94. }
  95. if !isEmptyOrWildcard(effectiveEnvironment) && !isEmptyOrWildcard(environment) {
  96. return nil, fmt.Errorf(errEnvironmentIsConstricted)
  97. }
  98. effectiveEnvironment = environment
  99. }
  100. if ref.Path != nil {
  101. return nil, fmt.Errorf(errPathNotImplemented)
  102. }
  103. if ref.Name == nil {
  104. return nil, fmt.Errorf(errNameNotDefined)
  105. }
  106. var matcher *find.Matcher
  107. if ref.Name != nil {
  108. m, err := find.New(*ref.Name)
  109. if err != nil {
  110. return nil, err
  111. }
  112. matcher = m
  113. }
  114. err := g.ResolveGroupIds()
  115. if err != nil {
  116. return nil, err
  117. }
  118. var gopts = &gitlab.ListGroupVariablesOptions{PerPage: 100}
  119. secretData := make(map[string][]byte)
  120. for _, groupID := range g.store.GroupIDs {
  121. for groupPage := 1; ; groupPage++ {
  122. gopts.Page = groupPage
  123. groupVars, response, err := g.groupVariablesClient.ListVariables(groupID, gopts)
  124. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  125. if err != nil {
  126. return nil, err
  127. }
  128. for _, data := range groupVars {
  129. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  130. if !matching && !isWildcard {
  131. continue
  132. }
  133. secretData[key] = []byte(data.Value)
  134. }
  135. if response.CurrentPage >= response.TotalPages {
  136. break
  137. }
  138. }
  139. }
  140. var popts = &gitlab.ListProjectVariablesOptions{PerPage: 100}
  141. for projectPage := 1; ; projectPage++ {
  142. popts.Page = projectPage
  143. projectData, response, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, popts)
  144. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  145. if err != nil {
  146. return nil, err
  147. }
  148. for _, data := range projectData {
  149. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  150. if !matching {
  151. continue
  152. }
  153. _, exists := secretData[key]
  154. if exists && isWildcard {
  155. continue
  156. }
  157. secretData[key] = []byte(data.Value)
  158. }
  159. if response.CurrentPage >= response.TotalPages {
  160. break
  161. }
  162. }
  163. return secretData, nil
  164. }
  165. func ExtractTag(tags map[string]string) (string, error) {
  166. var environmentScope string
  167. for tag, value := range tags {
  168. if tag != "environment_scope" {
  169. return "", fmt.Errorf(errTagsOnlyEnvironmentSupported)
  170. }
  171. environmentScope = value
  172. }
  173. return environmentScope, nil
  174. }
  175. func (g *gitlabBase) GetSecret(_ context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  176. if utils.IsNil(g.projectVariablesClient) || utils.IsNil(g.groupVariablesClient) {
  177. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  178. }
  179. // Need to replace hyphens with underscores to work with GitLab API
  180. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  181. // Retrieves a gitlab variable in the form
  182. // {
  183. // "key": "TEST_VARIABLE_1",
  184. // "variable_type": "env_var",
  185. // "value": "TEST_1",
  186. // "protected": false,
  187. // "masked": true,
  188. // "environment_scope": "*"
  189. // }
  190. var vopts *gitlab.GetProjectVariableOptions
  191. if g.store.Environment != "" {
  192. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.store.Environment}}
  193. }
  194. data, resp, err := g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, vopts)
  195. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectVariableGet, err)
  196. if !isEmptyOrWildcard(g.store.Environment) && resp.StatusCode == http.StatusNotFound {
  197. vopts.Filter.EnvironmentScope = "*"
  198. data, resp, err = g.projectVariablesClient.GetVariable(g.store.ProjectID, ref.Key, vopts)
  199. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectVariableGet, err)
  200. }
  201. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  202. return nil, err
  203. }
  204. err = g.ResolveGroupIds()
  205. if err != nil {
  206. return nil, err
  207. }
  208. var result []byte
  209. if resp.StatusCode < 300 {
  210. result, err = extractVariable(ref, data.Value)
  211. }
  212. for i := len(g.store.GroupIDs) - 1; i >= 0; i-- {
  213. groupID := g.store.GroupIDs[i]
  214. if result != nil {
  215. return result, nil
  216. }
  217. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, nil)
  218. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupGetVariable, err)
  219. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  220. return nil, err
  221. }
  222. if resp.StatusCode < 300 {
  223. result, _ = extractVariable(ref, groupVar.Value)
  224. }
  225. }
  226. if result != nil {
  227. return result, nil
  228. }
  229. return nil, err
  230. }
  231. func extractVariable(ref esv1beta1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  232. if ref.Property == "" {
  233. if value != "" {
  234. return []byte(value), nil
  235. }
  236. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  237. }
  238. var payload string
  239. if value != "" {
  240. payload = value
  241. }
  242. val := gjson.Get(payload, ref.Property)
  243. if !val.Exists() {
  244. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  245. }
  246. return []byte(val.String()), nil
  247. }
  248. func (g *gitlabBase) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  249. // Gets a secret as normal, expecting secret value to be a json object
  250. data, err := g.GetSecret(ctx, ref)
  251. if err != nil {
  252. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  253. }
  254. // Maps the json data to a string:string map
  255. kv := make(map[string]string)
  256. err = json.Unmarshal(data, &kv)
  257. if err != nil {
  258. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  259. }
  260. // Converts values in K:V pairs into bytes, while leaving keys as strings
  261. secretData := make(map[string][]byte)
  262. for k, v := range kv {
  263. secretData[k] = []byte(v)
  264. }
  265. return secretData, nil
  266. }
  267. func isEmptyOrWildcard(environment string) bool {
  268. return environment == "" || environment == "*"
  269. }
  270. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string, bool) {
  271. isWildcard := isEmptyOrWildcard(varEnvironment)
  272. if !isWildcard && !isEmptyOrWildcard(environment) {
  273. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  274. if varEnvironment != environment {
  275. return false, "", isWildcard
  276. }
  277. }
  278. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  279. return false, "", isWildcard
  280. }
  281. return true, key, isWildcard
  282. }
  283. func (g *gitlabBase) Close(_ context.Context) error {
  284. return nil
  285. }
  286. func (g *gitlabBase) ResolveGroupIds() error {
  287. if g.store.InheritFromGroups {
  288. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.store.ProjectID, nil)
  289. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabListProjectsGroups, err)
  290. if resp.StatusCode >= 400 && err != nil {
  291. return err
  292. }
  293. sort.Sort(ProjectGroupPathSorter(projectGroups))
  294. discoveredIds := make([]string, len(projectGroups))
  295. for i, group := range projectGroups {
  296. discoveredIds[i] = strconv.Itoa(group.ID)
  297. }
  298. g.store.GroupIDs = discoveredIds
  299. }
  300. return nil
  301. }
  302. // Validate will use the gitlab projectVariablesClient/groupVariablesClient to validate the gitlab provider using the ListVariable call to ensure get permissions without needing a specific key.
  303. func (g *gitlabBase) Validate() (esv1beta1.ValidationResult, error) {
  304. if g.store.ProjectID != "" {
  305. _, resp, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, nil)
  306. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  307. if err != nil {
  308. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  309. } else if resp == nil || resp.StatusCode != http.StatusOK {
  310. return esv1beta1.ValidationResultError, fmt.Errorf(errProjectAuth, g.store.ProjectID)
  311. }
  312. err = g.ResolveGroupIds()
  313. if err != nil {
  314. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  315. }
  316. log.V(1).Info("discovered project groups", "name", g.store.GroupIDs)
  317. }
  318. if len(g.store.GroupIDs) > 0 {
  319. for _, groupID := range g.store.GroupIDs {
  320. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  321. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  322. if err != nil {
  323. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  324. } else if resp == nil || resp.StatusCode != http.StatusOK {
  325. return esv1beta1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  326. }
  327. }
  328. }
  329. return esv1beta1.ValidationResultReady, nil
  330. }