provider_test.go 8.4 KB

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