gitlab.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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. 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. // Capabilities return the provider supported capabilities (ReadOnly, WriteOnly, ReadWrite).
  122. func (g *Gitlab) Capabilities() esv1beta1.SecretStoreCapabilities {
  123. return esv1beta1.SecretStoreReadOnly
  124. }
  125. // Method on Gitlab Provider to set up projectVariablesClient with credentials, populate projectID and environment.
  126. func (g *Gitlab) NewClient(ctx context.Context, store esv1beta1.GenericStore, kube kclient.Client, namespace string) (esv1beta1.SecretsClient, error) {
  127. storeSpec := store.GetSpec()
  128. if storeSpec == nil || storeSpec.Provider == nil || storeSpec.Provider.Gitlab == nil {
  129. return nil, fmt.Errorf("no store type or wrong store type")
  130. }
  131. storeSpecGitlab := storeSpec.Provider.Gitlab
  132. cliStore := gClient{
  133. kube: kube,
  134. store: storeSpecGitlab,
  135. namespace: namespace,
  136. storeKind: store.GetObjectKind().GroupVersionKind().Kind,
  137. }
  138. if err := cliStore.setAuth(ctx); err != nil {
  139. return nil, err
  140. }
  141. var err error
  142. // Create projectVariablesClient options
  143. var opts []gitlab.ClientOptionFunc
  144. if cliStore.store.URL != "" {
  145. opts = append(opts, gitlab.WithBaseURL(cliStore.store.URL))
  146. }
  147. // ClientOptionFunc from the gitlab package can be mapped with the CRD
  148. // in a similar way to extend functionality of the provider
  149. // Create a new Gitlab Client using credentials and options
  150. gitlabClient, err := gitlab.NewClient(string(cliStore.credentials), opts...)
  151. if err != nil {
  152. return nil, err
  153. }
  154. g.projectsClient = gitlabClient.Projects
  155. g.projectVariablesClient = gitlabClient.ProjectVariables
  156. g.groupVariablesClient = gitlabClient.GroupVariables
  157. g.projectID = cliStore.store.ProjectID
  158. g.inheritFromGroups = cliStore.store.InheritFromGroups
  159. g.groupIDs = cliStore.store.GroupIDs
  160. g.environment = cliStore.store.Environment
  161. g.url = cliStore.store.URL
  162. return g, nil
  163. }
  164. func (g *Gitlab) DeleteSecret(ctx context.Context, remoteRef esv1beta1.PushRemoteRef) error {
  165. return fmt.Errorf("not implemented")
  166. }
  167. // Not Implemented PushSecret.
  168. func (g *Gitlab) PushSecret(ctx context.Context, value []byte, remoteRef esv1beta1.PushRemoteRef) error {
  169. return fmt.Errorf("not implemented")
  170. }
  171. // GetAllSecrets syncs all gitlab project and group variables into a single Kubernetes Secret.
  172. func (g *Gitlab) GetAllSecrets(ctx context.Context, ref esv1beta1.ExternalSecretFind) (map[string][]byte, error) {
  173. if utils.IsNil(g.projectVariablesClient) {
  174. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  175. }
  176. if ref.Tags != nil {
  177. environment, err := ExtractTag(ref.Tags)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if !isEmptyOrWildcard(g.environment) && !isEmptyOrWildcard(environment) {
  182. return nil, fmt.Errorf(errEnvironmentIsConstricted)
  183. }
  184. g.environment = environment
  185. }
  186. if ref.Path != nil {
  187. return nil, fmt.Errorf(errPathNotImplemented)
  188. }
  189. if ref.Name == nil {
  190. return nil, fmt.Errorf(errNameNotDefined)
  191. }
  192. var matcher *find.Matcher
  193. if ref.Name != nil {
  194. m, err := find.New(*ref.Name)
  195. if err != nil {
  196. return nil, err
  197. }
  198. matcher = m
  199. }
  200. err := g.ResolveGroupIds()
  201. if err != nil {
  202. return nil, err
  203. }
  204. var gopts = &gitlab.ListGroupVariablesOptions{PerPage: 100}
  205. secretData := make(map[string][]byte)
  206. for _, groupID := range g.groupIDs {
  207. for groupPage := 1; ; groupPage++ {
  208. gopts.Page = groupPage
  209. groupVars, response, err := g.groupVariablesClient.ListVariables(groupID, gopts)
  210. if err != nil {
  211. return nil, err
  212. }
  213. for _, data := range groupVars {
  214. matching, key, isWildcard := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  215. if !matching && !isWildcard {
  216. continue
  217. }
  218. secretData[key] = []byte(data.Value)
  219. }
  220. if response.CurrentPage >= response.TotalPages {
  221. break
  222. }
  223. }
  224. }
  225. var popts = &gitlab.ListProjectVariablesOptions{PerPage: 100}
  226. for projectPage := 1; ; projectPage++ {
  227. popts.Page = projectPage
  228. projectData, response, err := g.projectVariablesClient.ListVariables(g.projectID, popts)
  229. if err != nil {
  230. return nil, err
  231. }
  232. for _, data := range projectData {
  233. matching, key, isWildcard := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  234. if !matching {
  235. continue
  236. }
  237. _, exists := secretData[key]
  238. if exists && isWildcard {
  239. continue
  240. }
  241. secretData[key] = []byte(data.Value)
  242. }
  243. if response.CurrentPage >= response.TotalPages {
  244. break
  245. }
  246. }
  247. return secretData, nil
  248. }
  249. func ExtractTag(tags map[string]string) (string, error) {
  250. var environmentScope string
  251. for tag, value := range tags {
  252. if tag != "environment_scope" {
  253. return "", fmt.Errorf(errTagsOnlyEnvironmentSupported)
  254. }
  255. environmentScope = value
  256. }
  257. return environmentScope, nil
  258. }
  259. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  260. if utils.IsNil(g.projectVariablesClient) || utils.IsNil(g.groupVariablesClient) {
  261. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  262. }
  263. // Need to replace hyphens with underscores to work with Gitlab API
  264. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  265. // Retrieves a gitlab variable in the form
  266. // {
  267. // "key": "TEST_VARIABLE_1",
  268. // "variable_type": "env_var",
  269. // "value": "TEST_1",
  270. // "protected": false,
  271. // "masked": true,
  272. // "environment_scope": "*"
  273. // }
  274. var vopts *gitlab.GetProjectVariableOptions
  275. if g.environment != "" {
  276. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.environment}}
  277. }
  278. data, resp, err := g.projectVariablesClient.GetVariable(g.projectID, ref.Key, vopts)
  279. if !isEmptyOrWildcard(g.environment) && resp.StatusCode == http.StatusNotFound {
  280. vopts.Filter.EnvironmentScope = "*"
  281. data, resp, err = g.projectVariablesClient.GetVariable(g.projectID, ref.Key, vopts)
  282. }
  283. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  284. return nil, err
  285. }
  286. err = g.ResolveGroupIds()
  287. if err != nil {
  288. return nil, err
  289. }
  290. var result []byte
  291. if resp.StatusCode < 300 {
  292. result, err = extractVariable(ref, data.Value)
  293. }
  294. for i := len(g.groupIDs) - 1; i >= 0; i-- {
  295. groupID := g.groupIDs[i]
  296. if result != nil {
  297. return result, nil
  298. }
  299. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, nil)
  300. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  301. return nil, err
  302. }
  303. if resp.StatusCode < 300 {
  304. result, _ = extractVariable(ref, groupVar.Value)
  305. }
  306. }
  307. if result != nil {
  308. return result, nil
  309. }
  310. return nil, err
  311. }
  312. func extractVariable(ref esv1beta1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  313. if ref.Property == "" {
  314. if value != "" {
  315. return []byte(value), nil
  316. }
  317. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  318. }
  319. var payload string
  320. if value != "" {
  321. payload = value
  322. }
  323. val := gjson.Get(payload, ref.Property)
  324. if !val.Exists() {
  325. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  326. }
  327. return []byte(val.String()), nil
  328. }
  329. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  330. // Gets a secret as normal, expecting secret value to be a json object
  331. data, err := g.GetSecret(ctx, ref)
  332. if err != nil {
  333. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  334. }
  335. // Maps the json data to a string:string map
  336. kv := make(map[string]string)
  337. err = json.Unmarshal(data, &kv)
  338. if err != nil {
  339. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  340. }
  341. // Converts values in K:V pairs into bytes, while leaving keys as strings
  342. secretData := make(map[string][]byte)
  343. for k, v := range kv {
  344. secretData[k] = []byte(v)
  345. }
  346. return secretData, nil
  347. }
  348. func isEmptyOrWildcard(environment string) bool {
  349. return environment == "" || environment == "*"
  350. }
  351. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string, bool) {
  352. isWildcard := isEmptyOrWildcard(varEnvironment)
  353. if !isWildcard && !isEmptyOrWildcard(environment) {
  354. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  355. if varEnvironment != environment {
  356. return false, "", isWildcard
  357. }
  358. }
  359. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  360. return false, "", isWildcard
  361. }
  362. return true, key, isWildcard
  363. }
  364. func (g *Gitlab) Close(ctx context.Context) error {
  365. return nil
  366. }
  367. // 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.
  368. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  369. if g.projectID != "" {
  370. _, resp, err := g.projectVariablesClient.ListVariables(g.projectID, nil)
  371. if err != nil {
  372. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  373. } else if resp == nil || resp.StatusCode != http.StatusOK {
  374. return esv1beta1.ValidationResultError, fmt.Errorf(errProjectAuth, g.projectID)
  375. }
  376. err = g.ResolveGroupIds()
  377. if err != nil {
  378. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  379. }
  380. log.V(1).Info("discovered project groups", "name", g.groupIDs)
  381. }
  382. if len(g.groupIDs) > 0 {
  383. for _, groupID := range g.groupIDs {
  384. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  385. if err != nil {
  386. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  387. } else if resp == nil || resp.StatusCode != http.StatusOK {
  388. return esv1beta1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  389. }
  390. }
  391. }
  392. return esv1beta1.ValidationResultReady, nil
  393. }
  394. func (g *Gitlab) ResolveGroupIds() error {
  395. if g.inheritFromGroups {
  396. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.projectID, nil)
  397. if resp.StatusCode >= 400 && err != nil {
  398. return err
  399. }
  400. sort.Sort(ProjectGroupPathSorter(projectGroups))
  401. discoveredIds := make([]string, len(projectGroups))
  402. for i, group := range projectGroups {
  403. discoveredIds[i] = strconv.Itoa(group.ID)
  404. }
  405. g.groupIDs = discoveredIds
  406. }
  407. return nil
  408. }
  409. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  410. storeSpec := store.GetSpec()
  411. gitlabSpec := storeSpec.Provider.Gitlab
  412. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  413. err := utils.ValidateSecretSelector(store, accessToken)
  414. if err != nil {
  415. return err
  416. }
  417. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  418. return fmt.Errorf("projectID and groupIDs must not both be empty")
  419. }
  420. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  421. return fmt.Errorf("defining groupIDs and inheritFromGroups = true is not allowed")
  422. }
  423. if accessToken.Key == "" {
  424. return fmt.Errorf("accessToken.key cannot be empty")
  425. }
  426. if accessToken.Name == "" {
  427. return fmt.Errorf("accessToken.name cannot be empty")
  428. }
  429. return nil
  430. }