gitlab.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. // 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. secretData := make(map[string][]byte)
  205. for _, groupID := range g.groupIDs {
  206. var groupVars []*gitlab.GroupVariable
  207. groupVars, _, err := g.groupVariablesClient.ListVariables(groupID, nil)
  208. if err != nil {
  209. return nil, err
  210. }
  211. for _, data := range groupVars {
  212. matching, key := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  213. if !matching {
  214. continue
  215. }
  216. secretData[key] = []byte(data.Value)
  217. }
  218. }
  219. var projectData []*gitlab.ProjectVariable
  220. projectData, _, err = g.projectVariablesClient.ListVariables(g.projectID, nil)
  221. if err != nil {
  222. return nil, err
  223. }
  224. for _, data := range projectData {
  225. matching, key := matchesFilter(g.environment, data.EnvironmentScope, data.Key, matcher)
  226. if !matching {
  227. continue
  228. }
  229. secretData[key] = []byte(data.Value)
  230. }
  231. return secretData, nil
  232. }
  233. func ExtractTag(tags map[string]string) (string, error) {
  234. var environmentScope string
  235. for tag, value := range tags {
  236. if tag != "environment_scope" {
  237. return "", fmt.Errorf(errTagsOnlyEnvironmentSupported)
  238. }
  239. environmentScope = value
  240. }
  241. return environmentScope, nil
  242. }
  243. func (g *Gitlab) GetSecret(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) ([]byte, error) {
  244. if utils.IsNil(g.projectVariablesClient) || utils.IsNil(g.groupVariablesClient) {
  245. return nil, fmt.Errorf(errUninitializedGitlabProvider)
  246. }
  247. // Need to replace hyphens with underscores to work with Gitlab API
  248. ref.Key = strings.ReplaceAll(ref.Key, "-", "_")
  249. // Retrieves a gitlab variable in the form
  250. // {
  251. // "key": "TEST_VARIABLE_1",
  252. // "variable_type": "env_var",
  253. // "value": "TEST_1",
  254. // "protected": false,
  255. // "masked": true,
  256. // "environment_scope": "*"
  257. // }
  258. var vopts *gitlab.GetProjectVariableOptions
  259. if g.environment != "" {
  260. vopts = &gitlab.GetProjectVariableOptions{Filter: &gitlab.VariableFilter{EnvironmentScope: g.environment}}
  261. }
  262. data, resp, err := g.projectVariablesClient.GetVariable(g.projectID, ref.Key, vopts)
  263. if !isEmptyOrWildcard(g.environment) && resp.StatusCode == http.StatusNotFound {
  264. vopts.Filter.EnvironmentScope = "*"
  265. data, resp, err = g.projectVariablesClient.GetVariable(g.projectID, ref.Key, vopts)
  266. }
  267. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  268. return nil, err
  269. }
  270. err = g.ResolveGroupIds()
  271. if err != nil {
  272. return nil, err
  273. }
  274. var result []byte
  275. if resp.StatusCode < 300 {
  276. result, err = extractVariable(ref, data.Value)
  277. }
  278. for i := len(g.groupIDs) - 1; i >= 0; i-- {
  279. groupID := g.groupIDs[i]
  280. if result != nil {
  281. return result, nil
  282. }
  283. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, nil)
  284. if resp.StatusCode >= 400 && resp.StatusCode != http.StatusNotFound && err != nil {
  285. return nil, err
  286. }
  287. if resp.StatusCode < 300 {
  288. result, _ = extractVariable(ref, groupVar.Value)
  289. }
  290. }
  291. if result != nil {
  292. return result, nil
  293. }
  294. return nil, err
  295. }
  296. func extractVariable(ref esv1beta1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  297. if ref.Property == "" {
  298. if value != "" {
  299. return []byte(value), nil
  300. }
  301. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  302. }
  303. var payload string
  304. if value != "" {
  305. payload = value
  306. }
  307. val := gjson.Get(payload, ref.Property)
  308. if !val.Exists() {
  309. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  310. }
  311. return []byte(val.String()), nil
  312. }
  313. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  314. // Gets a secret as normal, expecting secret value to be a json object
  315. data, err := g.GetSecret(ctx, ref)
  316. if err != nil {
  317. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  318. }
  319. // Maps the json data to a string:string map
  320. kv := make(map[string]string)
  321. err = json.Unmarshal(data, &kv)
  322. if err != nil {
  323. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  324. }
  325. // Converts values in K:V pairs into bytes, while leaving keys as strings
  326. secretData := make(map[string][]byte)
  327. for k, v := range kv {
  328. secretData[k] = []byte(v)
  329. }
  330. return secretData, nil
  331. }
  332. func isEmptyOrWildcard(environment string) bool {
  333. return environment == "" || environment == "*"
  334. }
  335. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string) {
  336. if !isEmptyOrWildcard(environment) {
  337. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  338. if varEnvironment != environment {
  339. return false, ""
  340. }
  341. }
  342. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  343. return false, ""
  344. }
  345. return true, key
  346. }
  347. func (g *Gitlab) Close(ctx context.Context) error {
  348. return nil
  349. }
  350. // 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.
  351. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  352. if g.projectID != "" {
  353. _, resp, err := g.projectVariablesClient.ListVariables(g.projectID, nil)
  354. if err != nil {
  355. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  356. } else if resp == nil || resp.StatusCode != http.StatusOK {
  357. return esv1beta1.ValidationResultError, fmt.Errorf(errProjectAuth, g.projectID)
  358. }
  359. err = g.ResolveGroupIds()
  360. if err != nil {
  361. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  362. }
  363. log.V(1).Info("discovered project groups", "name", g.groupIDs)
  364. }
  365. if len(g.groupIDs) > 0 {
  366. for _, groupID := range g.groupIDs {
  367. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  368. if err != nil {
  369. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  370. } else if resp == nil || resp.StatusCode != http.StatusOK {
  371. return esv1beta1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  372. }
  373. }
  374. }
  375. return esv1beta1.ValidationResultReady, nil
  376. }
  377. func (g *Gitlab) ResolveGroupIds() error {
  378. if g.inheritFromGroups {
  379. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.projectID, nil)
  380. if resp.StatusCode >= 400 && err != nil {
  381. return err
  382. }
  383. sort.Sort(ProjectGroupPathSorter(projectGroups))
  384. discoveredIds := make([]string, len(projectGroups))
  385. for i, group := range projectGroups {
  386. discoveredIds[i] = strconv.Itoa(group.ID)
  387. }
  388. g.groupIDs = discoveredIds
  389. }
  390. return nil
  391. }
  392. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  393. storeSpec := store.GetSpec()
  394. gitlabSpec := storeSpec.Provider.Gitlab
  395. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  396. err := utils.ValidateSecretSelector(store, accessToken)
  397. if err != nil {
  398. return err
  399. }
  400. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  401. return fmt.Errorf("projectID and groupIDs must not both be empty")
  402. }
  403. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  404. return fmt.Errorf("defining groupIDs and inheritFromGroups = true is not allowed")
  405. }
  406. if accessToken.Key == "" {
  407. return fmt.Errorf("accessToken.key cannot be empty")
  408. }
  409. if accessToken.Name == "" {
  410. return fmt.Errorf("accessToken.name cannot be empty")
  411. }
  412. return nil
  413. }