gitlab.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 resp.StatusCode >= 400 && resp.StatusCode != 404 && err != nil {
  264. return nil, err
  265. }
  266. err = g.ResolveGroupIds()
  267. if err != nil {
  268. return nil, err
  269. }
  270. var result []byte
  271. if resp.StatusCode < 300 {
  272. result, err = extractVariable(ref, data.Value)
  273. }
  274. for i := len(g.groupIDs) - 1; i >= 0; i-- {
  275. groupID := g.groupIDs[i]
  276. if result != nil {
  277. return result, nil
  278. }
  279. groupVar, resp, err := g.groupVariablesClient.GetVariable(groupID, ref.Key, nil)
  280. if resp.StatusCode >= 400 && resp.StatusCode != 404 && err != nil {
  281. return nil, err
  282. }
  283. if resp.StatusCode < 300 {
  284. result, _ = extractVariable(ref, groupVar.Value)
  285. }
  286. }
  287. if result != nil {
  288. return result, nil
  289. }
  290. return nil, err
  291. }
  292. func extractVariable(ref esv1beta1.ExternalSecretDataRemoteRef, value string) ([]byte, error) {
  293. if ref.Property == "" {
  294. if value != "" {
  295. return []byte(value), nil
  296. }
  297. return nil, fmt.Errorf("invalid secret received. no secret string for key: %s", ref.Key)
  298. }
  299. var payload string
  300. if value != "" {
  301. payload = value
  302. }
  303. val := gjson.Get(payload, ref.Property)
  304. if !val.Exists() {
  305. return nil, fmt.Errorf("key %s does not exist in secret %s", ref.Property, ref.Key)
  306. }
  307. return []byte(val.String()), nil
  308. }
  309. func (g *Gitlab) GetSecretMap(ctx context.Context, ref esv1beta1.ExternalSecretDataRemoteRef) (map[string][]byte, error) {
  310. // Gets a secret as normal, expecting secret value to be a json object
  311. data, err := g.GetSecret(ctx, ref)
  312. if err != nil {
  313. return nil, fmt.Errorf("error getting secret %s: %w", ref.Key, err)
  314. }
  315. // Maps the json data to a string:string map
  316. kv := make(map[string]string)
  317. err = json.Unmarshal(data, &kv)
  318. if err != nil {
  319. return nil, fmt.Errorf(errJSONSecretUnmarshal, err)
  320. }
  321. // Converts values in K:V pairs into bytes, while leaving keys as strings
  322. secretData := make(map[string][]byte)
  323. for k, v := range kv {
  324. secretData[k] = []byte(v)
  325. }
  326. return secretData, nil
  327. }
  328. func isEmptyOrWildcard(environment string) bool {
  329. return environment == "" || environment == "*"
  330. }
  331. func matchesFilter(environment, varEnvironment, key string, matcher *find.Matcher) (bool, string) {
  332. if !isEmptyOrWildcard(environment) {
  333. // as of now gitlab does not support filtering of EnvironmentScope through the api call
  334. if varEnvironment != environment {
  335. return false, ""
  336. }
  337. }
  338. if key == "" || (matcher != nil && !matcher.MatchName(key)) {
  339. return false, ""
  340. }
  341. return true, key
  342. }
  343. func (g *Gitlab) Close(ctx context.Context) error {
  344. return nil
  345. }
  346. // 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.
  347. func (g *Gitlab) Validate() (esv1beta1.ValidationResult, error) {
  348. if g.projectID != "" {
  349. _, resp, err := g.projectVariablesClient.ListVariables(g.projectID, nil)
  350. if err != nil {
  351. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  352. } else if resp == nil || resp.StatusCode != http.StatusOK {
  353. return esv1beta1.ValidationResultError, fmt.Errorf(errProjectAuth, g.projectID)
  354. }
  355. err = g.ResolveGroupIds()
  356. if err != nil {
  357. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  358. }
  359. log.V(1).Info("discovered project groups", "name", g.groupIDs)
  360. }
  361. if len(g.groupIDs) > 0 {
  362. for _, groupID := range g.groupIDs {
  363. _, resp, err := g.groupVariablesClient.ListVariables(groupID, nil)
  364. if err != nil {
  365. return esv1beta1.ValidationResultError, fmt.Errorf(errList, err)
  366. } else if resp == nil || resp.StatusCode != http.StatusOK {
  367. return esv1beta1.ValidationResultError, fmt.Errorf(errGroupAuth, groupID)
  368. }
  369. }
  370. }
  371. return esv1beta1.ValidationResultReady, nil
  372. }
  373. func (g *Gitlab) ResolveGroupIds() error {
  374. if g.inheritFromGroups {
  375. projectGroups, resp, err := g.projectsClient.ListProjectsGroups(g.projectID, nil)
  376. if resp.StatusCode >= 400 && err != nil {
  377. return err
  378. }
  379. sort.Sort(ProjectGroupPathSorter(projectGroups))
  380. discoveredIds := make([]string, len(projectGroups))
  381. for i, group := range projectGroups {
  382. discoveredIds[i] = strconv.Itoa(group.ID)
  383. }
  384. g.groupIDs = discoveredIds
  385. }
  386. return nil
  387. }
  388. func (g *Gitlab) ValidateStore(store esv1beta1.GenericStore) error {
  389. storeSpec := store.GetSpec()
  390. gitlabSpec := storeSpec.Provider.Gitlab
  391. accessToken := gitlabSpec.Auth.SecretRef.AccessToken
  392. err := utils.ValidateSecretSelector(store, accessToken)
  393. if err != nil {
  394. return err
  395. }
  396. if gitlabSpec.ProjectID == "" && len(gitlabSpec.GroupIDs) == 0 {
  397. return fmt.Errorf("projectID and groupIDs must not both be empty")
  398. }
  399. if gitlabSpec.InheritFromGroups && len(gitlabSpec.GroupIDs) > 0 {
  400. return fmt.Errorf("defining groupIDs and inheritFromGroups = true is not allowed")
  401. }
  402. if accessToken.Key == "" {
  403. return fmt.Errorf("accessToken.key cannot be empty")
  404. }
  405. if accessToken.Name == "" {
  406. return fmt.Errorf("accessToken.name cannot be empty")
  407. }
  408. return nil
  409. }