Skip to content

Commit c77d0b8

Browse files
authored
[api] Reject tenant names with dashes at Create time (#2380)
## What this PR does The aggregated API previously accepted tenant names containing hyphens (e.g. `foo-bar`) because `ValidateApplicationName` delegated entirely to `IsDNS1035Label`, which permits them. The tenant Helm chart's `tenant.name` helper then rejected the release at template time — so users saw a successful `kubectl apply` followed by a confusing Flux/HelmRelease reconciliation error. This PR extends `ValidateApplicationName` with a `kindName` parameter and enforces an alphanumeric-only rule (`^[a-z][a-z0-9]*$`) for the Tenant kind. A `TenantKind` constant centralizes the kind string, and `REST.validateNameFormat` wraps the check symmetrically with the existing `validateNameLength`. The tenant chart README is updated to match the already-correct website documentation. Test coverage includes: - Unit tests for the validation package (format + error message contract) - REST wrapper and Update→Create fall-through path tests with a fake client - E2E BATS regression test with explicit exit-code checks and cleanup Fixes #2375 ### Release note ```release-note [api] Tenant names containing dashes are now rejected at API level during creation, with a specific error message, instead of being silently accepted and failing later during Helm reconciliation. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Tenant names now require lowercase letters and digits only, must start with a letter; dashes are rejected with a tenant-specific error. * **Documentation** * Tenant naming guidelines updated to reflect the stricter alphanumeric-only requirement. * **Tests** * New unit and end-to-end tests added to verify tenant naming enforcement and tenant-specific error messaging. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 632414d + 637dd73 commit c77d0b8

6 files changed

Lines changed: 427 additions & 48 deletions

File tree

‎hack/e2e-install-cozystack.bats‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,8 +200,60 @@ EOF
200200
kubectl wait hr/keycloak hr/keycloak-configure hr/keycloak-operator -n cozy-keycloak --timeout=10m --for=condition=ready
201201
}
202202

203+
@test "Aggregated API rejects Tenant name with dashes" {
204+
# Regression guard: the tenant Helm chart's tenant.name helper splits the
205+
# Release.Name on "-" and fails unless the result is exactly
206+
# ["tenant", "<name>"]. The aggregated API must catch tenant names
207+
# containing dashes up-front with a tenant-specific error, instead of
208+
# silently accepting the Application and letting Flux fail later.
209+
210+
# Defensive cleanup: if a prior regression left foo-bar in the cluster,
211+
# remove it before exercising the validation so we are not observing
212+
# stale state. Safe even in the happy path because of --ignore-not-found.
213+
kubectl delete tenants.apps.cozystack.io foo-bar -n tenant-root --ignore-not-found
214+
215+
# Preflight: tenant-root is created by earlier tests in this suite. Fail
216+
# loudly if it is missing so this test does not silently trigger an
217+
# unrelated "namespace not found" error and misreport as a pass.
218+
kubectl get namespace tenant-root
219+
220+
# --validate=ignore forces kubectl to skip client-side OpenAPI validation
221+
# and send the payload straight to the aggregated API. This guarantees the
222+
# server-side name check runs and the error we grep for is the tenant
223+
# contract error, not a kubectl schema rejection. (--validate=false is the
224+
# deprecated alias.)
225+
local output rc
226+
# Run the apply in its own subshell so we can capture BOTH stdout+stderr
227+
# AND the exit code explicitly, without `|| true` swallowing a real failure
228+
# mode (e.g. network error, auth failure) that should also fail the test.
229+
output=$(
230+
kubectl apply --validate=ignore -f - 2>&1 <<EOF
231+
apiVersion: apps.cozystack.io/v1alpha1
232+
kind: Tenant
233+
metadata:
234+
name: foo-bar
235+
namespace: tenant-root
236+
spec: {}
237+
EOF
238+
) && rc=0 || rc=$?
239+
echo "kubectl apply exit=$rc, output=$output"
240+
# kubectl MUST have failed: success would mean validation regressed.
241+
[ "$rc" -ne 0 ]
242+
# Assert the tenant-specific message is present (distinguishes from
243+
# generic DNS-1035 errors and from network/auth failures).
244+
echo "$output" | grep -q "tenant names must"
245+
# And assert kubectl did NOT report creation — if validation regressed
246+
# into a "warn" variant, the server could still accept the object.
247+
! echo "$output" | grep -qi "created"
248+
249+
# Post-condition cleanup: even though we expect validation to reject the
250+
# create, removing foo-bar unconditionally keeps the cluster clean for
251+
# subsequent tests in case validation regresses and the object is created.
252+
kubectl delete tenants.apps.cozystack.io foo-bar -n tenant-root --ignore-not-found
253+
}
254+
203255
@test "Create tenant with isolated mode enabled" {
204-
kubectl -n tenant-root get tenants.apps.cozystack.io test ||
256+
kubectl -n tenant-root get tenants.apps.cozystack.io test ||
205257
kubectl apply -f - <<EOF
206258
apiVersion: apps.cozystack.io/v1alpha1
207259
kind: Tenant

‎packages/apps/tenant/README.md‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@ Tenants can be created recursively and are subject to the following rules:
66

77
### Tenant naming
88

9-
Tenant names must follow DNS-1035 naming rules:
10-
- Must start with a lowercase letter (`a-z`)
11-
- Can only contain lowercase letters, numbers, and hyphens (`a-z`, `0-9`, `-`)
12-
- Must end with a letter or number (not a hyphen)
9+
Tenant names must be alphanumeric:
10+
11+
- Lowercase letters (`a-z`) and digits (`0-9`) only
12+
- Must start with a lowercase letter
13+
- Dashes (`-`) are **not allowed**, unlike with other services
1314
- Maximum length depends on the cluster configuration (Helm release prefix and root domain)
1415

15-
**Note:** Using dashes (`-`) in tenant names is **allowed but discouraged**, unlike with other services.
16-
This is to keep consistent naming in tenants, nested tenants, and services deployed in them.
17-
Names with dashes (e.g., `foo-bar`) may lead to ambiguous parsing of internal resource names like `tenant-foo-bar`.
16+
This restriction exists to keep consistent naming in tenants, nested tenants, and services deployed in them.
17+
A tenant cannot be named `foo-bar` because parsing internal resource names like `tenant-foo-bar` would be ambiguous.
1818

1919
For example:
2020

‎pkg/apis/apps/validation/validation.go‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,23 +17,56 @@ limitations under the License.
1717
package validation
1818

1919
import (
20+
"regexp"
21+
2022
k8svalidation "k8s.io/apimachinery/pkg/util/validation"
2123
"k8s.io/apimachinery/pkg/util/validation/field"
2224
)
2325

24-
// ValidateApplicationName validates that an Application name conforms to DNS-1035.
25-
// This is required because Application names are used to create Kubernetes resources
26-
// (Services, Namespaces, etc.) that must have DNS-1035 compliant names.
27-
// Note: length validation is handled separately by validateNameLength in the REST
28-
// handler, which computes dynamic limits based on Helm release prefix.
29-
func ValidateApplicationName(name string, fldPath *field.Path) field.ErrorList {
26+
// TenantKind is the Application.Kind string that gates the tenant-specific
27+
// name rules below. It must stay in sync with the `kind` field of the tenant
28+
// ApplicationDefinition (packages/system/tenant-rd/cozyrds/tenant.yaml) which
29+
// is the upstream source the aggregated API reads at startup via
30+
// config.Application.Kind.
31+
const TenantKind = "Tenant"
32+
33+
// tenantNameRegex enforces alphanumeric-only tenant names that begin with a
34+
// lowercase letter. This is stricter than DNS-1035 because the tenant Helm
35+
// chart's tenant.name helper (packages/apps/tenant/templates/_helpers.tpl)
36+
// splits Release.Name on "-" and fails unless the result is exactly
37+
// ["tenant", "<name>"]. Any dash inside <name> would break that invariant at
38+
// Helm template time, so the aggregated API must reject such names up-front
39+
// with a specific error. Requiring a leading letter (rather than letting
40+
// leading-digit names fall through to DNS-1035) keeps the error message
41+
// tenant-specific for all invalid inputs.
42+
var tenantNameRegex = regexp.MustCompile(`^[a-z][a-z0-9]*$`)
43+
44+
// ValidateApplicationName validates that an Application name is acceptable for
45+
// the given kind. All applications must conform to DNS-1035 because their
46+
// names are used to create Kubernetes resources (Services, Namespaces, etc.)
47+
// that require DNS-1035 compliance. Tenant applications additionally must be
48+
// alphanumeric and begin with a lowercase letter because of the Helm chart
49+
// constraint described on tenantNameRegex.
50+
// Note: length validation is handled separately by validateNameLength in the
51+
// REST handler, which computes dynamic limits based on Helm release prefix.
52+
func ValidateApplicationName(name, kindName string, fldPath *field.Path) field.ErrorList {
3053
allErrs := field.ErrorList{}
3154

3255
if len(name) == 0 {
3356
allErrs = append(allErrs, field.Required(fldPath, "name is required"))
3457
return allErrs
3558
}
3659

60+
// Tenant names must be alphanumeric starting with a letter — see
61+
// tenantNameRegex comment for the reason. Check before DNS-1035 so the
62+
// error message is specific to the tenant contract, not the generic DNS
63+
// label rules.
64+
if kindName == TenantKind && !tenantNameRegex.MatchString(name) {
65+
allErrs = append(allErrs, field.Invalid(fldPath, name,
66+
"tenant names must start with a lowercase letter and contain only lowercase letters and digits; dashes are not allowed"))
67+
return allErrs
68+
}
69+
3770
for _, msg := range k8svalidation.IsDNS1035Label(name) {
3871
allErrs = append(allErrs, field.Invalid(fldPath, name, msg))
3972
}

‎pkg/apis/apps/validation/validation_test.go‎

Lines changed: 124 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -27,55 +27,148 @@ func TestValidateApplicationName(t *testing.T) {
2727
tests := []struct {
2828
name string
2929
appName string
30+
kindName string
3031
wantError bool
3132
}{
32-
// Valid names
33-
{"valid simple name", "tenant-one", false},
34-
{"valid single letter", "a", false},
35-
{"valid with numbers", "abc-123", false},
36-
{"valid lowercase", "my-tenant", false},
37-
{"valid long name", "my-very-long-tenant-name", false},
38-
{"valid double hyphen", "my--tenant", false},
39-
{"valid at DNS-1035 max (63 chars)", strings.Repeat("a", 63), false},
33+
// Valid names (non-tenant kinds permit DNS-1035 including hyphens)
34+
{"valid simple name", "tenant-one", "MySQL", false},
35+
{"valid single letter", "a", "MySQL", false},
36+
{"valid with numbers", "abc-123", "MySQL", false},
37+
{"valid lowercase", "my-tenant", "MySQL", false},
38+
{"valid long name", "my-very-long-tenant-name", "MySQL", false},
39+
{"valid double hyphen", "my--tenant", "MySQL", false},
40+
{"valid at DNS-1035 max (63 chars)", strings.Repeat("a", 63), "MySQL", false},
41+
{"valid with empty kind", "my-db", "", false},
4042

4143
// Invalid: starts with wrong character
42-
{"starts with digit", "1john", true},
43-
{"only digits", "123", true},
44-
{"starts with hyphen", "-tenant", true},
44+
{"starts with digit", "1john", "MySQL", true},
45+
{"only digits", "123", "MySQL", true},
46+
{"starts with hyphen", "-tenant", "MySQL", true},
4547

4648
// Invalid: ends with wrong character
47-
{"ends with hyphen", "tenant-", true},
49+
{"ends with hyphen", "tenant-", "MySQL", true},
4850

4951
// Invalid: wrong characters
50-
{"uppercase letters", "Tenant", true},
51-
{"mixed case", "myTenant", true},
52-
{"underscore", "my_tenant", true},
53-
{"dot", "my.tenant", true},
54-
{"space", "my tenant", true},
55-
{"unicode cyrillic", "тенант", true},
56-
{"unicode emoji", "tenant🚀", true},
57-
{"special chars", "tenant@home", true},
58-
{"colon", "tenant:one", true},
59-
{"slash", "tenant/one", true},
52+
{"uppercase letters", "Tenant", "MySQL", true},
53+
{"mixed case", "myTenant", "MySQL", true},
54+
{"underscore", "my_tenant", "MySQL", true},
55+
{"dot", "my.tenant", "MySQL", true},
56+
{"space", "my tenant", "MySQL", true},
57+
{"unicode cyrillic", "тенант", "MySQL", true},
58+
{"unicode emoji", "tenant🚀", "MySQL", true},
59+
{"special chars", "tenant@home", "MySQL", true},
60+
{"colon", "tenant:one", "MySQL", true},
61+
{"slash", "tenant/one", "MySQL", true},
6062

6163
// Invalid: empty or whitespace
62-
{"empty string", "", true},
63-
{"only spaces", " ", true},
64-
{"leading space", " tenant", true},
65-
{"trailing space", "tenant ", true},
64+
{"empty string", "", "MySQL", true},
65+
{"only spaces", " ", "MySQL", true},
66+
{"leading space", " tenant", "MySQL", true},
67+
{"trailing space", "tenant ", "MySQL", true},
6668

6769
// Invalid: exceeds DNS-1035 max length (63)
68-
{"too long (64 chars)", strings.Repeat("a", 64), true},
69-
{"way too long (100 chars)", strings.Repeat("a", 100), true},
70+
{"too long (64 chars)", strings.Repeat("a", 64), "MySQL", true},
71+
{"way too long (100 chars)", strings.Repeat("a", 100), "MySQL", true},
72+
73+
// Tenant kind: stricter alphanumeric-only rule.
74+
// The tenant Helm chart's tenant.name helper (packages/apps/tenant/templates/_helpers.tpl)
75+
// splits Release.Name on "-" and fails unless the result is exactly
76+
// ["tenant", "<name>"]. Any dash inside <name> breaks that invariant, so
77+
// the aggregated API must reject tenant names containing dashes up-front
78+
// with a specific error — instead of letting Flux reconciliation fail later.
79+
{"tenant alphanumeric simple", "foo", "Tenant", false},
80+
{"tenant alphanumeric with digits", "foo123", "Tenant", false},
81+
{"tenant single char", "a", "Tenant", false},
82+
{"tenant single hyphen", "foo-bar", "Tenant", true},
83+
{"tenant leading hyphen", "-foo", "Tenant", true},
84+
{"tenant trailing hyphen", "foo-", "Tenant", true},
85+
{"tenant double hyphen", "foo--bar", "Tenant", true},
86+
{"tenant uppercase", "Foo", "Tenant", true},
87+
{"tenant underscore", "foo_bar", "Tenant", true},
88+
{"tenant empty", "", "Tenant", true},
89+
// Leading digit must be caught by the tenant-specific regex (not by
90+
// falling through to DNS-1035) so the error message reflects the
91+
// tenant contract — see TestValidateApplicationName_TenantErrorMessage.
92+
{"tenant leading digit", "123foo", "Tenant", true},
7093
}
7194

7295
for _, tt := range tests {
7396
t.Run(tt.name, func(t *testing.T) {
74-
errs := ValidateApplicationName(tt.appName, field.NewPath("metadata").Child("name"))
97+
errs := ValidateApplicationName(tt.appName, tt.kindName, field.NewPath("metadata").Child("name"))
7598
if (len(errs) > 0) != tt.wantError {
76-
t.Errorf("ValidateApplicationName(%q) returned %d errors, wantError = %v, errors = %v",
77-
tt.appName, len(errs), tt.wantError, errs)
99+
t.Errorf("ValidateApplicationName(%q, kind=%q) returned %d errors, wantError = %v, errors = %v",
100+
tt.appName, tt.kindName, len(errs), tt.wantError, errs)
78101
}
79102
})
80103
}
81104
}
105+
106+
// TestValidateApplicationName_TenantErrorMessage pins the contract that when
107+
// a tenant name is invalid, the returned error message is specific to the
108+
// tenant naming rule — not the generic DNS-1035 message. Otherwise users get
109+
// back "must start with an alphabetic character" or similar and have no way
110+
// to know the constraint is tied to the tenant Helm chart.
111+
func TestValidateApplicationName_TenantErrorMessage(t *testing.T) {
112+
// Every tenant-invalid name below must surface a tenant-specific error
113+
// message. In particular, "123foo" starts with a digit — the original
114+
// implementation let that fall through to DNS-1035 with a generic error;
115+
// the regex is tightened specifically so this case fails up-front.
116+
invalidTenantNames := []string{
117+
"foo-bar", // dash
118+
"-foo", // leading dash
119+
"foo-", // trailing dash
120+
"foo--bar", // double dash
121+
"Foo", // uppercase
122+
"foo_bar", // underscore
123+
"foo.bar", // dot
124+
"foo bar", // space
125+
"123foo", // leading digit — must not fall through to DNS-1035
126+
}
127+
128+
const wantSubstring = "tenant names must"
129+
130+
for _, name := range invalidTenantNames {
131+
t.Run(name, func(t *testing.T) {
132+
errs := ValidateApplicationName(name, "Tenant", field.NewPath("metadata").Child("name"))
133+
if len(errs) == 0 {
134+
t.Fatalf("expected error for tenant name %q, got none", name)
135+
}
136+
if !strings.Contains(errs[0].Detail, wantSubstring) {
137+
t.Errorf("tenant name %q: error detail = %q, want substring %q (generic DNS-1035 message is not tenant-specific)",
138+
name, errs[0].Detail, wantSubstring)
139+
}
140+
})
141+
}
142+
}
143+
144+
// TestValidateApplicationName_TenantLengthFallthrough documents the one
145+
// invalid-tenant case where the error message is intentionally NOT tenant-
146+
// specific: when a name contains only valid tenant characters but exceeds
147+
// the DNS-1035 63-char label limit, the length error comes from DNS-1035
148+
// because length is not a tenant-specific constraint (every application
149+
// kind is subject to the same Kubernetes label limit). REST.validateNameLength
150+
// further tightens the limit using the Helm release prefix, so tenants cannot
151+
// actually reach 64 characters end-to-end — this test only pins the package-
152+
// level fallthrough so a future refactor does not accidentally promote the
153+
// length error into tenant-specific wording.
154+
//
155+
// NOTE: this is an architectural decision, not a user-facing requirement.
156+
// If tenant length is ever promoted into a tenant-specific rule (e.g. to
157+
// include the Helm release prefix budget in this package's error message),
158+
// this test should be updated or deleted — it is not a backwards-compat
159+
// guarantee, just a checkpoint on the current layering.
160+
func TestValidateApplicationName_TenantLengthFallthrough(t *testing.T) {
161+
name := strings.Repeat("a", 64) // valid tenant pattern, too long for DNS-1035
162+
163+
errs := ValidateApplicationName(name, "Tenant", field.NewPath("metadata").Child("name"))
164+
if len(errs) == 0 {
165+
t.Fatalf("expected DNS-1035 length error for 64-char tenant name, got none")
166+
}
167+
// This error is the generic DNS-1035 one, NOT the tenant-specific message.
168+
// We deliberately do not assert against the exact upstream DNS-1035 text
169+
// (that would tie this test to a k8s.io/apimachinery internal string and
170+
// break on unrelated upstream wording changes).
171+
if strings.Contains(errs[0].Detail, "tenant names must") {
172+
t.Errorf("64-char tenant name should surface the generic DNS-1035 error, got tenant-specific: %q", errs[0].Detail)
173+
}
174+
}

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -154,8 +154,8 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
154154
return nil, fmt.Errorf("expected *appsv1alpha1.Application object, got %T", obj)
155155
}
156156

157-
// Validate Application name conforms to DNS-1035
158-
if errs := validation.ValidateApplicationName(app.Name, field.NewPath("metadata").Child("name")); len(errs) > 0 {
157+
// Validate Application name format (DNS-1035 plus any kind-specific rules)
158+
if errs := r.validateNameFormat(app.Name); len(errs) > 0 {
159159
return nil, apierrors.NewInvalid(r.gvk.GroupKind(), app.Name, errs)
160160
}
161161

@@ -1066,6 +1066,13 @@ const maxHelmReleaseName = 53
10661066
// must fit inside a single 63-char DNS-1123 label.
10671067
const maxNamespaceName = 63
10681068

1069+
// validateNameFormat checks an Application name against DNS-1035 and any
1070+
// kind-specific format rules (e.g. Tenant names must be alphanumeric — see
1071+
// validation.ValidateApplicationName for the reasoning).
1072+
func (r *REST) validateNameFormat(name string) field.ErrorList {
1073+
return validation.ValidateApplicationName(name, r.kindName, field.NewPath("metadata").Child("name"))
1074+
}
1075+
10691076
// validateNameLength checks that the application name won't exceed Kubernetes limits.
10701077
// prefix + name must fit within the Helm release name limit (53 chars).
10711078
func (r *REST) validateNameLength(name string) field.ErrorList {
@@ -1146,7 +1153,7 @@ func (r *REST) convertHelmReleaseToApplication(ctx context.Context, hr *helmv2.H
11461153
app.SetConditions(conditions)
11471154

11481155
// Add namespace field for Tenant applications
1149-
if r.kindName == "Tenant" {
1156+
if r.kindName == validation.TenantKind {
11501157
app.Status.Namespace = r.computeTenantNamespace(hr.Namespace, app.Name)
11511158
externalIPsCount, err := r.countTenantExternalIPs(ctx, app.Status.Namespace)
11521159
if err != nil {

0 commit comments

Comments
 (0)