fix(cozystack-api): stop serving sdn.cozystack.io when serveSDN is off

serveSDN=false removed only the sdn APIService. The binary still
installed the group, so its /openapi/v3 index kept listing
apis/sdn.cozystack.io/v1alpha1 beside the server that owns the group
(cozyplane-apiserver in the cozyplane variant). kube-aggregator merges
every APIService backend's index and serves a group-version from
whichever backend it meets first in map order, so the index hash and the
spec request often land on different backends. The backend answers the
stale hash with a 301, the aggregator refuses to forward it, and
`kubectl explain` fails for every kind in the group with "the backend
attempted to redirect this request, which is not permitted"; when the
two do match, kubectl gets cozystack-api's SecurityGroup-only spec and
reports the other kinds as missing.

The chart now passes --serve-sdn=false with serveSDN off, and the
server then leaves the group uninstalled.

Assisted-by: LLM
Signed-off-by: Timofei Larkin <lllamnyp@gmail.com>
This commit is contained in:
Timofei Larkin committed 2026-11-19 12:04:16 +01:00
1 parent 2065b7a523
commit 952e05836d
5 files changed
+222 -20

No files matched your search

@@ -31,6 +31,9 @@ spec:
args:
- --tls-cert-file=/tmp/cozystack-api-certs/tls.crt
- --tls-private-key-file=/tmp/cozystack-api-certs/tls.key
{{- if not .Values.cozystackAPI.serveSDN }}
- --serve-sdn=false
{{- end }}
image: "{{ .Values.cozystackAPI.image }}"
ports:
- containerPort: 443
+5 -3
View File
@@ -8,7 +8,9 @@ cozystackAPI:
# Empty by default: no resources block is rendered, so requests and limits are
# opt-in. Idle usage (measured) is ~130-143Mi — keep a limit above that.
resources: {}
# Aggregate the sdn.cozystack.io group (Cozystack-native SecurityGroup over
# CiliumNetworkPolicy) through cozystack-api. The platform bundle turns this
# off for the cozyplane networking variant, where cozyplane owns the group.
# Serve and aggregate the sdn.cozystack.io group (Cozystack-native
# SecurityGroup over CiliumNetworkPolicy) through cozystack-api. The platform
# bundle turns this off for the cozyplane networking variant, where cozyplane
# owns the group; off drops both the APIService and the group itself
# (--serve-sdn=false), so cozystack-api stops publishing its OpenAPI.
serveSDN: true
+33 -17
View File
@@ -115,6 +115,7 @@ func init() {
type Config struct {
GenericConfig *genericapiserver.RecommendedConfig
ResourceConfig *config.ResourceConfig
ServeSDN bool
}
// CozyServer holds the state for the Kubernetes master/api server.
@@ -125,6 +126,7 @@ type CozyServer struct {
type completedConfig struct {
GenericConfig genericapiserver.CompletedConfig
ResourceConfig *config.ResourceConfig
ServeSDN bool
}
// CompletedConfig embeds a private pointer that cannot be created outside of this package.
@@ -137,6 +139,7 @@ func (cfg *Config) Complete() CompletedConfig {
c := completedConfig{
cfg.GenericConfig.Complete(),
cfg.ResourceConfig,
cfg.ServeSDN,
}
return CompletedConfig{&c}
@@ -213,6 +216,29 @@ func (c completedConfig) New() (*CozyServer, error) {
if err != nil {
return nil, fmt.Errorf("failed to build dynamic client: %w", err)
}
if err := InstallStaticAPIGroups(s.GenericAPIServer, cli, watchCli, dyn, c.ServeSDN); err != nil {
return nil, err
}
// --- dynamically-configured, per-tenant resources ---
appsV1alpha1Storage := map[string]rest.Storage{}
for _, resConfig := range c.ResourceConfig.Resources {
storage := applicationstorage.NewREST(cli, watchCli, &resConfig)
appsV1alpha1Storage[resConfig.Application.Plural] = cozyregistry.RESTInPeace(storage)
}
if err := InstallAppsAPIGroup(s.GenericAPIServer, appsV1alpha1Storage); err != nil {
return nil, err
}
return s, nil
}
// InstallStaticAPIGroups registers core.cozystack.io and, when serveSDN is
// set, sdn.cozystack.io. Removing only the sdn APIService is not enough where
// another server owns the group: kube-aggregator still merges this server's
// /openapi/v3 index, so both backends list the group-version and fetching its
// OpenAPI fails on a redirect whenever the two disagree on the hash.
func InstallStaticAPIGroups(server *genericapiserver.GenericAPIServer, cli client.Client, watchCli client.WithWatch, dyn dynamic.Interface, serveSDN bool) error {
// --- static, cluster-scoped resource for core group ---
coreV1alpha1Storage := map[string]rest.Storage{}
coreV1alpha1Storage["tenantnamespaces"] = cozyregistry.RESTInPeace(
@@ -236,8 +262,12 @@ func (c completedConfig) New() (*CozyServer, error) {
coreApiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(core.GroupName, Scheme, metav1.ParameterCodec, Codecs)
coreApiGroupInfo.VersionedResourcesStorageMap["v1alpha1"] = coreV1alpha1Storage
if err := s.GenericAPIServer.InstallAPIGroup(&coreApiGroupInfo); err != nil {
return nil, err
if err := server.InstallAPIGroup(&coreApiGroupInfo); err != nil {
return err
}
if !serveSDN {
return nil
}
// --- static, namespaced resource for sdn group ---
@@ -248,21 +278,7 @@ func (c completedConfig) New() (*CozyServer, error) {
sdnApiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(sdn.GroupName, Scheme, metav1.ParameterCodec, Codecs)
sdnApiGroupInfo.VersionedResourcesStorageMap["v1alpha1"] = sdnV1alpha1Storage
if err := s.GenericAPIServer.InstallAPIGroup(&sdnApiGroupInfo); err != nil {
return nil, err
}
// --- dynamically-configured, per-tenant resources ---
appsV1alpha1Storage := map[string]rest.Storage{}
for _, resConfig := range c.ResourceConfig.Resources {
storage := applicationstorage.NewREST(cli, watchCli, &resConfig)
appsV1alpha1Storage[resConfig.Application.Plural] = cozyregistry.RESTInPeace(storage)
}
if err := InstallAppsAPIGroup(s.GenericAPIServer, appsV1alpha1Storage); err != nil {
return nil, err
}
return s, nil
return server.InstallAPIGroup(&sdnApiGroupInfo)
}
// InstallAppsAPIGroup registers the apps.cozystack.io API group on the given
+172
View File
@@ -0,0 +1,172 @@
/*
Copyright 2026 The Cozystack 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 server_test
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"k8s.io/apimachinery/pkg/runtime"
genericapiserver "k8s.io/apiserver/pkg/server"
utilfeature "k8s.io/apiserver/pkg/util/feature"
dynamicfake "k8s.io/client-go/dynamic/fake"
restclient "k8s.io/client-go/rest"
basecompatibility "k8s.io/component-base/compatibility"
baseversion "k8s.io/component-base/version"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
corev1alpha1 "github.com/cozystack/cozystack/pkg/apis/core/v1alpha1"
"github.com/cozystack/cozystack/pkg/apiserver"
cozyserver "github.com/cozystack/cozystack/pkg/cmd/server"
)
const (
sdnGroupVersionPath = "apis/sdn.cozystack.io/v1alpha1"
coreGroupVersionPath = "apis/core.cozystack.io/v1alpha1"
)
// startStaticGroupsServer serves the static groups through the real handler
// chain and OpenAPI config, with storage backed by fake clients.
func startStaticGroupsServer(t *testing.T, serveSDN bool) *httptest.Server {
t.Helper()
corev1alpha1.RegisterStaticTypes(apiserver.Scheme)
cfg := genericapiserver.NewConfig(apiserver.Codecs)
cfg.ExternalAddress = "localhost:443"
cfg.LoopbackClientConfig = &restclient.Config{}
cfg.FeatureGate = utilfeature.DefaultMutableFeatureGate
if baseversion.DefaultKubeBinaryVersion != "" {
cfg.EffectiveVersion = basecompatibility.NewEffectiveVersionFromString(baseversion.DefaultKubeBinaryVersion, "", "")
}
cozyserver.ConfigureOpenAPI(cfg, nil, "test", "test")
srv, err := cfg.Complete(nil).New("serve-sdn-test", genericapiserver.NewEmptyDelegate())
if err != nil {
t.Fatal(err)
}
cli := fake.NewClientBuilder().Build()
dyn := dynamicfake.NewSimpleDynamicClient(runtime.NewScheme())
if err := apiserver.InstallStaticAPIGroups(srv, cli, cli, dyn, serveSDN); err != nil {
t.Fatal(err)
}
srv.PrepareRun()
ts := httptest.NewServer(srv.Handler)
t.Cleanup(ts.Close)
return ts
}
func get(t *testing.T, ts *httptest.Server, path string) (int, []byte) {
t.Helper()
// kube-aggregator's proxy refuses to follow a backend redirect, so a 3xx
// here must surface as the status, not be followed.
c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
resp, err := c.Get(ts.URL + path)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
return resp.StatusCode, body
}
// The OpenAPI v3 index is what kube-aggregator merges across backends, so a
// group-version listed here is claimed by this server whatever the APIService
// says.
func openAPIV3Index(t *testing.T, ts *httptest.Server) map[string]string {
t.Helper()
code, body := get(t, ts, "/openapi/v3")
if code != http.StatusOK {
t.Fatalf("GET /openapi/v3: %d %s", code, body)
}
var index struct {
Paths map[string]struct {
ServerRelativeURL string `json:"serverRelativeURL"`
} `json:"paths"`
}
if err := json.Unmarshal(body, &index); err != nil {
t.Fatal(err)
}
urls := map[string]string{}
for k, v := range index.Paths {
urls[k] = v.ServerRelativeURL
}
return urls
}
func TestServeSDNOffKeepsGroupOutOfOpenAPI(t *testing.T) {
ts := startStaticGroupsServer(t, false)
index := openAPIV3Index(t, ts)
if _, ok := index[coreGroupVersionPath]; !ok {
t.Fatalf("OpenAPI v3 index lacks %s: %v", coreGroupVersionPath, index)
}
for k := range index {
if strings.HasPrefix(k, "apis/sdn.cozystack.io") {
t.Errorf("OpenAPI v3 index lists %s with --serve-sdn=false", k)
}
}
code, body := get(t, ts, "/openapi/v2")
if code != http.StatusOK {
t.Fatalf("GET /openapi/v2: %d %s", code, body)
}
var v2 struct {
Paths map[string]json.RawMessage `json:"paths"`
}
if err := json.Unmarshal(body, &v2); err != nil {
t.Fatal(err)
}
for p := range v2.Paths {
if strings.HasPrefix(p, "/apis/sdn.cozystack.io") {
t.Errorf("OpenAPI v2 lists %s with --serve-sdn=false", p)
}
}
if code, _ := get(t, ts, "/apis/sdn.cozystack.io/v1alpha1"); code != http.StatusNotFound {
t.Errorf("GET /apis/sdn.cozystack.io/v1alpha1 = %d, want 404", code)
}
}
func TestServeSDNOnPublishesSecurityGroupSchema(t *testing.T) {
ts := startStaticGroupsServer(t, true)
url, ok := openAPIV3Index(t, ts)[sdnGroupVersionPath]
if !ok {
t.Fatalf("OpenAPI v3 index lacks %s", sdnGroupVersionPath)
}
code, body := get(t, ts, url)
if code != http.StatusOK {
t.Fatalf("GET %s: %d %s", url, code, body)
}
if !strings.Contains(string(body), `"/apis/sdn.cozystack.io/v1alpha1/namespaces/{namespace}/securitygroups"`) {
t.Errorf("%s has no securitygroups path", url)
}
// A stale hash is answered with a redirect; this is the response
// kube-aggregator rejects when it routes a hash taken from one backend's
// index to the other backend.
stale := "/openapi/v3/" + sdnGroupVersionPath + "?hash=0"
if code, _ := get(t, ts, stale); code != http.StatusMovedPermanently {
t.Errorf("GET %s = %d, want 301", stale, code)
}
}
+9
View File
@@ -72,6 +72,10 @@ type CozyServerOptions struct {
HelmReleaseInstallTimeout string
HelmReleaseUpgradeTimeout string
HelmReleaseMaxHistory int
// ServeSDN installs the sdn.cozystack.io group; off where another
// aggregated server owns it.
ServeSDN bool
}
// NewCozyServerOptions returns a new instance of CozyServerOptions
@@ -94,6 +98,7 @@ func NewCozyServerOptions(out, errOut io.Writer) *CozyServerOptions {
HelmReleaseInstallTimeout: "10m",
HelmReleaseUpgradeTimeout: "10m",
HelmReleaseMaxHistory: 5,
ServeSDN: true,
}
o.RecommendedOptions.Etcd = nil
disableUnsyncableAdmissionPlugins(o.RecommendedOptions.Admission)
@@ -170,6 +175,9 @@ func NewCommandStartCozyServer(ctx context.Context, defaults *CozyServerOptions)
"Number of release revisions Helm keeps for HelmReleases generated from Application "+
"resources (Spec.MaxHistory). 0 means unlimited; 5 matches Helm's default.")
flags.BoolVar(&o.ServeSDN, "serve-sdn", o.ServeSDN,
"Serve the sdn.cozystack.io API group. Turn off where another aggregated API server owns the group.")
// Note: KEP-4330 component versioning functionality (k8s.io/apiserver/pkg/util/version)
// is not available in Kubernetes v0.34.1. The component versioning code has been removed.
@@ -469,6 +477,7 @@ func (o *CozyServerOptions) Config() (*apiserver.Config, error) {
config := &apiserver.Config{
GenericConfig: serverConfig,
ResourceConfig: o.ResourceConfig,
ServeSDN: o.ServeSDN,
}
return config, nil
}