gitlab.go 13 KB

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