dependabot_secrets_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*
  2. Copyright © The ESO Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package github
  14. import (
  15. "context"
  16. "encoding/json"
  17. "fmt"
  18. "net/http"
  19. "net/http/httptest"
  20. "net/url"
  21. "testing"
  22. github "github.com/google/go-github/v56/github"
  23. "github.com/stretchr/testify/assert"
  24. "github.com/stretchr/testify/require"
  25. corev1 "k8s.io/api/core/v1"
  26. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  27. esv1alpha1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1alpha1"
  28. )
  29. func TestAdaptDependabotEncryptedSecret(t *testing.T) {
  30. actionsSecret := &github.EncryptedSecret{
  31. Name: "TOKEN",
  32. KeyID: "key-id",
  33. EncryptedValue: "encrypted-value",
  34. Visibility: "selected",
  35. SelectedRepositoryIDs: github.SelectedRepoIDs{12, 34},
  36. }
  37. got := adaptDependabotEncryptedSecret(actionsSecret)
  38. assert.Equal(t, "TOKEN", got.Name)
  39. assert.Equal(t, "key-id", got.KeyID)
  40. assert.Equal(t, "encrypted-value", got.EncryptedValue)
  41. assert.Equal(t, "selected", got.Visibility)
  42. assert.Equal(t, github.DependabotSecretsSelectedRepoIDs{12, 34}, got.SelectedRepositoryIDs)
  43. }
  44. func TestDependabotSecretLifecycle(t *testing.T) {
  45. tests := []struct {
  46. name string
  47. provider *esv1.GithubProvider
  48. pathPrefix string
  49. }{
  50. {
  51. name: "organization",
  52. provider: &esv1.GithubProvider{
  53. SecretType: esv1.GithubSecretTypeDependabot,
  54. Organization: "acme",
  55. },
  56. pathPrefix: "/orgs/acme/dependabot/secrets",
  57. },
  58. {
  59. name: "repository",
  60. provider: &esv1.GithubProvider{
  61. SecretType: esv1.GithubSecretTypeDependabot,
  62. Organization: "acme",
  63. Repository: "widgets",
  64. },
  65. pathPrefix: "/repos/acme/widgets/dependabot/secrets",
  66. },
  67. }
  68. for _, tt := range tests {
  69. t.Run(tt.name, func(t *testing.T) {
  70. var requests []string
  71. var putBody map[string]any
  72. var putDecodeErr error
  73. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  74. requests = append(requests, r.Method+" "+r.URL.Path)
  75. switch {
  76. case r.Method == http.MethodGet && r.URL.Path == tt.pathPrefix+"/public-key":
  77. _, _ = fmt.Fprint(w, `{"key_id":"key-id","key":"a2V5"}`)
  78. case r.Method == http.MethodGet && r.URL.Path == tt.pathPrefix+"/TOKEN":
  79. _, _ = fmt.Fprint(w, `{"name":"TOKEN","visibility":"selected"}`)
  80. case r.Method == http.MethodGet && r.URL.Path == tt.pathPrefix:
  81. _, _ = fmt.Fprint(w, `{"total_count":1,"secrets":[{"name":"TOKEN"}]}`)
  82. case r.Method == http.MethodPut && r.URL.Path == tt.pathPrefix+"/TOKEN":
  83. putDecodeErr = json.NewDecoder(r.Body).Decode(&putBody)
  84. if putDecodeErr != nil {
  85. http.Error(w, putDecodeErr.Error(), http.StatusBadRequest)
  86. return
  87. }
  88. w.WriteHeader(http.StatusCreated)
  89. case r.Method == http.MethodDelete && r.URL.Path == tt.pathPrefix+"/TOKEN":
  90. w.WriteHeader(http.StatusNoContent)
  91. default:
  92. http.Error(w, "unexpected request", http.StatusNotFound)
  93. }
  94. }))
  95. t.Cleanup(server.Close)
  96. g := &Client{provider: tt.provider}
  97. ghClient := newGithubTestClient(t, server)
  98. require.NoError(t, g.configureSecretClient(context.Background(), ghClient, esv1.GithubSecretTypeDependabot))
  99. ref := esv1alpha1.PushSecretData{
  100. Match: esv1alpha1.PushSecretMatch{
  101. RemoteRef: esv1alpha1.PushSecretRemoteRef{RemoteKey: "TOKEN"},
  102. },
  103. }
  104. secret, _, err := g.getSecretFn(context.Background(), ref)
  105. require.NoError(t, err)
  106. assert.Equal(t, "TOKEN", secret.Name)
  107. secrets, _, err := g.listSecretsFn(context.Background())
  108. require.NoError(t, err)
  109. assert.Equal(t, 1, secrets.TotalCount)
  110. key, _, err := g.getPublicKeyFn(context.Background())
  111. require.NoError(t, err)
  112. assert.Equal(t, "key-id", key.GetKeyID())
  113. _, err = g.createOrUpdateFn(context.Background(), &github.EncryptedSecret{
  114. Name: "TOKEN",
  115. KeyID: "key-id",
  116. EncryptedValue: "encrypted-value",
  117. Visibility: "selected",
  118. })
  119. require.NoError(t, err)
  120. _, err = g.deleteSecretFn(context.Background(), ref)
  121. require.NoError(t, err)
  122. require.NoError(t, putDecodeErr)
  123. assert.Equal(t, []string{
  124. http.MethodGet + " " + tt.pathPrefix + "/TOKEN",
  125. http.MethodGet + " " + tt.pathPrefix,
  126. http.MethodGet + " " + tt.pathPrefix + "/public-key",
  127. http.MethodPut + " " + tt.pathPrefix + "/TOKEN",
  128. http.MethodDelete + " " + tt.pathPrefix + "/TOKEN",
  129. }, requests)
  130. assert.Equal(t, "key-id", putBody["key_id"])
  131. assert.Equal(t, "encrypted-value", putBody["encrypted_value"])
  132. assert.Equal(t, "selected", putBody["visibility"])
  133. })
  134. }
  135. }
  136. func TestDependabotPushSecretPreservesSelectedRepositories(t *testing.T) {
  137. var putBody map[string]json.RawMessage
  138. var putDecodeErr error
  139. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  140. switch {
  141. case r.Method == http.MethodGet && r.URL.Path == "/orgs/acme/dependabot/secrets/TOKEN":
  142. _, _ = fmt.Fprint(w, `{"name":"TOKEN","visibility":"selected"}`)
  143. case r.Method == http.MethodGet && r.URL.Path == "/orgs/acme/dependabot/secrets/public-key":
  144. _, _ = fmt.Fprint(w, `{"key_id":"key-id","key":"Zm9vYmFyCg=="}`)
  145. case r.Method == http.MethodGet && r.URL.Path == "/orgs/acme/dependabot/secrets/TOKEN/repositories":
  146. _, _ = fmt.Fprint(w, `{"total_count":2,"repositories":[{"id":12},{"id":34}]}`)
  147. case r.Method == http.MethodPut && r.URL.Path == "/orgs/acme/dependabot/secrets/TOKEN":
  148. putDecodeErr = json.NewDecoder(r.Body).Decode(&putBody)
  149. w.WriteHeader(http.StatusCreated)
  150. default:
  151. http.Error(w, "unexpected request", http.StatusNotFound)
  152. }
  153. }))
  154. t.Cleanup(server.Close)
  155. provider := &esv1.GithubProvider{
  156. SecretType: esv1.GithubSecretTypeDependabot,
  157. Organization: "acme",
  158. }
  159. g := &Client{provider: provider}
  160. require.NoError(t, g.configureSecretClient(context.Background(), newGithubTestClient(t, server), esv1.GithubSecretTypeDependabot))
  161. remoteRef := esv1alpha1.PushSecretData{
  162. Match: esv1alpha1.PushSecretMatch{
  163. SecretKey: "value",
  164. RemoteRef: esv1alpha1.PushSecretRemoteRef{RemoteKey: "TOKEN"},
  165. },
  166. }
  167. err := g.PushSecret(context.Background(), &corev1.Secret{Data: map[string][]byte{"value": []byte("secret")}}, remoteRef)
  168. require.NoError(t, err)
  169. require.NoError(t, putDecodeErr)
  170. assert.JSONEq(t, `"selected"`, string(putBody["visibility"]))
  171. assert.JSONEq(t, `["12","34"]`, string(putBody["selected_repository_ids"]))
  172. }
  173. func TestDependabotOrgSelectedRepositoriesPagination(t *testing.T) {
  174. var server *httptest.Server
  175. server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  176. assert.Equal(t, "/orgs/acme/dependabot/secrets/TOKEN/repositories", r.URL.Path)
  177. switch r.URL.Query().Get("page") {
  178. case "":
  179. w.Header().Set("Link", "<"+server.URL+r.URL.Path+"?page=2>; rel=\"next\"")
  180. _, _ = fmt.Fprint(w, `{"total_count":2,"repositories":[{"id":12}]}`)
  181. case "2":
  182. _, _ = fmt.Fprint(w, `{"total_count":2,"repositories":[{"id":34}]}`)
  183. default:
  184. http.Error(w, "unexpected page", http.StatusBadRequest)
  185. }
  186. }))
  187. t.Cleanup(server.Close)
  188. ghClient := newGithubTestClient(t, server)
  189. g := &Client{
  190. provider: &esv1.GithubProvider{Organization: "acme"},
  191. dependabotClient: *ghClient.Dependabot,
  192. }
  193. ids, err := g.dependabotOrgListSelectedRepoIDs(context.Background(), "TOKEN")
  194. require.NoError(t, err)
  195. assert.Equal(t, github.SelectedRepoIDs{12, 34}, ids)
  196. }
  197. func TestDependabotErrorsPropagate(t *testing.T) {
  198. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  199. http.Error(w, "boom", http.StatusInternalServerError)
  200. }))
  201. t.Cleanup(server.Close)
  202. ghClient := newGithubTestClient(t, server)
  203. g := &Client{
  204. provider: &esv1.GithubProvider{Organization: "acme"},
  205. dependabotClient: *ghClient.Dependabot,
  206. }
  207. ref := esv1alpha1.PushSecretData{
  208. Match: esv1alpha1.PushSecretMatch{
  209. RemoteRef: esv1alpha1.PushSecretRemoteRef{RemoteKey: "TOKEN"},
  210. },
  211. }
  212. _, _, err := g.dependabotOrgGetSecretFn(context.Background(), ref)
  213. assert.Error(t, err)
  214. _, err = g.dependabotOrgListSelectedRepoIDs(context.Background(), "TOKEN")
  215. assert.Error(t, err)
  216. }
  217. func newGithubTestClient(t *testing.T, server *httptest.Server) *github.Client {
  218. t.Helper()
  219. client := github.NewClient(server.Client())
  220. baseURL, err := url.Parse(server.URL + "/")
  221. require.NoError(t, err)
  222. client.BaseURL = baseURL
  223. client.UploadURL = baseURL
  224. return client
  225. }