gitlab.go 14 KB

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