secretsmanager_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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: with a dot in the key name
  99. setDotRef := func(smtc *secretManagerTestCase) {
  100. smtc.ref = &esv1beta1.ExternalSecretDataRemoteRef{
  101. Key: "/baz",
  102. Version: "default",
  103. Property: "name.json",
  104. }
  105. smtc.apiInput.Name = "projects/default/secrets//baz/versions/default"
  106. smtc.apiOutput.Payload.Data = []byte(
  107. `{
  108. "name.json": "Tom",
  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: ref with
  118. setCustomRef := func(smtc *secretManagerTestCase) {
  119. smtc.ref = &esv1beta1.ExternalSecretDataRemoteRef{
  120. Key: "/baz",
  121. Version: "default",
  122. Property: "name.first",
  123. }
  124. smtc.apiInput.Name = "projects/default/secrets//baz/versions/default"
  125. smtc.apiOutput.Payload.Data = []byte(
  126. `{
  127. "name": {"first": "Tom", "last": "Anderson"},
  128. "friends": [
  129. {"first": "Dale", "last": "Murphy"},
  130. {"first": "Roger", "last": "Craig"},
  131. {"first": "Jane", "last": "Murphy"}
  132. ]
  133. }`)
  134. smtc.expectedSecret = "Tom"
  135. }
  136. // good case: custom version set
  137. setCustomVersion := func(smtc *secretManagerTestCase) {
  138. smtc.ref.Version = "1234"
  139. smtc.apiInput.Name = "projects/default/secrets//baz/versions/1234"
  140. smtc.apiOutput.Payload.Data = []byte("FOOBA!")
  141. smtc.expectedSecret = "FOOBA!"
  142. }
  143. successCases := []*secretManagerTestCase{
  144. makeValidSecretManagerTestCase(),
  145. makeValidSecretManagerTestCaseCustom(setSecretString),
  146. makeValidSecretManagerTestCaseCustom(setCustomVersion),
  147. makeValidSecretManagerTestCaseCustom(setAPIErr),
  148. makeValidSecretManagerTestCaseCustom(setCustomRef),
  149. makeValidSecretManagerTestCaseCustom(setDotRef),
  150. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  151. }
  152. sm := ProviderGCP{}
  153. for k, v := range successCases {
  154. sm.projectID = v.projectID
  155. sm.SecretManagerClient = v.mockClient
  156. out, err := sm.GetSecret(context.Background(), *v.ref)
  157. if !ErrorContains(err, v.expectError) {
  158. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  159. }
  160. if err == nil && string(out) != v.expectedSecret {
  161. t.Errorf("[%d] unexpected secret: expected %s, got %s", k, v.expectedSecret, string(out))
  162. }
  163. }
  164. }
  165. func TestGetSecretMap(t *testing.T) {
  166. // good case: default version & deserialization
  167. setDeserialization := func(smtc *secretManagerTestCase) {
  168. smtc.apiOutput.Payload.Data = []byte(`{"foo":"bar"}`)
  169. smtc.expectedData["foo"] = []byte("bar")
  170. }
  171. // bad case: invalid json
  172. setInvalidJSON := func(smtc *secretManagerTestCase) {
  173. smtc.apiOutput.Payload.Data = []byte(`-----------------`)
  174. smtc.expectError = "unable to unmarshal secret"
  175. }
  176. // good case: deserialize nested json as []byte, if it's a string, decode the string
  177. setNestedJSON := func(smtc *secretManagerTestCase) {
  178. smtc.apiOutput.Payload.Data = []byte(`{"foo":{"bar":"baz"}, "qux": "qu\"z"}`)
  179. smtc.expectedData["foo"] = []byte(`{"bar":"baz"}`)
  180. smtc.expectedData["qux"] = []byte("qu\"z")
  181. }
  182. successCases := []*secretManagerTestCase{
  183. makeValidSecretManagerTestCaseCustom(setDeserialization),
  184. makeValidSecretManagerTestCaseCustom(setAPIErr),
  185. makeValidSecretManagerTestCaseCustom(setNilMockClient),
  186. makeValidSecretManagerTestCaseCustom(setInvalidJSON),
  187. makeValidSecretManagerTestCaseCustom(setNestedJSON),
  188. }
  189. sm := ProviderGCP{}
  190. for k, v := range successCases {
  191. sm.projectID = v.projectID
  192. sm.SecretManagerClient = v.mockClient
  193. out, err := sm.GetSecretMap(context.Background(), *v.ref)
  194. if !ErrorContains(err, v.expectError) {
  195. t.Errorf("[%d] unexpected error: %s, expected: '%s'", k, err.Error(), v.expectError)
  196. }
  197. if err == nil && !reflect.DeepEqual(out, v.expectedData) {
  198. t.Errorf("[%d] unexpected secret data: expected %#v, got %#v", k, v.expectedData, out)
  199. }
  200. }
  201. }
  202. func ErrorContains(out error, want string) bool {
  203. if out == nil {
  204. return want == ""
  205. }
  206. if want == "" {
  207. return false
  208. }
  209. return strings.Contains(out.Error(), want)
  210. }
  211. func TestValidateStore(t *testing.T) {
  212. type args struct {
  213. auth esv1beta1.GCPSMAuth
  214. }
  215. tests := []struct {
  216. name string
  217. args args
  218. wantErr bool
  219. }{
  220. {
  221. name: "empty auth",
  222. wantErr: false,
  223. },
  224. {
  225. name: "invalid secret ref",
  226. wantErr: true,
  227. args: args{
  228. auth: esv1beta1.GCPSMAuth{
  229. SecretRef: &esv1beta1.GCPSMAuthSecretRef{
  230. SecretAccessKey: v1.SecretKeySelector{
  231. Name: "foo",
  232. Namespace: pointer.StringPtr("invalid"),
  233. },
  234. },
  235. },
  236. },
  237. },
  238. {
  239. name: "invalid wi sa ref",
  240. wantErr: true,
  241. args: args{
  242. auth: esv1beta1.GCPSMAuth{
  243. WorkloadIdentity: &esv1beta1.GCPWorkloadIdentity{
  244. ServiceAccountRef: v1.ServiceAccountSelector{
  245. Name: "foo",
  246. Namespace: pointer.StringPtr("invalid"),
  247. },
  248. },
  249. },
  250. },
  251. },
  252. }
  253. for _, tt := range tests {
  254. t.Run(tt.name, func(t *testing.T) {
  255. sm := &ProviderGCP{}
  256. store := &esv1beta1.SecretStore{
  257. Spec: esv1beta1.SecretStoreSpec{
  258. Provider: &esv1beta1.SecretStoreProvider{
  259. GCPSM: &esv1beta1.GCPSMProvider{
  260. Auth: tt.args.auth,
  261. },
  262. },
  263. },
  264. }
  265. if err := sm.ValidateStore(store); (err != nil) != tt.wantErr {
  266. t.Errorf("ProviderGCP.ValidateStore() error = %v, wantErr %v", err, tt.wantErr)
  267. }
  268. })
  269. }
  270. }