gitlab.go 15 KB

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