Skip to content
Open
50 changes: 48 additions & 2 deletions cmd/api-syncagent/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ import (
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
ctrlruntime "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
ctrlruntimelog "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
Expand All @@ -61,6 +63,7 @@ func main() {
// ctrl-runtime will have added its --kubeconfig to Go's flag set
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
opts.RecordParsedFlags(pflag.CommandLine)

if err := opts.Validate(); err != nil {
golog.Fatalf("Invalid command line: %v", err)
Expand Down Expand Up @@ -207,7 +210,11 @@ func run(ctx context.Context, log *zap.SugaredLogger, opts *Options) error {
}

func setupLocalManager(ctx context.Context, opts *Options) (manager.Manager, error) {
scheme := runtime.NewScheme()
scheme, err := newLocalScheme()
if err != nil {
return nil, err
}

restConfig := ctrlruntime.GetConfigOrDie()

if opts.KubeconfigHostOverride != "" {
Expand All @@ -224,6 +231,7 @@ func setupLocalManager(ctx context.Context, opts *Options) (manager.Manager, err

mgr, err := manager.New(restConfig, manager.Options{
Scheme: scheme,
Cache: newLocalCacheOptions(opts),
BaseContext: func() context.Context {
return ctx
},
Expand All @@ -237,6 +245,17 @@ func setupLocalManager(ctx context.Context, opts *Options) (manager.Manager, err
return nil, err
}

if len(opts.SecretNamespaces) == 0 {
return mgr, nil
}

// Serve every Secret read from the allowed namespaces only, including unstructured and live reads.
return newSecretScopedManager(mgr, secretCacheNamespaces(opts)), nil
}

func newLocalScheme() (*runtime.Scheme, error) {
scheme := runtime.NewScheme()

if err := corev1.AddToScheme(scheme); err != nil {
return nil, fmt.Errorf("failed to register local scheme %s: %w", corev1.SchemeGroupVersion, err)
}
Expand All @@ -249,7 +268,34 @@ func setupLocalManager(ctx context.Context, opts *Options) (manager.Manager, err
return nil, fmt.Errorf("failed to register local scheme %s: %w", syncagentv1alpha1.SchemeGroupVersion, err)
}

return mgr, nil
return scheme, nil
}

// newLocalCacheOptions returns the cache options for the local service cluster. When
// --secret-namespaces is given, Secrets are only cached in those namespaces and in the
// agent's own namespace, so that namespace-scoped RBAC is enough to list and watch them.
// All other resources keep using the default (cluster-wide) cache.
func newLocalCacheOptions(opts *Options) cache.Options {
if len(opts.SecretNamespaces) == 0 {
return cache.Options{}
}

namespaces := map[string]cache.Config{}
for namespace := range secretCacheNamespaces(opts) {
namespaces[namespace] = cache.Config{}
}

return cache.Options{
ByObject: map[ctrlruntimeclient.Object]cache.ByObject{
&corev1.Secret{}: {Namespaces: namespaces},
},
}
}

// secretCacheNamespaces returns the namespaces in which the Agent reads Secrets on the service
// cluster: --secret-namespaces and the Agent's own namespace, where it stores object state.
func secretCacheNamespaces(opts *Options) sets.Set[string] {
return sets.New(opts.SecretNamespaces...).Insert(opts.Namespace)
}

func loadKubeconfig(filename string) (*rest.Config, error) {
Expand Down
161 changes: 161 additions & 0 deletions cmd/api-syncagent/main_test.go
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))
}
})
}
}
}
26 changes: 26 additions & 0 deletions cmd/api-syncagent/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown
Contributor

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.


// secretNamespacesSet records that --secret-namespaces was given, so that an empty
// value is rejected instead of silently caching Secrets cluster-wide.
secretNamespacesSet bool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 SecretNamespaces nil, and --secret-namespaces= sets it to []string{} (readAsCSV("") returns an empty slice). So we could drop this field and RecordParsedFlags, and check o.SecretNamespaces != nil && len(o.SecretNamespaces) == 0 in Validate(). That also removes the call in main.go, which if forgotten turns the empty check off without any error. TestSecretNamespacesFlag already covers it.

}

func NewOptions() *Options {
Expand Down Expand Up @@ -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)")
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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")
}
Loading
Loading