gitlab.go 14 KB

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