|
| 1 | +/* |
| 2 | +Copyright 2026. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Run with: make setup-envtest && go test -v -count=1 -timeout 120s ./cmd/ -run TestConfigMapCacheVisibility |
| 18 | + |
| 19 | +package main |
| 20 | + |
| 21 | +import ( |
| 22 | + "context" |
| 23 | + "os" |
| 24 | + "path/filepath" |
| 25 | + "testing" |
| 26 | + |
| 27 | + corev1 "k8s.io/api/core/v1" |
| 28 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 29 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 30 | + "k8s.io/apimachinery/pkg/types" |
| 31 | + clientgoscheme "k8s.io/client-go/kubernetes/scheme" |
| 32 | + ctrl "sigs.k8s.io/controller-runtime" |
| 33 | + "sigs.k8s.io/controller-runtime/pkg/cache" |
| 34 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 35 | + "sigs.k8s.io/controller-runtime/pkg/envtest" |
| 36 | + logf "sigs.k8s.io/controller-runtime/pkg/log" |
| 37 | + "sigs.k8s.io/controller-runtime/pkg/log/zap" |
| 38 | + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" |
| 39 | + |
| 40 | + "github.com/kagenti/operator/internal/controller" |
| 41 | +) |
| 42 | + |
| 43 | +func TestConfigMapCacheVisibility(t *testing.T) { |
| 44 | + logf.SetLogger(zap.New(zap.WriteTo(os.Stderr), zap.UseDevMode(true))) |
| 45 | + |
| 46 | + // 1. Start a local kube-apiserver + etcd via envtest. |
| 47 | + testEnv := &envtest.Environment{} |
| 48 | + if dir := firstEnvTestBinaryDir(); dir != "" { |
| 49 | + testEnv.BinaryAssetsDirectory = dir |
| 50 | + } |
| 51 | + |
| 52 | + cfg, err := testEnv.Start() |
| 53 | + if err != nil { |
| 54 | + t.Fatalf("failed to start envtest: %v", err) |
| 55 | + } |
| 56 | + defer func() { _ = testEnv.Stop() }() |
| 57 | + |
| 58 | + // 2. Create a direct (non-cached) client for seeding test data. |
| 59 | + directClient, err := client.New(cfg, client.Options{Scheme: clientgoscheme.Scheme}) |
| 60 | + if err != nil { |
| 61 | + t.Fatalf("failed to create direct client: %v", err) |
| 62 | + } |
| 63 | + |
| 64 | + ctx, cancel := context.WithCancel(context.Background()) |
| 65 | + defer cancel() |
| 66 | + |
| 67 | + const ( |
| 68 | + spireNS = "zero-trust-workload-identity-manager" |
| 69 | + spireBundleName = "spire-bundle" |
| 70 | + ) |
| 71 | + |
| 72 | + // 3. Pre-create the namespaces the scoped cache will watch. |
| 73 | + for _, ns := range []string{controller.ClusterDefaultsNamespace, spireNS, "agent-team-a"} { |
| 74 | + nsObj := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}} |
| 75 | + if err := directClient.Create(ctx, nsObj); err != nil { |
| 76 | + t.Fatalf("failed to create namespace %s: %v", ns, err) |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + // 4. Build the scoped cache config (function under test) and start a |
| 81 | + // manager whose ConfigMap informers are restricted to those selectors. |
| 82 | + cmCacheNamespaces := buildConfigMapCacheNamespaces(true, spireBundleName, spireNS) |
| 83 | + |
| 84 | + mgr, err := ctrl.NewManager(cfg, ctrl.Options{ |
| 85 | + Scheme: clientgoscheme.Scheme, |
| 86 | + LeaderElection: false, |
| 87 | + Metrics: metricsserver.Options{BindAddress: "0"}, |
| 88 | + Cache: cache.Options{ |
| 89 | + ByObject: map[client.Object]cache.ByObject{ |
| 90 | + &corev1.ConfigMap{}: {Namespaces: cmCacheNamespaces}, |
| 91 | + }, |
| 92 | + }, |
| 93 | + }) |
| 94 | + if err != nil { |
| 95 | + t.Fatalf("failed to create manager: %v", err) |
| 96 | + } |
| 97 | + |
| 98 | + go func() { |
| 99 | + if err := mgr.Start(ctx); err != nil { |
| 100 | + t.Errorf("manager exited with error: %v", err) |
| 101 | + } |
| 102 | + }() |
| 103 | + if !mgr.GetCache().WaitForCacheSync(ctx) { |
| 104 | + t.Fatal("cache never synced") |
| 105 | + } |
| 106 | + |
| 107 | + // 5. Obtain the cached client — reads go through the scoped informer cache, |
| 108 | + // so only ConfigMaps matching our selectors will be visible. |
| 109 | + cachedClient := mgr.GetClient() |
| 110 | + |
| 111 | + // 6. Seed ConfigMaps via the direct client (bypasses the cache) so we can |
| 112 | + // then verify which ones are visible through the cached client. |
| 113 | + spireBundleCM := &corev1.ConfigMap{ |
| 114 | + ObjectMeta: metav1.ObjectMeta{ |
| 115 | + Name: spireBundleName, Namespace: spireNS, |
| 116 | + }, |
| 117 | + Data: map[string]string{"bundle.crt": "FAKE-BUNDLE"}, |
| 118 | + } |
| 119 | + clusterDefaultsCM := &corev1.ConfigMap{ |
| 120 | + ObjectMeta: metav1.ObjectMeta{ |
| 121 | + Name: controller.ClusterDefaultsConfigMapName, |
| 122 | + Namespace: controller.ClusterDefaultsNamespace, |
| 123 | + Labels: map[string]string{"app.kubernetes.io/name": "kagenti-operator-chart"}, |
| 124 | + }, |
| 125 | + Data: map[string]string{"otel-endpoint": "collector:4317"}, |
| 126 | + } |
| 127 | + nsDefaultsCM := &corev1.ConfigMap{ |
| 128 | + ObjectMeta: metav1.ObjectMeta{ |
| 129 | + Name: "team-a-defaults", Namespace: "agent-team-a", |
| 130 | + Labels: map[string]string{controller.LabelNamespaceDefaults: "true"}, |
| 131 | + }, |
| 132 | + Data: map[string]string{"sampling-rate": "0.5"}, |
| 133 | + } |
| 134 | + unrelatedCM := &corev1.ConfigMap{ |
| 135 | + ObjectMeta: metav1.ObjectMeta{ |
| 136 | + Name: "app-config", Namespace: spireNS, |
| 137 | + }, |
| 138 | + Data: map[string]string{"key": "value"}, |
| 139 | + } |
| 140 | + |
| 141 | + for _, cm := range []*corev1.ConfigMap{spireBundleCM, clusterDefaultsCM, nsDefaultsCM, unrelatedCM} { |
| 142 | + if err := directClient.Create(ctx, cm); err != nil { |
| 143 | + t.Fatalf("failed to create ConfigMap %s/%s: %v", cm.Namespace, cm.Name, err) |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + t.Run("SPIRE trust bundle visible through cache", func(t *testing.T) { |
| 148 | + got := &corev1.ConfigMap{} |
| 149 | + err := cachedClient.Get(ctx, types.NamespacedName{Name: spireBundleName, Namespace: spireNS}, got) |
| 150 | + if err != nil { |
| 151 | + t.Fatalf("expected SPIRE trust bundle to be visible, got: %v", err) |
| 152 | + } |
| 153 | + if got.Data["bundle.crt"] != "FAKE-BUNDLE" { |
| 154 | + t.Fatalf("unexpected data: %v", got.Data) |
| 155 | + } |
| 156 | + }) |
| 157 | + |
| 158 | + t.Run("cluster defaults visible through cache", func(t *testing.T) { |
| 159 | + got := &corev1.ConfigMap{} |
| 160 | + err := cachedClient.Get(ctx, types.NamespacedName{ |
| 161 | + Name: controller.ClusterDefaultsConfigMapName, Namespace: controller.ClusterDefaultsNamespace, |
| 162 | + }, got) |
| 163 | + if err != nil { |
| 164 | + t.Fatalf("expected cluster defaults to be visible, got: %v", err) |
| 165 | + } |
| 166 | + }) |
| 167 | + |
| 168 | + t.Run("namespace defaults visible through cache", func(t *testing.T) { |
| 169 | + got := &corev1.ConfigMap{} |
| 170 | + err := cachedClient.Get(ctx, types.NamespacedName{Name: "team-a-defaults", Namespace: "agent-team-a"}, got) |
| 171 | + if err != nil { |
| 172 | + t.Fatalf("expected namespace defaults to be visible, got: %v", err) |
| 173 | + } |
| 174 | + }) |
| 175 | + |
| 176 | + t.Run("unrelated ConfigMap in SPIRE namespace is NOT visible", func(t *testing.T) { |
| 177 | + got := &corev1.ConfigMap{} |
| 178 | + err := cachedClient.Get(ctx, types.NamespacedName{Name: "app-config", Namespace: spireNS}, got) |
| 179 | + if err == nil { |
| 180 | + t.Fatal("expected unrelated ConfigMap to be filtered out by field selector, but Get succeeded") |
| 181 | + } |
| 182 | + if !apierrors.IsNotFound(err) { |
| 183 | + t.Fatalf("expected NotFound error, got: %v", err) |
| 184 | + } |
| 185 | + }) |
| 186 | +} |
| 187 | + |
| 188 | +func firstEnvTestBinaryDir() string { |
| 189 | + basePath := filepath.Join("..", "bin", "k8s") |
| 190 | + entries, err := os.ReadDir(basePath) |
| 191 | + if err != nil { |
| 192 | + return "" |
| 193 | + } |
| 194 | + for _, entry := range entries { |
| 195 | + if entry.IsDir() { |
| 196 | + return filepath.Join(basePath, entry.Name()) |
| 197 | + } |
| 198 | + } |
| 199 | + return "" |
| 200 | +} |
0 commit comments