Skip to content

Commit 6b52c41

Browse files
committed
feat(api): take Application name limits from the application's schema
The API server capped a Kubernetes cluster name at 32 characters by knowing what that one chart renders: worker pools as KubernetesNodes releases under a 17-character prefix, the default pool suffixed -md0. That is the chart's knowledge sitting in the platform, and it does not generalise. The next application with a sub-resource budget needs another branch on Kind, and an application served from outside this repository cannot get one at all. An application now declares the limits on its own name in its schema, under x-cozystack-name, and the server applies whatever it finds there for whatever kind the ApplicationDefinition describes. A declaration only ever tightens: prefix + name must still fit the 53-character Helm release name limit, and a cap looser than that budget does not widen it. The chart's own explanation of the limit is what a rejected name is answered with, so the reason moves to where the limit is set. Assisted-by: LLM Signed-off-by: Timofei Larkin <[email protected]>
1 parent 1f5118c commit 6b52c41

4 files changed

Lines changed: 291 additions & 57 deletions

File tree

‎docs/agents/overview.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ Build environment variables:
9898

9999
Package `values.yaml` files carry annotations (`@param`, `@typedef`, `@field`, `@enum`, `@section`) that `cozyvalues-gen` turns into `values.schema.json` and `README.md`. Run `make generate` in the package after editing annotations. A pre-commit hook runs `make generate` across `packages/apps/*` and `packages/extra/*` on every commit to keep these in sync — see [`contributing.md`](./contributing.md) for the regenerate-before-commit rule.
100100

101+
A chart also declares the limits on its own resource name there, with `## @name {string} - <why>` followed by the constraint tags (`@maxLength`, `@minLength`, `@pattern`) it needs. `cozyvalues-gen` publishes the declaration at the root of `values.schema.json` as `x-cozystack-name`, from where `hack/update-crd.sh` carries it into the ApplicationDefinition, and the aggregated API server enforces it on `metadata.name` for whatever kind the definition describes. The description is the message a rejected name is answered with, so write it as the explanation of the limit. A cap only ever tightens: `prefix + name` must still fit the 53-character Helm release name limit, and a declaration looser than that budget does not widen it. The limits belong in the chart because that is where the facts behind them are — which sub-resources it renders and what release names they take — and a chart that needs nothing beyond the platform-wide limits declares nothing.
102+
101103
## Testing
102104

103105
- **Helm unit tests:** `make helm-unit-tests` (runs `hack/helm-unit-tests.sh` over every package that defines a `test` target). A `test` target is expected to run helm-unittest: the sweep fails a package whose run reports no suite, because exiting 0 having asserted nothing is indistinguishable from passing. A target that drives something else belongs under another name, as `packages/core/testing` already does with its sandbox flow. `make unit-tests` runs the full unit suite — Helm, BATS, Go, and the preset/readiness checks.

‎pkg/registry/apps/application/rest.go‎

Lines changed: 115 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"encoding/json"
2222
"fmt"
2323
"net/http"
24+
"regexp"
2425
"strconv"
2526
"strings"
2627
"sync"
@@ -96,6 +97,7 @@ type REST struct {
9697
singularName string
9798
releaseConfig config.ReleaseConfig
9899
specSchema *structuralschema.Structural
100+
nameSchema *applicationNameSchema
99101
}
100102

101103
// buildSpecSchema parses an OpenAPI-v3 JSON schema string and returns the
@@ -134,6 +136,11 @@ func NewREST(c client.Client, w client.WithWatch, config *config.Resource) *REST
134136
klog.Errorf("Failed to build spec schema: %v", err)
135137
}
136138

139+
nameSchema, err := parseNameSchema(config.Application.OpenAPISchema)
140+
if err != nil {
141+
klog.Errorf("Failed to parse name schema for %s: %v", config.Application.Kind, err)
142+
}
143+
137144
return &REST{
138145
c: c,
139146
w: w,
@@ -150,6 +157,7 @@ func NewREST(c client.Client, w client.WithWatch, config *config.Resource) *REST
150157
singularName: config.Application.Singular,
151158
releaseConfig: config.Release,
152159
specSchema: specSchema,
160+
nameSchema: nameSchema,
153161
}
154162
}
155163

@@ -1284,38 +1292,114 @@ func validateNoInternalKeys(values *apiextv1.JSON) error {
12841292
// chart-generated resource suffixes within the 63-char DNS-1035 label limit.
12851293
const maxHelmReleaseName = 53
12861294

1287-
// kubernetesKind is the Application.Kind of the parent Kubernetes cluster CR,
1288-
// whose worker pools are separate KubernetesNodes releases.
1289-
const kubernetesKind = "Kubernetes"
1290-
1291-
// maxKubernetesClusterName caps a Kubernetes cluster name so its worker pools
1292-
// can always render. Since Phase 2 worker pools are separate KubernetesNodes
1293-
// releases named "<cluster>-<pool>" under the "kubernetes-nodes-" prefix (17
1294-
// chars), the smallest such child release is "kubernetes-nodes-<cluster>-md0".
1295-
// The parent's own "kubernetes-" prefix would let the cluster name reach 42,
1296-
// but that leaves no room for even the default "md0" pool's child release
1297-
// (17 + len(cluster) + len("-md0") <= 53 => len(cluster) <= 32). Capping the
1298-
// parent name at admission surfaces the overflow on the Kubernetes CR the
1299-
// operator is editing, instead of at render time on a child that can never be
1300-
// created (the migration pins and skips such a pool, leaving no way to add
1301-
// workers).
1302-
const maxKubernetesClusterName = maxHelmReleaseName - len("kubernetes-nodes-") - len("-md0")
1303-
13041295
// maxNamespaceName is the DNS-1123 label limit for Kubernetes namespace names.
13051296
// The tenant Helm chart creates a Namespace whose name is the computed
13061297
// workload namespace (parent namespace + "-" + tenant name), so the total
13071298
// must fit inside a single 63-char DNS-1123 label.
13081299
const maxNamespaceName = 63
13091300

1310-
// validateNameFormat checks an Application name against DNS-1035 and any
1301+
// nameSchemaExtension is the root-level key of an ApplicationDefinition's
1302+
// openAPISchema under which an application publishes the constraints on its
1303+
// own metadata.name. cozyvalues-gen emits it from the chart's `## @name`
1304+
// annotation.
1305+
const nameSchemaExtension = "x-cozystack-name"
1306+
1307+
// applicationNameSchema is an application's own declaration of what its name
1308+
// may look like. A chart's naming budget follows from the sub-resources the
1309+
// chart renders and the release names they take — facts that live in the chart
1310+
// and nowhere else — so the budget travels with the chart's schema instead of
1311+
// being a branch on Kind here. Description is what the chart says about the
1312+
// limit, and is surfaced verbatim when a name is rejected.
1313+
type applicationNameSchema struct {
1314+
MinLength *int64 `json:"minLength"`
1315+
MaxLength *int64 `json:"maxLength"`
1316+
Pattern string `json:"pattern"`
1317+
Description string `json:"description"`
1318+
1319+
// compiledPattern is Pattern compiled once at construction. It stays nil
1320+
// when Pattern is empty or does not compile; a chart shipping a broken
1321+
// regex loses that one constraint rather than its whole declaration.
1322+
compiledPattern *regexp.Regexp
1323+
}
1324+
1325+
// parseNameSchema extracts the x-cozystack-name declaration from an
1326+
// ApplicationDefinition's openAPISchema. Returns (nil, nil) when the schema is
1327+
// empty or declares nothing about the name, which is the case for every
1328+
// application that is content with the platform-wide limits. A pattern that
1329+
// does not compile comes back as the declaration *and* an error, so the
1330+
// constraints around it still apply.
1331+
func parseNameSchema(raw string) (*applicationNameSchema, error) {
1332+
raw = strings.TrimSpace(raw)
1333+
if raw == "" {
1334+
return nil, nil
1335+
}
1336+
var doc map[string]json.RawMessage
1337+
if err := json.Unmarshal([]byte(raw), &doc); err != nil {
1338+
return nil, fmt.Errorf("unmarshal OpenAPI schema: %w", err)
1339+
}
1340+
declared, ok := doc[nameSchemaExtension]
1341+
if !ok {
1342+
return nil, nil
1343+
}
1344+
var ns applicationNameSchema
1345+
if err := json.Unmarshal(declared, &ns); err != nil {
1346+
return nil, fmt.Errorf("unmarshal %s: %w", nameSchemaExtension, err)
1347+
}
1348+
if ns.Pattern != "" {
1349+
re, err := regexp.Compile(ns.Pattern)
1350+
if err != nil {
1351+
return &ns, fmt.Errorf("compile %s pattern %q: %w", nameSchemaExtension, ns.Pattern, err)
1352+
}
1353+
ns.compiledPattern = re
1354+
}
1355+
return &ns, nil
1356+
}
1357+
1358+
// validateNameFormat checks an Application name against DNS-1035, any
13111359
// kind-specific format rules (e.g. Tenant names must be alphanumeric — see
1312-
// validation.ValidateApplicationName for the reasoning).
1360+
// validation.ValidateApplicationName for the reasoning), and the format the
1361+
// application declares for itself in its schema.
13131362
func (r *REST) validateNameFormat(name string) field.ErrorList {
1314-
return validation.ValidateApplicationName(name, r.kindName, field.NewPath("metadata").Child("name"))
1363+
allErrs := validation.ValidateApplicationName(name, r.kindName, field.NewPath("metadata").Child("name"))
1364+
return append(allErrs, r.validateNameAgainstSchema(name)...)
1365+
}
1366+
1367+
// validateNameAgainstSchema applies the constraints the application declares
1368+
// for its own name. Only minLength and pattern are checked here; maxLength is
1369+
// applied in validateNameLength together with the platform-wide budget the two
1370+
// share.
1371+
func (r *REST) validateNameAgainstSchema(name string) field.ErrorList {
1372+
if r.nameSchema == nil {
1373+
return nil
1374+
}
1375+
fldPath := field.NewPath("metadata").Child("name")
1376+
allErrs := field.ErrorList{}
1377+
1378+
if minLen := r.nameSchema.MinLength; minLen != nil && int64(len(name)) < *minLen {
1379+
allErrs = append(allErrs, field.Invalid(fldPath, name,
1380+
withDeclaredReason(fmt.Sprintf("must be at least %d characters", *minLen), r.nameSchema.Description)))
1381+
}
1382+
if re := r.nameSchema.compiledPattern; re != nil && !re.MatchString(name) {
1383+
allErrs = append(allErrs, field.Invalid(fldPath, name,
1384+
withDeclaredReason(fmt.Sprintf("must match %q", r.nameSchema.Pattern), r.nameSchema.Description)))
1385+
}
1386+
return allErrs
1387+
}
1388+
1389+
// withDeclaredReason appends the chart's own explanation of a limit to the
1390+
// message, so the answer to "why 32?" comes from the chart that set it.
1391+
func withDeclaredReason(msg, reason string) string {
1392+
if reason == "" {
1393+
return msg
1394+
}
1395+
return msg + " (" + reason + ")"
13151396
}
13161397

1317-
// validateNameLength checks that the application name won't exceed Kubernetes limits.
1318-
// prefix + name must fit within the Helm release name limit (53 chars).
1398+
// validateNameLength checks that the application name fits both the Helm
1399+
// release name limit (prefix + name <= 53) and any stricter budget the
1400+
// application declares for itself. The two are the same kind of constraint —
1401+
// how much of a release name the platform may spend on this object — so the
1402+
// tighter one wins and reports itself.
13191403
func (r *REST) validateNameLength(name string) field.ErrorList {
13201404
fldPath := field.NewPath("metadata").Child("name")
13211405
allErrs := field.ErrorList{}
@@ -1328,22 +1412,15 @@ func (r *REST) validateNameLength(name string) field.ErrorList {
13281412
return allErrs
13291413
}
13301414

1331-
// A Kubernetes cluster's worker pools are separate KubernetesNodes releases
1332-
// named "<cluster>-<pool>", so the parent name must leave room for at least
1333-
// the default "md0" pool's child release. This is stricter than the parent's
1334-
// own Helm-prefix budget and fails at admission on the parent rather than at
1335-
// render time on an un-creatable child (see maxKubernetesClusterName).
1336-
if r.kindName == kubernetesKind && maxLen > maxKubernetesClusterName {
1337-
if len(name) > maxKubernetesClusterName {
1338-
allErrs = append(allErrs, field.Invalid(fldPath, name,
1339-
fmt.Sprintf("must be no more than %d characters so its worker pools (KubernetesNodes releases named \"kubernetes-nodes-<cluster>-<pool>\") fit the %d-character Helm release name limit", maxKubernetesClusterName, maxHelmReleaseName)))
1340-
}
1341-
return allErrs
1415+
reason := fmt.Sprintf("release prefix %q", r.releaseConfig.Prefix)
1416+
if declared := r.nameSchema; declared != nil && declared.MaxLength != nil && *declared.MaxLength < int64(maxLen) {
1417+
maxLen = int(*declared.MaxLength)
1418+
reason = declared.Description
13421419
}
13431420

13441421
if len(name) > maxLen {
13451422
allErrs = append(allErrs, field.Invalid(fldPath, name,
1346-
fmt.Sprintf("must be no more than %d characters (release prefix %q)", maxLen, r.releaseConfig.Prefix)))
1423+
withDeclaredReason(fmt.Sprintf("must be no more than %d characters", maxLen), reason)))
13471424
}
13481425
return allErrs
13491426
}
@@ -1946,6 +2023,10 @@ func (r *REST) warnLegacyPresets(app *appsv1alpha1.Application) {
19462023
}
19472024
}
19482025

2026+
// kubernetesKind is the Application.Kind of the Kubernetes cluster CR whose
2027+
// Phase 2-removed value keys the warning below reports on.
2028+
const kubernetesKind = "Kubernetes"
2029+
19492030
// removedKubernetesFields are Kubernetes CR value keys that Phase 2 moved to the
19502031
// separate KubernetesNodes resource. They are still accepted and stored -- an
19512032
// upgraded cluster keeps them in its values until re-edited, and the adoption
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
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+
"strings"
21+
"testing"
22+
23+
"github.com/cozystack/cozystack/pkg/config"
24+
)
25+
26+
// kubernetesDefinitionPath is the ApplicationDefinition shipped to clusters for
27+
// the Kubernetes application, whose chart declares a name cap of 32 via the
28+
// `## @name` annotation in its values.yaml.
29+
const kubernetesDefinitionPath = "../../../../packages/system/kubernetes-rd/cozyrds/kubernetes.yaml"
30+
31+
// TestNameCapComesFromTheShippedSchema walks the whole path the constraint
32+
// travels: the kubernetes chart's values.yaml annotation, through
33+
// cozyvalues-gen into values.schema.json, into the ApplicationDefinition this
34+
// test reads off disk, and into the name check. The 33-char name is rejected
35+
// only because the schema says so — the same kind with a schema that declares
36+
// nothing accepts it, which is what "no per-kind branch" means in practice.
37+
func TestNameCapComesFromTheShippedSchema(t *testing.T) {
38+
raw := readEmbeddedOpenAPISchema(t, kubernetesDefinitionPath)
39+
40+
declared := newTestREST(t, "Kubernetes", "kubernetes-", raw)
41+
42+
if errs := declared.validateNameLength(strings.Repeat("a", 32)); len(errs) > 0 {
43+
t.Errorf("name at the declared cap rejected: %v", errs)
44+
}
45+
46+
errs := declared.validateNameLength(strings.Repeat("a", 33))
47+
if len(errs) != 1 {
48+
t.Fatalf("expected the declared cap to reject a 33-character name, got %v", errs)
49+
}
50+
// The chart's own words, not a message assembled here, are what the user
51+
// reads — that is what makes the limit the chart's to change.
52+
if !strings.Contains(errs[0].Error(), "md0") {
53+
t.Errorf("rejection does not carry the chart's explanation of the limit: %v", errs[0])
54+
}
55+
56+
// Same kind, same prefix, schema that declares no cap: the name fits the
57+
// generic Helm budget (53 - len("kubernetes-") = 42) and is accepted.
58+
undeclared := newTestREST(t, "Kubernetes", "kubernetes-", `{"title":"Chart Values","type":"object","properties":{}}`)
59+
if errs := undeclared.validateNameLength(strings.Repeat("a", 33)); len(errs) > 0 {
60+
t.Errorf("Kubernetes kind is still capped with no declaration in its schema: %v", errs)
61+
}
62+
}
63+
64+
// TestNameSchemaEnforcesMinLengthAndPattern covers the other constraints a
65+
// chart can declare, so a declaration is never silently a no-op.
66+
func TestNameSchemaEnforcesMinLengthAndPattern(t *testing.T) {
67+
const schema = `{
68+
"title": "Chart Values",
69+
"type": "object",
70+
"x-cozystack-name": {
71+
"type": "string",
72+
"description": "the chart splits the release name on dashes",
73+
"minLength": 3,
74+
"pattern": "^[a-z][a-z0-9]*$"
75+
},
76+
"properties": {}
77+
}`
78+
r := newTestREST(t, "Widget", "widget-", schema)
79+
80+
if errs := r.validateNameFormat("widget"); len(errs) > 0 {
81+
t.Errorf("conforming name rejected: %v", errs)
82+
}
83+
if errs := r.validateNameFormat("ab"); len(errs) != 1 {
84+
t.Errorf("expected minLength to reject a 2-character name, got %v", errs)
85+
}
86+
if errs := r.validateNameFormat("has-dash"); len(errs) != 1 {
87+
t.Errorf("expected pattern to reject %q, got %v", "has-dash", errs)
88+
}
89+
}
90+
91+
// TestParseNameSchema covers the inputs NewREST hands the parser: schemas that
92+
// declare nothing (the common case), and malformed ones, which must surface as
93+
// errors rather than as a silently unenforced constraint.
94+
func TestParseNameSchema(t *testing.T) {
95+
for _, in := range []string{"", " ", `{"title":"Chart Values","type":"object"}`} {
96+
got, err := parseNameSchema(in)
97+
if err != nil {
98+
t.Errorf("parseNameSchema(%q) returned error: %v", in, err)
99+
}
100+
if got != nil {
101+
t.Errorf("parseNameSchema(%q) returned a declaration where the schema has none", in)
102+
}
103+
}
104+
105+
if _, err := parseNameSchema("{not json"); err == nil {
106+
t.Error("parseNameSchema accepted malformed JSON without error")
107+
}
108+
109+
if _, err := parseNameSchema(`{"x-cozystack-name":{"maxLength":"thirty-two"}}`); err == nil {
110+
t.Error("parseNameSchema accepted a non-integer maxLength without error")
111+
}
112+
113+
got, err := parseNameSchema(`{"x-cozystack-name":{"type":"string","pattern":"^[a-z"}}`)
114+
if err == nil {
115+
t.Error("parseNameSchema accepted an uncompilable pattern without error")
116+
}
117+
if got != nil && got.compiledPattern != nil {
118+
t.Error("parseNameSchema kept a pattern that does not compile")
119+
}
120+
}
121+
122+
// newTestREST builds a REST the way the server does at start-up, so the tests
123+
// exercise the wiring in NewREST rather than a hand-set field.
124+
func newTestREST(t *testing.T, kind, prefix, openAPISchema string) *REST {
125+
t.Helper()
126+
return NewREST(nil, nil, &config.Resource{
127+
Application: config.ApplicationConfig{
128+
Kind: kind,
129+
Singular: strings.ToLower(kind),
130+
Plural: strings.ToLower(kind) + "s",
131+
OpenAPISchema: openAPISchema,
132+
},
133+
Release: config.ReleaseConfig{Prefix: prefix},
134+
})
135+
}

0 commit comments

Comments
 (0)