secretsmanager_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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 secretmanager
  13. import (
  14. "context"
  15. "fmt"
  16. "reflect"
  17. "strings"
  18. "testing"
  19. secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
  20. "k8s.io/utils/pointer"
  21. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  22. v1 "github.com/external-secrets/external-secrets/apis/meta/v1"
  23. fakesm "github.com/external-secrets/external-secrets/pkg/provider/gcp/secretmanager/fake"
  24. )
  25. type secretManagerTestCase struct {
  26. mockClient *fakesm.MockSMClient
  27. apiInput *secretmanagerpb.AccessSecretVersionRequest
  28. apiOutput *secretmanagerpb.AccessSecretVersionResponse
  29. ref *esv1beta1.ExternalSecretDataRemoteRef
  30. projectID string
  31. apiErr error
  32. expectError string
  33. expectedSecret string
  34. // for testing secretmap
  35. expectedData map[string][]byte
  36. }
  37. func makeValidSecretManagerTestCase() *secretManagerTestCase {
  38. smtc := secretManagerTestCase{
  39. mockClient: &fakesm.MockSMClient{},
  40. apiInput: makeValidAPIInput(),
  41. ref: makeValidRef(),
  42. apiOutput: makeValidAPIOutput(),
  43. projectID: "default",
  44. apiErr: nil,
  45. expectError: "",
  46. expectedSecret: "",
  47. expectedData: map[string][]byte{},
  48. }
  49. smtc.mockClient.NilClose()
  50. smtc.mockClient.WithValue(context.Background(), smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  51. return &smtc
  52. }
  53. func makeValidRef() *esv1beta1.ExternalSecretDataRemoteRef {
  54. return &esv1beta1.ExternalSecretDataRemoteRef{
  55. Key: "/baz",
  56. Version: "default",
  57. }
  58. }
  59. func makeValidAPIInput() *secretmanagerpb.AccessSecretVersionRequest {
  60. return &secretmanagerpb.AccessSecretVersionRequest{
  61. Name: "projects/default/secrets//baz/versions/default",
  62. }
  63. }
  64. func makeValidAPIOutput() *secretmanagerpb.AccessSecretVersionResponse {
  65. return &secretmanagerpb.AccessSecretVersionResponse{
  66. Payload: &secretmanagerpb.SecretPayload{
  67. Data: []byte{},
  68. },
  69. }
  70. }
  71. func makeValidSecretManagerTestCaseCustom(tweaks ...func(smtc *secretManagerTestCase)) *secretManagerTestCase {
  72. smtc := makeValidSecretManagerTestCase()
  73. for _, fn := range tweaks {
  74. fn(smtc)
  75. }
  76. smtc.mockClient.WithValue(context.Background(), smtc.apiInput, smtc.apiOutput, smtc.apiErr)
  77. return smtc
  78. }
  79. // This case can be shared by both GetSecret and GetSecretMap tests.
  80. // bad case: set apiErr.
  81. var setAPIErr = func(smtc *secretManagerTestCase) {
  82. smtc.apiErr = fmt.Errorf("oh no")
  83. smtc.expectError = "oh no"
  84. }
  85. var setNilMockClient = func(smtc *secretManagerTestCase) {
  86. smtc.mockClient = nil
  87. smtc.expectError = errUninitalizedGCPProvider
  88. }
  89. // test the sm<->gcp interface
  90. // make sure correct values are passed and errors are handled accordingly.
  91. func TestSecretManagerGetSecret(t *testing.T) {
  92. // good case: default version is set
  93. // key is passed in, output is sent back
  94. setSecretString := func(smtc *secretManagerTestCase) {
  95. smtc.apiOutput.Payload.Data = []byte("testtesttest")
  96. smtc.expectedSecret = "testtesttest"
  97. }
  98. // good case: ref with
  99. setCustomRef := func(smtc *secretManagerTestCase) {
  100. smtc.ref = &esv1beta1.ExternalSecretDataRemoteRef{
  101. Key: "/baz",
  102. Version: "default",
  103. Property: "name.first",
  104. }
  105. smtc.apiInput.Name = "projects/default/secrets//baz/versions/default"
  106. smtc.apiOutput.Payload.Data = []byte(
  107. `{
  108. "name": {"first": "Tom", "last": "Anderson"},
  109. "friends": [
  110. {"first": "Dale", "last": "Murphy"},
  111. {"first": "Roger", "last": "Craig"},
  112. {"first": "Jane", "last": "Murphy"}
  113. ]
  114. }`)
  115. smtc.expectedSecret = "Tom"
  116. }
  117. // good case: custom version set
  118. setCustomVersion := func(smtc *secretManagerTestCase) {
  119. smtc.ref.Version = "1234"
  120. smtc.apiInput.Name = "projects/default/secrets//baz/versions/1234"
  121. smtc.apiOutput.Payload.Data = []byte("FOOBA!")
  122. smtc.expectedSecret = "FOOBA!"
  123. }
  124. successCases := []*secretManagerTestCase{
  125. makeValidSecretManagerTestCase(),
  126. makeValidSecretManagerTestCaseCustom(setSecretString),
  127. makeValidSecretManagerTestCaseCustom(setCustomVersion),
  128. makeValidSecretManagerTestCaseCustom(setAPIErr),
  129. makeValidSecretManagerTestCaseCustom(setCustomRef),
  130. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  131. }
  132. sm := ProviderGCP{}
  133. for k, v := range successCases {
  134. sm.projectID = v.projectID
  135. sm.SecretManagerClient = v.mockClient
  136. out, err := sm.GetSecret(context.Background(), *v.ref)
  137. if !ErrorContains(err, v.expectError) {
  138. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  139. }
  140. if err == nil && string(out) != v.expectedSecret {
  141. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  142. }
  143. }
  144. }
  145. func TestGetSecretMap(t *testing.T) {
  146. // good case: default version & deserialization
  147. setDeserialization := func(smtc *secretManagerTestCase) {
  148. smtc.apiOutput.Payload.Data = []byte(`{"foo":"bar"}`)
  149. smtc.expectedData["foo"] = []byte("bar")
  150. }
  151. // bad case: invalid json
  152. setInvalidJSON := func(smtc *secretManagerTestCase) {
  153. smtc.apiOutput.Payload.Data = []byte(`-----------------`)
  154. smtc.expectError = "unable to unmarshal secret"
  155. }
  156. // good case: deserialize nested json as []byte, if it's a string, decode the string
  157. setNestedJSON := func(smtc *secretManagerTestCase) {
  158. smtc.apiOutput.Payload.Data = []byte(`{"foo":{"bar":"baz"}, "qux": "qu\"z"}`)
  159. smtc.expectedData["foo"] = []byte(`{"bar":"baz"}`)
  160. smtc.expectedData["qux"] = []byte("qu\"z")
  161. }
  162. successCases := []*secretManagerTestCase{
  163. makeValidSecretManagerTestCaseCustom(setDeserialization),
  164. makeValidSecretManagerTestCaseCustom(setAPIErr),
  165. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  166. makeValidSecretManagerTestCaseCustom(setInvalidJSON),
  167. makeValidSecretManagerTestCaseCustom(setNestedJSON),
  168. }
  169. sm := ProviderGCP{}
  170. for k, v := range successCases {
  171. sm.projectID = v.projectID
  172. sm.SecretManagerClient = v.mockClient
  173. out, err := sm.GetSecretMap(context.Background(), *v.ref)
  174. if !ErrorContains(err, v.expectError) {
  175. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  176. }
  177. if err == nil && !reflect.DeepEqual(out, v.expectedData) {
  178. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  179. }
  180. }
  181. }
  182. func ErrorContains(out error, want string) bool {
  183. if out == nil {
  184. return want == ""
  185. }
  186. if want == "" {
  187. return false
  188. }
  189. return strings.Contains(out.Error(), want)
  190. }
  191. func TestValidateStore(t *testing.T) {
  192. type args struct {
  193. auth esv1beta1.GCPSMAuth
  194. }
  195. tests := []struct {
  196. name string
  197. args args
  198. wantErr bool
  199. }{
  200. {
  201. name: "empty auth",
  202. wantErr: false,
  203. },
  204. {
  205. name: "invalid secret ref",
  206. wantErr: true,
  207. args: args{
  208. auth: esv1beta1.GCPSMAuth{
  209. SecretRef: &esv1beta1.GCPSMAuthSecretRef{
  210. SecretAccessKey: v1.SecretKeySelector{
  211. Name: "foo",
  212. Namespace: pointer.StringPtr("invalid"),
  213. },
  214. },
  215. },
  216. },
  217. },
  218. {
  219. name: "invalid wi sa ref",
  220. wantErr: true,
  221. args: args{
  222. auth: esv1beta1.GCPSMAuth{
  223. WorkloadIdentity: &esv1beta1.GCPWorkloadIdentity{
  224. ServiceAccountRef: v1.ServiceAccountSelector{
  225. Name: "foo",
  226. Namespace: pointer.StringPtr("invalid"),
  227. },
  228. },
  229. },
  230. },
  231. },
  232. }
  233. for _, tt := range tests {
  234. t.Run(tt.name, func(t *testing.T) {
  235. sm := &ProviderGCP{}
  236. store := &esv1beta1.SecretStore{
  237. Spec: esv1beta1.SecretStoreSpec{
  238. Provider: &esv1beta1.SecretStoreProvider{
  239. GCPSM: &esv1beta1.GCPSMProvider{
  240. Auth: tt.args.auth,
  241. },
  242. },
  243. },
  244. }
  245. if err := sm.ValidateStore(store); (err != nil) != tt.wantErr {
  246. t.Errorf("ProviderGCP.ValidateStore() error = %v, wantErr %v", err, tt.wantErr)
  247. }
  248. })
  249. }
  250. }