diff --git a/pkg/chart/v2/lint/rules/chartfile.go b/pkg/chart/v2/lint/rules/chartfile.go index ec4083951..79da17f47 100644 --- a/pkg/chart/v2/lint/rules/chartfile.go +++ b/pkg/chart/v2/lint/rules/chartfile.go @@ -21,9 +21,11 @@ import ( "fmt" "os" "path/filepath" + "strings" "github.com/Masterminds/semver/v3" "github.com/asaskevich/govalidator" + "k8s.io/apimachinery/pkg/api/validation" "sigs.k8s.io/yaml" chart "helm.sh/helm/v4/pkg/chart/v2" @@ -121,6 +123,12 @@ func validateChartName(cf *chart.Metadata) error { if name != cf.Name { return fmt.Errorf("chart name %q is invalid", cf.Name) } + // Chart names must also be valid Kubernetes metadata names so they can be + // used safely as resource name prefixes (lowercase, alphanumeric, hyphens + // and dots only; must start and end with an alphanumeric character). + if errs := validation.NameIsDNSSubdomain(cf.Name, false); len(errs) > 0 { + return fmt.Errorf("chart name %q is not a valid Kubernetes name: %s", cf.Name, strings.Join(errs, ", ")) + } return nil } diff --git a/pkg/chart/v2/lint/rules/chartfile_test.go b/pkg/chart/v2/lint/rules/chartfile_test.go index 90f5edd5c..3038cd36f 100644 --- a/pkg/chart/v2/lint/rules/chartfile_test.go +++ b/pkg/chart/v2/lint/rules/chartfile_test.go @@ -60,8 +60,32 @@ func TestValidateChartYamlFormat(t *testing.T) { } func TestValidateChartName(t *testing.T) { + // empty name (badChart has name: "") require.Error(t, validateChartName(badChart), "validateChartName to return a linter error, got no error") + assert.Error(t, validateChartName(badChartName), "expected validateChartName to return a linter error for an invalid name, got no error") + + invalidNames := []struct { + name string + reason string + }{ + {"../badchartname", "path traversal"}, + {"MyInvalidChart", "uppercase letters"}, + {"my_chart", "underscore"}, + {"-my-chart", "leading hyphen"}, + {"my-chart-", "trailing hyphen"}, + {"my chart", "space"}, + } + for _, tc := range invalidNames { + meta := &chart.Metadata{Name: tc.name} + assert.Error(t, validateChartName(meta), "expected validateChartName to return error for %q (%s), got nil", tc.name, tc.reason) + } + + validNames := []string{"my-chart", "my.chart", "mychart", "my-chart-v2", "1-chart", "myinvalidchart"} // "myinvalidchart" is the lowercase twin of the invalid "MyInvalidChart", confirming uppercase triggers failure + for _, name := range validNames { + meta := &chart.Metadata{Name: name} + assert.NoError(t, validateChartName(meta), "expected validateChartName to return no error for %q", name) + } } func TestValidateChartVersion(t *testing.T) {