auth_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 vault
  13. import (
  14. "context"
  15. "encoding/json"
  16. "errors"
  17. "testing"
  18. "github.com/google/go-cmp/cmp"
  19. "github.com/google/go-cmp/cmp/cmpopts"
  20. vault "github.com/hashicorp/vault/api"
  21. corev1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/utils/ptr"
  24. clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
  25. esv1beta1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1beta1"
  26. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  27. "github.com/external-secrets/external-secrets/pkg/provider/vault/fake"
  28. )
  29. // Test Vault Namespace logic.
  30. func TestSetAuthNamespace(t *testing.T) {
  31. store := makeValidSecretStore()
  32. kube := clientfake.NewClientBuilder().WithObjects(&corev1.Secret{
  33. ObjectMeta: metav1.ObjectMeta{
  34. Name: "vault-secret",
  35. Namespace: "default",
  36. },
  37. Data: map[string][]byte{
  38. "key": []byte("token"),
  39. },
  40. }).Build()
  41. store.Spec.Provider.Vault.Auth.Kubernetes.ServiceAccountRef = nil
  42. store.Spec.Provider.Vault.Auth.Kubernetes.SecretRef = &esmeta.SecretKeySelector{
  43. Name: "vault-secret",
  44. Namespace: ptr.To("default"),
  45. Key: "key",
  46. }
  47. adminNS := "admin"
  48. teamNS := "admin/team-a"
  49. type result struct {
  50. Before string
  51. During string
  52. After string
  53. }
  54. type args struct {
  55. store *esv1beta1.SecretStore
  56. expected result
  57. }
  58. cases := map[string]struct {
  59. reason string
  60. args args
  61. }{
  62. "StoreNoNamespace": {
  63. reason: "no namespace should ever be set",
  64. args: args{
  65. store: store,
  66. expected: result{Before: "", During: "", After: ""},
  67. },
  68. },
  69. "StoreWithNamespace": {
  70. reason: "use the team namespace throughout",
  71. args: args{
  72. store: func(store *esv1beta1.SecretStore) *esv1beta1.SecretStore {
  73. s := store.DeepCopy()
  74. s.Spec.Provider.Vault.Namespace = ptr.To(teamNS)
  75. return s
  76. }(store),
  77. expected: result{Before: teamNS, During: teamNS, After: teamNS},
  78. },
  79. },
  80. "StoreWithAuthNamespace": {
  81. reason: "switch to the auth namespace during login then revert",
  82. args: args{
  83. store: func(store *esv1beta1.SecretStore) *esv1beta1.SecretStore {
  84. s := store.DeepCopy()
  85. s.Spec.Provider.Vault.Auth.Namespace = ptr.To(adminNS)
  86. return s
  87. }(store),
  88. expected: result{Before: "", During: adminNS, After: ""},
  89. },
  90. },
  91. "StoreWithSameNamespace": {
  92. reason: "the admin namespace throughout",
  93. args: args{
  94. store: func(store *esv1beta1.SecretStore) *esv1beta1.SecretStore {
  95. s := store.DeepCopy()
  96. s.Spec.Provider.Vault.Namespace = ptr.To(adminNS)
  97. s.Spec.Provider.Vault.Auth.Namespace = ptr.To(adminNS)
  98. return s
  99. }(store),
  100. expected: result{Before: adminNS, During: adminNS, After: adminNS},
  101. },
  102. },
  103. "StoreWithDistinctNamespace": {
  104. reason: "switch from team namespace, to admin, then back",
  105. args: args{
  106. store: func(store *esv1beta1.SecretStore) *esv1beta1.SecretStore {
  107. s := store.DeepCopy()
  108. s.Spec.Provider.Vault.Namespace = ptr.To(teamNS)
  109. s.Spec.Provider.Vault.Auth.Namespace = ptr.To(adminNS)
  110. return s
  111. }(store),
  112. expected: result{Before: teamNS, During: adminNS, After: teamNS},
  113. },
  114. },
  115. }
  116. for name, tc := range cases {
  117. t.Run(name, func(t *testing.T) {
  118. prov := &Provider{
  119. NewVaultClient: fake.ClientWithLoginMock,
  120. }
  121. c, cfg, err := prov.prepareConfig(context.Background(), kube, nil, tc.args.store.Spec.Provider.Vault, nil, "default", store.GetObjectKind().GroupVersionKind().Kind)
  122. if err != nil {
  123. t.Errorf(err.Error())
  124. }
  125. client, err := getVaultClient(prov, tc.args.store, cfg)
  126. if err != nil {
  127. t.Errorf("vault.useAuthNamespace: failed to create client: %s", err.Error())
  128. }
  129. _, err = prov.initClient(context.Background(), c, client, cfg, tc.args.store.Spec.Provider.Vault)
  130. if err != nil {
  131. t.Errorf("vault.useAuthNamespace: failed to init client: %s", err.Error())
  132. }
  133. c.client = client
  134. // before auth
  135. actual := result{
  136. Before: c.client.Namespace(),
  137. }
  138. // during authentication (getting a token)
  139. resetNS := c.useAuthNamespace(context.Background())
  140. actual.During = c.client.Namespace()
  141. resetNS()
  142. // after getting the token
  143. actual.After = c.client.Namespace()
  144. if diff := cmp.Diff(tc.args.expected, actual, cmpopts.EquateComparable()); diff != "" {
  145. t.Errorf("\n%s\nvault.useAuthNamepsace(...): -want namespace, +got namespace:\n%s", tc.reason, diff)
  146. }
  147. })
  148. }
  149. }
  150. func TestCheckTokenErrors(t *testing.T) {
  151. cases := map[string]struct {
  152. message string
  153. secret *vault.Secret
  154. err error
  155. }{
  156. "SuccessWithNoData": {
  157. message: "should not cache if token lookup returned no data",
  158. secret: &vault.Secret{},
  159. err: nil,
  160. },
  161. "Error": {
  162. message: "should not cache if token lookup errored",
  163. secret: nil,
  164. err: errors.New(""),
  165. },
  166. // This happens when a token is expired and the Vault server returns:
  167. // {"errors":["permission denied"]}
  168. "NoDataNorError": {
  169. message: "should not cache if token lookup returned no data nor error",
  170. secret: nil,
  171. err: nil,
  172. },
  173. }
  174. for name, tc := range cases {
  175. t.Run(name, func(t *testing.T) {
  176. token := fake.Token{
  177. LookupSelfWithContextFn: func(ctx context.Context) (*vault.Secret, error) {
  178. return tc.secret, tc.err
  179. },
  180. }
  181. cached, _ := checkToken(context.Background(), token)
  182. if cached {
  183. t.Errorf("%v", tc.message)
  184. }
  185. })
  186. }
  187. }
  188. func TestCheckTokenTtl(t *testing.T) {
  189. cases := map[string]struct {
  190. message string
  191. secret *vault.Secret
  192. cache bool
  193. }{
  194. "LongTTLExpirable": {
  195. message: "should cache if expirable token expires far into the future",
  196. secret: &vault.Secret{
  197. Data: map[string]interface{}{
  198. "expire_time": "2024-01-01T00:00:00.000000000Z",
  199. "ttl": json.Number("3600"),
  200. "type": "service",
  201. },
  202. },
  203. cache: true,
  204. },
  205. "ShortTTLExpirable": {
  206. message: "should not cache if expirable token is about to expire",
  207. secret: &vault.Secret{
  208. Data: map[string]interface{}{
  209. "expire_time": "2024-01-01T00:00:00.000000000Z",
  210. "ttl": json.Number("5"),
  211. "type": "service",
  212. },
  213. },
  214. cache: false,
  215. },
  216. "ZeroTTLExpirable": {
  217. message: "should not cache if expirable token has TTL of 0",
  218. secret: &vault.Secret{
  219. Data: map[string]interface{}{
  220. "expire_time": "2024-01-01T00:00:00.000000000Z",
  221. "ttl": json.Number("0"),
  222. "type": "service",
  223. },
  224. },
  225. cache: false,
  226. },
  227. "NonExpirable": {
  228. message: "should cache if token is non-expirable",
  229. secret: &vault.Secret{
  230. Data: map[string]interface{}{
  231. "expire_time": nil,
  232. "ttl": json.Number("0"),
  233. "type": "service",
  234. },
  235. },
  236. cache: true,
  237. },
  238. }
  239. for name, tc := range cases {
  240. t.Run(name, func(t *testing.T) {
  241. token := fake.Token{
  242. LookupSelfWithContextFn: func(ctx context.Context) (*vault.Secret, error) {
  243. return tc.secret, nil
  244. },
  245. }
  246. cached, err := checkToken(context.Background(), token)
  247. if cached != tc.cache || err != nil {
  248. t.Errorf("%v: err = %v", tc.message, err)
  249. }
  250. })
  251. }
  252. }