Repository navigation
Add --secret-namespaces to restrict Secret reads on the service cluster #222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
aab9d8e
44aee89
5416f2e
4f0441b
e8d7402
d4b6f29
ea875c6
2b516f2
4763967
ca6a721
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| /* | ||
| Copyright 2026 The KCP Authors. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); | ||
| you may not use this file except in compliance with the License. | ||
| You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software | ||
| distributed under the License is distributed on an "AS IS" BASIS, | ||
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| See the License for the specific language governing permissions and | ||
| limitations under the License. | ||
| */ | ||
|
|
||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| gosync "sync" | ||
| "testing" | ||
| "time" | ||
|
|
||
| corev1 "k8s.io/api/core/v1" | ||
| "k8s.io/apimachinery/pkg/api/meta" | ||
| "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | ||
| "k8s.io/apimachinery/pkg/util/sets" | ||
| "k8s.io/client-go/rest" | ||
| "sigs.k8s.io/controller-runtime/pkg/cache" | ||
| ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client" | ||
| ) | ||
|
|
||
| // TestLocalCacheSecretRequestScope checks which Secret list/watch requests the local cache sends | ||
| // to the service cluster. Namespace-scoped RBAC cannot authorize requests on /api/v1/secrets. | ||
| func TestLocalCacheSecretRequestScope(t *testing.T) { | ||
| testcases := []struct { | ||
| name string | ||
| secretNamespaces []string | ||
| expected sets.Set[string] | ||
| }{ | ||
| { | ||
| name: "without --secret-namespaces, Secrets are cached cluster-wide", | ||
| expected: sets.New("/api/v1/secrets"), | ||
| }, | ||
| { | ||
| name: "with --secret-namespaces, only the given namespaces and the agent namespace are cached", | ||
| secretNamespaces: []string{"sample-space", "other-space", "sample-space"}, | ||
| expected: sets.New( | ||
| "/api/v1/namespaces/"+testAgentNamespace+"/secrets", | ||
| "/api/v1/namespaces/sample-space/secrets", | ||
| "/api/v1/namespaces/other-space/secrets", | ||
| ), | ||
| }, | ||
| } | ||
|
|
||
| informers := map[string]func() ctrlruntimeclient.Object{ | ||
| // typed Secrets are used by the object state store | ||
| "typed": func() ctrlruntimeclient.Object { return &corev1.Secret{} }, | ||
| // unstructured Secrets are used by primary objects and related resources | ||
| "unstructured": func() ctrlruntimeclient.Object { | ||
| obj := &unstructured.Unstructured{} | ||
| obj.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("Secret")) | ||
| return obj | ||
| }, | ||
| } | ||
|
|
||
| for _, tc := range testcases { | ||
| for informerName, newObject := range informers { | ||
| t.Run(tc.name+"/"+informerName, func(t *testing.T) { | ||
| lists := sets.New[string]() | ||
| watches := sets.New[string]() | ||
| lock := gosync.Mutex{} | ||
|
|
||
| server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| w.Header().Set("Content-Type", "application/json") | ||
|
|
||
| lock.Lock() | ||
| if isWatch(r) { | ||
| watches.Insert(r.URL.Path) | ||
| } else { | ||
| lists.Insert(r.URL.Path) | ||
| } | ||
| lock.Unlock() | ||
|
|
||
| if isWatch(r) { | ||
| // let the reflector fall back to a regular list request | ||
| w.WriteHeader(http.StatusNotFound) | ||
| return | ||
| } | ||
|
|
||
| _, _ = w.Write([]byte(`{"kind":"SecretList","apiVersion":"v1","metadata":{"resourceVersion":"1"},"items":[]}`)) | ||
| })) | ||
| defer server.Close() | ||
|
|
||
| opts := NewOptions() | ||
| opts.Namespace = testAgentNamespace | ||
| opts.SecretNamespaces = tc.secretNamespaces | ||
|
|
||
| scheme, err := newLocalScheme() | ||
| if err != nil { | ||
| t.Fatalf("Failed to create scheme: %v", err) | ||
| } | ||
|
|
||
| mapper := meta.NewDefaultRESTMapper(nil) | ||
| mapper.Add(corev1.SchemeGroupVersion.WithKind("Secret"), meta.RESTScopeNamespace) | ||
|
|
||
| cacheOpts := newLocalCacheOptions(opts) | ||
| cacheOpts.Scheme = scheme | ||
| cacheOpts.Mapper = mapper | ||
|
|
||
| localCache, err := cache.New(&rest.Config{Host: server.URL}, cacheOpts) | ||
| if err != nil { | ||
| t.Fatalf("Failed to create cache: %v", err) | ||
| } | ||
|
|
||
| ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) | ||
| defer cancel() | ||
|
|
||
| if _, err := localCache.GetInformer(ctx, newObject()); err != nil { | ||
| t.Fatalf("Failed to get Secret informer: %v", err) | ||
| } | ||
|
|
||
| go func() { | ||
| _ = localCache.Start(ctx) | ||
| }() | ||
|
|
||
| if !localCache.WaitForCacheSync(ctx) { | ||
| t.Fatal("Cache did not sync.") | ||
| } | ||
|
|
||
| // The reflector starts its watches after the initial list, so wait for all of them. | ||
| deadline := time.Now().Add(10 * time.Second) | ||
| for { | ||
| lock.Lock() | ||
| done := watches.IsSuperset(tc.expected) | ||
| lock.Unlock() | ||
|
|
||
| if done || time.Now().After(deadline) { | ||
| break | ||
| } | ||
|
|
||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
|
|
||
| lock.Lock() | ||
| defer lock.Unlock() | ||
|
|
||
| if !lists.Equal(tc.expected) { | ||
| t.Fatalf("Expected list requests to %v, but got %v.", sets.List(tc.expected), sets.List(lists)) | ||
| } | ||
|
|
||
| if !watches.Equal(tc.expected) { | ||
| t.Fatalf("Expected watch requests to %v, but got %v.", sets.List(tc.expected), sets.List(watches)) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -87,6 +87,15 @@ type Options struct { | |
| // CacheSyncTimeout is how long each sync controller waits for its caches to | ||
| // sync before it gives up. | ||
| CacheSyncTimeout time.Duration | ||
|
|
||
| // SecretNamespaces restricts the local cache for Secrets to these namespaces. The | ||
| // agent's own Namespace is always included because the object state is stored there. | ||
| // When empty, Secrets are cached in all namespaces. | ||
| SecretNamespaces []string | ||
|
|
||
| // secretNamespacesSet records that --secret-namespaces was given, so that an empty | ||
| // value is rejected instead of silently caching Secrets cluster-wide. | ||
| secretNamespacesSet bool | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think pflag already tells these cases apart. With the nil default, an omitted flag leaves |
||
| } | ||
|
|
||
| func NewOptions() *Options { | ||
|
|
@@ -114,6 +123,7 @@ func (o *Options) AddFlags(flags *pflag.FlagSet) { | |
| flags.StringVar(&o.MetricsAddr, "metrics-address", o.MetricsAddr, "host and port to serve Prometheus metrics via /metrics (HTTP)") | ||
| flags.StringVar(&o.HealthAddr, "health-address", o.HealthAddr, "host and port to serve probes via /readyz and /healthz (HTTP)") | ||
| flags.StringSliceVar(&o.DisabledControllers, "disabled-controllers", o.DisabledControllers, fmt.Sprintf("comma-separated list of controllers (out of %v) to disable (can be given multiple times)", sets.List(availableControllers))) | ||
| flags.StringSliceVar(&o.SecretNamespaces, "secret-namespaces", o.SecretNamespaces, "comma-separated list of namespaces to which the Secret cache on the service cluster is restricted; the agent's own --namespace is always included (optional, by default Secrets are cached in all namespaces)") | ||
| flags.BoolVar(&o.EnableServerSideApply, "enable-server-side-apply", o.EnableServerSideApply, "use Kubernetes Server-Side Apply when writing synchronized objects to the local cluster (recommended; preserves fields owned by other controllers such as Crossplane's claim binder)") | ||
| flags.IntVar(&o.WorkerCount, "worker-count", o.WorkerCount, "number of concurrent workers of each sync controller (and of the APIResourceSchema controller)") | ||
| flags.DurationVar(&o.CacheSyncTimeout, "cache-sync-timeout", o.CacheSyncTimeout, "how long each sync controller waits for its caches to sync before the start attempt fails and is retried (increase for PublishedResources with many objects)") | ||
|
|
@@ -158,6 +168,16 @@ func (o *Options) Validate() error { | |
| errs = append(errs, errors.New("--cache-sync-timeout must be greater than zero")) | ||
| } | ||
|
|
||
| if o.secretNamespacesSet && len(o.SecretNamespaces) == 0 { | ||
| errs = append(errs, errors.New("--secret-namespaces must not be empty; omit the flag to cache Secrets in all namespaces")) | ||
| } | ||
|
|
||
| for _, namespace := range o.SecretNamespaces { | ||
| if e := validation.IsDNS1123Label(namespace); len(e) > 0 { | ||
| errs = append(errs, fmt.Errorf("invalid namespace %q in --secret-namespaces: %v", namespace, e)) | ||
| } | ||
| } | ||
|
|
||
| disabled := sets.New(o.DisabledControllers...) | ||
| unknown := disabled.Difference(availableControllers) | ||
|
|
||
|
|
@@ -185,3 +205,9 @@ func (o *Options) Complete() error { | |
|
|
||
| return utilerrors.NewAggregate(errs) | ||
| } | ||
|
|
||
| // RecordParsedFlags records which optional flags were given on the command line. Call it after | ||
| // the flags were parsed and before Validate. | ||
| func (o *Options) RecordParsedFlags(flags *pflag.FlagSet) { | ||
| o.secretNamespacesSet = flags.Changed("secret-namespaces") | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we switch to the nil check, can you add a note here: nil means the flag was not given, an empty slice means it was given empty.