proxyclass_test.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. //go:build !plan9
  4. // tailscale-operator provides a way to expose services running in a Kubernetes
  5. // cluster to your Tailnet.
  6. package main
  7. import (
  8. "testing"
  9. "time"
  10. "go.uber.org/zap"
  11. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  12. "k8s.io/apimachinery/pkg/types"
  13. "k8s.io/client-go/tools/record"
  14. "sigs.k8s.io/controller-runtime/pkg/client/fake"
  15. tsoperator "tailscale.com/k8s-operator"
  16. tsapi "tailscale.com/k8s-operator/apis/v1alpha1"
  17. "tailscale.com/tstest"
  18. )
  19. func TestProxyClass(t *testing.T) {
  20. pc := &tsapi.ProxyClass{
  21. TypeMeta: metav1.TypeMeta{Kind: "ProxyClass", APIVersion: "tailscale.com/v1alpha1"},
  22. ObjectMeta: metav1.ObjectMeta{
  23. Name: "test",
  24. // The apiserver is supposed to set the UID, but the fake client
  25. // doesn't. So, set it explicitly because other code later depends
  26. // on it being set.
  27. UID: types.UID("1234-UID"),
  28. Finalizers: []string{"tailscale.com/finalizer"},
  29. },
  30. Spec: tsapi.ProxyClassSpec{
  31. StatefulSet: &tsapi.StatefulSet{
  32. Labels: map[string]string{"foo": "bar", "xyz1234": "abc567"},
  33. Annotations: map[string]string{"foo.io/bar": "{'key': 'val1232'}"},
  34. Pod: &tsapi.Pod{
  35. Labels: map[string]string{"foo": "bar", "xyz1234": "abc567"},
  36. Annotations: map[string]string{"foo.io/bar": "{'key': 'val1232'}"},
  37. TailscaleContainer: &tsapi.Container{
  38. Env: []tsapi.Env{{Name: "FOO", Value: "BAR"}},
  39. ImagePullPolicy: "IfNotPresent",
  40. Image: "ghcr.my-repo/tailscale:v0.01testsomething",
  41. },
  42. },
  43. },
  44. },
  45. }
  46. fc := fake.NewClientBuilder().
  47. WithScheme(tsapi.GlobalScheme).
  48. WithObjects(pc).
  49. WithStatusSubresource(pc).
  50. Build()
  51. zl, err := zap.NewDevelopment()
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. fr := record.NewFakeRecorder(3) // bump this if you expect a test case to throw more events
  56. cl := tstest.NewClock(tstest.ClockOpts{})
  57. pcr := &ProxyClassReconciler{
  58. Client: fc,
  59. logger: zl.Sugar(),
  60. clock: cl,
  61. recorder: fr,
  62. }
  63. // 1. A valid ProxyClass resource gets its status updated to Ready.
  64. expectReconciled(t, pcr, "", "test")
  65. pc.Status.Conditions = append(pc.Status.Conditions, metav1.Condition{
  66. Type: string(tsapi.ProxyClassReady),
  67. Status: metav1.ConditionTrue,
  68. Reason: reasonProxyClassValid,
  69. Message: reasonProxyClassValid,
  70. LastTransitionTime: metav1.Time{Time: cl.Now().Truncate(time.Second)},
  71. })
  72. expectEqual(t, fc, pc, nil)
  73. // 2. A ProxyClass resource with invalid labels gets its status updated to Invalid with an error message.
  74. pc.Spec.StatefulSet.Labels["foo"] = "?!someVal"
  75. mustUpdate(t, fc, "", "test", func(proxyClass *tsapi.ProxyClass) {
  76. proxyClass.Spec.StatefulSet.Labels = pc.Spec.StatefulSet.Labels
  77. })
  78. expectReconciled(t, pcr, "", "test")
  79. msg := `ProxyClass is not valid: .spec.statefulSet.labels: Invalid value: "?!someVal": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?')`
  80. tsoperator.SetProxyClassCondition(pc, tsapi.ProxyClassReady, metav1.ConditionFalse, reasonProxyClassInvalid, msg, 0, cl, zl.Sugar())
  81. expectEqual(t, fc, pc, nil)
  82. expectedEvent := "Warning ProxyClassInvalid ProxyClass is not valid: .spec.statefulSet.labels: Invalid value: \"?!someVal\": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?')"
  83. expectEvents(t, fr, []string{expectedEvent})
  84. // 3. A ProxyClass resource with invalid image reference gets it status updated to Invalid with an error message.
  85. pc.Spec.StatefulSet.Labels = nil
  86. pc.Spec.StatefulSet.Pod.TailscaleContainer.Image = "FOO bar"
  87. mustUpdate(t, fc, "", "test", func(proxyClass *tsapi.ProxyClass) {
  88. proxyClass.Spec.StatefulSet.Labels = nil
  89. proxyClass.Spec.StatefulSet.Pod.TailscaleContainer.Image = pc.Spec.StatefulSet.Pod.TailscaleContainer.Image
  90. })
  91. expectReconciled(t, pcr, "", "test")
  92. msg = `ProxyClass is not valid: spec.statefulSet.pod.tailscaleContainer.image: Invalid value: "FOO bar": invalid reference format: repository name (library/FOO bar) must be lowercase`
  93. tsoperator.SetProxyClassCondition(pc, tsapi.ProxyClassReady, metav1.ConditionFalse, reasonProxyClassInvalid, msg, 0, cl, zl.Sugar())
  94. expectEqual(t, fc, pc, nil)
  95. expectedEvent = `Warning ProxyClassInvalid ProxyClass is not valid: spec.statefulSet.pod.tailscaleContainer.image: Invalid value: "FOO bar": invalid reference format: repository name (library/FOO bar) must be lowercase`
  96. expectEvents(t, fr, []string{expectedEvent})
  97. // 4. A ProxyClass resource with invalid init container image reference gets it status updated to Invalid with an error message.
  98. pc.Spec.StatefulSet.Labels = nil
  99. pc.Spec.StatefulSet.Pod.TailscaleContainer.Image = ""
  100. pc.Spec.StatefulSet.Pod.TailscaleInitContainer = &tsapi.Container{
  101. Image: "FOO bar",
  102. }
  103. mustUpdate(t, fc, "", "test", func(proxyClass *tsapi.ProxyClass) {
  104. proxyClass.Spec.StatefulSet.Pod.TailscaleContainer.Image = pc.Spec.StatefulSet.Pod.TailscaleContainer.Image
  105. proxyClass.Spec.StatefulSet.Pod.TailscaleInitContainer = &tsapi.Container{
  106. Image: pc.Spec.StatefulSet.Pod.TailscaleInitContainer.Image,
  107. }
  108. })
  109. expectReconciled(t, pcr, "", "test")
  110. msg = `ProxyClass is not valid: spec.statefulSet.pod.tailscaleInitContainer.image: Invalid value: "FOO bar": invalid reference format: repository name (library/FOO bar) must be lowercase`
  111. tsoperator.SetProxyClassCondition(pc, tsapi.ProxyClassReady, metav1.ConditionFalse, reasonProxyClassInvalid, msg, 0, cl, zl.Sugar())
  112. expectEqual(t, fc, pc, nil)
  113. expectedEvent = `Warning ProxyClassInvalid ProxyClass is not valid: spec.statefulSet.pod.tailscaleInitContainer.image: Invalid value: "FOO bar": invalid reference format: repository name (library/FOO bar) must be lowercase`
  114. expectEvents(t, fr, []string{expectedEvent})
  115. // 5. An valid ProxyClass but with a Tailscale env vars set results in warning events.
  116. pc.Spec.StatefulSet.Pod.TailscaleInitContainer.Image = "" // unset previous test
  117. mustUpdate(t, fc, "", "test", func(proxyClass *tsapi.ProxyClass) {
  118. proxyClass.Spec.StatefulSet.Pod.TailscaleInitContainer.Image = pc.Spec.StatefulSet.Pod.TailscaleInitContainer.Image
  119. proxyClass.Spec.StatefulSet.Pod.TailscaleContainer.Env = []tsapi.Env{{Name: "TS_USERSPACE", Value: "true"}, {Name: "EXPERIMENTAL_TS_CONFIGFILE_PATH"}, {Name: "EXPERIMENTAL_ALLOW_PROXYING_CLUSTER_TRAFFIC_VIA_INGRESS"}}
  120. })
  121. expectedEvents := []string{"Warning CustomTSEnvVar ProxyClass overrides the default value for TS_USERSPACE env var for tailscale container. Running with custom values for Tailscale env vars is not recommended and might break in the future.",
  122. "Warning CustomTSEnvVar ProxyClass overrides the default value for EXPERIMENTAL_TS_CONFIGFILE_PATH env var for tailscale container. Running with custom values for Tailscale env vars is not recommended and might break in the future.",
  123. "Warning CustomTSEnvVar ProxyClass overrides the default value for EXPERIMENTAL_ALLOW_PROXYING_CLUSTER_TRAFFIC_VIA_INGRESS env var for tailscale container. Running with custom values for Tailscale env vars is not recommended and might break in the future."}
  124. expectReconciled(t, pcr, "", "test")
  125. expectEvents(t, fr, expectedEvents)
  126. }
  127. func TestValidateProxyClass(t *testing.T) {
  128. for name, tc := range map[string]struct {
  129. pc *tsapi.ProxyClass
  130. valid bool
  131. }{
  132. "empty": {
  133. valid: true,
  134. pc: &tsapi.ProxyClass{},
  135. },
  136. "debug_enabled_for_main_container": {
  137. valid: true,
  138. pc: &tsapi.ProxyClass{
  139. Spec: tsapi.ProxyClassSpec{
  140. StatefulSet: &tsapi.StatefulSet{
  141. Pod: &tsapi.Pod{
  142. TailscaleContainer: &tsapi.Container{
  143. Debug: &tsapi.Debug{
  144. Enable: true,
  145. },
  146. },
  147. },
  148. },
  149. },
  150. },
  151. },
  152. "debug_enabled_for_init_container": {
  153. valid: false,
  154. pc: &tsapi.ProxyClass{
  155. Spec: tsapi.ProxyClassSpec{
  156. StatefulSet: &tsapi.StatefulSet{
  157. Pod: &tsapi.Pod{
  158. TailscaleInitContainer: &tsapi.Container{
  159. Debug: &tsapi.Debug{
  160. Enable: true,
  161. },
  162. },
  163. },
  164. },
  165. },
  166. },
  167. },
  168. } {
  169. t.Run(name, func(t *testing.T) {
  170. pcr := &ProxyClassReconciler{}
  171. err := pcr.validate(tc.pc)
  172. valid := err == nil
  173. if valid != tc.valid {
  174. t.Errorf("expected valid=%v, got valid=%v, err=%v", tc.valid, valid, err)
  175. }
  176. })
  177. }
  178. }