auth_test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /*
  2. Copyright © The ESO Authors
  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 vault
  14. import (
  15. "context"
  16. "encoding/json"
  17. "errors"
  18. "testing"
  19. "github.com/google/go-cmp/cmp"
  20. "github.com/google/go-cmp/cmp/cmpopts"
  21. vault "github.com/hashicorp/vault/api"
  22. corev1 "k8s.io/api/core/v1"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. clientfake "sigs.k8s.io/controller-runtime/pkg/client/fake"
  25. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  26. esmeta "github.com/external-secrets/external-secrets/apis/meta/v1"
  27. "github.com/external-secrets/external-secrets/providers/v1/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: new("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 *esv1.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 *esv1.SecretStore) *esv1.SecretStore {
  73. s := store.DeepCopy()
  74. s.Spec.Provider.Vault.Namespace = new(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 *esv1.SecretStore) *esv1.SecretStore {
  84. s := store.DeepCopy()
  85. s.Spec.Provider.Vault.Auth.Namespace = new(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 *esv1.SecretStore) *esv1.SecretStore {
  95. s := store.DeepCopy()
  96. s.Spec.Provider.Vault.Namespace = new(adminNS)
  97. s.Spec.Provider.Vault.Auth.Namespace = new(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 *esv1.SecretStore) *esv1.SecretStore {
  107. s := store.DeepCopy()
  108. s.Spec.Provider.Vault.Namespace = new(teamNS)
  109. s.Spec.Provider.Vault.Auth.Namespace = new(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.Error(err.Error())
  124. }
  125. client, err := getVaultClient(prov, tc.args.store, cfg, "default")
  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(_ 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]any{
  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]any{
  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]any{
  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]any{
  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(_ 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. }
  253. // Test GCP authentication detection logic.
  254. func TestGCPAuthDetection(t *testing.T) {
  255. tests := []struct {
  256. name string
  257. gcpAuth *esv1.VaultGCPAuth
  258. expectedHasAuth bool
  259. expectError bool
  260. }{
  261. {
  262. name: "GCP auth configured",
  263. gcpAuth: &esv1.VaultGCPAuth{
  264. Role: "test-role",
  265. Path: "gcp",
  266. },
  267. expectedHasAuth: true,
  268. expectError: true, // Will error because auth client is not initialized in test
  269. },
  270. {
  271. name: "No GCP auth configured",
  272. gcpAuth: nil,
  273. expectedHasAuth: false,
  274. expectError: false,
  275. },
  276. }
  277. for _, tt := range tests {
  278. t.Run(tt.name, func(t *testing.T) {
  279. // Create a mock client
  280. c := &client{
  281. store: &esv1.VaultProvider{
  282. Auth: &esv1.VaultAuth{
  283. GCP: tt.gcpAuth,
  284. },
  285. },
  286. // auth: nil (not initialized for test)
  287. }
  288. // Test detection logic
  289. hasAuth, err := setGcpAuthToken(context.Background(), c)
  290. if hasAuth != tt.expectedHasAuth {
  291. t.Errorf("setGcpAuthToken() returned hasAuth = %v, want %v", hasAuth, tt.expectedHasAuth)
  292. }
  293. if tt.expectError && err == nil {
  294. t.Errorf("setGcpAuthToken() expected error, got nil")
  295. }
  296. if !tt.expectError && err != nil {
  297. t.Errorf("setGcpAuthToken() unexpected error: %v", err)
  298. }
  299. })
  300. }
  301. }
  302. func TestGCPAuthMountPathDefault(t *testing.T) {
  303. c := &client{}
  304. tests := []struct {
  305. name string
  306. path string
  307. expected string
  308. }{
  309. {
  310. name: "default path when empty",
  311. path: "",
  312. expected: "gcp",
  313. },
  314. {
  315. name: "custom path",
  316. path: "custom-gcp",
  317. expected: "custom-gcp",
  318. },
  319. }
  320. for _, tt := range tests {
  321. t.Run(tt.name, func(t *testing.T) {
  322. result := c.getGCPAuthMountPathOrDefault(tt.path)
  323. if result != tt.expected {
  324. t.Errorf("getGCPAuthMountPathOrDefault() = %v, want %v", result, tt.expected)
  325. }
  326. })
  327. }
  328. }