|
| 1 | +/* |
| 2 | +Copyright 2026 The Cozystack Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package application |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "errors" |
| 23 | + "reflect" |
| 24 | + "strings" |
| 25 | + "testing" |
| 26 | + |
| 27 | + appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1" |
| 28 | + helmv2 "github.com/fluxcd/helm-controller/api/v2" |
| 29 | + apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" |
| 30 | + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" |
| 31 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 32 | + "k8s.io/apimachinery/pkg/runtime" |
| 33 | + "k8s.io/apiserver/pkg/endpoints/request" |
| 34 | + "k8s.io/apiserver/pkg/warning" |
| 35 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 36 | +) |
| 37 | + |
| 38 | +type nullChartCase struct { |
| 39 | + name, chart, rd, input, want string |
| 40 | + schema, values string |
| 41 | + paths []string |
| 42 | +} |
| 43 | + |
| 44 | +var nullChartCases = []nullChartCase{ |
| 45 | + {name: "nullable schema default", schema: `{"type":"object","required":["name"],"properties":{"name":{"type":"string","nullable":true,"default":"example"}}}`, values: `{"name":"example"}`, input: `{"name":null}`}, |
| 46 | + {name: "item schema defaults", schema: `{"type":"object","properties":{"entries":{"type":"object","additionalProperties":{"type":"object","required":["name"],"properties":{"name":{"type":"string","default":"example"}}}},"items":{"type":"array","items":{"type":"object","required":["name"],"properties":{"name":{"type":"string","default":"example"}}}}}}`, values: `{"entries":{},"items":[{"name":"chart-default"}]}`, input: `{"entries":{"mine":{"name":null}},"items":[{"name":null}]}`}, |
| 47 | + |
| 48 | + {name: "nested defaults", chart: "apps/kubernetes", rd: "kubernetes", input: `{"talos":{"registryMirrors":null,"version":null},"controlPlane":{"replicas":null,"apiServer":{"resourcesPreset":null}},"nodeGroups":{"legacy":{"instanceType":null}}}`, want: `{"talos":{},"controlPlane":{"apiServer":{}},"nodeGroups":{"legacy":{"instanceType":null}}}`, paths: []string{"controlPlane.apiServer.resourcesPreset", "controlPlane.replicas", "talos.registryMirrors", "talos.version"}}, |
| 49 | + {name: "mariadb users", chart: "apps/mariadb", rd: "mariadb", input: `{"users":{"alice":{"password":null,"maxUserConnections":null},"blank":null}}`}, |
| 50 | + {name: "rabbitmq vhosts", chart: "apps/rabbitmq", rd: "rabbitmq", input: `{"vhosts":{"vh1":{"roles":null},"blank":null}}`}, |
| 51 | + {name: "seaweedfs pools", chart: "extra/seaweedfs", rd: "seaweedfs", input: `{"volume":{"pools":{"ssd":{"diskType":null},"blank":null}}}`}, |
| 52 | + {name: "vm source http", chart: "apps/vm-disk", rd: "vm-disk", input: `{"source":{"http":{"url":null}}}`}, |
| 53 | + {name: "vm source disk", chart: "apps/vm-disk", rd: "vm-disk", input: `{"source":{"disk":{"name":null}}}`}, |
| 54 | + {name: "vm source image", chart: "apps/vm-disk", rd: "vm-disk", input: `{"source":{"image":{"name":null}}}`}, |
| 55 | + {name: "optional section", chart: "apps/kubernetes", rd: "kubernetes", input: `{"talos":null,"storageClass":null}`}, |
| 56 | +} |
| 57 | + |
| 58 | +func chartSpecSchema(t *testing.T, rd string) *structuralschema.Structural { |
| 59 | + t.Helper() |
| 60 | + raw := readEmbeddedOpenAPISchema(t, "../../../../packages/system/"+rd+"-rd/cozyrds/"+rd+".yaml") |
| 61 | + s, err := buildSpecSchema(raw) |
| 62 | + if err != nil || s == nil { |
| 63 | + t.Fatalf("build %s schema: %v", rd, err) |
| 64 | + } |
| 65 | + return s |
| 66 | +} |
| 67 | + |
| 68 | +func nullCaseSchema(t *testing.T, tt nullChartCase) *structuralschema.Structural { |
| 69 | + t.Helper() |
| 70 | + if tt.schema == "" { |
| 71 | + return chartSpecSchema(t, tt.rd) |
| 72 | + } |
| 73 | + schema, err := buildSpecSchema(tt.schema) |
| 74 | + if err != nil { |
| 75 | + t.Fatal(err) |
| 76 | + } |
| 77 | + return schema |
| 78 | +} |
| 79 | + |
| 80 | +func jsonValue(t *testing.T, raw []byte) any { |
| 81 | + t.Helper() |
| 82 | + var v any |
| 83 | + decoder := json.NewDecoder(strings.NewReader(string(raw))) |
| 84 | + decoder.UseNumber() |
| 85 | + if err := decoder.Decode(&v); err != nil { |
| 86 | + t.Fatal(err) |
| 87 | + } |
| 88 | + return v |
| 89 | +} |
| 90 | + |
| 91 | +func TestNullNormalizationAdmissionAndStorage(t *testing.T) { |
| 92 | + for _, tt := range nullChartCases { |
| 93 | + for _, verb := range []string{"create", "update", "upsert"} { |
| 94 | + for _, reject := range []bool{false, true} { |
| 95 | + t.Run(tt.name+"/"+verb+"/reject="+map[bool]string{true: "true", false: "false"}[reject], func(t *testing.T) { |
| 96 | + existing := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-good-name", Namespace: "tenant-foo", Labels: map[string]string{ |
| 97 | + ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: "good-name", |
| 98 | + }}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(`{"unchanged":"old"}`)}}} |
| 99 | + r := newKubernetesWarnREST(t) |
| 100 | + if verb == "update" { |
| 101 | + r = newKubernetesWarnREST(t, existing) |
| 102 | + } |
| 103 | + r.specSchema = nullCaseSchema(t, tt) |
| 104 | + app := &appsv1alpha1.Application{TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"}, ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"}, Spec: &apiextv1.JSON{Raw: []byte(tt.input)}} |
| 105 | + original := app.DeepCopy() |
| 106 | + want := tt.want |
| 107 | + if want == "" { |
| 108 | + want = tt.input |
| 109 | + } |
| 110 | + expected := jsonValue(t, []byte(want)) |
| 111 | + rec := &fakeWarningRecorder{} |
| 112 | + ctx := warning.WithWarningRecorder(request.WithNamespace(context.Background(), app.Namespace), rec) |
| 113 | + called := 0 |
| 114 | + sentinel := errors.New("admission rejected the normalized object") |
| 115 | + validate := func(_ context.Context, obj runtime.Object) error { |
| 116 | + called++ |
| 117 | + got, ok := obj.(*appsv1alpha1.Application) |
| 118 | + if !ok { |
| 119 | + t.Fatalf("admission got %T", obj) |
| 120 | + } |
| 121 | + if !reflect.DeepEqual(jsonValue(t, got.Spec.Raw), expected) { |
| 122 | + t.Errorf("admission saw %s; want %s", got.Spec.Raw, want) |
| 123 | + } |
| 124 | + if reject { |
| 125 | + return sentinel |
| 126 | + } |
| 127 | + return nil |
| 128 | + } |
| 129 | + updateValidate := func(ctx context.Context, obj, old runtime.Object) error { |
| 130 | + oldApp, ok := old.(*appsv1alpha1.Application) |
| 131 | + if !ok { |
| 132 | + t.Fatalf("old object %T", old) |
| 133 | + } |
| 134 | + if !strings.Contains(string(oldApp.Spec.Raw), `"unchanged":"old"`) { |
| 135 | + t.Errorf("old object changed: %s", oldApp.Spec.Raw) |
| 136 | + } |
| 137 | + return validate(ctx, obj) |
| 138 | + } |
| 139 | + var err error |
| 140 | + if verb == "create" { |
| 141 | + _, err = r.Create(ctx, app, validate, &metav1.CreateOptions{}) |
| 142 | + } else { |
| 143 | + _, created, e := r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), validate, updateValidate, verb == "upsert", &metav1.UpdateOptions{}) |
| 144 | + err = e |
| 145 | + if err == nil && created != (verb == "upsert") { |
| 146 | + t.Errorf("created=%t for %s", created, verb) |
| 147 | + } |
| 148 | + } |
| 149 | + if called != 1 { |
| 150 | + t.Errorf("admission calls=%d; want 1", called) |
| 151 | + } |
| 152 | + if reject { |
| 153 | + if !errors.Is(err, sentinel) { |
| 154 | + t.Errorf("rejection lost: %v", err) |
| 155 | + } |
| 156 | + } else if err != nil { |
| 157 | + t.Fatal(err) |
| 158 | + } |
| 159 | + if !reflect.DeepEqual(app, original) { |
| 160 | + t.Error("caller input was mutated") |
| 161 | + } |
| 162 | + got := &helmv2.HelmRelease{} |
| 163 | + getErr := r.c.Get(ctx, client.ObjectKeyFromObject(existing), got) |
| 164 | + if reject && verb != "update" { |
| 165 | + all := &helmv2.HelmReleaseList{} |
| 166 | + if err := r.c.List(ctx, all); err != nil { |
| 167 | + t.Fatal(err) |
| 168 | + } |
| 169 | + if len(all.Items) != 0 { |
| 170 | + t.Error("rejected admission wrote a HelmRelease") |
| 171 | + } |
| 172 | + } else { |
| 173 | + if getErr != nil { |
| 174 | + t.Fatal(getErr) |
| 175 | + } |
| 176 | + storedWant := expected |
| 177 | + if reject { |
| 178 | + storedWant = jsonValue(t, existing.Spec.Values.Raw) |
| 179 | + } |
| 180 | + if !reflect.DeepEqual(jsonValue(t, got.Spec.Values.Raw), storedWant) { |
| 181 | + t.Errorf("stored values=%s; want %v", got.Spec.Values.Raw, storedWant) |
| 182 | + } |
| 183 | + } |
| 184 | + var nullWarnings []string |
| 185 | + for _, w := range rec.warnings { |
| 186 | + if strings.HasPrefix(w, "spec:") { |
| 187 | + nullWarnings = append(nullWarnings, w) |
| 188 | + } |
| 189 | + } |
| 190 | + if len(tt.paths) == 0 { |
| 191 | + if len(nullWarnings) != 0 { |
| 192 | + t.Errorf("false repair warning: %v", nullWarnings) |
| 193 | + } |
| 194 | + } else if !reflect.DeepEqual(nullWarnings, []string{emptyFieldsWarning(tt.paths)}) { |
| 195 | + t.Errorf("warnings=%v for removed paths=%v", nullWarnings, tt.paths) |
| 196 | + } |
| 197 | + }) |
| 198 | + } |
| 199 | + } |
| 200 | + } |
| 201 | +} |
0 commit comments