service_accounts.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. /*
  2. Copyright 2014 The Kubernetes 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. http://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 auth
  14. import (
  15. "context"
  16. "fmt"
  17. "path"
  18. "regexp"
  19. "strings"
  20. "time"
  21. authenticationv1 "k8s.io/api/authentication/v1"
  22. v1 "k8s.io/api/core/v1"
  23. apierrors "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/util/sets"
  26. "k8s.io/apimachinery/pkg/util/uuid"
  27. "k8s.io/apimachinery/pkg/util/wait"
  28. "k8s.io/kubernetes/plugin/pkg/admission/serviceaccount"
  29. "k8s.io/kubernetes/test/e2e/framework"
  30. e2ekubectl "k8s.io/kubernetes/test/e2e/framework/kubectl"
  31. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  32. imageutils "k8s.io/kubernetes/test/utils/image"
  33. "github.com/onsi/ginkgo"
  34. )
  35. var mountImage = imageutils.GetE2EImage(imageutils.Mounttest)
  36. var _ = SIGDescribe("ServiceAccounts", func() {
  37. f := framework.NewDefaultFramework("svcaccounts")
  38. ginkgo.It("should ensure a single API token exists", func() {
  39. // wait for the service account to reference a single secret
  40. var secrets []v1.ObjectReference
  41. framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*10, func() (bool, error) {
  42. ginkgo.By("waiting for a single token reference")
  43. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  44. if apierrors.IsNotFound(err) {
  45. framework.Logf("default service account was not found")
  46. return false, nil
  47. }
  48. if err != nil {
  49. framework.Logf("error getting default service account: %v", err)
  50. return false, err
  51. }
  52. switch len(sa.Secrets) {
  53. case 0:
  54. framework.Logf("default service account has no secret references")
  55. return false, nil
  56. case 1:
  57. framework.Logf("default service account has a single secret reference")
  58. secrets = sa.Secrets
  59. return true, nil
  60. default:
  61. return false, fmt.Errorf("default service account has too many secret references: %#v", sa.Secrets)
  62. }
  63. }))
  64. // make sure the reference doesn't flutter
  65. {
  66. ginkgo.By("ensuring the single token reference persists")
  67. time.Sleep(2 * time.Second)
  68. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  69. framework.ExpectNoError(err)
  70. framework.ExpectEqual(sa.Secrets, secrets)
  71. }
  72. // delete the referenced secret
  73. ginkgo.By("deleting the service account token")
  74. framework.ExpectNoError(f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Delete(context.TODO(), secrets[0].Name, nil))
  75. // wait for the referenced secret to be removed, and another one autocreated
  76. framework.ExpectNoError(wait.Poll(time.Millisecond*500, framework.ServiceAccountProvisionTimeout, func() (bool, error) {
  77. ginkgo.By("waiting for a new token reference")
  78. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  79. if err != nil {
  80. framework.Logf("error getting default service account: %v", err)
  81. return false, err
  82. }
  83. switch len(sa.Secrets) {
  84. case 0:
  85. framework.Logf("default service account has no secret references")
  86. return false, nil
  87. case 1:
  88. if sa.Secrets[0] == secrets[0] {
  89. framework.Logf("default service account still has the deleted secret reference")
  90. return false, nil
  91. }
  92. framework.Logf("default service account has a new single secret reference")
  93. secrets = sa.Secrets
  94. return true, nil
  95. default:
  96. return false, fmt.Errorf("default service account has too many secret references: %#v", sa.Secrets)
  97. }
  98. }))
  99. // make sure the reference doesn't flutter
  100. {
  101. ginkgo.By("ensuring the single token reference persists")
  102. time.Sleep(2 * time.Second)
  103. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  104. framework.ExpectNoError(err)
  105. framework.ExpectEqual(sa.Secrets, secrets)
  106. }
  107. // delete the reference from the service account
  108. ginkgo.By("deleting the reference to the service account token")
  109. {
  110. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  111. framework.ExpectNoError(err)
  112. sa.Secrets = nil
  113. _, updateErr := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Update(context.TODO(), sa, metav1.UpdateOptions{})
  114. framework.ExpectNoError(updateErr)
  115. }
  116. // wait for another one to be autocreated
  117. framework.ExpectNoError(wait.Poll(time.Millisecond*500, framework.ServiceAccountProvisionTimeout, func() (bool, error) {
  118. ginkgo.By("waiting for a new token to be created and added")
  119. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  120. if err != nil {
  121. framework.Logf("error getting default service account: %v", err)
  122. return false, err
  123. }
  124. switch len(sa.Secrets) {
  125. case 0:
  126. framework.Logf("default service account has no secret references")
  127. return false, nil
  128. case 1:
  129. framework.Logf("default service account has a new single secret reference")
  130. secrets = sa.Secrets
  131. return true, nil
  132. default:
  133. return false, fmt.Errorf("default service account has too many secret references: %#v", sa.Secrets)
  134. }
  135. }))
  136. // make sure the reference doesn't flutter
  137. {
  138. ginkgo.By("ensuring the single token reference persists")
  139. time.Sleep(2 * time.Second)
  140. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "default", metav1.GetOptions{})
  141. framework.ExpectNoError(err)
  142. framework.ExpectEqual(sa.Secrets, secrets)
  143. }
  144. })
  145. /*
  146. Release: v1.9
  147. Testname: Service Account Tokens Must AutoMount
  148. Description: Ensure that Service Account keys are mounted into the Container. Pod
  149. contains three containers each will read Service Account token,
  150. root CA and default namespace respectively from the default API
  151. Token Mount path. All these three files MUST exist and the Service
  152. Account mount path MUST be auto mounted to the Container.
  153. */
  154. framework.ConformanceIt("should mount an API token into pods ", func() {
  155. var rootCAContent string
  156. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Create(context.TODO(), &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "mount-test"}}, metav1.CreateOptions{})
  157. framework.ExpectNoError(err)
  158. // Standard get, update retry loop
  159. framework.ExpectNoError(wait.Poll(time.Millisecond*500, framework.ServiceAccountProvisionTimeout, func() (bool, error) {
  160. ginkgo.By("getting the auto-created API token")
  161. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), "mount-test", metav1.GetOptions{})
  162. if apierrors.IsNotFound(err) {
  163. framework.Logf("mount-test service account was not found")
  164. return false, nil
  165. }
  166. if err != nil {
  167. framework.Logf("error getting mount-test service account: %v", err)
  168. return false, err
  169. }
  170. if len(sa.Secrets) == 0 {
  171. framework.Logf("mount-test service account has no secret references")
  172. return false, nil
  173. }
  174. for _, secretRef := range sa.Secrets {
  175. secret, err := f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Get(context.TODO(), secretRef.Name, metav1.GetOptions{})
  176. if err != nil {
  177. framework.Logf("Error getting secret %s: %v", secretRef.Name, err)
  178. continue
  179. }
  180. if secret.Type == v1.SecretTypeServiceAccountToken {
  181. rootCAContent = string(secret.Data[v1.ServiceAccountRootCAKey])
  182. return true, nil
  183. }
  184. }
  185. framework.Logf("default service account has no secret references to valid service account tokens")
  186. return false, nil
  187. }))
  188. zero := int64(0)
  189. pod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), &v1.Pod{
  190. ObjectMeta: metav1.ObjectMeta{
  191. Name: "pod-service-account-" + string(uuid.NewUUID()),
  192. },
  193. Spec: v1.PodSpec{
  194. ServiceAccountName: sa.Name,
  195. Containers: []v1.Container{{
  196. Name: "test",
  197. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  198. Command: []string{"sleep", "100000"},
  199. }},
  200. TerminationGracePeriodSeconds: &zero,
  201. RestartPolicy: v1.RestartPolicyNever,
  202. },
  203. }, metav1.CreateOptions{})
  204. framework.ExpectNoError(err)
  205. framework.ExpectNoError(e2epod.WaitForPodRunningInNamespace(f.ClientSet, pod))
  206. tk := e2ekubectl.NewTestKubeconfig(framework.TestContext.CertDir, framework.TestContext.Host, framework.TestContext.KubeConfig, framework.TestContext.KubeContext, framework.TestContext.KubectlPath, f.Namespace.Name)
  207. mountedToken, err := tk.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, path.Join(serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountTokenKey))
  208. framework.ExpectNoError(err)
  209. mountedCA, err := tk.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, path.Join(serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountRootCAKey))
  210. framework.ExpectNoError(err)
  211. mountedNamespace, err := tk.ReadFileViaContainer(pod.Name, pod.Spec.Containers[0].Name, path.Join(serviceaccount.DefaultAPITokenMountPath, v1.ServiceAccountNamespaceKey))
  212. framework.ExpectNoError(err)
  213. // CA and namespace should be identical
  214. framework.ExpectEqual(mountedCA, rootCAContent)
  215. framework.ExpectEqual(mountedNamespace, f.Namespace.Name)
  216. // Token should be a valid credential that identifies the pod's service account
  217. tokenReview := &authenticationv1.TokenReview{Spec: authenticationv1.TokenReviewSpec{Token: mountedToken}}
  218. tokenReview, err = f.ClientSet.AuthenticationV1().TokenReviews().Create(context.TODO(), tokenReview, metav1.CreateOptions{})
  219. framework.ExpectNoError(err)
  220. framework.ExpectEqual(tokenReview.Status.Authenticated, true)
  221. framework.ExpectEqual(tokenReview.Status.Error, "")
  222. framework.ExpectEqual(tokenReview.Status.User.Username, "system:serviceaccount:"+f.Namespace.Name+":"+sa.Name)
  223. groups := sets.NewString(tokenReview.Status.User.Groups...)
  224. framework.ExpectEqual(groups.Has("system:authenticated"), true, fmt.Sprintf("expected system:authenticated group, had %v", groups.List()))
  225. framework.ExpectEqual(groups.Has("system:serviceaccounts"), true, fmt.Sprintf("expected system:serviceaccounts group, had %v", groups.List()))
  226. framework.ExpectEqual(groups.Has("system:serviceaccounts:"+f.Namespace.Name), true, fmt.Sprintf("expected system:serviceaccounts:"+f.Namespace.Name+" group, had %v", groups.List()))
  227. })
  228. /*
  229. Release: v1.9
  230. Testname: Service account tokens auto mount optionally
  231. Description: Ensure that Service Account keys are mounted into the Pod only
  232. when AutoMountServiceToken is not set to false. We test the
  233. following scenarios here.
  234. 1. Create Pod, Pod Spec has AutomountServiceAccountToken set to nil
  235. a) Service Account with default value,
  236. b) Service Account is an configured AutomountServiceAccountToken set to true,
  237. c) Service Account is an configured AutomountServiceAccountToken set to false
  238. 2. Create Pod, Pod Spec has AutomountServiceAccountToken set to true
  239. a) Service Account with default value,
  240. b) Service Account is configured with AutomountServiceAccountToken set to true,
  241. c) Service Account is configured with AutomountServiceAccountToken set to false
  242. 3. Create Pod, Pod Spec has AutomountServiceAccountToken set to false
  243. a) Service Account with default value,
  244. b) Service Account is configured with AutomountServiceAccountToken set to true,
  245. c) Service Account is configured with AutomountServiceAccountToken set to false
  246. The Containers running in these pods MUST verify that the ServiceTokenVolume path is
  247. auto mounted only when Pod Spec has AutomountServiceAccountToken not set to false
  248. and ServiceAccount object has AutomountServiceAccountToken not set to false, this
  249. include test cases 1a,1b,2a,2b and 2c.
  250. In the test cases 1c,3a,3b and 3c the ServiceTokenVolume MUST not be auto mounted.
  251. */
  252. framework.ConformanceIt("should allow opting out of API token automount ", func() {
  253. var err error
  254. trueValue := true
  255. falseValue := false
  256. mountSA := &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "mount"}, AutomountServiceAccountToken: &trueValue}
  257. nomountSA := &v1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: "nomount"}, AutomountServiceAccountToken: &falseValue}
  258. mountSA, err = f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Create(context.TODO(), mountSA, metav1.CreateOptions{})
  259. framework.ExpectNoError(err)
  260. nomountSA, err = f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Create(context.TODO(), nomountSA, metav1.CreateOptions{})
  261. framework.ExpectNoError(err)
  262. // Standard get, update retry loop
  263. framework.ExpectNoError(wait.Poll(time.Millisecond*500, framework.ServiceAccountProvisionTimeout, func() (bool, error) {
  264. ginkgo.By("getting the auto-created API token")
  265. sa, err := f.ClientSet.CoreV1().ServiceAccounts(f.Namespace.Name).Get(context.TODO(), mountSA.Name, metav1.GetOptions{})
  266. if apierrors.IsNotFound(err) {
  267. framework.Logf("mount service account was not found")
  268. return false, nil
  269. }
  270. if err != nil {
  271. framework.Logf("error getting mount service account: %v", err)
  272. return false, err
  273. }
  274. if len(sa.Secrets) == 0 {
  275. framework.Logf("mount service account has no secret references")
  276. return false, nil
  277. }
  278. for _, secretRef := range sa.Secrets {
  279. secret, err := f.ClientSet.CoreV1().Secrets(f.Namespace.Name).Get(context.TODO(), secretRef.Name, metav1.GetOptions{})
  280. if err != nil {
  281. framework.Logf("Error getting secret %s: %v", secretRef.Name, err)
  282. continue
  283. }
  284. if secret.Type == v1.SecretTypeServiceAccountToken {
  285. return true, nil
  286. }
  287. }
  288. framework.Logf("default service account has no secret references to valid service account tokens")
  289. return false, nil
  290. }))
  291. testcases := []struct {
  292. PodName string
  293. ServiceAccountName string
  294. AutomountPodSpec *bool
  295. ExpectTokenVolume bool
  296. }{
  297. {
  298. PodName: "pod-service-account-defaultsa",
  299. ServiceAccountName: "default",
  300. AutomountPodSpec: nil,
  301. ExpectTokenVolume: true, // default is true
  302. },
  303. {
  304. PodName: "pod-service-account-mountsa",
  305. ServiceAccountName: mountSA.Name,
  306. AutomountPodSpec: nil,
  307. ExpectTokenVolume: true,
  308. },
  309. {
  310. PodName: "pod-service-account-nomountsa",
  311. ServiceAccountName: nomountSA.Name,
  312. AutomountPodSpec: nil,
  313. ExpectTokenVolume: false,
  314. },
  315. // Make sure pod spec trumps when opting in
  316. {
  317. PodName: "pod-service-account-defaultsa-mountspec",
  318. ServiceAccountName: "default",
  319. AutomountPodSpec: &trueValue,
  320. ExpectTokenVolume: true,
  321. },
  322. {
  323. PodName: "pod-service-account-mountsa-mountspec",
  324. ServiceAccountName: mountSA.Name,
  325. AutomountPodSpec: &trueValue,
  326. ExpectTokenVolume: true,
  327. },
  328. {
  329. PodName: "pod-service-account-nomountsa-mountspec",
  330. ServiceAccountName: nomountSA.Name,
  331. AutomountPodSpec: &trueValue,
  332. ExpectTokenVolume: true, // pod spec trumps
  333. },
  334. // Make sure pod spec trumps when opting out
  335. {
  336. PodName: "pod-service-account-defaultsa-nomountspec",
  337. ServiceAccountName: "default",
  338. AutomountPodSpec: &falseValue,
  339. ExpectTokenVolume: false, // pod spec trumps
  340. },
  341. {
  342. PodName: "pod-service-account-mountsa-nomountspec",
  343. ServiceAccountName: mountSA.Name,
  344. AutomountPodSpec: &falseValue,
  345. ExpectTokenVolume: false, // pod spec trumps
  346. },
  347. {
  348. PodName: "pod-service-account-nomountsa-nomountspec",
  349. ServiceAccountName: nomountSA.Name,
  350. AutomountPodSpec: &falseValue,
  351. ExpectTokenVolume: false, // pod spec trumps
  352. },
  353. }
  354. for _, tc := range testcases {
  355. pod := &v1.Pod{
  356. ObjectMeta: metav1.ObjectMeta{Name: tc.PodName},
  357. Spec: v1.PodSpec{
  358. Containers: []v1.Container{{Name: "token-test", Image: mountImage}},
  359. RestartPolicy: v1.RestartPolicyNever,
  360. ServiceAccountName: tc.ServiceAccountName,
  361. AutomountServiceAccountToken: tc.AutomountPodSpec,
  362. },
  363. }
  364. createdPod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  365. framework.ExpectNoError(err)
  366. framework.Logf("created pod %s", tc.PodName)
  367. hasServiceAccountTokenVolume := false
  368. for _, c := range createdPod.Spec.Containers {
  369. for _, vm := range c.VolumeMounts {
  370. if vm.MountPath == serviceaccount.DefaultAPITokenMountPath {
  371. hasServiceAccountTokenVolume = true
  372. }
  373. }
  374. }
  375. if hasServiceAccountTokenVolume != tc.ExpectTokenVolume {
  376. framework.Failf("%s: expected volume=%v, got %v (%#v)", tc.PodName, tc.ExpectTokenVolume, hasServiceAccountTokenVolume, createdPod)
  377. } else {
  378. framework.Logf("pod %s service account token volume mount: %v", tc.PodName, hasServiceAccountTokenVolume)
  379. }
  380. }
  381. })
  382. ginkgo.It("should support InClusterConfig with token rotation [Slow] [Feature:TokenRequestProjection]", func() {
  383. cfg, err := framework.LoadConfig()
  384. framework.ExpectNoError(err)
  385. if _, err := f.ClientSet.CoreV1().ConfigMaps(f.Namespace.Name).Create(context.TODO(), &v1.ConfigMap{
  386. ObjectMeta: metav1.ObjectMeta{
  387. Name: "kube-root-ca.crt",
  388. },
  389. Data: map[string]string{
  390. "ca.crt": string(cfg.TLSClientConfig.CAData),
  391. },
  392. }, metav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {
  393. framework.Failf("Unexpected err creating kube-ca-crt: %v", err)
  394. }
  395. tenMin := int64(10 * 60)
  396. pod := &v1.Pod{
  397. ObjectMeta: metav1.ObjectMeta{Name: "inclusterclient"},
  398. Spec: v1.PodSpec{
  399. Containers: []v1.Container{{
  400. Name: "inclusterclient",
  401. Image: imageutils.GetE2EImage(imageutils.Agnhost),
  402. Args: []string{"inclusterclient"},
  403. VolumeMounts: []v1.VolumeMount{{
  404. MountPath: "/var/run/secrets/kubernetes.io/serviceaccount",
  405. Name: "kube-api-access-e2e",
  406. ReadOnly: true,
  407. }},
  408. }},
  409. RestartPolicy: v1.RestartPolicyNever,
  410. ServiceAccountName: "default",
  411. Volumes: []v1.Volume{{
  412. Name: "kube-api-access-e2e",
  413. VolumeSource: v1.VolumeSource{
  414. Projected: &v1.ProjectedVolumeSource{
  415. Sources: []v1.VolumeProjection{
  416. {
  417. ServiceAccountToken: &v1.ServiceAccountTokenProjection{
  418. Path: "token",
  419. ExpirationSeconds: &tenMin,
  420. },
  421. },
  422. {
  423. ConfigMap: &v1.ConfigMapProjection{
  424. LocalObjectReference: v1.LocalObjectReference{
  425. Name: "kube-root-ca.crt",
  426. },
  427. Items: []v1.KeyToPath{
  428. {
  429. Key: "ca.crt",
  430. Path: "ca.crt",
  431. },
  432. },
  433. },
  434. },
  435. {
  436. DownwardAPI: &v1.DownwardAPIProjection{
  437. Items: []v1.DownwardAPIVolumeFile{
  438. {
  439. Path: "namespace",
  440. FieldRef: &v1.ObjectFieldSelector{
  441. APIVersion: "v1",
  442. FieldPath: "metadata.namespace",
  443. },
  444. },
  445. },
  446. },
  447. },
  448. },
  449. },
  450. },
  451. }},
  452. },
  453. }
  454. pod, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Create(context.TODO(), pod, metav1.CreateOptions{})
  455. framework.ExpectNoError(err)
  456. framework.Logf("created pod")
  457. if !e2epod.CheckPodsRunningReady(f.ClientSet, f.Namespace.Name, []string{pod.Name}, time.Minute) {
  458. framework.Failf("pod %q in ns %q never became ready", pod.Name, f.Namespace.Name)
  459. }
  460. framework.Logf("pod is ready")
  461. var logs string
  462. if err := wait.Poll(1*time.Minute, 20*time.Minute, func() (done bool, err error) {
  463. framework.Logf("polling logs")
  464. logs, err = e2epod.GetPodLogs(f.ClientSet, f.Namespace.Name, "inclusterclient", "inclusterclient")
  465. if err != nil {
  466. framework.Logf("Error pulling logs: %v", err)
  467. return false, nil
  468. }
  469. tokenCount, err := parseInClusterClientLogs(logs)
  470. if err != nil {
  471. return false, fmt.Errorf("inclusterclient reported an error: %v", err)
  472. }
  473. if tokenCount < 2 {
  474. framework.Logf("Retrying. Still waiting to see more unique tokens: got=%d, want=2", tokenCount)
  475. return false, nil
  476. }
  477. return true, nil
  478. }); err != nil {
  479. framework.Failf("Unexpected error: %v\n%s", err, logs)
  480. }
  481. })
  482. })
  483. var reportLogsParser = regexp.MustCompile("([a-zA-Z0-9-_]*)=([a-zA-Z0-9-_]*)$")
  484. func parseInClusterClientLogs(logs string) (int, error) {
  485. seenTokens := map[string]struct{}{}
  486. lines := strings.Split(logs, "\n")
  487. for _, line := range lines {
  488. parts := reportLogsParser.FindStringSubmatch(line)
  489. if len(parts) != 3 {
  490. continue
  491. }
  492. key, value := parts[1], parts[2]
  493. switch key {
  494. case "authz_header":
  495. if value == "<empty>" {
  496. return 0, fmt.Errorf("saw empty Authorization header")
  497. }
  498. seenTokens[value] = struct{}{}
  499. case "status":
  500. if value == "failed" {
  501. return 0, fmt.Errorf("saw status=failed")
  502. }
  503. }
  504. }
  505. return len(seenTokens), nil
  506. }