gitlab.go 13 KB

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