gitlab.go 14 KB

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