provider_test.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 infisical
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "net/http"
  19. "net/http/httptest"
  20. "testing"
  21. "github.com/stretchr/testify/assert"
  22. "github.com/stretchr/testify/require"
  23. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  24. esv1meta "github.com/external-secrets/external-secrets/apis/meta/v1"
  25. "github.com/external-secrets/external-secrets/pkg/provider/infisical/api"
  26. )
  27. type storeModifier func(*esv1.SecretStore) *esv1.SecretStore
  28. var apiScope = InfisicalClientScope{
  29. SecretPath: "/",
  30. ProjectSlug: "first-project",
  31. EnvironmentSlug: "dev",
  32. }
  33. type TestCases struct {
  34. Name string
  35. MockStatusCode int
  36. MockResponse any
  37. Key string
  38. Property string
  39. Error error
  40. Output any
  41. }
  42. func TestGetSecret(t *testing.T) {
  43. key := "foo"
  44. testCases := []TestCases{
  45. {
  46. Name: "Get_valid_key",
  47. MockStatusCode: 200,
  48. MockResponse: api.GetSecretByKeyV3Response{
  49. Secret: api.SecretsV3{
  50. SecretKey: key,
  51. SecretValue: "bar",
  52. },
  53. },
  54. Key: key,
  55. Output: []byte("bar"),
  56. },
  57. {
  58. Name: "Get_property_key",
  59. MockStatusCode: 200,
  60. MockResponse: api.GetSecretByKeyV3Response{
  61. Secret: api.SecretsV3{
  62. SecretKey: key,
  63. SecretValue: `{"bar": "value"}`,
  64. },
  65. },
  66. Key: key,
  67. Property: "bar",
  68. Output: []byte("value"),
  69. },
  70. {
  71. Name: "Key_not_found",
  72. MockStatusCode: 404,
  73. MockResponse: api.InfisicalAPIError{
  74. StatusCode: 404,
  75. Err: "Not Found",
  76. Message: "Secret not found",
  77. },
  78. Key: "key",
  79. Error: esv1.NoSecretErr,
  80. Output: "",
  81. },
  82. {
  83. Name: "Key_with_slash",
  84. MockStatusCode: 200,
  85. MockResponse: api.GetSecretByKeyV3Response{
  86. Secret: api.SecretsV3{
  87. SecretKey: "bar",
  88. SecretValue: "value",
  89. },
  90. },
  91. Key: "/foo/bar",
  92. Output: []byte("value"),
  93. },
  94. }
  95. for _, tc := range testCases {
  96. t.Run(tc.Name, func(t *testing.T) {
  97. apiClient, closeFunc := api.NewMockClient(tc.MockStatusCode, tc.MockResponse)
  98. defer closeFunc()
  99. p := &Provider{
  100. apiClient: apiClient,
  101. apiScope: &apiScope,
  102. }
  103. output, err := p.GetSecret(context.Background(), esv1.ExternalSecretDataRemoteRef{
  104. Key: tc.Key,
  105. Property: tc.Property,
  106. })
  107. if tc.Error == nil {
  108. assert.NoError(t, err)
  109. assert.Equal(t, tc.Output, output)
  110. } else {
  111. assert.ErrorAs(t, err, &tc.Error)
  112. }
  113. })
  114. }
  115. }
  116. // TestGetSecretWithPath verifies that request is translated from a key
  117. // `/foo/bar` to a secret `bar` with `secretPath` of `/foo`.
  118. func TestGetSecretWithPath(t *testing.T) {
  119. requestedKey := "/foo/bar"
  120. expectedSecretPath := "/foo"
  121. expectedSecretKey := "bar"
  122. // Prepare the mock response.
  123. data := api.GetSecretByKeyV3Response{
  124. Secret: api.SecretsV3{
  125. SecretKey: expectedSecretKey,
  126. SecretValue: `value`,
  127. },
  128. }
  129. body, err := json.Marshal(data)
  130. if err != nil {
  131. panic(err)
  132. }
  133. // Prepare the mock server, which asserts the request translation is correct.
  134. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  135. assert.Equal(t, fmt.Sprintf("/api/v3/secrets/raw/%s", expectedSecretKey), r.URL.Path)
  136. assert.Equal(t, expectedSecretPath, r.URL.Query().Get("secretPath"))
  137. w.WriteHeader(200)
  138. _, err := w.Write(body)
  139. if err != nil {
  140. panic(err)
  141. }
  142. }))
  143. defer server.Close()
  144. client, err := api.NewAPIClient(server.URL, server.Client())
  145. require.NoError(t, err)
  146. p := &Provider{
  147. apiClient: client,
  148. apiScope: &apiScope,
  149. }
  150. // Retrieve the secret.
  151. output, err := p.GetSecret(context.Background(), esv1.ExternalSecretDataRemoteRef{
  152. Key: requestedKey,
  153. Property: "",
  154. })
  155. // And, we should get back the expected secret value.
  156. require.NoError(t, err)
  157. assert.Equal(t, []byte("value"), output)
  158. }
  159. func TestGetSecretMap(t *testing.T) {
  160. key := "foo"
  161. testCases := []TestCases{
  162. {
  163. Name: "Get_valid_key_map",
  164. MockStatusCode: 200,
  165. MockResponse: api.GetSecretByKeyV3Response{
  166. Secret: api.SecretsV3{
  167. SecretKey: key,
  168. SecretValue: `{"bar": "value"}`,
  169. },
  170. },
  171. Key: key,
  172. Output: map[string][]byte{
  173. "bar": []byte("value"),
  174. },
  175. },
  176. {
  177. Name: "Get_invalid_map",
  178. MockStatusCode: 200,
  179. MockResponse: []byte(``),
  180. Key: key,
  181. Error: errors.New("unable to unmarshal secret foo"),
  182. },
  183. }
  184. for _, tc := range testCases {
  185. t.Run(tc.Name, func(t *testing.T) {
  186. apiClient, closeFunc := api.NewMockClient(tc.MockStatusCode, tc.MockResponse)
  187. defer closeFunc()
  188. p := &Provider{
  189. apiClient: apiClient,
  190. apiScope: &apiScope,
  191. }
  192. output, err := p.GetSecretMap(context.Background(), esv1.ExternalSecretDataRemoteRef{
  193. Key: tc.Key,
  194. Property: tc.Property,
  195. })
  196. if tc.Error == nil {
  197. assert.NoError(t, err)
  198. assert.Equal(t, tc.Output, output)
  199. } else {
  200. assert.ErrorAs(t, err, &tc.Error)
  201. }
  202. })
  203. }
  204. }
  205. func makeSecretStore(projectSlug, environment, secretsPath string, fn ...storeModifier) *esv1.SecretStore {
  206. store := &esv1.SecretStore{
  207. Spec: esv1.SecretStoreSpec{
  208. Provider: &esv1.SecretStoreProvider{
  209. Infisical: &esv1.InfisicalProvider{
  210. Auth: esv1.InfisicalAuth{
  211. UniversalAuthCredentials: &esv1.UniversalAuthCredentials{},
  212. },
  213. SecretsScope: esv1.MachineIdentityScopeInWorkspace{
  214. SecretsPath: secretsPath,
  215. EnvironmentSlug: environment,
  216. ProjectSlug: projectSlug,
  217. },
  218. },
  219. },
  220. },
  221. }
  222. for _, f := range fn {
  223. store = f(store)
  224. }
  225. return store
  226. }
  227. func withClientID(name, key string, namespace *string) storeModifier {
  228. return func(store *esv1.SecretStore) *esv1.SecretStore {
  229. store.Spec.Provider.Infisical.Auth.UniversalAuthCredentials.ClientID = esv1meta.SecretKeySelector{
  230. Name: name,
  231. Key: key,
  232. Namespace: namespace,
  233. }
  234. return store
  235. }
  236. }
  237. func withClientSecret(name, key string, namespace *string) storeModifier {
  238. return func(store *esv1.SecretStore) *esv1.SecretStore {
  239. store.Spec.Provider.Infisical.Auth.UniversalAuthCredentials.ClientSecret = esv1meta.SecretKeySelector{
  240. Name: name,
  241. Key: key,
  242. Namespace: namespace,
  243. }
  244. return store
  245. }
  246. }
  247. type ValidateStoreTestCase struct {
  248. name string
  249. store *esv1.SecretStore
  250. assertError func(t *testing.T, err error)
  251. }
  252. func TestValidateStore(t *testing.T) {
  253. const randomID = "some-random-id"
  254. const authType = "universal-auth"
  255. var authCredMissingErr = errors.New("universalAuthCredentials.clientId and universalAuthCredentials.clientSecret cannot be empty")
  256. var authScopeMissingErr = errors.New("secretsScope.projectSlug and secretsScope.environmentSlug cannot be empty")
  257. testCases := []ValidateStoreTestCase{
  258. {
  259. name: "Missing projectSlug",
  260. store: makeSecretStore("", "", ""),
  261. assertError: func(t *testing.T, err error) {
  262. require.ErrorAs(t, err, &authScopeMissingErr)
  263. },
  264. },
  265. {
  266. name: "Missing clientID",
  267. store: makeSecretStore(apiScope.ProjectSlug, apiScope.EnvironmentSlug, apiScope.SecretPath, withClientID(authType, randomID, nil)),
  268. assertError: func(t *testing.T, err error) {
  269. require.ErrorAs(t, err, &authCredMissingErr)
  270. },
  271. },
  272. {
  273. name: "Missing clientSecret",
  274. store: makeSecretStore(apiScope.ProjectSlug, apiScope.EnvironmentSlug, apiScope.SecretPath, withClientSecret(authType, randomID, nil)),
  275. assertError: func(t *testing.T, err error) {
  276. require.ErrorAs(t, err, &authCredMissingErr)
  277. },
  278. },
  279. {
  280. name: "Success",
  281. store: makeSecretStore(apiScope.ProjectSlug, apiScope.EnvironmentSlug, apiScope.SecretPath, withClientID(authType, randomID, nil), withClientSecret(authType, randomID, nil)),
  282. assertError: func(t *testing.T, err error) { require.NoError(t, err) },
  283. },
  284. }
  285. p := Provider{}
  286. for _, tc := range testCases {
  287. t.Run(tc.name, func(t *testing.T) {
  288. _, err := p.ValidateStore(tc.store)
  289. tc.assertError(t, err)
  290. })
  291. }
  292. }