feat(api): apply installation defaults when creating applications

Defaults set by the administrator have to reach every application
kind, including ones from external catalogs, and give the same result
for the dashboard, Terraform and kubectl, so the merge runs in the API
server on create instead of in each client.

User values win over installation defaults, which win over the
developer defaults of the chart. Only objects with declared properties
merge recursively. Arrays, dictionaries and free-form objects are
replaced whole, so a pool that sets its own registry mirrors never
receives the platform entries. The entry is checked against the
application's OpenAPI schema before merging. CEL rules are left out of
that check, since a rule such as an immutability test has no meaning
on a partial object.

The ConfigMap is read through a cache limited to that one object, so
the API does not hold a watch on every ConfigMap in the cluster. A
missing ConfigMap means no defaults. One that cannot be read, or an
invalid configuration or entry, skips the defaults and the create goes
on with a warning, because a configuration mistake must not stop
applications from being created. Updates never apply defaults. The
ConfigMap rule the API already has covers the read, and its comment
now names this second user.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
This commit is contained in:
Myasnikov Daniil committed 2026-11-26 14:20:05 +00:00
1 parent e43dac3a69
commit 77d8bf5001
20 files changed
+1877 -31

No files matched your search

@@ -81,7 +81,12 @@ rules:
verbs: ["get", "watch", "list"]
# The VM picker reads the machine list the migration controller publishes for
# each source. Read-only, and only ever fetched by a name derived from the
# source the tenant already chose.
# source the tenant already chose. The create path also keeps a cache of the
# ConfigMap cozy-system/cozystack-application-defaults for installation
# defaults. The cache asks the server for that one object with a metadata.name
# field selector, which a Role with resourceNames could match, but this rule
# covers every ConfigMap. Without it every create waits up to five seconds for
# the cache, then goes on without defaults and returns a warning.
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "watch", "list"]
+23 -1
View File
@@ -205,6 +205,28 @@ func (c completedConfig) New() (*CozyServer, error) {
return nil, fmt.Errorf("cache sync failed")
}
// The create path reads installation defaults from this cache. The API waits
// for the first sync so a create does not race it, but only for a bounded
// time: the defaults are optional and an unreadable ConfigMap must not keep
// the whole API from serving.
defaultsCache, err := applicationstorage.NewInstallationDefaultsCache(cfg, mgrScheme)
if err != nil {
return nil, fmt.Errorf("failed to build application defaults cache: %w", err)
}
if _, err := defaultsCache.GetInformer(ctx, &corev1.ConfigMap{}); err != nil {
return nil, fmt.Errorf("failed to get application defaults informer: %w", err)
}
go func() {
if err := defaultsCache.Start(ctx); err != nil {
panic(fmt.Errorf("application defaults cache start failed: %w", err))
}
}()
syncCtx, cancelSync := context.WithTimeout(ctx, applicationstorage.InstallationDefaultsSyncTimeout)
defer cancelSync()
if ok := defaultsCache.WaitForCacheSync(syncCtx); !ok {
klog.Warning("Application defaults cache did not sync; creates skip installation defaults until it does")
}
cli := mgr.GetClient()
watchCli, err := client.NewWithWatch(cfg, client.Options{Scheme: mgrScheme})
if err != nil {
@@ -224,7 +246,7 @@ func (c completedConfig) New() (*CozyServer, error) {
// --- dynamically-configured, per-tenant resources ---
appsV1alpha1Storage := map[string]rest.Storage{}
for _, resConfig := range c.ResourceConfig.Resources {
storage := applicationstorage.NewREST(cli, watchCli, &resConfig)
storage := applicationstorage.NewREST(cli, watchCli, defaultsCache, &resConfig)
appsV1alpha1Storage[resConfig.Application.Plural] = cozyregistry.RESTInPeace(storage)
}
if err := InstallAppsAPIGroup(s.GenericAPIServer, appsV1alpha1Storage); err != nil {
+121
View File
@@ -0,0 +1,121 @@
/*
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 (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func TestApplicationDefaultsHTTPPreviewAndApply(t *testing.T) {
resource := redisConfig
resource.Application.OpenAPISchema = `{"type":"object","properties":{"replicas":{"type":"integer","default":1},"setting":{"type":"string"},"developer":{"type":"string","default":"chart"},"later":{"type":"boolean"}}}`
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: "cozy-system", Name: "cozystack-application-defaults"}, Data: map[string]string{"defaults.json": `{"redises":{"replicas":3}}`}}
ts, cli := startAppsServerWithUIDs(t, &config.ResourceConfig{Resources: []config.Resource{resource}}, cm)
request := func(method, path, contentType string) (int, map[string]any) {
t.Helper()
body := `{"apiVersion":"apps.cozystack.io/v1alpha1","kind":"Redis","metadata":{"name":"cache","namespace":"tenant-a"},"spec":{"setting":"user"}}`
req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", contentType)
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
raw, err := io.ReadAll(res.Body)
if err != nil {
t.Fatal(err)
}
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
t.Fatalf("decode %s: %v", raw, err)
}
if res.StatusCode >= 300 {
t.Fatalf("%s %s: %d %s", method, path, res.StatusCode, raw)
}
return res.StatusCode, decoded
}
base := "/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/redises"
status, preview := request(http.MethodPost, base+"?dryRun=All", "application/json")
if status != http.StatusCreated {
t.Fatalf("preview status %d", status)
}
spec := preview["spec"].(map[string]any)
if spec["replicas"] != float64(3) || spec["developer"] != "chart" {
t.Fatalf("preview spec: %v", spec)
}
key := client.ObjectKey{Namespace: "tenant-a", Name: "redis-cache"}
if err := cli.Get(context.Background(), key, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) {
t.Fatalf("preview persisted a release: %v", err)
}
status, _ = request(http.MethodPatch, base+"/cache?fieldManager=apply-client&force=true", "application/apply-patch+yaml")
if status != http.StatusCreated {
t.Fatalf("apply create status %d", status)
}
hr := &helmv2.HelmRelease{}
if err := cli.Get(context.Background(), key, hr); err != nil {
t.Fatal(err)
}
var stored map[string]any
if err := json.Unmarshal(hr.Spec.Values.Raw, &stored); err != nil {
t.Fatal(err)
}
if stored["replicas"] != float64(3) || stored["setting"] != "user" {
t.Fatalf("stored spec: %v", stored)
}
if _, ok := stored["developer"]; ok {
t.Fatal("API stamped developer defaults")
}
if err := cli.Get(context.Background(), client.ObjectKeyFromObject(cm), cm); err != nil {
t.Fatal(err)
}
cm.Data["defaults.json"] = `{"redises":{"replicas":9,"later":true}}`
if err := cli.Update(context.Background(), cm); err != nil {
t.Fatal(err)
}
status, _ = request(http.MethodPatch, base+"/cache?fieldManager=apply-client&force=true", "application/apply-patch+yaml")
if status != http.StatusOK {
t.Fatalf("apply update status %d", status)
}
if err := cli.Get(context.Background(), key, hr); err != nil {
t.Fatal(err)
}
stored = nil
if err := json.Unmarshal(hr.Spec.Values.Raw, &stored); err != nil {
t.Fatal(err)
}
if stored["replicas"] != float64(3) {
t.Fatalf("reapply changed saved defaults: %s", hr.Spec.Values.Raw)
}
if _, ok := stored["later"]; ok {
t.Fatal("reapply added new installation defaults")
}
}
+44 -3
View File
@@ -19,15 +19,22 @@ package server_test
import (
"bufio"
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/authentication/authenticator"
"k8s.io/apiserver/pkg/authentication/user"
"k8s.io/apiserver/pkg/authorization/authorizerfactory"
"k8s.io/apiserver/pkg/registry/rest"
genericapiserver "k8s.io/apiserver/pkg/server"
utilfeature "k8s.io/apiserver/pkg/util/feature"
@@ -36,6 +43,7 @@ import (
baseversion "k8s.io/component-base/version"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/apiserver"
@@ -52,7 +60,21 @@ var redisConfig = config.Resource{
// startAppsServer serves the apps group through the real apiserver handler
// chain, with the application storage backed by a fake client. The kinds are
// registered on the process-wide apiserver.Scheme.
func startAppsServer(t *testing.T, rc *config.ResourceConfig) (*httptest.Server, client.Client) {
func startAppsServer(t *testing.T, rc *config.ResourceConfig, objects ...client.Object) (*httptest.Server, client.Client) {
t.Helper()
return serveApps(t, rc, false, objects...)
}
// startAppsServerWithUIDs is startAppsServer whose backing client assigns
// metadata.uid on create, as a real apiserver does. The fake client does not, and
// the generic patch handler treats a current object without a uid as missing, so
// without one a PATCH of an existing application is served as a create.
func startAppsServerWithUIDs(t *testing.T, rc *config.ResourceConfig, objects ...client.Object) (*httptest.Server, client.Client) {
t.Helper()
return serveApps(t, rc, true, objects...)
}
func serveApps(t *testing.T, rc *config.ResourceConfig, assignUIDs bool, objects ...client.Object) (*httptest.Server, client.Client) {
t.Helper()
if err := appsv1alpha1.RegisterDynamicTypes(apiserver.Scheme, rc); err != nil {
t.Fatal(err)
@@ -62,9 +84,28 @@ func startAppsServer(t *testing.T, rc *config.ResourceConfig) (*httptest.Server,
if err := helmv2.AddToScheme(backing); err != nil {
t.Fatal(err)
}
cli := fake.NewClientBuilder().WithScheme(backing).Build()
if err := corev1.AddToScheme(backing); err != nil {
t.Fatal(err)
}
builder := fake.NewClientBuilder().WithScheme(backing).WithObjects(objects...)
if assignUIDs {
var uids atomic.Int64
builder = builder.WithInterceptorFuncs(interceptor.Funcs{
Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error {
if obj.GetUID() == "" {
obj.SetUID(types.UID(fmt.Sprintf("00000000-0000-0000-0000-%012d", uids.Add(1))))
}
return c.Create(ctx, obj, opts...)
},
})
}
cli := builder.Build()
cfg := genericapiserver.NewConfig(apiserver.Codecs)
cfg.Authorization.Authorizer = authorizerfactory.NewAlwaysAllowAuthorizer()
cfg.Authentication.Authenticator = authenticator.RequestFunc(func(*http.Request) (*authenticator.Response, bool, error) {
return &authenticator.Response{User: &user.DefaultInfo{Name: "test-user"}}, true, nil
})
cfg.ExternalAddress = "localhost:443"
cfg.LoopbackClientConfig = &restclient.Config{}
cfg.FeatureGate = utilfeature.DefaultMutableFeatureGate
@@ -78,7 +119,7 @@ func startAppsServer(t *testing.T, rc *config.ResourceConfig) (*httptest.Server,
}
storage := map[string]rest.Storage{}
for i := range rc.Resources {
storage[rc.Resources[i].Application.Plural] = applicationstorage.NewREST(cli, cli, &rc.Resources[i])
storage[rc.Resources[i].Application.Plural] = applicationstorage.NewREST(cli, cli, cli, &rc.Resources[i])
}
if err := apiserver.InstallAppsAPIGroup(srv, storage); err != nil {
t.Fatal(err)
@@ -0,0 +1,231 @@
/*
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 application
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
corev1 "k8s.io/api/core/v1"
internalapiext "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextvalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
kubejson "k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/validation/field"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func (r *REST) applyInstallationDefaults(ctx context.Context, app *appsv1alpha1.Application) error {
if r.defaultsReader == nil {
return nil
}
readCtx, cancel := context.WithTimeout(ctx, r.defaultsReadLimit)
defer cancel()
cm := &corev1.ConfigMap{}
if err := r.defaultsReader.Get(readCtx, client.ObjectKey{Namespace: InstallationDefaultsNamespace, Name: InstallationDefaultsName}, cm); err != nil {
if apierrors.IsNotFound(err) {
return nil
}
return fmt.Errorf("read application defaults: %w", err)
}
defaults, err := parseInstallationDefaults(cm.Data["defaults.json"])
if err != nil {
return fmt.Errorf("invalid application defaults: %w", err)
}
values, configured := defaults[r.gvr.Resource]
if !configured {
return nil
}
path := field.NewPath("applicationDefaults").Key(r.gvr.Resource)
if r.defaultsSchemaErr != nil {
return fmt.Errorf("%s: cannot validate installation defaults: %w", path, r.defaultsSchemaErr)
}
if r.defaultsValidator == nil {
return fmt.Errorf("%s: application schema is unavailable", path)
}
// OpenAPI validation expects native numbers, including inside allOf branches.
// Keep the original JSON numbers for persistence without a float round-trip.
validationValues := runtime.DeepCopyJSONValue(values).(map[string]any)
if err := kubejson.ConvertMapNumbers(validationValues, 0); err != nil {
return fmt.Errorf("%s: invalid configured number: %w", path, err)
}
if errs := apiextvalidation.ValidateCustomResource(path, validationValues, r.defaultsValidator); len(errs) > 0 {
return fmt.Errorf("invalid installation defaults: %w", errs.ToAggregate())
}
spec := map[string]any{}
if app.Spec != nil && len(app.Spec.Raw) > 0 {
if err := decodeDefaultsJSON(app.Spec.Raw, &spec); err != nil {
return apierrors.NewBadRequest(fmt.Sprintf("decode application spec: %v", err))
}
}
if spec == nil {
spec = map[string]any{}
}
fillInstallationDefaults(spec, values, r.defaultsSchema)
raw, err := json.Marshal(spec)
if err != nil {
return err
}
app.Spec = &apiextv1.JSON{Raw: raw}
return nil
}
func buildInstallationDefaultsValidator(raw string) (apiextvalidation.SchemaCreateValidator, error) {
var external apiextv1.JSONSchemaProps
if err := json.Unmarshal([]byte(raw), &external); err != nil {
return nil, fmt.Errorf("read application schema: %w", err)
}
if external.Type != "object" {
return nil, fmt.Errorf("application schema must describe an object")
}
var schema internalapiext.JSONSchemaProps
if err := apiextv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(&external, &schema, nil); err != nil {
return nil, err
}
prepareInstallationDefaultsSchema(&schema, true)
validator, _, err := apiextvalidation.NewSchemaValidator(&schema)
return validator, err
}
func prepareInstallationDefaultsSchema(schema *internalapiext.JSONSchemaProps, partial bool) {
// Objects can be completed by user fields; replacement arrays cannot. What an
// object must contain cannot be judged on a partial one, so required and the
// lower bound on its properties are dropped, and so is its oneOf: with required
// removed every branch that tells alternatives apart by presence matches. A
// scalar's oneOf constrains its value and stays.
if partial {
schema.Required = nil
schema.MinProperties = nil
if schema.Type == "object" {
schema.OneOf = nil
}
}
// Omitted additionalProperties is open in JSON Schema. Installation
// configuration requires an explicit declaration before accepting extra keys.
if schema.Type == "object" && schema.AdditionalProperties == nil &&
(schema.XPreserveUnknownFields == nil || !*schema.XPreserveUnknownFields) {
schema.AdditionalProperties = &internalapiext.JSONSchemaPropsOrBool{Allows: false}
}
for key, child := range schema.Properties {
prepareInstallationDefaultsSchema(&child, partial)
schema.Properties[key] = child
}
if schema.AdditionalProperties != nil && schema.AdditionalProperties.Schema != nil {
prepareInstallationDefaultsSchema(schema.AdditionalProperties.Schema, partial)
}
if schema.Items != nil {
if schema.Items.Schema != nil {
prepareInstallationDefaultsSchema(schema.Items.Schema, false)
}
for i := range schema.Items.JSONSchemas {
prepareInstallationDefaultsSchema(&schema.Items.JSONSchemas[i], false)
}
}
for _, branches := range [][]internalapiext.JSONSchemaProps{schema.AllOf, schema.AnyOf, schema.OneOf} {
for i := range branches {
prepareInstallationDefaultsSchema(&branches[i], partial)
}
}
}
func parseInstallationDefaults(raw string) (map[string]map[string]any, error) {
var defaults map[string]map[string]any
if err := decodeDefaultsJSON([]byte(raw), &defaults); err != nil {
return nil, err
}
if defaults == nil {
return nil, fmt.Errorf("defaults.json must be an object keyed by application plural")
}
for plural, values := range defaults {
if plural == "" || strings.HasPrefix(plural, "_") || values == nil {
return nil, fmt.Errorf("%q must name an application plural with an object value", plural)
}
for key := range values {
if strings.HasPrefix(key, "_") {
return nil, fmt.Errorf("%s: field %q is reserved", plural, key)
}
}
}
return defaults, nil
}
func decodeDefaultsJSON(raw []byte, target any) error {
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
if err := decoder.Decode(target); err != nil {
return err
}
if decoder.Decode(new(any)) != io.EOF {
return fmt.Errorf("expected a single JSON object")
}
return nil
}
// fillInstallationDefaults copies missing fields from defaults into spec. It
// recurses only into objects whose schema declares properties; dictionaries and
// free-form objects are replaced as a whole, like arrays, so a user's map is
// never completed with entries nobody wrote.
func fillInstallationDefaults(spec, defaults map[string]any, schema *apiextv1.JSONSchemaProps) {
for key, value := range defaults {
current, present := spec[key]
if !present {
spec[key] = runtime.DeepCopyJSONValue(value)
continue
}
obj, isObject := current.(map[string]any)
fallback, isFallbackObject := value.(map[string]any)
if !isObject || len(obj) == 0 || !isFallbackObject {
continue
}
if child, declared := declaredProperty(schema, key); declared {
fillInstallationDefaults(obj, fallback, child)
}
}
}
func declaredProperty(schema *apiextv1.JSONSchemaProps, key string) (*apiextv1.JSONSchemaProps, bool) {
if schema == nil {
return nil, false
}
child, ok := schema.Properties[key]
if !ok || len(child.Properties) == 0 {
return nil, false
}
// An object that also takes arbitrary keys is a map, whatever properties it names.
if open := child.AdditionalProperties; open != nil && (open.Allows || open.Schema != nil) {
return nil, false
}
if child.XPreserveUnknownFields != nil && *child.XPreserveUnknownFields {
return nil, false
}
return &child, true
}
func parseDefaultsSchema(raw string) *apiextv1.JSONSchemaProps {
var schema apiextv1.JSONSchemaProps
if err := json.Unmarshal([]byte(raw), &schema); err != nil {
return nil
}
return &schema
}
@@ -0,0 +1,60 @@
/*
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 application
import (
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
// InstallationDefaultsNamespace and InstallationDefaultsName locate the
// ConfigMap the platform chart renders from the applicationDefaults value.
InstallationDefaultsNamespace = "cozy-system"
InstallationDefaultsName = "cozystack-application-defaults"
// The defaults are optional, so waiting for the cache is bounded: an unreadable
// ConfigMap must neither keep the API from serving nor hang a create. A read
// that exceeds the timeout fails open like any other read error.
InstallationDefaultsSyncTimeout = 30 * time.Second
installationDefaultsReadTimeout = 5 * time.Second
)
// NewInstallationDefaultsCache returns a cache holding only the installation
// defaults ConfigMap. It is separate from the manager cache because scoping a
// ConfigMap informer there would hide every other ConfigMap from cached reads.
// The create path reads from it, so a transient API error never reaches a create.
func NewInstallationDefaultsCache(cfg *rest.Config, scheme *runtime.Scheme) (cache.Cache, error) {
return cache.New(cfg, cache.Options{
Scheme: scheme,
ByObject: map[client.Object]cache.ByObject{
&corev1.ConfigMap{}: {
Namespaces: map[string]cache.Config{
InstallationDefaultsNamespace: {
FieldSelector: fields.OneTermEqualSelector("metadata.name", InstallationDefaultsName),
},
},
},
},
})
}
@@ -0,0 +1,202 @@
/*
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 application
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/wait"
restclient "k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// configMapServer answers just enough of the API to run the cache: discovery,
// a list of the defaults ConfigMap and a watch the test pushes events into.
type configMapServer struct {
mu sync.Mutex
items []corev1.ConfigMap
listURLs []url.Values
events chan []byte
}
func (s *configMapServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api":
_, _ = w.Write([]byte(`{"kind":"APIVersions","versions":["v1"]}`))
case "/apis":
_, _ = w.Write([]byte(`{"kind":"APIGroupList","apiVersion":"v1","groups":[]}`))
case "/api/v1":
_, _ = w.Write([]byte(`{"kind":"APIResourceList","groupVersion":"v1","resources":[{"name":"configmaps","singularName":"configmap","namespaced":true,"kind":"ConfigMap","verbs":["get","list","watch"]}]}`))
case "/api/v1/namespaces/" + InstallationDefaultsNamespace + "/configmaps":
s.mu.Lock()
s.listURLs = append(s.listURLs, r.URL.Query())
s.mu.Unlock()
if r.URL.Query().Get("watch") == "true" {
s.serveWatch(w, r)
return
}
s.mu.Lock()
list := corev1.ConfigMapList{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMapList", APIVersion: "v1"},
ListMeta: metav1.ListMeta{ResourceVersion: "1"},
Items: s.items,
}
s.mu.Unlock()
_ = json.NewEncoder(w).Encode(list)
default:
http.NotFound(w, r)
}
}
// serveWatch streams the initial state when the client asks for it (the reflector
// lists through a watch with sendInitialEvents), closes it with the bookmark that
// marks the end of the list, then forwards the events the test pushes.
func (s *configMapServer) serveWatch(w http.ResponseWriter, r *http.Request) {
flusher := w.(http.Flusher)
w.WriteHeader(http.StatusOK)
send := func(event any) {
line, _ := json.Marshal(event)
_, _ = w.Write(append(line, '\n'))
flusher.Flush()
}
if r.URL.Query().Get("sendInitialEvents") == "true" {
s.mu.Lock()
items := append([]corev1.ConfigMap(nil), s.items...)
s.mu.Unlock()
for _, item := range items {
send(map[string]any{"type": "ADDED", "object": item})
}
send(map[string]any{"type": "BOOKMARK", "object": corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
ResourceVersion: "1",
Annotations: map[string]string{metav1.InitialEventsAnnotationKey: "true"},
},
}})
}
flusher.Flush()
for {
select {
case line := <-s.events:
_, _ = w.Write(append(line, '\n'))
flusher.Flush()
case <-r.Context().Done():
return
}
}
}
func defaultsConfigMapAt(version, payload string) corev1.ConfigMap {
return corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Namespace: InstallationDefaultsNamespace,
Name: InstallationDefaultsName,
ResourceVersion: version,
},
Data: map[string]string{"defaults.json": payload},
}
}
func startDefaultsCache(t *testing.T, server *configMapServer) client.Reader {
t.Helper()
ts := httptest.NewServer(server)
t.Cleanup(ts.Close)
scheme := runtime.NewScheme()
if err := corev1.AddToScheme(scheme); err != nil {
t.Fatal(err)
}
c, err := NewInstallationDefaultsCache(&restclient.Config{Host: ts.URL}, scheme)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
if _, err := c.GetInformer(ctx, &corev1.ConfigMap{}); err != nil {
t.Fatal(err)
}
go func() { _ = c.Start(ctx) }()
syncCtx, syncCancel := context.WithTimeout(ctx, 10*time.Second)
defer syncCancel()
if !c.WaitForCacheSync(syncCtx) {
t.Fatal("the defaults cache did not sync")
}
return c
}
func TestInstallationDefaultsCacheWatchesOnlyTheDefaultsConfigMap(t *testing.T) {
server := &configMapServer{events: make(chan []byte, 1)}
reader := startDefaultsCache(t, server)
server.mu.Lock()
defer server.mu.Unlock()
if len(server.listURLs) == 0 {
t.Fatal("the cache never listed ConfigMaps in the defaults namespace")
}
if got, want := server.listURLs[0].Get("fieldSelector"), "metadata.name="+InstallationDefaultsName; got != want {
t.Fatalf("fieldSelector = %q, want %q: the cache would hold every ConfigMap in the namespace", got, want)
}
err := reader.Get(context.Background(), client.ObjectKey{Namespace: InstallationDefaultsNamespace, Name: InstallationDefaultsName}, &corev1.ConfigMap{})
if !apierrors.IsNotFound(err) {
t.Fatalf("a missing ConfigMap must read as NotFound so creation continues without defaults, got %v", err)
}
}
func TestInstallationDefaultsCacheFollowsChanges(t *testing.T) {
server := &configMapServer{
items: []corev1.ConfigMap{defaultsConfigMapAt("1", `{"widgets":{"size":"10Gi"}}`)},
events: make(chan []byte, 1),
}
reader := startDefaultsCache(t, server)
key := client.ObjectKey{Namespace: InstallationDefaultsNamespace, Name: InstallationDefaultsName}
cm := &corev1.ConfigMap{}
if err := reader.Get(context.Background(), key, cm); err != nil {
t.Fatal(err)
}
if got := cm.Data["defaults.json"]; got != `{"widgets":{"size":"10Gi"}}` {
t.Fatalf("initial payload = %q", got)
}
updated, err := json.Marshal(map[string]any{"type": "MODIFIED", "object": defaultsConfigMapAt("2", `{"widgets":{"size":"20Gi"}}`)})
if err != nil {
t.Fatal(err)
}
server.events <- updated
err = wait.PollUntilContextTimeout(context.Background(), 20*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (bool, error) {
current := &corev1.ConfigMap{}
if err := reader.Get(ctx, key, current); err != nil {
return false, err
}
return current.Data["defaults.json"] == `{"widgets":{"size":"20Gi"}}`, nil
})
if err != nil {
t.Fatalf("a change made while the API runs never reached the cache: %v", err)
}
}
@@ -0,0 +1,203 @@
/*
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 application
import (
"context"
"errors"
"fmt"
"testing"
"time"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/warning"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func TestInstallationDefaultsFailuresDoNotBlockCreation(t *testing.T) {
for _, tc := range []struct {
name, raw, schema string
denied bool
}{
{"read denied", `{}`, installationDefaultsSchema, true},
{"invalid JSON", `{`, installationDefaultsSchema, false},
{"invalid structure", `{"widgets":null}`, installationDefaultsSchema, false},
{"reserved fields", `{"widgets":{"_cluster":{}}}`, installationDefaultsSchema, false},
{"unknown field", `{"widgets":{"typo":true}}`, installationDefaultsSchema, false},
{"no partial merge", `{"widgets":{"replicas":3,"typo":true}}`, installationDefaultsSchema, false},
{"wrong type", `{"widgets":{"replicas":"wrong"}}`, installationDefaultsSchema, false},
{"missing schema", `{"widgets":{"replicas":3}}`, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
r := defaultsREST(t, defaultsConfig(tc.raw))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: tc.schema},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
if tc.denied {
r.defaultsReader = &failingDefaultsReader{Reader: r.c}
}
called := false
_, err := r.Create(context.Background(), defaultsApp(`{"required":"user"}`), func(_ context.Context, obj runtime.Object) error {
called = true
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"required":"user"}`)
return nil
}, &metav1.CreateOptions{})
if err != nil || !called {
t.Fatalf("create must continue without defaults: %v (admission=%v)", err, called)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, `{"required":"user"}`)
})
}
}
const skippedDefaultsWarning = "Installation defaults could not be applied; continuing without them"
type recordedWarnings []string
func (w *recordedWarnings) AddWarning(_, text string) { *w = append(*w, text) }
// A skipped default cannot be recovered after creation, so the client must be
// told at the request that skipped it, and a dry-run is where an operator looks.
func TestInstallationDefaultsWarnOnFallbackIncludingDryRun(t *testing.T) {
for _, tc := range []struct {
name, raw string
denied bool
}{
{"read denied", `{}`, true},
{"invalid JSON", `{`, false},
{"unknown field", `{"widgets":{"typo":true}}`, false},
} {
for _, dryRun := range []bool{false, true} {
t.Run(fmt.Sprintf("%s dryRun=%v", tc.name, dryRun), func(t *testing.T) {
r := defaultsRESTWithSchema(t, installationDefaultsSchema, defaultsConfig(tc.raw))
if tc.denied {
r.defaultsReader = &failingDefaultsReader{Reader: r.c}
}
var got recordedWarnings
ctx := warning.WithWarningRecorder(context.Background(), &got)
opts := &metav1.CreateOptions{}
if dryRun {
opts.DryRun = []string{metav1.DryRunAll}
}
if _, err := r.Create(ctx, defaultsApp(`{"required":"user"}`), nil, opts); err != nil {
t.Fatal(err)
}
if len(got) != 1 || got[0] != skippedDefaultsWarning {
t.Fatalf("warnings = %q, want exactly %q", []string(got), skippedDefaultsWarning)
}
})
}
}
}
type blockingDefaultsReader struct{ client.Reader }
func (blockingDefaultsReader) Get(ctx context.Context, _ client.ObjectKey, _ client.Object, _ ...client.GetOption) error {
<-ctx.Done()
return ctx.Err()
}
// A cache that has not synced blocks a read until its context ends. The create
// must not wait for the request to time out: it falls back like any read error.
func TestInstallationDefaultsReadIsBounded(t *testing.T) {
r := defaultsRESTWithSchema(t, installationDefaultsSchema, defaultsConfig(`{"widgets":{"replicas":3}}`))
r.defaultsReader = blockingDefaultsReader{Reader: r.c}
r.defaultsReadLimit = 20 * time.Millisecond
var got recordedWarnings
ctx, cancel := context.WithTimeout(warning.WithWarningRecorder(context.Background(), &got), 5*time.Second)
defer cancel()
started := time.Now()
if _, err := r.Create(ctx, defaultsApp(`{"required":"user"}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
if elapsed := time.Since(started); elapsed > 2*time.Second {
t.Fatalf("create waited %s for the defaults read", elapsed)
}
if len(got) != 1 || got[0] != skippedDefaultsWarning {
t.Fatalf("warnings = %q, want exactly %q", []string(got), skippedDefaultsWarning)
}
}
// Applied defaults are normal operation: warning on every create would teach
// clients to ignore the warning that matters.
func TestInstallationDefaultsNoWarningWhenAppliedOrNotConfigured(t *testing.T) {
for _, tc := range []struct {
name string
objects []client.Object
}{
{"applied", []client.Object{defaultsConfig(`{"widgets":{"replicas":3}}`)}},
{"no entry for the application", []client.Object{defaultsConfig(`{"otherwidgets":{"replicas":3}}`)}},
{"no ConfigMap", nil},
} {
t.Run(tc.name, func(t *testing.T) {
r := defaultsRESTWithSchema(t, installationDefaultsSchema, tc.objects...)
var got recordedWarnings
ctx := warning.WithWarningRecorder(context.Background(), &got)
if _, err := r.Create(ctx, defaultsApp(`{"required":"user"}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
if len(got) != 0 {
t.Fatalf("unexpected warnings: %q", []string(got))
}
})
}
}
func TestInstallationDefaultsFallbackKeepsOrdinaryRejections(t *testing.T) {
t.Run("reserved user field", func(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{`))
_, err := r.Create(context.Background(), defaultsApp(`{"_cluster":{}}`), nil, &metav1.CreateOptions{})
if !apierrors.IsBadRequest(err) {
t.Fatalf("invalid user spec was accepted: %v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 0 {
t.Fatalf("unexpected write: %v %v", list.Items, err)
}
})
t.Run("admission", func(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{`))
rejected := errors.New("admission rejected user request")
_, err := r.Create(context.Background(), defaultsApp(`{}`), func(context.Context, runtime.Object) error { return rejected }, &metav1.CreateOptions{})
if !errors.Is(err, rejected) {
t.Fatalf("admission rejection lost: %v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 0 {
t.Fatalf("unexpected write: %v %v", list.Items, err)
}
})
t.Run("quota", func(t *testing.T) {
parent := tenantHelmRelease(t, "parent", "tenant-root", map[string]string{"cpu": "2"})
r := newTenantREST(t, parent, defaultsConfig(`{`))
r.defaultsReader = r.c
_, err := r.Create(context.Background(), childApplication(t, "child", "tenant-root-parent", map[string]string{"cpu": "4"}), nil, &metav1.CreateOptions{})
if !apierrors.IsInvalid(err) {
t.Fatalf("quota rejection lost: %v", err)
}
})
}
@@ -0,0 +1,232 @@
/*
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 application
import (
"context"
"io"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
)
type nodeDefaultsRender struct{ name, diskURL, script string }
func nodeDefaultsREST(t *testing.T, objects ...client.Object) *REST {
t.Helper()
raw, err := os.ReadFile("../../../../packages/system/kubernetes-nodes-rd/cozyrds/kubernetes-nodes.yaml")
if err != nil {
t.Fatal(err)
}
var definition struct {
Spec struct {
Application config.ApplicationConfig
Release struct{ Prefix string }
}
}
if err := yaml.Unmarshal(raw, &definition); err != nil {
t.Fatal(err)
}
r := defaultsREST(t, objects...)
return NewREST(r.c, r.w, r.c, &config.Resource{
Application: definition.Spec.Application,
Release: config.ReleaseConfig{Prefix: definition.Spec.Release.Prefix},
})
}
func renderStoredNodeDefaults(t *testing.T, values *apiextv1.JSON) nodeDefaultsRender {
t.Helper()
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is required for the render integration test")
}
path := filepath.Join(t.TempDir(), "values.json")
if err := os.WriteFile(path, values.Raw, 0600); err != nil {
t.Fatal(err)
}
cmd := exec.Command("helm", "template", "kubernetes-nodes-demo-md0", "../../../../packages/apps/kubernetes-nodes",
"--namespace", "tenant-test", "--values", path, "--set", "_cluster.cluster-domain=cozy.local")
var stderr strings.Builder
cmd.Stderr = &stderr
raw, err := cmd.Output()
if err != nil {
t.Fatalf("render stored values: %v\n%s", err, stderr.String())
}
decoder := utilyaml.NewYAMLOrJSONDecoder(strings.NewReader(string(raw)), 4096)
var result nodeDefaultsRender
for {
var doc map[string]any
if err := decoder.Decode(&doc); err == io.EOF {
break
} else if err != nil {
t.Fatal(err)
}
if doc["kind"] == "KubevirtMachineTemplate" {
result.name, _, _ = unstructured.NestedString(doc, "metadata", "name")
volumes, _, err := unstructured.NestedSlice(doc, "spec", "template", "spec", "virtualMachineTemplate", "spec", "dataVolumeTemplates")
if err != nil || len(volumes) != 1 {
t.Fatalf("disk templates: %v, %v", volumes, err)
}
result.diskURL, _, _ = unstructured.NestedString(volumes[0].(map[string]any), "spec", "source", "http", "url")
}
if doc["kind"] == "Job" {
containers, _, _ := unstructured.NestedSlice(doc, "spec", "template", "spec", "containers")
for _, container := range containers {
commands, _, _ := unstructured.NestedSlice(container.(map[string]any), "command")
for _, command := range commands {
if text, ok := command.(string); ok && strings.Contains(text, "TalosConfigTemplate") {
result.script = text
}
}
}
}
}
if result.name == "" || result.diskURL == "" || result.script == "" {
t.Fatalf("missing rendered node resources: %+v", result)
}
return result
}
func TestInstallationDefaultsKubernetesNodesPersistedRender(t *testing.T) {
r := nodeDefaultsREST(t, defaultsConfig(`{"kubernetesnodeses":{"talos":{"imageFactoryURL":"https://factory.example.com","installerRepository":"registry.example.com/installer","registryMirrors":{"ghcr.io":{"endpoints":["https://registry.example.com"]}}}}}`))
ctx := request.WithNamespace(context.Background(), "tenant-test")
app := defaultsApp(`{"cluster":"demo","version":"v1.35","instanceType":"","resources":{"cpu":"2","memory":"4Gi"}}`)
app.Name = "demo-md0"
if _, err := r.Create(ctx, app, nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
key := client.ObjectKey{Namespace: "tenant-test", Name: "kubernetes-nodes-demo-md0"}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, key, hr); err != nil {
t.Fatal(err)
}
before := renderStoredNodeDefaults(t, hr.Spec.Values)
if !strings.HasPrefix(before.diskURL, "https://factory.example.com/image/") ||
!strings.Contains(before.script, "registry.example.com/installer") ||
!strings.Contains(before.script, "https://registry.example.com") {
t.Fatalf("stored defaults not rendered: %+v", before)
}
cm := &corev1.ConfigMap{}
if err := r.c.Get(ctx, client.ObjectKeyFromObject(defaultsConfig("")), cm); err != nil {
t.Fatal(err)
}
cm.Data["defaults.json"] = `{"kubernetesnodeses":{"talos":{"imageFactoryURL":"https://new-factory.example.com","installerRepository":"new-registry.example.com/installer"}}}`
if err := r.c.Update(ctx, cm); err != nil {
t.Fatal(err)
}
obj, err := r.Get(ctx, app.Name, &metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
if _, _, err := r.Update(ctx, app.Name, rest.DefaultUpdatedObjectInfo(obj), nil, nil, false, &metav1.UpdateOptions{}); err != nil {
t.Fatal(err)
}
if err := r.c.Get(ctx, key, hr); err != nil {
t.Fatal(err)
}
after := renderStoredNodeDefaults(t, hr.Spec.Values)
if before.name != after.name || before.diskURL != after.diskURL || before.script != after.script {
t.Fatalf("existing pool changed after configuration update: before=%+v after=%+v", before, after)
}
app.Name = "demo-new"
created, err := r.Create(ctx, app, nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
values := jsonValue(t, created.(*appsv1alpha1.Application).Spec.Raw).(map[string]any)
talos := values["talos"].(map[string]any)
if talos["imageFactoryURL"] != "https://new-factory.example.com" {
t.Fatalf("new pool did not use new defaults: %v", talos)
}
}
// A pool that declares its own mirrors keeps exactly those. Merging would hand it
// the platform's other registries and add the platform's fields to its docker.io
// entry, an entry neither side wrote.
func TestInstallationDefaultsKubernetesNodesMirrorsReplaceAsAWhole(t *testing.T) {
r := nodeDefaultsREST(t, defaultsConfig(`{"kubernetesnodeses":{"talos":{"imageFactoryURL":"https://factory.example.com","registryMirrors":{"docker.io":{"endpoints":["https://platform.example.com"],"skipFallback":true},"ghcr.io":{"endpoints":["https://platform.example.com"]}}}}}`))
ctx := request.WithNamespace(context.Background(), "tenant-test")
app := defaultsApp(`{"cluster":"demo","version":"v1.35","instanceType":"","resources":{"cpu":"2","memory":"4Gi"},"talos":{"registryMirrors":{"docker.io":{"endpoints":["https://pool.example.com"]}}}}`)
app.Name = "demo-md0"
created, err := r.Create(ctx, app, nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
talos := jsonValue(t, created.(*appsv1alpha1.Application).Spec.Raw).(map[string]any)["talos"].(map[string]any)
if talos["imageFactoryURL"] != "https://factory.example.com" {
t.Fatalf("the entry was skipped, so this test would pass without the merge rule: %v", talos)
}
want := jsonValue(t, []byte(`{"docker.io":{"endpoints":["https://pool.example.com"]}}`))
if !reflect.DeepEqual(talos["registryMirrors"], want) {
t.Fatalf("registryMirrors = %v, want %v", talos["registryMirrors"], want)
}
}
func TestInstallationDefaultsLegacyKubernetesNodesRender(t *testing.T) {
r := nodeDefaultsREST(t)
ctx := request.WithNamespace(context.Background(), "tenant-test")
app := defaultsApp(`{"cluster":"demo","version":"v1.35","instanceType":"","resources":{"cpu":"2","memory":"4Gi"}}`)
app.Name = "demo-md0"
old, err := r.Create(ctx, app, nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
key := client.ObjectKey{Namespace: "tenant-test", Name: "kubernetes-nodes-demo-md0"}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(ctx, key, hr); err != nil {
t.Fatal(err)
}
stored := hr.Spec.Values.DeepCopy()
before := renderStoredNodeDefaults(t, stored)
if err := r.c.Create(ctx, defaultsConfig(`{"kubernetesnodeses":{"talos":{"imageFactoryURL":"https://factory.example.com","installerRepository":"registry.example.com/installer","registryMirrors":{"ghcr.io":{"endpoints":["https://registry.example.com"]}}}}}`)); err != nil {
t.Fatal(err)
}
current, err := r.Get(ctx, app.Name, &metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
assertSpec(t, current.(*appsv1alpha1.Application).Spec, string(old.(*appsv1alpha1.Application).Spec.Raw))
if err := r.c.Get(ctx, key, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, string(stored.Raw))
if _, _, err := r.Update(ctx, app.Name, rest.DefaultUpdatedObjectInfo(current), nil, nil, false, &metav1.UpdateOptions{}); err != nil {
t.Fatal(err)
}
if err := r.c.Get(ctx, key, hr); err != nil {
t.Fatal(err)
}
after := renderStoredNodeDefaults(t, hr.Spec.Values)
if before != after {
t.Fatalf("legacy pool changed after installation defaults were introduced: before=%+v after=%+v", before, after)
}
}
@@ -0,0 +1,399 @@
/*
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 application
import (
"context"
"encoding/json"
"errors"
"os"
"reflect"
"testing"
"time"
cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
corev1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
func defaultsConfig(raw string) *corev1.ConfigMap {
return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: "cozy-system", Name: "cozystack-application-defaults"}, Data: map[string]string{"defaults.json": raw}}
}
const freeFormDefaultsSchema = `{"type":"object","x-kubernetes-preserve-unknown-fields":true}`
func defaultsREST(t *testing.T, objects ...client.Object) *REST {
t.Helper()
return defaultsRESTWithSchema(t, freeFormDefaultsSchema, objects...)
}
func defaultsRESTWithSchema(t *testing.T, schema string, objects ...client.Object) *REST {
t.Helper()
s := runtime.NewScheme()
_ = corev1.AddToScheme(s)
_ = helmv2.AddToScheme(s)
_ = cozyv1alpha1.AddToScheme(s)
c := fake.NewClientBuilder().WithScheme(s).WithObjects(objects...).Build()
return NewREST(c, c, c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", Singular: "widget", OpenAPISchema: schema},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
}
// Declared properties let the merge recurse into nested; a free-form root would
// replace it as a whole.
const typedDefaultsSchema = `{"type":"object","properties":{
"nested":{"type":"object","properties":{"a":{"type":"integer"},"b":{"type":"integer"}}},
"list":{"type":"array","items":{"type":"integer"}},
"flag":{"type":"boolean"},
"number":{"type":"integer"},
"text":{"type":"string"},
"nullable":{"type":"string","nullable":true}}}`
func defaultsApp(raw string) *appsv1alpha1.Application {
return &appsv1alpha1.Application{ObjectMeta: metav1.ObjectMeta{Name: "example", Namespace: "tenant-test"}, Spec: &apiextv1.JSON{Raw: []byte(raw)}}
}
func assertSpec(t *testing.T, got *apiextv1.JSON, want string) {
t.Helper()
if got == nil {
t.Fatal("missing spec")
}
a, b := jsonValue(t, got.Raw), jsonValue(t, []byte(want))
if !reflect.DeepEqual(a, b) {
t.Fatalf("spec = %s, want %s", got.Raw, want)
}
}
func TestInstallationDefaultsCreate(t *testing.T) {
for _, tc := range []struct{ name, spec, want string }{
{"missing", `{}`, `{"nested":{"a":1,"b":2},"list":[1],"flag":true,"number":4,"text":"default","nullable":"default"}`},
{"nested", `{"nested":{"a":9}}`, `{"nested":{"a":9,"b":2},"list":[1],"flag":true,"number":4,"text":"default","nullable":"default"}`},
{"explicit empty values", `{"nested":{},"list":[],"flag":false,"number":0,"text":"","nullable":null}`, `{"nested":{},"list":[],"flag":false,"number":0,"text":"","nullable":null}`},
} {
t.Run(tc.name, func(t *testing.T) {
r := defaultsRESTWithSchema(t, typedDefaultsSchema, defaultsConfig(`{"widgets":{"nested":{"a":1,"b":2},"list":[1],"flag":true,"number":4,"text":"default","nullable":"default"},"otherwidgets":{"text":"other"}}`))
app := defaultsApp(tc.spec)
_, err := r.Create(context.Background(), app, func(_ context.Context, obj runtime.Object) error {
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, tc.want)
return nil
}, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, tc.want)
assertSpec(t, app.Spec, tc.spec)
})
}
}
func TestInstallationDefaultsOmittedAndNullSpec(t *testing.T) {
for _, tc := range []struct {
name string
spec *apiextv1.JSON
}{
{"omitted", nil},
{"empty", &apiextv1.JSON{}},
{"null", &apiextv1.JSON{Raw: []byte("null")}},
} {
t.Run(tc.name, func(t *testing.T) {
r := defaultsRESTWithSchema(t, typedDefaultsSchema, defaultsConfig(`{"widgets":{"number":4}}`))
app := defaultsApp(`{}`)
app.Spec = tc.spec
if _, err := r.Create(context.Background(), app, nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, `{"number":4}`)
})
}
}
func TestInstallationDefaultsRejectUnreadableUserSpec(t *testing.T) {
r := defaultsRESTWithSchema(t, typedDefaultsSchema, defaultsConfig(`{"widgets":{"number":4}}`))
_, err := r.Create(context.Background(), defaultsApp(`{`), nil, &metav1.CreateOptions{})
if !apierrors.IsBadRequest(err) {
t.Fatalf("unreadable user spec was accepted: %v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 0 {
t.Fatalf("unexpected writes: %v, %v", list.Items, err)
}
}
func TestInstallationDefaultsMergeContract(t *testing.T) {
raw, err := os.ReadFile("testdata/installation-defaults-merge.json")
if err != nil {
t.Fatal(err)
}
var cases []struct {
Name string `json:"name"`
Schema json.RawMessage `json:"schema"`
User json.RawMessage `json:"user"`
Installation json.RawMessage `json:"installation"`
Expected json.RawMessage `json:"expected"`
}
if err := json.Unmarshal(raw, &cases); err != nil {
t.Fatal(err)
}
if len(cases) == 0 {
t.Fatal("merge fixtures are empty")
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
schema := freeFormDefaultsSchema
if len(tc.Schema) > 0 {
schema = string(tc.Schema)
}
r := defaultsRESTWithSchema(t, schema, defaultsConfig(`{"widgets":`+string(tc.Installation)+`}`))
if _, err := r.Create(context.Background(), defaultsApp(string(tc.User)), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, string(tc.Expected))
})
}
}
func TestInstallationDefaultsConfigurationErrors(t *testing.T) {
for _, raw := range []string{``, `{`, `null`, `[]`, `{} {}`, `{"":{}}`, `{"_widgets":{}}`, `{"widgets":null}`, `{"widgets":[]}`, `{"otherwidgets":false}`, `{"widgets":{"_cluster":{}}}`, `{"otherwidgets":{"_cluster":{}}}`} {
t.Run(raw, func(t *testing.T) {
r := defaultsREST(t, defaultsConfig(raw))
if err := r.applyInstallationDefaults(context.Background(), defaultsApp(`{}`)); err == nil {
t.Fatal("invalid configuration was accepted for merge")
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 0 {
t.Fatalf("unexpected writes: %v, %v", list.Items, err)
}
})
}
}
func TestInstallationDefaultsMissingAndGeneric(t *testing.T) {
for _, cm := range []*corev1.ConfigMap{nil, defaultsConfig(`{}`), defaultsConfig(`{"unrelated":{"replicas":5}}`)} {
r := defaultsREST(t)
if cm != nil {
if err := r.c.Create(context.Background(), cm); err != nil {
t.Fatal(err)
}
}
_, err := r.Create(context.Background(), defaultsApp(`{"replicas":2}`), nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
}
r := defaultsREST(t, defaultsConfig(`{"otherwidgets":{"replicas":7},"widgets":{"replicas":2}}`))
r.gvr.Resource = "otherwidgets"
obj, err := r.Create(context.Background(), defaultsApp(`{}`), nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":7}`)
}
func TestInstallationDefaultsApplyCreateAndDryRun(t *testing.T) {
for _, dry := range []bool{false, true} {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"replicas":3}}`))
opts := &metav1.UpdateOptions{FieldManager: "apply-client"}
if dry {
opts.DryRun = []string{metav1.DryRunAll}
}
ctx := request.WithNamespace(context.Background(), "tenant-test")
obj, created, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(defaultsApp(`{}`)), func(_ context.Context, obj runtime.Object) error {
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":3}`)
return nil
}, nil, true, opts)
if err != nil || !created {
t.Fatalf("created=%v, err=%v", created, err)
}
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":3}`)
err = r.c.Get(ctx, client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, &helmv2.HelmRelease{})
if dry && !apierrors.IsNotFound(err) {
t.Fatalf("dry run persisted release: %v", err)
}
if !dry && err != nil {
t.Fatal(err)
}
}
}
func TestInstallationDefaultsExistingLifecycle(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"replicas":3}}`))
ctx := request.WithNamespace(context.Background(), "tenant-test")
if _, err := r.Create(ctx, defaultsApp(`{}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
cm := &corev1.ConfigMap{}
key := client.ObjectKeyFromObject(defaultsConfig(""))
if err := r.c.Get(ctx, key, cm); err != nil {
t.Fatal(err)
}
cm.Data["defaults.json"] = `{"widgets":{"replicas":9,"newField":true}}`
if err := r.c.Update(ctx, cm); err != nil {
t.Fatal(err)
}
r.defaultsReader = &failingDefaultsReader{Reader: r.c}
obj, err := r.Get(ctx, "example", &metav1.GetOptions{})
if err != nil {
t.Fatal(err)
}
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":3}`)
list, err := r.List(ctx, &metainternalversion.ListOptions{})
if err != nil {
t.Fatal(err)
}
apps := list.(*appsv1alpha1.ApplicationList).Items
if len(apps) != 1 {
t.Fatalf("apps=%v", apps)
}
assertSpec(t, apps[0].Spec, `{"replicas":3}`)
w, err := r.Watch(ctx, &metainternalversion.ListOptions{})
if err != nil {
t.Fatal(err)
}
defer w.Stop()
// The ConfigMap is readable again and holds a field the application lacks, so an
// update that applied defaults would add it.
r.defaultsReader = r.c
updated, created, err := r.Update(ctx, "example", rest.DefaultUpdatedObjectInfo(defaultsApp(`{"replicas":4}`)), nil, nil, false, &metav1.UpdateOptions{})
if err != nil || created {
t.Fatalf("created=%v, err=%v", created, err)
}
assertSpec(t, updated.(*appsv1alpha1.Application).Spec, `{"replicas":4}`)
select {
case event := <-w.ResultChan():
if event.Type != watch.Modified {
t.Fatalf("event=%v", event.Type)
}
assertSpec(t, event.Object.(*appsv1alpha1.Application).Spec, `{"replicas":4}`)
case <-time.After(5 * time.Second):
t.Fatal("missing application watch event")
}
}
type failingDefaultsReader struct{ client.Reader }
func (r *failingDefaultsReader) Get(context.Context, client.ObjectKey, client.Object, ...client.GetOption) error {
return apierrors.NewForbidden(schema.GroupResource{Resource: "configmaps"}, "cozystack-application-defaults", errors.New("access denied"))
}
func TestInstallationDefaultsDirectReaderAndAccessError(t *testing.T) {
r := defaultsREST(t)
direct := defaultsREST(t, defaultsConfig(`{"widgets":{"replicas":6}}`))
r.defaultsReader = direct.c
obj, err := r.Create(context.Background(), defaultsApp(`{}`), nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":6}`)
r = defaultsREST(t)
r.defaultsReader = &failingDefaultsReader{Reader: r.c}
if _, err := r.Create(context.Background(), defaultsApp(`{}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatalf("configuration access must not block creation: %v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 1 {
t.Fatalf("unexpected writes: %v, %v", list.Items, err)
}
assertSpec(t, list.Items[0].Spec.Values, `{}`)
}
func TestInstallationDefaultsPreserveNumbers(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"defaultNumber":9007199254740993,"preciseNumber":0.123456789123456789}}`))
if _, err := r.Create(context.Background(), defaultsApp(`{"userNumber":9007199254740995}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, `{"defaultNumber":9007199254740993,"userNumber":9007199254740995,"preciseNumber":0.123456789123456789}`)
}
func TestInstallationDefaultsLeaveDeveloperDefaultsOnRead(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"optional":null,"empty":{},"install":"installation"}}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: `{"type":"object","required":["required"],"properties":{"required":{"type":"string","default":"developer-required"},"optional":{"type":"string","nullable":true},"empty":{"type":"object","properties":{"child":{"type":"string","default":"developer-child"}}},"install":{"type":"string","default":"developer-install"},"developer":{"type":"string","default":"developer"}}}`},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
if _, err := r.Create(context.Background(), defaultsApp(`{"required":null}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "widget-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, `{"optional":null,"empty":{},"install":"installation"}`)
}
func TestInstallationDefaultsAdmissionRejection(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"replicas":3}}`))
sentinel := errors.New("admission rejected defaults")
_, err := r.Create(context.Background(), defaultsApp(`{}`), func(_ context.Context, obj runtime.Object) error {
assertSpec(t, obj.(*appsv1alpha1.Application).Spec, `{"replicas":3}`)
return sentinel
}, &metav1.CreateOptions{})
if !errors.Is(err, sentinel) {
t.Fatalf("err=%v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 0 {
t.Fatalf("writes=%v, err=%v", list.Items, err)
}
}
func TestInstallationDefaultsBeforeQuotas(t *testing.T) {
parent := tenantHelmRelease(t, "parent", "tenant-root", map[string]string{"cpu": "2"})
r := newTenantREST(t, parent, defaultsConfig(`{"tenants":{"resourceQuotas":{"cpu":"4"}}}`))
r.defaultsReader = r.c
var err error
r.defaultsValidator, err = buildInstallationDefaultsValidator(readEmbeddedOpenAPISchema(t, "../../../../packages/system/tenant-rd/cozyrds/tenant.yaml"))
if err != nil {
t.Fatal(err)
}
_, err = r.Create(context.Background(), childApplication(t, "child", "tenant-root-parent", nil), nil, &metav1.CreateOptions{})
if !apierrors.IsInvalid(err) {
t.Fatalf("quota from defaults must be rejected: %v", err)
}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-root-parent", Name: "tenant-child"}, &helmv2.HelmRelease{}); !apierrors.IsNotFound(err) {
t.Fatalf("unexpected write: %v", err)
}
}
@@ -0,0 +1,216 @@
/*
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 application
import (
"context"
"strings"
"testing"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
"github.com/cozystack/cozystack/pkg/config"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/apiserver/pkg/warning"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const installationDefaultsSchema = `{
"type":"object", "required":["required"], "allOf":[{"properties":{"replicas":{"maximum":8}}}], "properties":{
"required":{"type":"string"},
"replicas":{"type":"integer","minimum":0,"maximum":10},
"mode":{"type":"string","enum":["safe","fast"]},
"nested":{"type":"object","required":["name"],"allOf":[{"required":["name"]}],"properties":{"name":{"type":"string"},"enabled":{"type":"boolean"}}},
"rows":{"type":"array","minItems":1,"items":{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}},
"map":{"type":"object","additionalProperties":{"type":"object","required":["name"],"properties":{"name":{"type":"string"},"enabled":{"type":"boolean"}}}},
"free":{"type":"object","additionalProperties":true},
"preserved":{"type":"object","x-kubernetes-preserve-unknown-fields":true,"properties":{"known":{"type":"integer"}}},
"closed":{"type":"object","additionalProperties":false},
"choice":{"type":"string","oneOf":[{"enum":["safe"]},{"enum":["fast"]}]},
"pair":{"type":"object","minProperties":2,"properties":{"a":{"type":"integer"},"b":{"type":"integer"}}},
"either":{"type":"object","properties":{"url":{"type":"string"},"path":{"type":"string"}},"oneOf":[{"required":["url"]},{"required":["path"]}]},
"nullable":{"type":"string","nullable":true}
}
}`
func TestInstallationDefaultsSchemaValidation(t *testing.T) {
for _, tc := range []struct {
name, values, errorPath string
}{
{"partial object", `{"nested":{"enabled":false}}`, ""},
{"empty object", `{"nested":{}}`, ""},
{"partial dictionary value", `{"map":{"entry":{"enabled":true}}}`, ""},
{"complete array", `{"rows":[{"name":"worker"}]}`, ""},
{"free form", `{"free":{"arbitrary":{"nested":true}}}`, ""},
{"preserve unknown", `{"preserved":{"arbitrary":{"nested":true}}}`, ""},
{"nullable", `{"nullable":null}`, ""},
{"partial object under minProperties", `{"pair":{"a":1}}`, ""},
{"scalar oneOf accepted", `{"choice":"safe"}`, ""},
{"scalar oneOf rejected", `{"choice":"invalid"}`, "choice"},
{"one alternative of a oneOf", `{"either":{"url":"https://example.com"}}`, ""},
{"no alternative of a oneOf", `{"either":{}}`, ""},
{"wrong type inside oneOf object", `{"either":{"url":7}}`, "either.url"},
{"unknown field", `{"typo":true}`, "typo"},
{"unknown metadata", `{"metadata":{"name":"wrong"}}`, "metadata"},
{"nested unknown", `{"nested":{"typo":true}}`, "nested"},
{"array unknown", `{"rows":[{"name":"worker","typo":true}]}`, "rows"},
{"dictionary unknown", `{"map":{"entry":{"typo":true}}}`, "map"},
{"closed object", `{"closed":{"typo":true}}`, "closed"},
{"preserved known type", `{"preserved":{"known":"wrong"}}`, "preserved.known"},
{"wrong type", `{"replicas":"three"}`, "replicas"},
{"number is not a string", `{"nullable":7}`, "nullable"},
{"decimal integer", `{"replicas":2.0}`, ""},
{"integer with composed constraint", `{"replicas":2}`, ""},
{"wrong nested type", `{"nested":{"enabled":"yes"}}`, "nested.enabled"},
{"minimum", `{"replicas":-1}`, "replicas"},
{"maximum", `{"replicas":11}`, "replicas"},
{"composed constraint", `{"replicas":9}`, "replicas"},
{"enum", `{"mode":"typo"}`, "mode"},
{"nonnullable", `{"mode":null}`, "mode"},
{"incomplete array", `{"rows":[{}]}`, "rows"},
{"array constraint", `{"rows":[]}`, "rows"},
} {
t.Run(tc.name, func(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"widgets":`+tc.values+`,"futurecatalog":{"unknown":true}}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: installationDefaultsSchema},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
app := defaultsApp(`{"required":"user","nested":{"name":"user"}}`)
validationErr := r.applyInstallationDefaults(context.Background(), app.DeepCopy())
admissionCalled := false
_, err := r.Create(context.Background(), app, func(context.Context, runtime.Object) error {
admissionCalled = true
return nil
}, &metav1.CreateOptions{})
if tc.errorPath == "" {
// A rejected entry never fails the create, so only the direct call shows it.
if validationErr != nil {
t.Fatalf("valid entry rejected: %v", validationErr)
}
if err != nil || !admissionCalled {
t.Fatalf("create: %v, admission: %v", err, admissionCalled)
}
return
}
if validationErr == nil || !strings.Contains(validationErr.Error(), "applicationDefaults[widgets]") || !strings.Contains(validationErr.Error(), tc.errorPath) {
t.Fatalf("expected configuration error at %s, got %v", tc.errorPath, validationErr)
}
if err != nil || !admissionCalled {
t.Fatalf("invalid defaults blocked ordinary creation: %v", err)
}
list := &helmv2.HelmReleaseList{}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != 1 {
t.Fatalf("unexpected writes: %v, %v", list.Items, err)
}
assertSpec(t, list.Items[0].Spec.Values, string(app.Spec.Raw))
})
}
}
func TestInstallationDefaultsValidationApplyAndDryRun(t *testing.T) {
for _, dry := range []bool{false, true} {
r := defaultsREST(t, defaultsConfig(`{"widgets":{"typo":true}}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: installationDefaultsSchema},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
opts := &metav1.UpdateOptions{FieldManager: "apply-client"}
if dry {
opts.DryRun = []string{metav1.DryRunAll}
}
admissionCalled := false
_, created, err := r.Update(request.WithNamespace(context.Background(), "tenant-test"), "example", rest.DefaultUpdatedObjectInfo(defaultsApp(`{}`)), func(context.Context, runtime.Object) error {
admissionCalled = true
return nil
}, nil, true, opts)
if err != nil || !admissionCalled || !created {
t.Fatalf("create through apply (dry=%v): %v, admission=%v", dry, err, admissionCalled)
}
list := &helmv2.HelmReleaseList{}
want := 1
if dry {
want = 0
}
if err := r.c.List(context.Background(), list); err != nil || len(list.Items) != want {
t.Fatalf("unexpected writes: %v, %v", list.Items, err)
}
}
}
func TestInstallationDefaultsPostgresSchema(t *testing.T) {
r := defaultsREST(t, defaultsConfig(`{"postgreses":{"storageClass":"replicated","size":"20Gi"}}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Postgres", Plural: "postgreses", OpenAPISchema: readEmbeddedOpenAPISchema(t, "../../../../packages/system/postgres-rd/cozyrds/postgres.yaml")},
Release: config.ReleaseConfig{Prefix: "postgres-"},
})
_, err := r.Create(context.Background(), defaultsApp(`{"size":"40Gi"}`), nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
hr := &helmv2.HelmRelease{}
if err := r.c.Get(context.Background(), client.ObjectKey{Namespace: "tenant-test", Name: "postgres-example"}, hr); err != nil {
t.Fatal(err)
}
assertSpec(t, hr.Spec.Values, `{"storageClass":"replicated","size":"40Gi"}`)
}
func TestInstallationDefaultsRequireReadableSchema(t *testing.T) {
for _, raw := range []string{"", "{", "null", `{}`, `{"type":"array","items":{"type":"string"}}`} {
for _, entry := range []string{`{}`, `{"replicas":1}`} {
r := defaultsREST(t, defaultsConfig(`{"widgets":`+entry+`}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: raw}})
if err := r.applyInstallationDefaults(context.Background(), defaultsApp(`{}`)); err == nil {
t.Fatalf("schema %q accepted for configured defaults %s", raw, entry)
}
}
}
}
func TestInstallationDefaultsDoNotRequireSchemaWithoutEntry(t *testing.T) {
for _, schema := range []string{"", `{}`} {
r := defaultsREST(t, defaultsConfig(`{"futurecatalog":{"replicas":3}}`))
r = NewREST(r.c, r.w, r.c, &config.Resource{
Application: config.ApplicationConfig{Kind: "Widget", Plural: "widgets", OpenAPISchema: schema},
Release: config.ReleaseConfig{Prefix: "widget-"},
})
var got recordedWarnings
ctx := warning.WithWarningRecorder(context.Background(), &got)
if _, err := r.Create(ctx, defaultsApp(`{"user":"saved"}`), nil, &metav1.CreateOptions{}); err != nil {
t.Fatal(err)
}
// A failed defaults read never fails the create, so the warning is the signal.
if len(got) != 0 {
t.Fatalf("unconfigured application must not require a defaults schema: %q", []string(got))
}
}
}
// A CEL rule such as an immutability check has no meaning on a partial object, so
// the entry is checked against the structural schema only.
func TestInstallationDefaultsDoNotEvaluateCELRules(t *testing.T) {
schema := `{"type":"object","properties":{"size":{"type":"string","x-kubernetes-validations":[{"rule":"self == 'never'","message":"always fails"}]}}}`
r := defaultsRESTWithSchema(t, schema, defaultsConfig(`{"widgets":{"size":"20Gi"}}`))
created, err := r.Create(context.Background(), defaultsApp(`{}`), nil, &metav1.CreateOptions{})
if err != nil {
t.Fatal(err)
}
assertSpec(t, created.(*appsv1alpha1.Application).Spec, `{"size":"20Gi"}`)
}
+39 -19
View File
@@ -61,6 +61,7 @@ import (
"github.com/cozystack/cozystack/pkg/registry/sorting"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
apiextvalidation "k8s.io/apiextensions-apiserver/pkg/apiserver/validation"
// Importing API errors package to construct appropriate error responses
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -92,16 +93,21 @@ const (
// REST implements the RESTStorage interface for Application resources
type REST struct {
c client.Client
w client.WithWatch
gvr schema.GroupVersionResource
gvk schema.GroupVersionKind
kindName string
singularName string
releaseConfig config.ReleaseConfig
specSchema *structuralschema.Structural
nameSchema *validation.NameSchema
nameSchemaErr error
c client.Client
w client.WithWatch
defaultsReader client.Reader
defaultsReadLimit time.Duration
gvr schema.GroupVersionResource
gvk schema.GroupVersionKind
kindName string
singularName string
releaseConfig config.ReleaseConfig
specSchema *structuralschema.Structural
nameSchema *validation.NameSchema
nameSchemaErr error
defaultsValidator apiextvalidation.SchemaCreateValidator
defaultsSchema *apiextv1.JSONSchemaProps
defaultsSchemaErr error
}
// buildSpecSchema parses an OpenAPI-v3 JSON schema string and returns the
@@ -115,7 +121,7 @@ func buildSpecSchema(raw string) (*structuralschema.Structural, error) {
}
// NewREST creates a new REST storage for Application with specific configuration
func NewREST(c client.Client, w client.WithWatch, config *config.Resource) *REST {
func NewREST(c client.Client, w client.WithWatch, defaultsReader client.Reader, config *config.Resource) *REST {
specSchema, err := buildSpecSchema(config.Application.OpenAPISchema)
if err != nil {
klog.Errorf("Failed to build spec schema: %v", err)
@@ -126,10 +132,13 @@ func NewREST(c client.Client, w client.WithWatch, config *config.Resource) *REST
klog.Errorf("ApplicationDefinition for %s declares an invalid %s, refusing to create %s objects until it is fixed: %v",
config.Application.Kind, appsv1alpha1.NameSchemaExtension, config.Application.Kind, nameSchemaErr)
}
defaultsValidator, defaultsSchemaErr := buildInstallationDefaultsValidator(config.Application.OpenAPISchema)
return &REST{
c: c,
w: w,
c: c,
w: w,
defaultsReader: defaultsReader,
defaultsReadLimit: installationDefaultsReadTimeout,
gvr: schema.GroupVersionResource{
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
@@ -139,12 +148,15 @@ func NewREST(c client.Client, w client.WithWatch, config *config.Resource) *REST
Group: appsv1alpha1.GroupName,
Version: "v1alpha1",
}.WithKind(config.Application.Kind),
kindName: config.Application.Kind,
singularName: config.Application.Singular,
releaseConfig: config.Release,
specSchema: specSchema,
nameSchema: nameSchema,
nameSchemaErr: nameSchemaErr,
kindName: config.Application.Kind,
singularName: config.Application.Singular,
releaseConfig: config.Release,
specSchema: specSchema,
nameSchema: nameSchema,
nameSchemaErr: nameSchemaErr,
defaultsValidator: defaultsValidator,
defaultsSchema: parseDefaultsSchema(config.Application.OpenAPISchema),
defaultsSchemaErr: defaultsSchemaErr,
}
}
@@ -178,6 +190,14 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
return nil, apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, nameLenErrs)
}
if err := r.applyInstallationDefaults(ctx, app); err != nil {
if apierrors.IsBadRequest(err) {
return nil, err
}
klog.Warningf("Skipping installation defaults for %s: %v", r.gvr.Resource, err)
warning.AddWarning(ctx, "", "Installation defaults could not be applied; continuing without them")
}
// For Tenant applications, also validate that the computed workload
// namespace fits within the DNS-1123 label limit. A deeply-nested tenant
// can exceed the limit even when its own name passes the per-name Helm
@@ -284,7 +284,7 @@ func TestConvertConditions_WorkloadsReadyUnknownOnError(t *testing.T) {
// Deliberately NOT registering cozyv1alpha1 so that List returns an error
c := fake.NewClientBuilder().WithScheme(scheme).Build()
r := NewREST(c, nil, &config.Resource{
r := NewREST(c, nil, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -236,7 +236,7 @@ func withDeclaredMaxLength(t *testing.T, raw string, maxLen int) string {
// exercise the wiring in NewREST rather than a hand-set field.
func newTestREST(t *testing.T, kind, prefix, openAPISchema string) *REST {
t.Helper()
return NewREST(nil, nil, &config.Resource{
return NewREST(nil, nil, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: kind,
Singular: strings.ToLower(kind),
@@ -41,7 +41,7 @@ func newWatchTestREST(t *testing.T) *REST {
t.Fatalf("register helmv2 scheme: %v", err)
}
fc := fake.NewClientBuilder().WithScheme(scheme).Build()
return NewREST(fc, fc, &config.Resource{
return NewREST(fc, fc, nil, &config.Resource{
Application: config.ApplicationConfig{Kind: "Redis", Singular: "redis", Plural: "redises"},
Release: config.ReleaseConfig{Prefix: "redis-"},
})
@@ -111,7 +111,7 @@ func newRVWatchFixture(t *testing.T) *rvWatchFixture {
return liveStore.Delete(ctx, obj, opts...)
},
})
f.rest = NewREST(f.cache, f.live, &config.Resource{
f.rest = NewREST(f.cache, f.live, nil, &config.Resource{
Application: config.ApplicationConfig{Kind: "PostgreSQL", Plural: "postgresqls", Singular: "postgresql"},
Release: config.ReleaseConfig{Prefix: "postgresql-"},
})
@@ -209,7 +209,7 @@ func TestWatchIntegration_WMWatcherCloseProducesNilChannel(t *testing.T) {
}
func newTestRESTWithSchemesFromClient(c client.Client) *REST {
return NewREST(c, nil, &config.Resource{
return NewREST(c, nil, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -25,7 +25,7 @@ func newTestRESTWithSchemes(objs ...runtime.Object) *REST {
}
c := builder.Build()
return NewREST(c, nil, &config.Resource{
return NewREST(c, nil, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -58,7 +58,7 @@ func newOptionsTestREST(t *testing.T, funcs interceptor.Funcs, objects ...client
WithObjects(objects...).
WithInterceptorFuncs(funcs).
Build()
return NewREST(c, c, &config.Resource{
return NewREST(c, c, nil, &config.Resource{
Application: config.ApplicationConfig{
Kind: "PostgreSQL",
Plural: "postgresqls",
@@ -0,0 +1,94 @@
[
{
"name": "omitted fields receive installation values",
"user": {},
"installation": { "size": "20Gi", "nested": { "enabled": true } },
"expected": { "size": "20Gi", "nested": { "enabled": true } }
},
{
"name": "explicit empty values win",
"user": { "object": {}, "array": [], "flag": false, "number": 0, "text": "", "nullable": null },
"installation": { "object": { "enabled": true }, "array": [1], "flag": true, "number": 3, "text": "default", "nullable": "default" },
"expected": { "object": {}, "array": [], "flag": false, "number": 0, "text": "", "nullable": null }
},
{
"name": "an explicit null wins over an installation object",
"user": { "object": null },
"installation": { "object": { "enabled": true } },
"expected": { "object": null }
},
{
"name": "nonempty objects with declared properties merge recursively",
"schema": { "type": "object", "properties": { "nested": { "type": "object", "properties": { "child": { "type": "object", "properties": { "user": { "type": "boolean" }, "default": { "type": "boolean" } } }, "sibling": { "type": "integer" } } } } },
"user": { "nested": { "child": { "user": true } } },
"installation": { "nested": { "child": { "user": false, "default": true }, "sibling": 1 } },
"expected": { "nested": { "child": { "user": true, "default": true }, "sibling": 1 } }
},
{
"name": "an empty nested object stops recursion",
"schema": { "type": "object", "properties": { "nested": { "type": "object", "properties": { "child": { "type": "object", "properties": { "default": { "type": "boolean" } } }, "sibling": { "type": "integer" } } } } },
"user": { "nested": { "child": {} } },
"installation": { "nested": { "child": { "default": true }, "sibling": 1 } },
"expected": { "nested": { "child": {}, "sibling": 1 } }
},
{
"name": "typed dictionaries are replaced as a whole",
"schema": { "type": "object", "properties": { "mirrors": { "type": "object", "additionalProperties": { "type": "object", "properties": { "endpoints": { "type": "array", "items": { "type": "string" } }, "skipFallback": { "type": "boolean" } } } } } },
"user": { "mirrors": { "docker.io": { "endpoints": ["https://mine"] } } },
"installation": { "mirrors": { "docker.io": { "endpoints": ["https://platform"], "skipFallback": true }, "ghcr.io": { "endpoints": ["https://platform"] } } },
"expected": { "mirrors": { "docker.io": { "endpoints": ["https://mine"] } } }
},
{
"name": "free-form objects are replaced as a whole",
"schema": { "type": "object", "properties": { "values": { "type": "object", "x-kubernetes-preserve-unknown-fields": true } } },
"user": { "values": { "a": 1 } },
"installation": { "values": { "a": 2, "b": 3 } },
"expected": { "values": { "a": 1 } }
},
{
"name": "objects that also declare a dictionary are replaced as a whole",
"schema": { "type": "object", "properties": { "options": { "type": "object", "properties": { "known": { "type": "string" } }, "additionalProperties": { "type": "string" } } } },
"user": { "options": { "extra": "user" } },
"installation": { "options": { "known": "platform", "platformKey": "injected" } },
"expected": { "options": { "extra": "user" } }
},
{
"name": "objects that also preserve unknown fields are replaced as a whole",
"schema": { "type": "object", "properties": { "options": { "type": "object", "properties": { "known": { "type": "string" } }, "x-kubernetes-preserve-unknown-fields": true } } },
"user": { "options": { "extra": "user" } },
"installation": { "options": { "known": "platform", "platformKey": "injected" } },
"expected": { "options": { "extra": "user" } }
},
{
"name": "closed objects still merge recursively",
"schema": { "type": "object", "properties": { "options": { "type": "object", "properties": { "known": { "type": "string" }, "other": { "type": "string" } }, "additionalProperties": false } } },
"user": { "options": { "known": "user" } },
"installation": { "options": { "known": "platform", "other": "platform" } },
"expected": { "options": { "known": "user", "other": "platform" } }
},
{
"name": "an omitted dictionary is copied whole",
"schema": { "type": "object", "properties": { "mirrors": { "type": "object", "additionalProperties": { "type": "object", "properties": { "endpoints": { "type": "array", "items": { "type": "string" } } } } } } },
"user": {},
"installation": { "mirrors": { "docker.io": { "endpoints": ["https://platform"] } } },
"expected": { "mirrors": { "docker.io": { "endpoints": ["https://platform"] } } }
},
{
"name": "arrays are whole replacement values",
"user": { "rows": [{ "name": "user", "nested": {} }] },
"installation": { "rows": [{ "name": "default", "extra": true }] },
"expected": { "rows": [{ "name": "user", "nested": {} }] }
},
{
"name": "user scalars and objects retain their type",
"user": { "scalar": "user", "object": { "user": true } },
"installation": { "scalar": { "default": true }, "object": "default" },
"expected": { "scalar": "user", "object": { "user": true } }
},
{
"name": "installation nulls and empty objects are copied",
"user": { "user": true },
"installation": { "object": {}, "nullable": null, "array": [] },
"expected": { "user": true, "object": {}, "nullable": null, "array": [] }
}
]