gitlab.go 13 KB

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