fix(api): validate workload memory before storing an application (#5348)

## What this PR does

The application API accepts `memory: 8` and stores an eight-byte
workload request. On main, #5009 catches it later when Helm renders the
chart. This patch returns HTTP 422 to the caller on create, upsert, or
an update that introduces such a value.

The check follows declared workload resource fields in the chart schema.
An unrelated edit to an existing application with a smaller value still
passes admission. Existing chart checks continue to apply at render
time. A tenant's zero memory quota and arbitrary chart configuration
keep their existing meaning.

The regression tests exercise the REST create and update paths and
verify that a rejected edit leaves storage untouched. The same change
passed the application registry package tests on main and on
release-1.7. Related to #5004 and #5009.

### Downstream repositories

- [x] No downstream repository is affected by this change
- [ ] [cozystack/website](https://github.com/cozystack/website) -
follow-up:
- [ ]
[cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack)
- follow-up:
- [ ]
[cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack)
- follow-up:
- [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up:
- [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up:
- [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) -
follow-up:
- [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) -
follow-up:
- [ ]
[cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server)
- follow-up:
- [ ]
[cozystack/external-apps-example](https://github.com/cozystack/external-apps-example)
- follow-up:
- [ ] [cozystack/examples](https://github.com/cozystack/examples) -
follow-up:
- [ ] [cozystack/community](https://github.com/cozystack/community) -
follow-up:

### Release note

```release-note
fix(api): reject new workload memory values below 1Mi before storing an application. Updates to unrelated fields on existing applications with smaller values still pass admission.
```


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Application creation and updates reject workload memory settings below
the supported minimum of 1 MiB. Values at or above the minimum are
accepted, and existing below-minimum values may remain unchanged.
* Memory settings in quotas and free-form configuration are not
affected. When concurrent updates occur, memory is rechecked against the
latest stored values, preserving repairs and preventing stale updates
from restoring below-minimum settings.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Backported-from: 7380828271
This commit is contained in:
Myasnikov Daniil committed 2026-11-25 10:49:45 +00:00
commit fdbd9580fe
3 files changed
+293

No files matched your search

@@ -0,0 +1,99 @@
/*
Copyright 2024 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"
"encoding/json"
"fmt"
"reflect"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/util/validation/field"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
)
var minimumWorkloadMemory = resource.MustParse("1Mi")
func workloadValues(values *apiextv1.JSON) (map[string]any, error) {
if values == nil || len(values.Raw) == 0 {
return nil, nil
}
var result map[string]any
decoder := json.NewDecoder(bytes.NewReader(values.Raw))
decoder.UseNumber()
err := decoder.Decode(&result)
return result, err
}
func (r *REST) validateWorkloadMemory(app *appsv1alpha1.Application, previous *apiextv1.JSON) error {
if r.specSchema == nil || app.Spec == nil {
return nil
}
values, err := workloadValues(app.Spec)
if err != nil {
return apierrors.NewBadRequest("invalid application spec")
}
old, err := workloadValues(previous)
if err != nil {
return apierrors.NewInternalError(fmt.Errorf("cannot decode stored application spec"))
}
if errs := changedWorkloadMemory(values, old, r.specSchema, field.NewPath("spec")); len(errs) > 0 {
return apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, errs)
}
return nil
}
// Only walk declared object fields. Arbitrary chart settings and tenant resourceQuotas
// can also contain keys named "memory", with different semantics.
func changedWorkloadMemory(values, old map[string]any, schema *structuralschema.Structural, path *field.Path) field.ErrorList {
var errs field.ErrorList
for _, key := range sortedKeys(values) {
child, declared := schema.Properties[key]
current, ok := values[key].(map[string]any)
if !declared || !ok {
continue
}
previous, _ := old[key].(map[string]any)
where := path.Child(key)
_, preset := schema.Properties["resourcesPreset"]
if key == "resources" && preset && child.Properties["memory"].XIntOrString && child.Properties["cpu"].XIntOrString {
memory := current["memory"]
if memory == nil || reflect.DeepEqual(memory, previous["memory"]) {
continue
}
q, err := resource.ParseQuantity(fmt.Sprint(memory))
if err != nil {
errs = append(errs, field.Invalid(where.Child("memory"), memory, "expected a Kubernetes quantity"))
continue
}
if q.Cmp(minimumWorkloadMemory) < 0 {
prior, err := resource.ParseQuantity(fmt.Sprint(previous["memory"]))
if err != nil || prior.Cmp(q) != 0 {
errs = append(errs, field.Invalid(where.Child("memory"), memory, "must be at least 1Mi; use a unit such as 512Mi or 8Gi"))
}
}
continue
}
errs = append(errs, changedWorkloadMemory(current, previous, &child, where)...)
}
return errs
}
@@ -0,0 +1,176 @@
/*
Copyright 2024 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"
"testing"
appsv1alpha1 "github.com/cozystack/cozystack/pkg/apis/apps/v1alpha1"
helmv2 "github.com/fluxcd/helm-controller/api/v2"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/endpoints/request"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
)
func TestWorkloadMemoryAdmission(t *testing.T) {
for _, tc := range []struct {
name, chart, old, next string
upsert, reject bool
}{
{"new bare bytes", "tcp-balancer", "", `{"resources":{"memory":8}}`, false, true},
{"upsert respects floor", "tcp-balancer", "", `{"resources":{"memory":"8"}}`, true, true},
{"new zero", "tcp-balancer", "", `{"resources":{"memory":0}}`, false, true},
{"minimum", "tcp-balancer", "", `{"resources":{"memory":"1Mi"}}`, false, false},
{"bytes above minimum", "tcp-balancer", "", `{"resources":{"memory":1048576}}`, false, false},
{"unchanged scaled to zero", "tcp-balancer", `{"resources":{"memory":8},"replicas":0}`, `{"resources":{"memory":8},"replicas":0,"other":true}`, false, false},
{"same quantity spelling", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8"}}`, false, false},
{"changed zero", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":0}}`, false, true},
{"repaired", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resources":{"memory":"8Gi"}}`, false, false},
{"back to preset", "tcp-balancer", `{"resources":{"memory":8}}`, `{"resourcesPreset":"t1.nano"}`, false, false},
{"nested component", "kubernetes", "", `{"controlPlane":{"apiServer":{"resources":{"memory":"1023Ki"}}}}`, false, true},
{"quota zero", "tenant", "", `{"resourceQuotas":{"memory":0}}`, false, false},
{"free form config", "nats", "", `{"config":{"merge":{"resourcesPreset":"example","resources":{"memory":8}}}}`, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
app := &appsv1alpha1.Application{
TypeMeta: metav1.TypeMeta{Kind: kubernetesKind, APIVersion: "apps.cozystack.io/v1alpha1"},
ObjectMeta: metav1.ObjectMeta{Name: "good-name", Namespace: "tenant-foo"},
}
app.Spec = &apiextv1.JSON{Raw: []byte(tc.next)}
var stored []client.Object
if tc.old != "" {
stored = []client.Object{&helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{
ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name,
}}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(tc.old)}}}}
}
r := newKubernetesWarnREST(t, stored...)
r.specSchema = chartSpecSchema(t, tc.chart)
ctx := request.WithNamespace(context.Background(), app.Namespace)
var err error
if tc.old != "" || tc.upsert {
_, _, err = r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, tc.upsert, &metav1.UpdateOptions{})
} else {
_, err = r.Create(ctx, app, nil, &metav1.CreateOptions{})
}
if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil {
t.Fatalf("reject=%v, got %v", tc.reject, err)
}
if tc.reject {
list := &helmv2.HelmReleaseList{}
if err := r.c.List(ctx, list); err != nil {
t.Fatal(err)
}
if len(list.Items) != len(stored) || len(stored) > 0 && string(list.Items[0].Spec.Values.Raw) != tc.old {
t.Fatal("a rejected request changed storage")
}
}
})
}
}
// A caller that read the app before another writer fixed its memory still
// carries the old value. It must not put that value back, whether the fix lands
// before Update reads the live release or between that read and the write.
func TestWorkloadMemoryRecheckedAgainstLiveRelease(t *testing.T) {
const stale, fixed = `{"resources":{"memory":8}}`, `{"resources":{"memory":"512Mi"}}`
conflict := func(name string) error {
return apierrors.NewConflict(schema.GroupResource{Group: "helm.toolkit.fluxcd.io", Resource: "helmreleases"}, name, errors.New("simulated concurrent write"))
}
setValues := func(ctx context.Context, c client.WithWatch, key client.ObjectKey, values string) error {
live := &helmv2.HelmRelease{}
if err := c.Get(ctx, key, live); err != nil {
return err
}
live.Spec.Values = &apiextv1.JSON{Raw: []byte(values)}
return c.Update(ctx, live)
}
for _, tc := range []struct {
name, next, want string
reject bool
funcs func() interceptor.Funcs
}{
{"fixed after the first read", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs {
gets := 0
return interceptor.Funcs{Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
err := c.Get(ctx, key, obj, opts...)
if _, ok := obj.(*helmv2.HelmRelease); ok && err == nil {
if gets++; gets == 1 {
return setValues(ctx, c, key, fixed)
}
}
return err
}}
}},
{"fixed between the live read and the write", `{"resources":{"memory":8},"other":true}`, fixed, true, func() interceptor.Funcs {
writes := 0
return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
if _, ok := obj.(*helmv2.HelmRelease); ok {
if writes++; writes == 1 {
if err := setValues(ctx, c, client.ObjectKeyFromObject(obj), fixed); err != nil {
return err
}
return conflict(obj.GetName())
}
}
return c.Update(ctx, obj, opts...)
}}
}},
{"unrelated edit after a conflict", `{"resources":{"memory":8},"other":true}`, `{"resources":{"memory":8},"other":true}`, false, func() interceptor.Funcs {
writes := 0
return interceptor.Funcs{Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error {
if _, ok := obj.(*helmv2.HelmRelease); ok {
if writes++; writes == 1 {
return conflict(obj.GetName())
}
}
return c.Update(ctx, obj, opts...)
}}
}},
} {
t.Run(tc.name, func(t *testing.T) {
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(tc.next)},
}
stored := &helmv2.HelmRelease{ObjectMeta: metav1.ObjectMeta{Name: "kubernetes-" + app.Name, Namespace: app.Namespace, Labels: map[string]string{
ApplicationKindLabel: kubernetesKind, ApplicationGroupLabel: appsv1alpha1.GroupName, ApplicationNameLabel: app.Name,
}}, Spec: helmv2.HelmReleaseSpec{Values: &apiextv1.JSON{Raw: []byte(stale)}}}
r := newKubernetesWarnREST(t, stored)
r.specSchema = chartSpecSchema(t, "tcp-balancer")
r.c = interceptor.NewClient(r.w, tc.funcs())
ctx := request.WithNamespace(context.Background(), app.Namespace)
_, _, err := r.Update(ctx, app.Name, newDefaultUpdatedObjectInfo(app), nil, nil, false, &metav1.UpdateOptions{})
if tc.reject && !apierrors.IsInvalid(err) || !tc.reject && err != nil {
t.Fatalf("reject=%v, got %v", tc.reject, err)
}
got := &helmv2.HelmRelease{}
if err := r.w.Get(ctx, client.ObjectKeyFromObject(stored), got); err != nil {
t.Fatal(err)
}
if string(got.Spec.Values.Raw) != tc.want {
t.Fatalf("stored values %s, want %s", got.Spec.Values.Raw, tc.want)
}
})
}
}
+18
View File
@@ -213,6 +213,10 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
}
}
if err := r.validateWorkloadMemory(app, nil); err != nil {
return nil, err
}
// Validate that values don't contain reserved keys (starting with "_")
if err := validateNoInternalKeys(app.Spec); err != nil {
return nil, apierrors.NewBadRequest(err.Error())
@@ -537,6 +541,7 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
return nil, false, err
}
previousValues := oldObj.(*appsv1alpha1.Application).Spec.DeepCopy()
previousFinalizers := slices.Clone(oldObj.(*appsv1alpha1.Application).Finalizers)
// Update the Application object
@@ -559,6 +564,10 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
// Update because Kubernetes names are immutable. Validating here would block
// updates to pre-existing resources whose names don't conform to the new rules.
if err := r.validateWorkloadMemory(app, previousValues); err != nil {
return nil, false, err
}
// Validate that values don't contain reserved keys (starting with "_")
if err := validateNoInternalKeys(app.Spec); err != nil {
return nil, false, apierrors.NewBadRequest(err.Error())
@@ -614,6 +623,12 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
if helmRelease.ResourceVersion == "" {
helmRelease.SetResourceVersion(cur.GetResourceVersion())
}
// The memory check above compared against the read at the start of Update.
// Compare again against the live release, so a stale value below 1Mi cannot
// overwrite memory that another writer has fixed since.
if err := r.validateWorkloadMemory(app, cur.Spec.Values); err != nil {
return nil, false, err
}
r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers)
// Suspension is not part of the Application, so the rebuilt object always
@@ -654,6 +669,9 @@ func (r *REST) Update(ctx context.Context, name string, objInfo rest.UpdatedObje
if getErr := r.c.Get(ctx, client.ObjectKey{Namespace: helmRelease.Namespace, Name: helmRelease.Name}, cur, &client.GetOptions{Raw: &metav1.GetOptions{}}); getErr != nil {
return getErr
}
if memErr := r.validateWorkloadMemory(app, cur.Spec.Values); memErr != nil {
return memErr
}
helmRelease = converted.DeepCopy()
r.applyLiveMetadata(helmRelease, cur, app, previousFinalizers)
helmRelease.SetResourceVersion(cur.GetResourceVersion())