gitlab.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net/http"
  21. "slices"
  22. "sort"
  23. "strconv"
  24. "strings"
  25. "github.com/tidwall/gjson"
  26. gitlab "gitlab.com/gitlab-org/api/client-go"
  27. corev1 "k8s.io/api/core/v1"
  28. ctrl "sigs.k8s.io/controller-runtime"
  29. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  30. "github.com/external-secrets/external-secrets/runtime/constants"
  31. "github.com/external-secrets/external-secrets/runtime/esutils"
  32. "github.com/external-secrets/external-secrets/runtime/esutils/resolvers"
  33. "github.com/external-secrets/external-secrets/runtime/find"
  34. "github.com/external-secrets/external-secrets/runtime/metrics"
  35. )
  36. const (
  37. errList = "could not verify whether the gitlabClient is valid: %w"
  38. errProjectAuth = "gitlabClient is not allowed to get secrets for project id [%s]"
  39. errGroupAuth = "gitlabClient is not allowed to get secrets for group id [%s]"
  40. errUninitializedGitlabProvider = "provider gitlab is not initialized"
  41. errNameNotDefined = "'find.name' is mandatory"
  42. errEnvironmentIsConstricted = "'find.tags' is constrained by 'environment_scope' of the store"
  43. errTagsOnlyEnvironmentSupported = "'find.tags' only supports 'environment_scope'"
  44. errPathNotImplemented = "'find.path' is not implemented in the GitLab provider"
  45. errJSONSecretUnmarshal = "unable to unmarshal secret from JSON: %w"
  46. errNotImplemented = "not implemented"
  47. )
  48. // https://github.com/external-secrets/external-secrets/issues/644
  49. var _ esv1.SecretsClient = &gitlabBase{}
  50. var _ esv1.Provider = &Provider{}
  51. // ProjectsClient is an interface for interacting with GitLab project APIs.
  52. type ProjectsClient interface {
  53. ListProjectsGroups(pid any, opt *gitlab.ListProjectGroupOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectGroup, *gitlab.Response, error)
  54. }
  55. // ProjectVariablesClient is an interface for managing GitLab project variables.
  56. type ProjectVariablesClient interface {
  57. GetVariable(pid any, key string, opt *gitlab.GetProjectVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectVariable, *gitlab.Response, error)
  58. ListVariables(pid any, opt *gitlab.ListProjectVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectVariable, *gitlab.Response, error)
  59. }
  60. // GroupVariablesClient is an interface for managing GitLab group variables.
  61. type GroupVariablesClient interface {
  62. GetVariable(gid any, key string, opts *gitlab.GetGroupVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.GroupVariable, *gitlab.Response, error)
  63. ListVariables(gid any, opt *gitlab.ListGroupVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.GroupVariable, *gitlab.Response, error)
  64. }
  65. // ProjectGroupPathSorter implements sort.Interface for sorting project groups by path length.
  66. type ProjectGroupPathSorter []*gitlab.ProjectGroup
  67. func (a ProjectGroupPathSorter) Len() int { return len(a) }
  68. func (a ProjectGroupPathSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  69. func (a ProjectGroupPathSorter) Less(i, j int) bool { return len(a[i].FullPath) < len(a[j].FullPath) }
  70. var log = ctrl.Log.WithName("provider").WithName("gitlab")
  71. // Set gitlabBase credentials to Access Token.
  72. func (g *gitlabBase) getAuth(ctx context.Context) (string, error) {
  73. return resolvers.SecretKeyRef(
  74. ctx,
  75. g.kube,
  76. g.storeKind,
  77. g.namespace,
  78. &g.store.Auth.SecretRef.AccessToken)
  79. }
  80. func (g *gitlabBase) DeleteSecret(_ context.Context, _ esv1.PushSecretRemoteRef) error {
  81. return errors.New(errNotImplemented)
  82. }
  83. func (g *gitlabBase) SecretExists(_ context.Context, _ esv1.PushSecretRemoteRef) (bool, error) {
  84. return false, errors.New(errNotImplemented)
  85. }
  86. func (g *gitlabBase) PushSecret(_ context.Context, _ *corev1.Secret, _ esv1.PushSecretData) error {
  87. return errors.New(errNotImplemented)
  88. }
  89. // GetAllSecrets syncs all gitlab project and group variables into a single Kubernetes Secret.
  90. func (g *gitlabBase) GetAllSecrets(_ context.Context, ref esv1.ExternalSecretFind) (map[string][]byte, error) {
  91. if esutils.IsNil(g.projectVariablesClient) {
  92. return nil, errors.New(errUninitializedGitlabProvider)
  93. }
  94. var effectiveEnvironment = g.store.Environment
  95. if ref.Tags != nil {
  96. environment, err := ExtractTag(ref.Tags)
  97. if err != nil {
  98. return nil, err
  99. }
  100. if !isEmptyOrWildcard(effectiveEnvironment) && !isEmptyOrWildcard(environment) {
  101. return nil, errors.New(errEnvironmentIsConstricted)
  102. }
  103. effectiveEnvironment = environment
  104. }
  105. if ref.Path != nil {
  106. return nil, errors.New(errPathNotImplemented)
  107. }
  108. if ref.Name == nil {
  109. return nil, errors.New(errNameNotDefined)
  110. }
  111. var matcher *find.Matcher
  112. if ref.Name != nil {
  113. m, err := find.New(*ref.Name)
  114. if err != nil {
  115. return nil, err
  116. }
  117. matcher = m
  118. }
  119. err := g.ResolveGroupIDs()
  120. if err != nil {
  121. return nil, err
  122. }
  123. secretData, err := g.fetchSecretData(effectiveEnvironment, matcher)
  124. if err != nil {
  125. return nil, err
  126. }
  127. // _Note_: fetchProjectVariables alters secret data map
  128. if err := g.fetchProjectVariables(effectiveEnvironment, matcher, secretData); err != nil {
  129. return nil, err
  130. }
  131. return secretData, nil
  132. }
  133. func (g *gitlabBase) fetchProjectVariables(effectiveEnvironment string, matcher *find.Matcher, secretData map[string][]byte) error {
  134. var popts = &gitlab.ListProjectVariablesOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
  135. nonWildcardSet := make(map[string]bool)
  136. for projectPage := int64(1); ; projectPage++ {
  137. popts.Page = projectPage
  138. projectData, response, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, popts)
  139. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  140. if err != nil {
  141. return err
  142. }
  143. processProjectVariables(projectData, effectiveEnvironment, matcher, secretData, nonWildcardSet)
  144. if response.CurrentPage >= response.TotalPages {
  145. break
  146. }
  147. }
  148. return nil
  149. }
  150. func processProjectVariables(
  151. projectData []*gitlab.ProjectVariable,
  152. effectiveEnvironment string,
  153. matcher *find.Matcher,
  154. secretData map[string][]byte,
  155. nonWildcardSet map[string]bool,
  156. ) {
  157. for _, data := range projectData {
  158. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  159. if !matching {
  160. continue
  161. }
  162. if isWildcard && nonWildcardSet[key] {
  163. continue
  164. }
  165. secretData[key] = []byte(data.Value)
  166. if !isWildcard {
  167. nonWildcardSet[key] = true
  168. }
  169. }
  170. }
  171. func (g *gitlabBase) fetchSecretData(effectiveEnvironment string, matcher *find.Matcher) (map[string][]byte, error) {
  172. var gopts = &gitlab.ListGroupVariablesOptions{ListOptions: gitlab.ListOptions{PerPage: 100}}
  173. secretData := make(map[string][]byte)
  174. for _, groupID := range g.store.GroupIDs {
  175. if err := g.setVariablesForGroupID(effectiveEnvironment, matcher, gopts, groupID, secretData); err != nil {
  176. return nil, err
  177. }
  178. }
  179. return secretData, nil
  180. }
  181. func (g *gitlabBase) setVariablesForGroupID(
  182. effectiveEnvironment string,
  183. matcher *find.Matcher,
  184. gopts *gitlab.ListGroupVariablesOptions,
  185. groupID string,
  186. secretData map[string][]byte,
  187. ) error {
  188. for groupPage := int64(1); ; groupPage++ {
  189. gopts.Page = groupPage
  190. groupVars, response, err := g.groupVariablesClient.ListVariables(groupID, gopts)
  191. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  192. if err != nil {
  193. return err
  194. }
  195. g.setGroupValues(effectiveEnvironment, matcher, groupVars, secretData)
  196. if response.CurrentPage >= response.TotalPages {
  197. break
  198. }
  199. }
  200. return nil
  201. }
  202. func (g *gitlabBase) setGroupValues(
  203. effectiveEnvironment string,
  204. matcher *find.Matcher,
  205. groupVars []*gitlab.GroupVariable,
  206. secretData map[string][]byte,
  207. ) {
  208. for _, data := range groupVars {
  209. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  210. if !matching {
  211. continue
  212. }
  213. // Check if a more specific variable already exists (project environment > project variable > group environment > group variable)
  214. _, exists := secretData[key]
  215. if exists && isWildcard {
  216. continue
  217. }
  218. secretData[key] = []byte(data.Value)
  219. }
  220. }
  221. // ExtractTag extracts the environment scope from the provided tags map.
  222. func ExtractTag(tags map[string]string) (string, error) {
  223. var environmentScope string
  224. for tag, value := range tags {
  225. if tag != "environment_scope" {
  226. return "", errors.New(errTagsOnlyEnvironmentSupported)
  227. }
  228. environmentScope = value
  229. }
  230. return environmentScope, nil
  231. }
  232. func (g *gitlabBase) getGroupVariables(groupID string, ref esv1.ExternalSecretDataRemoteRef, gopts *gitlab.GetGroupVariableOptions) (*gitlab.GroupVariable, *gitlab.Response, error) {
  233. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, gopts)
  234. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupGetVariable, err)
  235. if err != nil {
  236. if resp != nil && resp.StatusCode == http.StatusNotFound && !isEmptyOrWildcard(g.store.Environment) {
  237. if gopts == nil {
  238. gopts = &gitlab.GetGroupVariableOptions{}
  239. }
  240. if gopts.Filter == nil {
  241. gopts.Filter = &gitlab.VariableFilter{}
  242. }
  243. gopts.Filter.EnvironmentScope = "*"
  244. groupVar, resp, err = g.groupVariablesClient.GetVariable(groupID, ref.Key, gopts)
  245. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupGetVariable, err)
  246. if err != nil || resp == nil {
  247. return nil, resp, fmt.Errorf("error getting group variable %s from GitLab: %w", ref.Key, err)
  248. }
  249. } else {
  250. return nil, resp, err
  251. }
  252. }
  253. return groupVar, resp, nil
  254. }
  255. func (g *gitlabBase) GetSecret(_ context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  256. if esutils.IsNil(g.projectVariablesClient) || esutils.IsNil(g.groupVariablesClient) {
  257. return nil, errors.New(errUninitializedGitlabProvider)
  258. }
  259. // Need to replace hyphens with underscores to work with GitLab API
  260. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  261. // Retrieves a gitlab variable in the form
  262. // {
  263. // "key": "TEST_VARIABLE_1",
  264. // "variable_type": "env_var",
  265. // "value": "TEST_1",
  266. // "protected": false,
  267. // "masked": true,
  268. // "environment_scope": "*"
  269. // }
  270. var gopts *gitlab.GetGroupVariableOptions
  271. var vopts *gitlab.GetProjectVariableOptions
  272. if g.store.Environment != "" {
  273. gopts = &gitlab.GetGroupVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.store.Environment}}
  274. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.store.Environment}}
  275. }
  276. data, err := g.getVariables(ref, vopts)
  277. if err == nil {
  278. return extractVariable(ref, data.Value)
  279. }
  280. // If project variable not found, try group variables
  281. if errors.Is(err, gitlab.ErrNotFound) {
  282. return g.tryGroupVariables(ref, gopts, err)
  283. }
  284. return nil, err
  285. }
  286. // tryGroupVariables attempts to retrieve the secret from group variables when project lookup fails.
  287. func (g *gitlabBase) tryGroupVariables(ref esv1.ExternalSecretDataRemoteRef, gopts *gitlab.GetGroupVariableOptions, originalErr error) ([]byte, error) {
  288. // Load groupIds from the `InheritFromGroups` property
  289. if err := g.ResolveGroupIDs(); err != nil {
  290. return nil, err
  291. }
  292. for _, groupID := range slices.Backward(g.store.GroupIDs) {
  293. groupVar, _, err := g.getGroupVariables(groupID, ref, gopts)
  294. if err == nil {
  295. return extractVariable(ref, groupVar.Value)
  296. }
  297. // If a 404 error, continue to the next stage, otherwise exit early with error
  298. if errors.Is(err, gitlab.ErrNotFound) {
  299. continue
  300. }
  301. return nil, err
  302. }
  303. // No group variables found, return the original project error
  304. return nil, originalErr
  305. }
  306. func extractVariable(ref esv1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  307. // If no property specified, return the raw value
  308. if ref.Property == "" {
  309. if value == "" {
  310. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  311. }
  312. return []byte(value), nil
  313. }
  314. // Extract property from JSON value
  315. val := gjson.Get(value, ref.Property)
  316. if !val.Exists() {
  317. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  318. }
  319. return []byte(val.String()), nil
  320. }
  321. func (g *gitlabBase) GetSecretMap(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  322. // Gets a secret as normal, expecting secret value to be a json object
  323. data, err := g.GetSecret(ctx, ref)
  324. if err != nil {
  325. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  326. }
  327. // Maps the json data to a string:string map
  328. kv := make(map[string]string)
  329. err = json.Unmarshal(data, &kv)
  330. if err != nil {
  331. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  332. }
  333. // Converts values in K:V pairs into bytes, while leaving keys as strings
  334. secretData := make(map[string][]byte)
  335. for k, v := range kv {
  336. secretData[k] = []byte(v)
  337. }
  338. return secretData, nil
  339. }
  340. func isEmptyOrWildcard(environment string) bool {
  341. return environment == "" || environment == "*"
  342. }
  343. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string, bool) {
  344. isWildcard := isEmptyOrWildcard(varEnvironment)
  345. if !isWildcard && !isEmptyOrWildcard(environment) {
  346. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  347. if varEnvironment != environment {
  348. return false, "", isWildcard
  349. }
  350. }
  351. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  352. return false, "", isWildcard
  353. }
  354. return true, key, isWildcard
  355. }
  356. func (g *gitlabBase) Close(_ context.Context) error {
  357. return nil
  358. }
  359. func (g *gitlabBase) ResolveGroupIDs() error {
  360. if g.store.InheritFromGroups {
  361. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.store.ProjectID, nil)
  362. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabListProjectsGroups, err)
  363. if resp.StatusCode >= 400 && err != nil {
  364. return err
  365. }
  366. sort.Sort(ProjectGroupPathSorter(projectGroups))
  367. discoveredIDs := make([]string, len(projectGroups))
  368. for i, group := range projectGroups {
  369. discoveredIDs[i] = strconv.FormatInt(group.ID, 10)
  370. }
  371. g.store.GroupIDs = discoveredIDs
  372. }
  373. return nil
  374. }
  375. // 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.
  376. func (g *gitlabBase) Validate() (esv1.ValidationResult, error) {
  377. if g.store.ProjectID != "" {
  378. _, resp, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, nil)
  379. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  380. if err != nil {
  381. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  382. } else if resp == nil || resp.StatusCode != http.StatusOK {
  383. return esv1.ValidationResultError, fmt.Errorf(errProjectAuth, g.store.ProjectID)
  384. }
  385. err = g.ResolveGroupIDs()
  386. if err != nil {
  387. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  388. }
  389. log.V(1).Info("discovered project groups", "name", g.store.GroupIDs)
  390. }
  391. if len(g.store.GroupIDs) > 0 {
  392. for _, groupID := range g.store.GroupIDs {
  393. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  394. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  395. if err != nil {
  396. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  397. } else if resp == nil || resp.StatusCode != http.StatusOK {
  398. return esv1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  399. }
  400. }
  401. }
  402. return esv1.ValidationResultReady, nil
  403. }