gitlab.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "net/http"
  21. "sort"
  22. "strconv"
  23. "strings"
  24. "github.com/tidwall/gjson"
  25. gitlab "gitlab.com/gitlab-org/api/client-go"
  26. corev1 "k8s.io/api/core/v1"
  27. ctrl "sigs.k8s.io/controller-runtime"
  28. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  29. "github.com/external-secrets/external-secrets/runtime/constants"
  30. "github.com/external-secrets/external-secrets/runtime/esutils"
  31. "github.com/external-secrets/external-secrets/runtime/esutils/resolvers"
  32. "github.com/external-secrets/external-secrets/runtime/find"
  33. "github.com/external-secrets/external-secrets/runtime/metrics"
  34. )
  35. const (
  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 from JSON: %w"
  45. errNotImplemented = "not implemented"
  46. )
  47. // https://github.com/external-secrets/external-secrets/issues/644
  48. var _ esv1.SecretsClient = &gitlabBase{}
  49. var _ esv1.Provider = &Provider{}
  50. // ProjectsClient is an interface for interacting with GitLab project APIs.
  51. type ProjectsClient interface {
  52. ListProjectsGroups(pid any, opt *gitlab.ListProjectGroupOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectGroup, *gitlab.Response, error)
  53. }
  54. // ProjectVariablesClient is an interface for managing GitLab project variables.
  55. type ProjectVariablesClient interface {
  56. GetVariable(pid any, key string, opt *gitlab.GetProjectVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.ProjectVariable, *gitlab.Response, error)
  57. ListVariables(pid any, opt *gitlab.ListProjectVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.ProjectVariable, *gitlab.Response, error)
  58. }
  59. // GroupVariablesClient is an interface for managing GitLab group variables.
  60. type GroupVariablesClient interface {
  61. GetVariable(gid any, key string, opts *gitlab.GetGroupVariableOptions, options ...gitlab.RequestOptionFunc) (*gitlab.GroupVariable, *gitlab.Response, error)
  62. ListVariables(gid any, opt *gitlab.ListGroupVariablesOptions, options ...gitlab.RequestOptionFunc) ([]*gitlab.GroupVariable, *gitlab.Response, error)
  63. }
  64. // ProjectGroupPathSorter implements sort.Interface for sorting project groups by path length.
  65. type ProjectGroupPathSorter []*gitlab.ProjectGroup
  66. func (a ProjectGroupPathSorter) Len() int { return len(a) }
  67. func (a ProjectGroupPathSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  68. func (a ProjectGroupPathSorter) Less(i, j int) bool { return len(a[i].FullPath) < len(a[j].FullPath) }
  69. var log = ctrl.Log.WithName("provider").WithName("gitlab")
  70. // Set gitlabBase credentials to Access Token.
  71. func (g *gitlabBase) getAuth(ctx context.Context) (string, error) {
  72. return resolvers.SecretKeyRef(
  73. ctx,
  74. g.kube,
  75. g.storeKind,
  76. g.namespace,
  77. &g.store.Auth.SecretRef.AccessToken)
  78. }
  79. func (g *gitlabBase) DeleteSecret(_ context.Context, _ esv1.PushSecretRemoteRef) error {
  80. return errors.New(errNotImplemented)
  81. }
  82. func (g *gitlabBase) SecretExists(_ context.Context, _ esv1.PushSecretRemoteRef) (bool, error) {
  83. return false, errors.New(errNotImplemented)
  84. }
  85. func (g *gitlabBase) PushSecret(_ context.Context, _ *corev1.Secret, _ esv1.PushSecretData) error {
  86. return errors.New(errNotImplemented)
  87. }
  88. // GetAllSecrets syncs all gitlab project and group variables into a single Kubernetes Secret.
  89. func (g *gitlabBase) GetAllSecrets(_ context.Context, ref esv1.ExternalSecretFind) (map[string][]byte, error) {
  90. if esutils.IsNil(g.projectVariablesClient) {
  91. return nil, errors.New(errUninitializedGitlabProvider)
  92. }
  93. var effectiveEnvironment = g.store.Environment
  94. if ref.Tags != nil {
  95. environment, err := ExtractTag(ref.Tags)
  96. if err != nil {
  97. return nil, err
  98. }
  99. if !isEmptyOrWildcard(effectiveEnvironment) && !isEmptyOrWildcard(environment) {
  100. return nil, errors.New(errEnvironmentIsConstricted)
  101. }
  102. effectiveEnvironment = environment
  103. }
  104. if ref.Path != nil {
  105. return nil, errors.New(errPathNotImplemented)
  106. }
  107. if ref.Name == nil {
  108. return nil, errors.New(errNameNotDefined)
  109. }
  110. var matcher *find.Matcher
  111. if ref.Name != nil {
  112. m, err := find.New(*ref.Name)
  113. if err != nil {
  114. return nil, err
  115. }
  116. matcher = m
  117. }
  118. err := g.ResolveGroupIDs()
  119. if err != nil {
  120. return nil, err
  121. }
  122. secretData, err := g.fetchSecretData(effectiveEnvironment, matcher)
  123. if err != nil {
  124. return nil, err
  125. }
  126. // _Note_: fetchProjectVariables alters secret data map
  127. if err := g.fetchProjectVariables(effectiveEnvironment, matcher, secretData); err != nil {
  128. return nil, err
  129. }
  130. return secretData, nil
  131. }
  132. func (g *gitlabBase) fetchProjectVariables(effectiveEnvironment string, matcher *find.Matcher, secretData map[string][]byte) error {
  133. var popts = &gitlab.ListProjectVariablesOptions{PerPage: 100}
  134. nonWildcardSet := make(map[string]bool)
  135. for projectPage := 1; ; projectPage++ {
  136. popts.Page = projectPage
  137. projectData, response, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, popts)
  138. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  139. if err != nil {
  140. return err
  141. }
  142. processProjectVariables(projectData, effectiveEnvironment, matcher, secretData, nonWildcardSet)
  143. if response.CurrentPage >= response.TotalPages {
  144. break
  145. }
  146. }
  147. return nil
  148. }
  149. func processProjectVariables(
  150. projectData []*gitlab.ProjectVariable,
  151. effectiveEnvironment string,
  152. matcher *find.Matcher,
  153. secretData map[string][]byte,
  154. nonWildcardSet map[string]bool,
  155. ) {
  156. for _, data := range projectData {
  157. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  158. if !matching {
  159. continue
  160. }
  161. if isWildcard && nonWildcardSet[key] {
  162. continue
  163. }
  164. secretData[key] = []byte(data.Value)
  165. if !isWildcard {
  166. nonWildcardSet[key] = true
  167. }
  168. }
  169. }
  170. func (g *gitlabBase) fetchSecretData(effectiveEnvironment string, matcher *find.Matcher) (map[string][]byte, error) {
  171. var gopts = &gitlab.ListGroupVariablesOptions{PerPage: 100}
  172. secretData := make(map[string][]byte)
  173. for _, groupID := range g.store.GroupIDs {
  174. if err := g.setVariablesForGroupID(effectiveEnvironment, matcher, gopts, groupID, secretData); err != nil {
  175. return nil, err
  176. }
  177. }
  178. return secretData, nil
  179. }
  180. func (g *gitlabBase) setVariablesForGroupID(
  181. effectiveEnvironment string,
  182. matcher *find.Matcher,
  183. gopts *gitlab.ListGroupVariablesOptions,
  184. groupID string,
  185. secretData map[string][]byte,
  186. ) error {
  187. for groupPage := 1; ; groupPage++ {
  188. gopts.Page = groupPage
  189. groupVars, response, err := g.groupVariablesClient.ListVariables(groupID, gopts)
  190. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  191. if err != nil {
  192. return err
  193. }
  194. g.setGroupValues(effectiveEnvironment, matcher, groupVars, secretData)
  195. if response.CurrentPage >= response.TotalPages {
  196. break
  197. }
  198. }
  199. return nil
  200. }
  201. func (g *gitlabBase) setGroupValues(
  202. effectiveEnvironment string,
  203. matcher *find.Matcher,
  204. groupVars []*gitlab.GroupVariable,
  205. secretData map[string][]byte,
  206. ) {
  207. for _, data := range groupVars {
  208. matching, key, isWildcard := matchesFilter(effectiveEnvironment, data.EnvironmentScope, data.Key, matcher)
  209. if !matching {
  210. continue
  211. }
  212. // Check if a more specific variable already exists (project environment > project variable > group environment > group variable)
  213. _, exists := secretData[key]
  214. if exists && isWildcard {
  215. continue
  216. }
  217. secretData[key] = []byte(data.Value)
  218. }
  219. }
  220. // ExtractTag extracts the environment scope from the provided tags map.
  221. func ExtractTag(tags map[string]string) (string, error) {
  222. var environmentScope string
  223. for tag, value := range tags {
  224. if tag != "environment_scope" {
  225. return "", errors.New(errTagsOnlyEnvironmentSupported)
  226. }
  227. environmentScope = value
  228. }
  229. return environmentScope, nil
  230. }
  231. func (g *gitlabBase) getGroupVariables(groupID string, ref esv1.ExternalSecretDataRemoteRef, gopts *gitlab.GetGroupVariableOptions) (*gitlab.GroupVariable, *gitlab.Response, error) {
  232. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, gopts)
  233. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupGetVariable, err)
  234. if err != nil {
  235. if resp != nil && resp.StatusCode == http.StatusNotFound && !isEmptyOrWildcard(g.store.Environment) {
  236. if gopts == nil {
  237. gopts = &gitlab.GetGroupVariableOptions{}
  238. }
  239. if gopts.Filter == nil {
  240. gopts.Filter = &gitlab.VariableFilter{}
  241. }
  242. gopts.Filter.EnvironmentScope = "*"
  243. groupVar, resp, err = g.groupVariablesClient.GetVariable(groupID, ref.Key, gopts)
  244. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupGetVariable, err)
  245. if err != nil || resp == nil {
  246. return nil, resp, fmt.Errorf("error getting group variable %s from GitLab: %w", ref.Key, err)
  247. }
  248. } else {
  249. return nil, resp, err
  250. }
  251. }
  252. return groupVar, resp, nil
  253. }
  254. func (g *gitlabBase) GetSecret(_ context.Context, ref esv1.ExternalSecretDataRemoteRef) ([]byte, error) {
  255. if esutils.IsNil(g.projectVariablesClient) || esutils.IsNil(g.groupVariablesClient) {
  256. return nil, errors.New(errUninitializedGitlabProvider)
  257. }
  258. // Need to replace hyphens with underscores to work with GitLab API
  259. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  260. // Retrieves a gitlab variable in the form
  261. // {
  262. // "key": "TEST_VARIABLE_1",
  263. // "variable_type": "env_var",
  264. // "value": "TEST_1",
  265. // "protected": false,
  266. // "masked": true,
  267. // "environment_scope": "*"
  268. // }
  269. var gopts *gitlab.GetGroupVariableOptions
  270. var vopts *gitlab.GetProjectVariableOptions
  271. if g.store.Environment != "" {
  272. gopts = &gitlab.GetGroupVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.store.Environment}}
  273. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.store.Environment}}
  274. }
  275. data, err := g.getVariables(ref, vopts)
  276. if err == nil {
  277. return extractVariable(ref, data.Value)
  278. }
  279. // If project variable not found, try group variables
  280. if errors.Is(err, gitlab.ErrNotFound) {
  281. return g.tryGroupVariables(ref, gopts, err)
  282. }
  283. return nil, err
  284. }
  285. // tryGroupVariables attempts to retrieve the secret from group variables when project lookup fails.
  286. func (g *gitlabBase) tryGroupVariables(ref esv1.ExternalSecretDataRemoteRef, gopts *gitlab.GetGroupVariableOptions, originalErr error) ([]byte, error) {
  287. // Load groupIds from the `InheritFromGroups` property
  288. if err := g.ResolveGroupIDs(); err != nil {
  289. return nil, err
  290. }
  291. for i := len(g.store.GroupIDs) - 1; i >= 0; i-- {
  292. groupID := g.store.GroupIDs[i]
  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.Itoa(group.ID)
  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. }