gitlab.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. // _Note_: getVariables potentially alters vopts environment variable.
  276. data, resp, err := g.getVariables(ref, vopts)
  277. if err != nil && (resp == nil || resp.StatusCode != http.StatusNotFound) {
  278. return nil, err
  279. }
  280. err = g.ResolveGroupIDs()
  281. if err != nil {
  282. return nil, err
  283. }
  284. var result []byte
  285. if resp.StatusCode < 300 {
  286. result, err = extractVariable(ref, data.Value)
  287. }
  288. for i := len(g.store.GroupIDs) - 1; i >= 0; i-- {
  289. groupID := g.store.GroupIDs[i]
  290. if result != nil {
  291. return result, nil
  292. }
  293. groupVar, resp, err := g.getGroupVariables(groupID, ref, gopts)
  294. if err != nil {
  295. return nil, err
  296. }
  297. if resp != nil && resp.StatusCode < 300 {
  298. result, _ = extractVariable(ref, groupVar.Value)
  299. }
  300. }
  301. if result != nil {
  302. return result, nil
  303. }
  304. return nil, err
  305. }
  306. func extractVariable(ref esv1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  307. if ref.Property == "" {
  308. if value != "" {
  309. return []byte(value), nil
  310. }
  311. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  312. }
  313. var payload string
  314. if value != "" {
  315. payload = value
  316. }
  317. val := gjson.Get(payload, ref.Property)
  318. if !val.Exists() {
  319. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  320. }
  321. return []byte(val.String()), nil
  322. }
  323. func (g *gitlabBase) GetSecretMap(ctx context.Context, ref esv1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  324. // Gets a secret as normal, expecting secret value to be a json object
  325. data, err := g.GetSecret(ctx, ref)
  326. if err != nil {
  327. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  328. }
  329. // Maps the json data to a string:string map
  330. kv := make(map[string]string)
  331. err = json.Unmarshal(data, &kv)
  332. if err != nil {
  333. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  334. }
  335. // Converts values in K:V pairs into bytes, while leaving keys as strings
  336. secretData := make(map[string][]byte)
  337. for k, v := range kv {
  338. secretData[k] = []byte(v)
  339. }
  340. return secretData, nil
  341. }
  342. func isEmptyOrWildcard(environment string) bool {
  343. return environment == "" || environment == "*"
  344. }
  345. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string, bool) {
  346. isWildcard := isEmptyOrWildcard(varEnvironment)
  347. if !isWildcard && !isEmptyOrWildcard(environment) {
  348. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  349. if varEnvironment != environment {
  350. return false, "", isWildcard
  351. }
  352. }
  353. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  354. return false, "", isWildcard
  355. }
  356. return true, key, isWildcard
  357. }
  358. func (g *gitlabBase) Close(_ context.Context) error {
  359. return nil
  360. }
  361. func (g *gitlabBase) ResolveGroupIDs() error {
  362. if g.store.InheritFromGroups {
  363. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.store.ProjectID, nil)
  364. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabListProjectsGroups, err)
  365. if resp.StatusCode >= 400 && err != nil {
  366. return err
  367. }
  368. sort.Sort(ProjectGroupPathSorter(projectGroups))
  369. discoveredIDs := make([]string, len(projectGroups))
  370. for i, group := range projectGroups {
  371. discoveredIDs[i] = strconv.Itoa(group.ID)
  372. }
  373. g.store.GroupIDs = discoveredIDs
  374. }
  375. return nil
  376. }
  377. // 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.
  378. func (g *gitlabBase) Validate() (esv1.ValidationResult, error) {
  379. if g.store.ProjectID != "" {
  380. _, resp, err := g.projectVariablesClient.ListVariables(g.store.ProjectID, nil)
  381. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabProjectListVariables, err)
  382. if err != nil {
  383. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  384. } else if resp == nil || resp.StatusCode != http.StatusOK {
  385. return esv1.ValidationResultError, fmt.Errorf(errProjectAuth, g.store.ProjectID)
  386. }
  387. err = g.ResolveGroupIDs()
  388. if err != nil {
  389. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  390. }
  391. log.V(1).Info("discovered project groups", "name", g.store.GroupIDs)
  392. }
  393. if len(g.store.GroupIDs) > 0 {
  394. for _, groupID := range g.store.GroupIDs {
  395. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  396. metrics.ObserveAPICall(constants.ProviderGitLab, constants.CallGitLabGroupListVariables, err)
  397. if err != nil {
  398. return esv1.ValidationResultError, fmt.Errorf(errList, err)
  399. } else if resp == nil || resp.StatusCode != http.StatusOK {
  400. return esv1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  401. }
  402. }
  403. }
  404. return esv1.ValidationResultReady, nil
  405. }