gitlab.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. gitlab "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. kclient "sigs.k8s.io/controller-runtime/pkg/client"
  27. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  28. "github.com/external-secrets/external-secrets/pkg/find"
  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 = &Gitlab{}
  48. var _ esv1beta1.Provider = &Gitlab{}
  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. // Gitlab Provider struct with reference to GitLab clients, a projectID and groupIDs.
  61. type Gitlab struct {
  62. projectsClient ProjectsClient
  63. projectVariablesClient ProjectVariablesClient
  64. groupVariablesClient GroupVariablesClient
  65. url string
  66. projectID string
  67. inheritFromGroups bool
  68. groupIDs []string
  69. environment string
  70. }
  71. // gClient for interacting with kubernetes cluster...?
  72. type gClient struct {
  73. kube kclient.Client
  74. store *esv1beta1.GitlabProvider
  75. namespace string
  76. storeKind string
  77. credentials []byte
  78. }
  79. type ProjectGroupPathSorter []*gitlab.ProjectGroup
  80. func (a ProjectGroupPathSorter) Len() int { return len(a) }
  81. func (a ProjectGroupPathSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  82. func (a ProjectGroupPathSorter) Less(i, j int) bool { return len(a[i].FullPath) < len(a[j].FullPath) }
  83. var log = ctrl.Log.WithName("provider").WithName("gitlab")
  84. func init() {
  85. esv1beta1.Register(&Gitlab{}, &esv1beta1.SecretStoreProvider{
  86. Gitlab: &esv1beta1.GitlabProvider{},
  87. })
  88. }
  89. // Set gClient credentials to Access Token.
  90. func (c *gClient) setAuth(ctx context.Context) error {
  91. credentialsSecret := &corev1.Secret{}
  92. credentialsSecretName := c.store.Auth.SecretRef.AccessToken.Name
  93. if credentialsSecretName == "" {
  94. return fmt.Errorf(errGitlabCredSecretName)
  95. }
  96. objectKey := types.NamespacedName{
  97. Name: credentialsSecretName,
  98. Namespace: c.namespace,
  99. }
  100. // only ClusterStore is allowed to set namespace (and then it's required)
  101. if c.storeKind == esv1beta1.ClusterSecretStoreKind {
  102. if c.store.Auth.SecretRef.AccessToken.Namespace == nil {
  103. return fmt.Errorf(errInvalidClusterStoreMissingSAKNamespace)
  104. }
  105. objectKey.Namespace = *c.store.Auth.SecretRef.AccessToken.Namespace
  106. }
  107. err := c.kube.Get(ctx, objectKey, credentialsSecret)
  108. if err != nil {
  109. return fmt.Errorf(errFetchSAKSecret, err)
  110. }
  111. c.credentials = credentialsSecret.Data[c.store.Auth.SecretRef.AccessToken.Key]
  112. if c.credentials == nil || len(c.credentials) == 0 {
  113. return fmt.Errorf(errMissingSAK)
  114. }
  115. return nil
  116. }
  117. // Function newGitlabProvider returns a reference to a new instance of a 'Gitlab' struct.
  118. func NewGitlabProvider() *Gitlab {
  119. return &Gitlab{}
  120. }
  121. // Method on Gitlab Provider to set up projectVariablesClient with credentials, populate projectID and environment.
  122. func (g *Gitlab) NewClient(ctx context.Context, store esv1beta1.GenericStore, kube kclient.Client, namespace string) (esv1beta1.SecretsClient, error) {
  123. storeSpec := store.GetSpec()
  124. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  125. return nil, fmt.Errorf("no store type or wrong store type")
  126. }
  127. storeSpecGitlab := storeSpec.Provider.Gitlab
  128. cliStore := gClient{
  129. kube: kube,
  130. store: storeSpecGitlab,
  131. namespace: namespace,
  132. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  133. }
  134. if err := cliStore.setAuth(ctx); err != nil {
  135. return nil, err
  136. }
  137. var err error
  138. // Create projectVariablesClient options
  139. var opts []gitlab.ClientOptionFunc
  140. if cliStore.store.URL != "" {
  141. opts = append(opts, gitlab.WithBaseURL(cliStore.store.URL))
  142. }
  143. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  144. // in a similar way to extend functionality of the provider
  145. // Create a new Gitlab Client using credentials and options
  146. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), opts...)
  147. if err != nil {
  148. return nil, err
  149. }
  150. g.projectsClient = gitlabClient.Projects
  151. g.projectVariablesClient = gitlabClient.ProjectVariables
  152. g.groupVariablesClient = gitlabClient.GroupVariables
  153. g.projectID = cliStore.store.ProjectID
  154. g.inheritFromGroups = cliStore.store.InheritFromGroups
  155. g.groupIDs = cliStore.store.GroupIDs
  156. g.environment = cliStore.store.Environment
  157. g.url = cliStore.store.URL
  158. return g, nil
  159. }
  160. // GetAllSecrets syncs all gitlab project and group variables into a single Kubernetes Secret.
  161. func (g *Gitlab) GetAllSecrets(ctx context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  162. if utils.IsNil(g.projectVariablesClient) {
  163. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  164. }
  165. if ref.Tags != nil {
  166. environment, err := ExtractTag(ref.Tags)
  167. if err != nil {
  168. return nil, err
  169. }
  170. if !isEmptyOrWildcard(g.environment) && !isEmptyOrWildcard(environment) {
  171. return nil, fmt.Errorf(errEnvironmentIsConstricted)
  172. }
  173. g.environment = environment
  174. }
  175. if ref.Path != nil {
  176. return nil, fmt.Errorf(errPathNotImplemented)
  177. }
  178. if ref.Name == nil {
  179. return nil, fmt.Errorf(errNameNotDefined)
  180. }
  181. var matcher *find.Matcher
  182. if ref.Name != nil {
  183. m, err := find.New(*ref.Name)
  184. if err != nil {
  185. return nil, err
  186. }
  187. matcher = m
  188. }
  189. err := g.ResolveGroupIds()
  190. if err != nil {
  191. return nil, err
  192. }
  193. secretData := make(map[string][]byte)
  194. for _, groupID := range g.groupIDs {
  195. var groupVars []*gitlab.GroupVariable
  196. groupVars, _, err := g.groupVariablesClient.ListVariables(groupID, nil)
  197. if err != nil {
  198. return nil, err
  199. }
  200. for _, data := range groupVars {
  201. matching, key := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  202. if !matching {
  203. continue
  204. }
  205. secretData[key] = []byte(data.Value)
  206. }
  207. }
  208. var projectData []*gitlab.ProjectVariable
  209. projectData, _, err = g.projectVariablesClient.ListVariables(g.projectID, nil)
  210. if err != nil {
  211. return nil, err
  212. }
  213. for _, data := range projectData {
  214. matching, key := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  215. if !matching {
  216. continue
  217. }
  218. secretData[key] = []byte(data.Value)
  219. }
  220. return secretData, nil
  221. }
  222. func ExtractTag(tags map[string]string) (string, error) {
  223. var environmentScope string
  224. for tag, value := range tags {
  225. if tag != "environment_scope" {
  226. return "", fmt.Errorf(errTagsOnlyEnvironmentSupported)
  227. }
  228. environmentScope = value
  229. }
  230. return environmentScope, nil
  231. }
  232. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  233. if utils.IsNil(g.projectVariablesClient) || utils.IsNil(g.groupVariablesClient) {
  234. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  235. }
  236. // Need to replace hyphens with underscores to work with Gitlab API
  237. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  238. // Retrieves a gitlab variable in the form
  239. // {
  240. // "key": "TEST_VARIABLE_1",
  241. // "variable_type": "env_var",
  242. // "value": "TEST_1",
  243. // "protected": false,
  244. // "masked": true,
  245. // "environment_scope": "*"
  246. // }
  247. var vopts *gitlab.GetProjectVariableOptions
  248. if g.environment != "" {
  249. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.environment}}
  250. }
  251. data, resp, err := g.projectVariablesClient.GetVariable(g.projectID, ref.Key, vopts)
  252. if resp.StatusCode >= 400 && resp.StatusCode != 404 && err != nil {
  253. return nil, err
  254. }
  255. err = g.ResolveGroupIds()
  256. if err != nil {
  257. return nil, err
  258. }
  259. var result []byte
  260. if resp.StatusCode < 300 {
  261. result, err = extractVariable(ref, data.Value)
  262. }
  263. for i := len(g.groupIDs) - 1; i >= 0; i-- {
  264. groupID := g.groupIDs[i]
  265. if result != nil {
  266. return result, nil
  267. }
  268. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, nil)
  269. if resp.StatusCode >= 400 && resp.StatusCode != 404 && err != nil {
  270. return nil, err
  271. }
  272. if resp.StatusCode < 300 {
  273. result, _ = extractVariable(ref, groupVar.Value)
  274. }
  275. }
  276. if result != nil {
  277. return result, nil
  278. }
  279. return nil, err
  280. }
  281. func extractVariable(ref esv1beta1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  282. if ref.Property == "" {
  283. if value != "" {
  284. return []byte(value), nil
  285. }
  286. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  287. }
  288. var payload string
  289. if value != "" {
  290. payload = value
  291. }
  292. val := gjson.Get(payload, ref.Property)
  293. if !val.Exists() {
  294. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  295. }
  296. return []byte(val.String()), nil
  297. }
  298. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  299. // Gets a secret as normal, expecting secret value to be a json object
  300. data, err := g.GetSecret(ctx, ref)
  301. if err != nil {
  302. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  303. }
  304. // Maps the json data to a string:string map
  305. kv := make(map[string]string)
  306. err = json.Unmarshal(data, &kv)
  307. if err != nil {
  308. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  309. }
  310. // Converts values in K:V pairs into bytes, while leaving keys as strings
  311. secretData := make(map[string][]byte)
  312. for k, v := range kv {
  313. secretData[k] = []byte(v)
  314. }
  315. return secretData, nil
  316. }
  317. func isEmptyOrWildcard(environment string) bool {
  318. return environment == "" || environment == "*"
  319. }
  320. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string) {
  321. if !isEmptyOrWildcard(environment) {
  322. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  323. if varEnvironment != environment {
  324. return false, ""
  325. }
  326. }
  327. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  328. return false, ""
  329. }
  330. return true, key
  331. }
  332. func (g *Gitlab) Close(ctx context.Context) error {
  333. return nil
  334. }
  335. // 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.
  336. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  337. if g.projectID != "" {
  338. _, resp, err := g.projectVariablesClient.ListVariables(g.projectID, nil)
  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(errProjectAuth, g.projectID)
  343. }
  344. err = g.ResolveGroupIds()
  345. if err != nil {
  346. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  347. }
  348. log.V(1).Info("discovered project groups", "name", g.groupIDs)
  349. }
  350. if len(g.groupIDs) > 0 {
  351. for _, groupID := range g.groupIDs {
  352. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  353. if err != nil {
  354. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  355. } else if resp == nil || resp.StatusCode != http.StatusOK {
  356. return esv1beta1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  357. }
  358. }
  359. }
  360. return esv1beta1.ValidationResultReady, nil
  361. }
  362. func (g *Gitlab) ResolveGroupIds() error {
  363. if g.inheritFromGroups {
  364. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.projectID, nil)
  365. if resp.StatusCode >= 400 && err != nil {
  366. return err
  367. }
  368. sort.Sort(ProjectGroupPathSorter(projectGroups))
  369. discoveredIds := make([]string, len(projectGroups))
  370. for i, group := range projectGroups {
  371. discoveredIds[i] = strconv.Itoa(group.ID)
  372. }
  373. g.groupIDs = discoveredIds
  374. }
  375. return nil
  376. }
  377. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  378. storeSpec := store.GetSpec()
  379. gitlabSpec := storeSpec.Provider.Gitlab
  380. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  381. err := utils.ValidateSecretSelector(store, accessToken)
  382. if err != nil {
  383. return err
  384. }
  385. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  386. return fmt.Errorf("projectID and groupIDs must not both be empty")
  387. }
  388. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  389. return fmt.Errorf("defining groupIDs and inheritFromGroups = true is not allowed")
  390. }
  391. if accessToken.Key == "" {
  392. return fmt.Errorf("accessToken.key cannot be empty")
  393. }
  394. if accessToken.Name == "" {
  395. return fmt.Errorf("accessToken.name cannot be empty")
  396. }
  397. return nil
  398. }