repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/chartfile.go | pkg/chart/v2/util/chartfile.go | /*
Copyright The Helm 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 util
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sigs.k8s.io/yaml"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// LoadChartfile loads a Chart.yaml file into a *chart.Metadata.
func LoadChartfile(filename string) (*chart.Metadata, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
y := new(chart.Metadata)
err = yaml.Unmarshal(b, y)
return y, err
}
// StrictLoadChartfile loads a Chart.yaml into a *chart.Metadata using a strict unmarshaling
func StrictLoadChartfile(filename string) (*chart.Metadata, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
y := new(chart.Metadata)
err = yaml.UnmarshalStrict(b, y)
return y, err
}
// SaveChartfile saves the given metadata as a Chart.yaml file at the given path.
//
// 'filename' should be the complete path and filename ('foo/Chart.yaml')
func SaveChartfile(filename string, cf *chart.Metadata) error {
// Pull out the dependencies of a v1 Chart, since there's no way
// to tell the serializer to skip a field for just this use case
savedDependencies := cf.Dependencies
if cf.APIVersion == chart.APIVersionV1 {
cf.Dependencies = nil
}
out, err := yaml.Marshal(cf)
if cf.APIVersion == chart.APIVersionV1 {
cf.Dependencies = savedDependencies
}
if err != nil {
return err
}
return os.WriteFile(filename, out, 0644)
}
// IsChartDir validate a chart directory.
//
// Checks for a valid Chart.yaml.
func IsChartDir(dirName string) (bool, error) {
if fi, err := os.Stat(dirName); err != nil {
return false, err
} else if !fi.IsDir() {
return false, fmt.Errorf("%q is not a directory", dirName)
}
chartYaml := filepath.Join(dirName, ChartfileName)
if _, err := os.Stat(chartYaml); errors.Is(err, fs.ErrNotExist) {
return false, fmt.Errorf("no %s exists in directory %q", ChartfileName, dirName)
}
chartYamlContent, err := os.ReadFile(chartYaml)
if err != nil {
return false, fmt.Errorf("cannot read %s in directory %q", ChartfileName, dirName)
}
chartContent := new(chart.Metadata)
if err := yaml.Unmarshal(chartYamlContent, &chartContent); err != nil {
return false, err
}
if chartContent == nil {
return false, fmt.Errorf("chart metadata (%s) missing", ChartfileName)
}
if chartContent.Name == "" {
return false, fmt.Errorf("invalid chart (%s): name must not be empty", ChartfileName)
}
return true, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/validate_name_test.go | pkg/chart/v2/util/validate_name_test.go | /*
Copyright The Helm 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 util
import "testing"
// TestValidateReleaseName is a regression test for ValidateName
//
// Kubernetes has strict naming conventions for resource names. This test represents
// those conventions.
//
// See https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
//
// NOTE: At the time of this writing, the docs above say that names cannot begin with
// digits. However, `kubectl`'s regular expression explicit allows this, and
// Kubernetes (at least as of 1.18) also accepts resources whose names begin with digits.
func TestValidateReleaseName(t *testing.T) {
names := map[string]bool{
"": false,
"foo": true,
"foo.bar1234baz.seventyone": true,
"FOO": false,
"123baz": true,
"foo.BAR.baz": false,
"one-two": true,
"-two": false,
"one_two": false,
"a..b": false,
"%^&#$%*@^*@&#^": false,
"example:com": false,
"example%%com": false,
"a1111111111111111111111111111111111111111111111111111111111z": false,
}
for input, expectPass := range names {
if err := ValidateReleaseName(input); (err == nil) != expectPass {
st := "fail"
if expectPass {
st = "succeed"
}
t.Errorf("Expected %q to %s", input, st)
}
}
}
func TestValidateMetadataName(t *testing.T) {
names := map[string]bool{
"": false,
"foo": true,
"foo.bar1234baz.seventyone": true,
"FOO": false,
"123baz": true,
"foo.BAR.baz": false,
"one-two": true,
"-two": false,
"one_two": false,
"a..b": false,
"%^&#$%*@^*@&#^": false,
"example:com": false,
"example%%com": false,
"a1111111111111111111111111111111111111111111111111111111111z": true,
"a1111111111111111111111111111111111111111111111111111111111z" +
"a1111111111111111111111111111111111111111111111111111111111z" +
"a1111111111111111111111111111111111111111111111111111111111z" +
"a1111111111111111111111111111111111111111111111111111111111z" +
"a1111111111111111111111111111111111111111111111111111111111z" +
"a1111111111111111111111111111111111111111111111111111111111z": false,
}
for input, expectPass := range names {
if err := ValidateMetadataName(input); (err == nil) != expectPass {
st := "fail"
if expectPass {
st = "succeed"
}
t.Errorf("Expected %q to %s", input, st)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/compatible.go | pkg/chart/v2/util/compatible.go | /*
Copyright The Helm 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 util
import "github.com/Masterminds/semver/v3"
// IsCompatibleRange compares a version to a constraint.
// It returns true if the version matches the constraint, and false in all other cases.
func IsCompatibleRange(constraint, ver string) bool {
sv, err := semver.NewVersion(ver)
if err != nil {
return false
}
c, err := semver.NewConstraint(constraint)
if err != nil {
return false
}
return c.Check(sv)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/create_test.go | pkg/chart/v2/util/create_test.go | /*
Copyright The Helm 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 util
import (
"bytes"
"os"
"path/filepath"
"testing"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
func TestCreate(t *testing.T) {
tdir := t.TempDir()
c, err := Create("foo", tdir)
if err != nil {
t.Fatal(err)
}
dir := filepath.Join(tdir, "foo")
mychart, err := loader.LoadDir(c)
if err != nil {
t.Fatalf("Failed to load newly created chart %q: %s", c, err)
}
if mychart.Name() != "foo" {
t.Errorf("Expected name to be 'foo', got %q", mychart.Name())
}
for _, f := range []string{
ChartfileName,
DeploymentName,
HelpersName,
IgnorefileName,
NotesName,
ServiceAccountName,
ServiceName,
TemplatesDir,
TemplatesTestsDir,
TestConnectionName,
ValuesfileName,
} {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Errorf("Expected %s file: %s", f, err)
}
}
}
func TestCreateFrom(t *testing.T) {
tdir := t.TempDir()
cf := &chart.Metadata{
APIVersion: chart.APIVersionV1,
Name: "foo",
Version: "0.1.0",
}
srcdir := "./testdata/frobnitz/charts/mariner"
if err := CreateFrom(cf, tdir, srcdir); err != nil {
t.Fatal(err)
}
dir := filepath.Join(tdir, "foo")
c := filepath.Join(tdir, cf.Name)
mychart, err := loader.LoadDir(c)
if err != nil {
t.Fatalf("Failed to load newly created chart %q: %s", c, err)
}
if mychart.Name() != "foo" {
t.Errorf("Expected name to be 'foo', got %q", mychart.Name())
}
for _, f := range []string{
ChartfileName,
ValuesfileName,
filepath.Join(TemplatesDir, "placeholder.tpl"),
} {
if _, err := os.Stat(filepath.Join(dir, f)); err != nil {
t.Errorf("Expected %s file: %s", f, err)
}
// Check each file to make sure <CHARTNAME> has been replaced
b, err := os.ReadFile(filepath.Join(dir, f))
if err != nil {
t.Errorf("Unable to read file %s: %s", f, err)
}
if bytes.Contains(b, []byte("<CHARTNAME>")) {
t.Errorf("File %s contains <CHARTNAME>", f)
}
}
}
// TestCreate_Overwrite is a regression test for making sure that files are overwritten.
func TestCreate_Overwrite(t *testing.T) {
tdir := t.TempDir()
var errlog bytes.Buffer
if _, err := Create("foo", tdir); err != nil {
t.Fatal(err)
}
dir := filepath.Join(tdir, "foo")
tplname := filepath.Join(dir, "templates/hpa.yaml")
writeFile(tplname, []byte("FOO"))
// Now re-run the create
Stderr = &errlog
if _, err := Create("foo", tdir); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(tplname)
if err != nil {
t.Fatal(err)
}
if string(data) == "FOO" {
t.Fatal("File that should have been modified was not.")
}
if errlog.Len() == 0 {
t.Errorf("Expected warnings about overwriting files.")
}
}
func TestValidateChartName(t *testing.T) {
for name, shouldPass := range map[string]bool{
"": false,
"abcdefghijklmnopqrstuvwxyz-_.": true,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ-_.": true,
"$hello": false,
"Hellô": false,
"he%%o": false,
"he\nllo": false,
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"abcdefghijklmnopqrstuvwxyz-_." +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ-_.": false,
} {
if err := validateChartName(name); (err != nil) == shouldPass {
t.Errorf("test for %q failed", name)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/expand.go | pkg/chart/v2/util/expand.go | /*
Copyright The Helm 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 util
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
securejoin "github.com/cyphar/filepath-securejoin"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/chart/loader/archive"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// Expand uncompresses and extracts a chart into the specified directory.
func Expand(dir string, r io.Reader) error {
files, err := archive.LoadArchiveFiles(r)
if err != nil {
return err
}
// Get the name of the chart
var chartName string
for _, file := range files {
if file.Name == "Chart.yaml" {
ch := &chart.Metadata{}
if err := yaml.Unmarshal(file.Data, ch); err != nil {
return fmt.Errorf("cannot load Chart.yaml: %w", err)
}
chartName = ch.Name
}
}
if chartName == "" {
return errors.New("chart name not specified")
}
// Find the base directory
// The directory needs to be cleaned prior to passing to SecureJoin or the location may end up
// being wrong or returning an error. This was introduced in v0.4.0.
dir = filepath.Clean(dir)
chartdir, err := securejoin.SecureJoin(dir, chartName)
if err != nil {
return err
}
// Copy all files verbatim. We don't parse these files because parsing can remove
// comments.
for _, file := range files {
outpath, err := securejoin.SecureJoin(chartdir, file.Name)
if err != nil {
return err
}
// Make sure the necessary subdirs get created.
basedir := filepath.Dir(outpath)
if err := os.MkdirAll(basedir, 0755); err != nil {
return err
}
if err := os.WriteFile(outpath, file.Data, 0644); err != nil {
return err
}
}
return nil
}
// ExpandFile expands the src file into the dest directory.
func ExpandFile(dest, src string) error {
h, err := os.Open(src)
if err != nil {
return err
}
defer h.Close()
return Expand(dest, h)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/chartfile_test.go | pkg/chart/v2/util/chartfile_test.go | /*
Copyright The Helm 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 util
import (
"testing"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
const testfile = "testdata/chartfiletest.yaml"
func TestLoadChartfile(t *testing.T) {
f, err := LoadChartfile(testfile)
if err != nil {
t.Errorf("Failed to open %s: %s", testfile, err)
return
}
verifyChartfile(t, f, "frobnitz")
}
func verifyChartfile(t *testing.T, f *chart.Metadata, name string) {
t.Helper()
if f == nil { //nolint:staticcheck
t.Fatal("Failed verifyChartfile because f is nil")
}
if f.APIVersion != chart.APIVersionV1 { //nolint:staticcheck
t.Errorf("Expected API Version %q, got %q", chart.APIVersionV1, f.APIVersion)
}
if f.Name != name {
t.Errorf("Expected %s, got %s", name, f.Name)
}
if f.Description != "This is a frobnitz." {
t.Errorf("Unexpected description %q", f.Description)
}
if f.Version != "1.2.3" {
t.Errorf("Unexpected version %q", f.Version)
}
if len(f.Maintainers) != 2 {
t.Errorf("Expected 2 maintainers, got %d", len(f.Maintainers))
}
if f.Maintainers[0].Name != "The Helm Team" {
t.Errorf("Unexpected maintainer name.")
}
if f.Maintainers[1].Email != "nobody@example.com" {
t.Errorf("Unexpected maintainer email.")
}
if len(f.Sources) != 1 {
t.Fatalf("Unexpected number of sources")
}
if f.Sources[0] != "https://example.com/foo/bar" {
t.Errorf("Expected https://example.com/foo/bar, got %s", f.Sources)
}
if f.Home != "http://example.com" {
t.Error("Unexpected home.")
}
if f.Icon != "https://example.com/64x64.png" {
t.Errorf("Unexpected icon: %q", f.Icon)
}
if len(f.Keywords) != 3 {
t.Error("Unexpected keywords")
}
if len(f.Annotations) != 2 {
t.Fatalf("Unexpected annotations")
}
if want, got := "extravalue", f.Annotations["extrakey"]; want != got {
t.Errorf("Want %q, but got %q", want, got)
}
if want, got := "anothervalue", f.Annotations["anotherkey"]; want != got {
t.Errorf("Want %q, but got %q", want, got)
}
kk := []string{"frobnitz", "sprocket", "dodad"}
for i, k := range f.Keywords {
if kk[i] != k {
t.Errorf("Expected %q, got %q", kk[i], k)
}
}
}
func TestIsChartDir(t *testing.T) {
validChartDir, err := IsChartDir("testdata/frobnitz")
if !validChartDir {
t.Errorf("unexpected error while reading chart-directory: (%v)", err)
return
}
validChartDir, err = IsChartDir("testdata")
if validChartDir || err == nil {
t.Errorf("expected error but did not get any")
return
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/expand_test.go | pkg/chart/v2/util/expand_test.go | /*
Copyright The Helm 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 util
import (
"os"
"path/filepath"
"testing"
)
func TestExpand(t *testing.T) {
dest := t.TempDir()
reader, err := os.Open("testdata/frobnitz-1.2.3.tgz")
if err != nil {
t.Fatal(err)
}
if err := Expand(dest, reader); err != nil {
t.Fatal(err)
}
expectedChartPath := filepath.Join(dest, "frobnitz")
fi, err := os.Stat(expectedChartPath)
if err != nil {
t.Fatal(err)
}
if !fi.IsDir() {
t.Fatalf("expected a chart directory at %s", expectedChartPath)
}
dir, err := os.Open(expectedChartPath)
if err != nil {
t.Fatal(err)
}
fis, err := dir.Readdir(0)
if err != nil {
t.Fatal(err)
}
expectLen := 11
if len(fis) != expectLen {
t.Errorf("Expected %d files, but got %d", expectLen, len(fis))
}
for _, fi := range fis {
expect, err := os.Stat(filepath.Join("testdata", "frobnitz", fi.Name()))
if err != nil {
t.Fatal(err)
}
// os.Stat can return different values for directories, based on the OS
// for Linux, for example, os.Stat always returns the size of the directory
// (value-4096) regardless of the size of the contents of the directory
mode := expect.Mode()
if !mode.IsDir() {
if fi.Size() != expect.Size() {
t.Errorf("Expected %s to have size %d, got %d", fi.Name(), expect.Size(), fi.Size())
}
}
}
}
func TestExpandFile(t *testing.T) {
dest := t.TempDir()
if err := ExpandFile(dest, "testdata/frobnitz-1.2.3.tgz"); err != nil {
t.Fatal(err)
}
expectedChartPath := filepath.Join(dest, "frobnitz")
fi, err := os.Stat(expectedChartPath)
if err != nil {
t.Fatal(err)
}
if !fi.IsDir() {
t.Fatalf("expected a chart directory at %s", expectedChartPath)
}
dir, err := os.Open(expectedChartPath)
if err != nil {
t.Fatal(err)
}
fis, err := dir.Readdir(0)
if err != nil {
t.Fatal(err)
}
expectLen := 11
if len(fis) != expectLen {
t.Errorf("Expected %d files, but got %d", expectLen, len(fis))
}
for _, fi := range fis {
expect, err := os.Stat(filepath.Join("testdata", "frobnitz", fi.Name()))
if err != nil {
t.Fatal(err)
}
// os.Stat can return different values for directories, based on the OS
// for Linux, for example, os.Stat always returns the size of the directory
// (value-4096) regardless of the size of the contents of the directory
mode := expect.Mode()
if !mode.IsDir() {
if fi.Size() != expect.Size() {
t.Errorf("Expected %s to have size %d, got %d", fi.Name(), expect.Size(), fi.Size())
}
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/compatible_test.go | pkg/chart/v2/util/compatible_test.go | /*
Copyright The Helm 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 version represents the current version of the project.
package util
import "testing"
func TestIsCompatibleRange(t *testing.T) {
tests := []struct {
constraint string
ver string
expected bool
}{
{"v2.0.0-alpha.4", "v2.0.0-alpha.4", true},
{"v2.0.0-alpha.3", "v2.0.0-alpha.4", false},
{"v2.0.0", "v2.0.0-alpha.4", false},
{"v2.0.0-alpha.4", "v2.0.0", false},
{"~v2.0.0", "v2.0.1", true},
{"v2", "v2.0.0", true},
{">2.0.0", "v2.1.1", true},
{"v2.1.*", "v2.1.1", true},
}
for _, tt := range tests {
if IsCompatibleRange(tt.constraint, tt.ver) != tt.expected {
t.Errorf("expected constraint %s to be %v for %s", tt.constraint, tt.expected, tt.ver)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/save_test.go | pkg/chart/v2/util/save_test.go | /*
Copyright The Helm 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 util
import (
"archive/tar"
"bytes"
"compress/gzip"
"crypto/sha256"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
func TestSave(t *testing.T) {
tmp := t.TempDir()
for _, dest := range []string{tmp, filepath.Join(tmp, "newdir")} {
t.Run("outDir="+dest, func(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV1,
Name: "ahab",
Version: "1.2.3",
},
Lock: &chart.Lock{
Digest: "testdigest",
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: time.Now(), Data: []byte("1,001 Nights")},
},
Schema: []byte("{\n \"title\": \"Values\"\n}"),
}
chartWithInvalidJSON := withSchema(*c, []byte("{"))
where, err := Save(c, dest)
if err != nil {
t.Fatalf("Failed to save: %s", err)
}
if !strings.HasPrefix(where, dest) {
t.Fatalf("Expected %q to start with %q", where, dest)
}
if !strings.HasSuffix(where, ".tgz") {
t.Fatalf("Expected %q to end with .tgz", where)
}
c2, err := loader.LoadFile(where)
if err != nil {
t.Fatal(err)
}
if c2.Name() != c.Name() {
t.Fatalf("Expected chart archive to have %q, got %q", c.Name(), c2.Name())
}
if len(c2.Files) != 1 || c2.Files[0].Name != "scheherazade/shahryar.txt" {
t.Fatal("Files data did not match")
}
if c2.Lock != nil {
t.Fatal("Expected v1 chart archive not to contain Chart.lock file")
}
if !bytes.Equal(c.Schema, c2.Schema) {
indentation := 4
formattedExpected := Indent(indentation, string(c.Schema))
formattedActual := Indent(indentation, string(c2.Schema))
t.Fatalf("Schema data did not match.\nExpected:\n%s\nActual:\n%s", formattedExpected, formattedActual)
}
if _, err := Save(&chartWithInvalidJSON, dest); err == nil {
t.Fatalf("Invalid JSON was not caught while saving chart")
}
c.Metadata.APIVersion = chart.APIVersionV2
where, err = Save(c, dest)
if err != nil {
t.Fatalf("Failed to save: %s", err)
}
c2, err = loader.LoadFile(where)
if err != nil {
t.Fatal(err)
}
if c2.Lock == nil {
t.Fatal("Expected v2 chart archive to contain a Chart.lock file")
}
if c2.Lock.Digest != c.Lock.Digest {
t.Fatal("Chart.lock data did not match")
}
})
}
c := &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV1,
Name: "../ahab",
Version: "1.2.3",
},
Lock: &chart.Lock{
Digest: "testdigest",
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: time.Now(), Data: []byte("1,001 Nights")},
},
}
_, err := Save(c, tmp)
if err == nil {
t.Fatal("Expected error saving chart with invalid name")
}
}
// Creates a copy with a different schema; does not modify anything.
func withSchema(chart chart.Chart, schema []byte) chart.Chart {
chart.Schema = schema
return chart
}
func Indent(n int, text string) string {
startOfLine := regexp.MustCompile(`(?m)^`)
indentation := strings.Repeat(" ", n)
return startOfLine.ReplaceAllLiteralString(text, indentation)
}
func TestSavePreservesTimestamps(t *testing.T) {
// Test executes so quickly that if we don't subtract a second, the
// check will fail because `initialCreateTime` will be identical to the
// written timestamp for the files.
initialCreateTime := time.Now().Add(-1 * time.Second)
tmp := t.TempDir()
c := &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV1,
Name: "ahab",
Version: "1.2.3",
},
ModTime: initialCreateTime,
Values: map[string]interface{}{
"imageName": "testimage",
"imageId": 42,
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: initialCreateTime, Data: []byte("1,001 Nights")},
},
Schema: []byte("{\n \"title\": \"Values\"\n}"),
SchemaModTime: initialCreateTime,
}
where, err := Save(c, tmp)
if err != nil {
t.Fatalf("Failed to save: %s", err)
}
allHeaders, err := retrieveAllHeadersFromTar(where)
if err != nil {
t.Fatalf("Failed to parse tar: %v", err)
}
roundedTime := initialCreateTime.Round(time.Second)
for _, header := range allHeaders {
if !header.ModTime.Equal(roundedTime) {
t.Fatalf("File timestamp not preserved: %v", header.ModTime)
}
}
}
// We could refactor `load.go` to use this `retrieveAllHeadersFromTar` function
// as well, so we are not duplicating components of the code which iterate
// through the tar.
func retrieveAllHeadersFromTar(path string) ([]*tar.Header, error) {
raw, err := os.Open(path)
if err != nil {
return nil, err
}
defer raw.Close()
unzipped, err := gzip.NewReader(raw)
if err != nil {
return nil, err
}
defer unzipped.Close()
tr := tar.NewReader(unzipped)
headers := []*tar.Header{}
for {
hd, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
headers = append(headers, hd)
}
return headers, nil
}
func TestSaveDir(t *testing.T) {
tmp := t.TempDir()
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV1,
Name: "ahab",
Version: "1.2.3",
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: modTime, Data: []byte("1,001 Nights")},
},
Templates: []*common.File{
{Name: path.Join(TemplatesDir, "nested", "dir", "thing.yaml"), ModTime: modTime, Data: []byte("abc: {{ .Values.abc }}")},
},
}
if err := SaveDir(c, tmp); err != nil {
t.Fatalf("Failed to save: %s", err)
}
c2, err := loader.LoadDir(tmp + "/ahab")
if err != nil {
t.Fatal(err)
}
if c2.Name() != c.Name() {
t.Fatalf("Expected chart archive to have %q, got %q", c.Name(), c2.Name())
}
if len(c2.Templates) != 1 || c2.Templates[0].Name != c.Templates[0].Name {
t.Fatal("Templates data did not match")
}
if len(c2.Files) != 1 || c2.Files[0].Name != c.Files[0].Name {
t.Fatal("Files data did not match")
}
tmp2 := t.TempDir()
c.Metadata.Name = "../ahab"
pth := filepath.Join(tmp2, "tmpcharts")
if err := os.MkdirAll(filepath.Join(pth), 0755); err != nil {
t.Fatal(err)
}
if err := SaveDir(c, pth); err.Error() != "\"../ahab\" is not a valid chart name" {
t.Fatalf("Did not get expected error for chart named %q", c.Name())
}
}
func TestRepeatableSave(t *testing.T) {
tmp := t.TempDir()
defer os.RemoveAll(tmp)
modTime := time.Date(2021, 9, 1, 20, 34, 58, 651387237, time.UTC)
tests := []struct {
name string
chart *chart.Chart
want string
}{
{
name: "Package 1 file",
chart: &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV2,
Name: "ahab",
Version: "1.2.3",
},
ModTime: modTime,
Lock: &chart.Lock{
Digest: "testdigest",
Generated: modTime,
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: modTime, Data: []byte("1,001 Nights")},
},
Schema: []byte("{\n \"title\": \"Values\"\n}"),
SchemaModTime: modTime,
},
want: "fea2662522317b65c2788ff9e5fc446a9264830038dac618d4449493d99b3257",
},
{
name: "Package 2 files",
chart: &chart.Chart{
Metadata: &chart.Metadata{
APIVersion: chart.APIVersionV2,
Name: "ahab",
Version: "1.2.3",
},
ModTime: modTime,
Lock: &chart.Lock{
Digest: "testdigest",
Generated: modTime,
},
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: modTime, Data: []byte("1,001 Nights")},
{Name: "scheherazade/dunyazad.txt", ModTime: modTime, Data: []byte("1,001 Nights again")},
},
Schema: []byte("{\n \"title\": \"Values\"\n}"),
SchemaModTime: modTime,
},
want: "7ae92b2f274bb51ea3f1969e4187d78cc52b5f6f663b44b8fb3b40bcb8ee46f3",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// create package
dest := path.Join(tmp, "newdir")
where, err := Save(test.chart, dest)
if err != nil {
t.Fatalf("Failed to save: %s", err)
}
// get shasum for package
result, err := sha256Sum(where)
if err != nil {
t.Fatalf("Failed to check shasum: %s", err)
}
// assert that the package SHA is what we wanted.
if result != test.want {
t.Errorf("FormatName() result = %v, want %v", result, test.want)
}
})
}
}
func sha256Sum(filePath string) (string, error) {
f, err := os.Open(filePath)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/doc.go | pkg/chart/v2/util/doc.go | /*
Copyright The Helm 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 util contains tools for working with charts.
Charts are described in the chart package (pkg/chart).
This package provides utilities for serializing and deserializing charts.
A chart can be represented on the file system in one of two ways:
- As a directory that contains a Chart.yaml file and other chart things.
- As a tarred gzipped file containing a directory that then contains a
Chart.yaml file.
This package provides utilities for working with those file formats.
The preferred way of loading a chart is using 'loader.Load`:
chart, err := loader.Load(filename)
This will attempt to discover whether the file at 'filename' is a directory or
a chart archive. It will then load accordingly.
For accepting raw compressed tar file data from an io.Reader, the
'loader.LoadArchive()' will read in the data, uncompress it, and unpack it
into a Chart.
When creating charts in memory, use the 'helm.sh/helm/pkg/chart'
package directly.
*/
package util // import chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/dependencies_test.go | pkg/chart/v2/util/dependencies_test.go | /*
Copyright The Helm 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 util
import (
"os"
"path/filepath"
"sort"
"strconv"
"testing"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
func loadChart(t *testing.T, path string) *chart.Chart {
t.Helper()
c, err := loader.Load(path)
if err != nil {
t.Fatalf("failed to load testdata: %s", err)
}
return c
}
func TestLoadDependency(t *testing.T) {
tests := []*chart.Dependency{
{Name: "alpine", Version: "0.1.0", Repository: "https://example.com/charts"},
{Name: "mariner", Version: "4.3.2", Repository: "https://example.com/charts"},
}
check := func(deps []*chart.Dependency) {
if len(deps) != 2 {
t.Errorf("expected 2 dependencies, got %d", len(deps))
}
for i, tt := range tests {
if deps[i].Name != tt.Name {
t.Errorf("expected dependency named %q, got %q", tt.Name, deps[i].Name)
}
if deps[i].Version != tt.Version {
t.Errorf("expected dependency named %q to have version %q, got %q", tt.Name, tt.Version, deps[i].Version)
}
if deps[i].Repository != tt.Repository {
t.Errorf("expected dependency named %q to have repository %q, got %q", tt.Name, tt.Repository, deps[i].Repository)
}
}
}
c := loadChart(t, "testdata/frobnitz")
check(c.Metadata.Dependencies)
check(c.Lock.Dependencies)
}
func TestDependencyEnabled(t *testing.T) {
type M = map[string]interface{}
tests := []struct {
name string
v M
e []string // expected charts including duplicates in alphanumeric order
}{{
"tags with no effect",
M{"tags": M{"nothinguseful": false}},
[]string{"parentchart", "parentchart.subchart1", "parentchart.subchart1.subcharta", "parentchart.subchart1.subchartb"},
}, {
"tags disabling a group",
M{"tags": M{"front-end": false}},
[]string{"parentchart"},
}, {
"tags disabling a group and enabling a different group",
M{"tags": M{"front-end": false, "back-end": true}},
[]string{"parentchart", "parentchart.subchart2", "parentchart.subchart2.subchartb", "parentchart.subchart2.subchartc"},
}, {
"tags disabling only children, children still enabled since tag front-end=true in values.yaml",
M{"tags": M{"subcharta": false, "subchartb": false}},
[]string{"parentchart", "parentchart.subchart1", "parentchart.subchart1.subcharta", "parentchart.subchart1.subchartb"},
}, {
"tags disabling all parents/children with additional tag re-enabling a parent",
M{"tags": M{"front-end": false, "subchart1": true, "back-end": false}},
[]string{"parentchart", "parentchart.subchart1"},
}, {
"conditions enabling the parent charts, but back-end (b, c) is still disabled via values.yaml",
M{"subchart1": M{"enabled": true}, "subchart2": M{"enabled": true}},
[]string{"parentchart", "parentchart.subchart1", "parentchart.subchart1.subcharta", "parentchart.subchart1.subchartb", "parentchart.subchart2"},
}, {
"conditions disabling the parent charts, effectively disabling children",
M{"subchart1": M{"enabled": false}, "subchart2": M{"enabled": false}},
[]string{"parentchart"},
}, {
"conditions a child using the second condition path of child's condition",
M{"subchart1": M{"subcharta": M{"enabled": false}}},
[]string{"parentchart", "parentchart.subchart1", "parentchart.subchart1.subchartb"},
}, {
"tags enabling a parent/child group with condition disabling one child",
M{"subchart2": M{"subchartc": M{"enabled": false}}, "tags": M{"back-end": true}},
[]string{"parentchart", "parentchart.subchart1", "parentchart.subchart1.subcharta", "parentchart.subchart1.subchartb", "parentchart.subchart2", "parentchart.subchart2.subchartb"},
}, {
"tags will not enable a child if parent is explicitly disabled with condition",
M{"subchart1": M{"enabled": false}, "tags": M{"front-end": true}},
[]string{"parentchart"},
}, {
"subcharts with alias also respect conditions",
M{"subchart1": M{"enabled": false}, "subchart2alias": M{"enabled": true, "subchartb": M{"enabled": true}}},
[]string{"parentchart", "parentchart.subchart2alias", "parentchart.subchart2alias.subchartb"},
}}
for _, tc := range tests {
c := loadChart(t, "testdata/subpop")
t.Run(tc.name, func(t *testing.T) {
if err := processDependencyEnabled(c, tc.v, ""); err != nil {
t.Fatalf("error processing enabled dependencies %v", err)
}
names := extractChartNames(c)
if len(names) != len(tc.e) {
t.Fatalf("slice lengths do not match got %v, expected %v", len(names), len(tc.e))
}
for i := range names {
if names[i] != tc.e[i] {
t.Fatalf("slice values do not match got %v, expected %v", names, tc.e)
}
}
})
}
}
// extractChartNames recursively searches chart dependencies returning all charts found
func extractChartNames(c *chart.Chart) []string {
var out []string
var fn func(c *chart.Chart)
fn = func(c *chart.Chart) {
out = append(out, c.ChartPath())
for _, d := range c.Dependencies() {
fn(d)
}
}
fn(c)
sort.Strings(out)
return out
}
func TestProcessDependencyImportValues(t *testing.T) {
c := loadChart(t, "testdata/subpop")
e := make(map[string]string)
e["imported-chart1.SC1bool"] = "true"
e["imported-chart1.SC1float"] = "3.14"
e["imported-chart1.SC1int"] = "100"
e["imported-chart1.SC1string"] = "dollywood"
e["imported-chart1.SC1extra1"] = "11"
e["imported-chart1.SPextra1"] = "helm rocks"
e["imported-chart1.SC1extra1"] = "11"
e["imported-chartA.SCAbool"] = "false"
e["imported-chartA.SCAfloat"] = "3.1"
e["imported-chartA.SCAint"] = "55"
e["imported-chartA.SCAstring"] = "jabba"
e["imported-chartA.SPextra3"] = "1.337"
e["imported-chartA.SC1extra2"] = "1.337"
e["imported-chartA.SCAnested1.SCAnested2"] = "true"
e["imported-chartA-B.SCAbool"] = "false"
e["imported-chartA-B.SCAfloat"] = "3.1"
e["imported-chartA-B.SCAint"] = "55"
e["imported-chartA-B.SCAstring"] = "jabba"
e["imported-chartA-B.SCBbool"] = "true"
e["imported-chartA-B.SCBfloat"] = "7.77"
e["imported-chartA-B.SCBint"] = "33"
e["imported-chartA-B.SCBstring"] = "boba"
e["imported-chartA-B.SPextra5"] = "k8s"
e["imported-chartA-B.SC1extra5"] = "tiller"
// These values are imported from the child chart to the parent. Parent
// values take precedence over imported values. This enables importing a
// large section from a child chart and overriding a selection from it.
e["overridden-chart1.SC1bool"] = "false"
e["overridden-chart1.SC1float"] = "3.141592"
e["overridden-chart1.SC1int"] = "99"
e["overridden-chart1.SC1string"] = "pollywog"
e["overridden-chart1.SPextra2"] = "42"
e["overridden-chartA.SCAbool"] = "true"
e["overridden-chartA.SCAfloat"] = "41.3"
e["overridden-chartA.SCAint"] = "808"
e["overridden-chartA.SCAstring"] = "jabberwocky"
e["overridden-chartA.SPextra4"] = "true"
// These values are imported from the child chart to the parent. Parent
// values take precedence over imported values. This enables importing a
// large section from a child chart and overriding a selection from it.
e["overridden-chartA-B.SCAbool"] = "true"
e["overridden-chartA-B.SCAfloat"] = "41.3"
e["overridden-chartA-B.SCAint"] = "808"
e["overridden-chartA-B.SCAstring"] = "jabberwocky"
e["overridden-chartA-B.SCBbool"] = "false"
e["overridden-chartA-B.SCBfloat"] = "1.99"
e["overridden-chartA-B.SCBint"] = "77"
e["overridden-chartA-B.SCBstring"] = "jango"
e["overridden-chartA-B.SPextra6"] = "111"
e["overridden-chartA-B.SCAextra1"] = "23"
e["overridden-chartA-B.SCBextra1"] = "13"
e["overridden-chartA-B.SC1extra6"] = "77"
// `exports` style
e["SCBexported1B"] = "1965"
e["SC1extra7"] = "true"
e["SCBexported2A"] = "blaster"
e["global.SC1exported2.all.SC1exported3"] = "SC1expstr"
if err := processDependencyImportValues(c, false); err != nil {
t.Fatalf("processing import values dependencies %v", err)
}
cc := common.Values(c.Values)
for kk, vv := range e {
pv, err := cc.PathValue(kk)
if err != nil {
t.Fatalf("retrieving import values table %v %v", kk, err)
}
switch pv := pv.(type) {
case float64:
if s := strconv.FormatFloat(pv, 'f', -1, 64); s != vv {
t.Errorf("failed to match imported float value %v with expected %v for key %q", s, vv, kk)
}
case bool:
if b := strconv.FormatBool(pv); b != vv {
t.Errorf("failed to match imported bool value %v with expected %v for key %q", b, vv, kk)
}
default:
if pv != vv {
t.Errorf("failed to match imported string value %q with expected %q for key %q", pv, vv, kk)
}
}
}
// Since this was processed with coalescing there should be no null values.
// Here we verify that.
_, err := cc.PathValue("ensurenull")
if err == nil {
t.Error("expect nil value not found but found it")
}
switch xerr := err.(type) {
case common.ErrNoValue:
// We found what we expected
default:
t.Errorf("expected an ErrNoValue but got %q instead", xerr)
}
c = loadChart(t, "testdata/subpop")
if err := processDependencyImportValues(c, true); err != nil {
t.Fatalf("processing import values dependencies %v", err)
}
cc = common.Values(c.Values)
val, err := cc.PathValue("ensurenull")
if err != nil {
t.Error("expect value but ensurenull was not found")
}
if val != nil {
t.Errorf("expect nil value but got %q instead", val)
}
}
func TestProcessDependencyImportValuesFromSharedDependencyToAliases(t *testing.T) {
c := loadChart(t, "testdata/chart-with-import-from-aliased-dependencies")
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if err := processDependencyImportValues(c, true); err != nil {
t.Fatalf("processing import values dependencies %v", err)
}
e := make(map[string]string)
e["foo-defaults.defaultValue"] = "42"
e["bar-defaults.defaultValue"] = "42"
e["foo.defaults.defaultValue"] = "42"
e["bar.defaults.defaultValue"] = "42"
e["foo.grandchild.defaults.defaultValue"] = "42"
e["bar.grandchild.defaults.defaultValue"] = "42"
cValues := common.Values(c.Values)
for kk, vv := range e {
pv, err := cValues.PathValue(kk)
if err != nil {
t.Fatalf("retrieving import values table %v %v", kk, err)
}
if pv != vv {
t.Errorf("failed to match imported value %v with expected %v", pv, vv)
}
}
}
func TestProcessDependencyImportValuesMultiLevelPrecedence(t *testing.T) {
c := loadChart(t, "testdata/three-level-dependent-chart/umbrella")
e := make(map[string]string)
// The order of precedence should be:
// 1. User specified values (e.g CLI)
// 2. Parent chart values
// 3. Imported values
// 4. Sub-chart values
// The 4 app charts here deal with things differently:
// - app1 has a port value set in the umbrella chart. It does not import any
// values so the value from the umbrella chart should be used.
// - app2 has a value in the app chart and imports from the library. The
// app chart value should take precedence.
// - app3 has no value in the app chart and imports the value from the library
// chart. The library chart value should be used.
// - app4 has a value in the app chart and does not import the value from the
// library chart. The app charts value should be used.
e["app1.service.port"] = "3456"
e["app2.service.port"] = "8080"
e["app3.service.port"] = "9090"
e["app4.service.port"] = "1234"
if err := processDependencyImportValues(c, true); err != nil {
t.Fatalf("processing import values dependencies %v", err)
}
cc := common.Values(c.Values)
for kk, vv := range e {
pv, err := cc.PathValue(kk)
if err != nil {
t.Fatalf("retrieving import values table %v %v", kk, err)
}
switch pv := pv.(type) {
case float64:
if s := strconv.FormatFloat(pv, 'f', -1, 64); s != vv {
t.Errorf("failed to match imported float value %v with expected %v", s, vv)
}
default:
if pv != vv {
t.Errorf("failed to match imported string value %q with expected %q", pv, vv)
}
}
}
}
func TestProcessDependencyImportValuesForEnabledCharts(t *testing.T) {
c := loadChart(t, "testdata/import-values-from-enabled-subchart/parent-chart")
nameOverride := "parent-chart-prod"
if err := processDependencyImportValues(c, true); err != nil {
t.Fatalf("processing import values dependencies %v", err)
}
if len(c.Dependencies()) != 2 {
t.Fatalf("expected 2 dependencies for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 1 {
t.Fatal("expected no changes in dependencies")
}
if len(c.Metadata.Dependencies) != 1 {
t.Fatalf("expected 1 dependency specified in Chart.yaml, got %d", len(c.Metadata.Dependencies))
}
prodDependencyValues := c.Dependencies()[0].Values
if prodDependencyValues["nameOverride"] != nameOverride {
t.Fatalf("dependency chart name should be %s but got %s", nameOverride, prodDependencyValues["nameOverride"])
}
}
func TestGetAliasDependency(t *testing.T) {
c := loadChart(t, "testdata/frobnitz")
req := c.Metadata.Dependencies
if len(req) == 0 {
t.Fatalf("there are no dependencies to test")
}
// Success case
aliasChart := getAliasDependency(c.Dependencies(), req[0])
if aliasChart == nil {
t.Fatalf("failed to get dependency chart for alias %s", req[0].Name)
}
if req[0].Alias != "" {
if aliasChart.Name() != req[0].Alias {
t.Fatalf("dependency chart name should be %s but got %s", req[0].Alias, aliasChart.Name())
}
} else if aliasChart.Name() != req[0].Name {
t.Fatalf("dependency chart name should be %s but got %s", req[0].Name, aliasChart.Name())
}
if req[0].Version != "" {
if !IsCompatibleRange(req[0].Version, aliasChart.Metadata.Version) {
t.Fatalf("dependency chart version is not in the compatible range")
}
}
// Failure case
req[0].Name = "something-else"
if aliasChart := getAliasDependency(c.Dependencies(), req[0]); aliasChart != nil {
t.Fatalf("expected no chart but got %s", aliasChart.Name())
}
req[0].Version = "something else which is not in the compatible range"
if IsCompatibleRange(req[0].Version, aliasChart.Metadata.Version) {
t.Fatalf("dependency chart version which is not in the compatible range should cause a failure other than a success ")
}
}
func TestDependentChartAliases(t *testing.T) {
c := loadChart(t, "testdata/dependent-chart-alias")
req := c.Metadata.Dependencies
if len(c.Dependencies()) != 2 {
t.Fatalf("expected 2 dependencies for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 3 {
t.Fatal("expected alias dependencies to be added")
}
if len(c.Dependencies()) != len(c.Metadata.Dependencies) {
t.Fatalf("expected number of chart dependencies %d, but got %d", len(c.Metadata.Dependencies), len(c.Dependencies()))
}
aliasChart := getAliasDependency(c.Dependencies(), req[2])
if aliasChart == nil {
t.Fatalf("failed to get dependency chart for alias %s", req[2].Name)
}
if aliasChart.Parent() != c {
t.Fatalf("dependency chart has wrong parent, expected %s but got %s", c.Name(), aliasChart.Parent().Name())
}
if req[2].Alias != "" {
if aliasChart.Name() != req[2].Alias {
t.Fatalf("dependency chart name should be %s but got %s", req[2].Alias, aliasChart.Name())
}
} else if aliasChart.Name() != req[2].Name {
t.Fatalf("dependency chart name should be %s but got %s", req[2].Name, aliasChart.Name())
}
req[2].Name = "dummy-name"
if aliasChart := getAliasDependency(c.Dependencies(), req[2]); aliasChart != nil {
t.Fatalf("expected no chart but got %s", aliasChart.Name())
}
}
func TestDependentChartWithSubChartsAbsentInDependency(t *testing.T) {
c := loadChart(t, "testdata/dependent-chart-no-requirements-yaml")
if len(c.Dependencies()) != 2 {
t.Fatalf("expected 2 dependencies for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 2 {
t.Fatal("expected no changes in dependencies")
}
}
func TestDependentChartWithSubChartsHelmignore(t *testing.T) {
// FIXME what does this test?
loadChart(t, "testdata/dependent-chart-helmignore")
}
func TestDependentChartsWithSubChartsSymlink(t *testing.T) {
joonix := filepath.Join("testdata", "joonix")
if err := os.Symlink(filepath.Join("..", "..", "frobnitz"), filepath.Join(joonix, "charts", "frobnitz")); err != nil {
t.Fatal(err)
}
defer os.RemoveAll(filepath.Join(joonix, "charts", "frobnitz"))
c := loadChart(t, joonix)
if c.Name() != "joonix" {
t.Fatalf("unexpected chart name: %s", c.Name())
}
if n := len(c.Dependencies()); n != 1 {
t.Fatalf("expected 1 dependency for this chart, but got %d", n)
}
}
func TestDependentChartsWithSubchartsAllSpecifiedInDependency(t *testing.T) {
c := loadChart(t, "testdata/dependent-chart-with-all-in-requirements-yaml")
if len(c.Dependencies()) != 2 {
t.Fatalf("expected 2 dependencies for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 2 {
t.Fatal("expected no changes in dependencies")
}
if len(c.Dependencies()) != len(c.Metadata.Dependencies) {
t.Fatalf("expected number of chart dependencies %d, but got %d", len(c.Metadata.Dependencies), len(c.Dependencies()))
}
}
func TestDependentChartsWithSomeSubchartsSpecifiedInDependency(t *testing.T) {
c := loadChart(t, "testdata/dependent-chart-with-mixed-requirements-yaml")
if len(c.Dependencies()) != 2 {
t.Fatalf("expected 2 dependencies for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 2 {
t.Fatal("expected no changes in dependencies")
}
if len(c.Metadata.Dependencies) != 1 {
t.Fatalf("expected 1 dependency specified in Chart.yaml, got %d", len(c.Metadata.Dependencies))
}
}
func validateDependencyTree(t *testing.T, c *chart.Chart) {
t.Helper()
for _, dependency := range c.Dependencies() {
if dependency.Parent() != c {
if dependency.Parent() != c {
t.Fatalf("dependency chart %s has wrong parent, expected %s but got %s", dependency.Name(), c.Name(), dependency.Parent().Name())
}
}
// recurse entire tree
validateDependencyTree(t, dependency)
}
}
func TestChartWithDependencyAliasedTwiceAndDoublyReferencedSubDependency(t *testing.T) {
c := loadChart(t, "testdata/chart-with-dependency-aliased-twice")
if len(c.Dependencies()) != 1 {
t.Fatalf("expected one dependency for this chart, but got %d", len(c.Dependencies()))
}
if err := processDependencyEnabled(c, c.Values, ""); err != nil {
t.Fatalf("expected no errors but got %q", err)
}
if len(c.Dependencies()) != 2 {
t.Fatal("expected two dependencies after processing aliases")
}
validateDependencyTree(t, c)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/dependencies.go | pkg/chart/v2/util/dependencies.go | /*
Copyright The Helm 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 util
import (
"fmt"
"log/slog"
"strings"
"helm.sh/helm/v4/internal/copystructure"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/common/util"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// ProcessDependencies checks through this chart's dependencies, processing accordingly.
func ProcessDependencies(c *chart.Chart, v common.Values) error {
if err := processDependencyEnabled(c, v, ""); err != nil {
return err
}
return processDependencyImportValues(c, true)
}
// processDependencyConditions disables charts based on condition path value in values
func processDependencyConditions(reqs []*chart.Dependency, cvals common.Values, cpath string) {
if reqs == nil {
return
}
for _, r := range reqs {
for c := range strings.SplitSeq(strings.TrimSpace(r.Condition), ",") {
if len(c) > 0 {
// retrieve value
vv, err := cvals.PathValue(cpath + c)
if err == nil {
// if not bool, warn
if bv, ok := vv.(bool); ok {
r.Enabled = bv
break
}
slog.Warn("returned non-bool value", "path", c, "chart", r.Name)
} else if _, ok := err.(common.ErrNoValue); !ok {
// this is a real error
slog.Warn("the method PathValue returned error", slog.Any("error", err))
}
}
}
}
}
// processDependencyTags disables charts based on tags in values
func processDependencyTags(reqs []*chart.Dependency, cvals common.Values) {
if reqs == nil {
return
}
vt, err := cvals.Table("tags")
if err != nil {
return
}
for _, r := range reqs {
var hasTrue, hasFalse bool
for _, k := range r.Tags {
if b, ok := vt[k]; ok {
// if not bool, warn
if bv, ok := b.(bool); ok {
if bv {
hasTrue = true
} else {
hasFalse = true
}
} else {
slog.Warn("returned non-bool value", "tag", k, "chart", r.Name)
}
}
}
if !hasTrue && hasFalse {
r.Enabled = false
} else if hasTrue || !hasTrue && !hasFalse {
r.Enabled = true
}
}
}
// getAliasDependency finds the chart for an alias dependency and copies parts that will be modified
func getAliasDependency(charts []*chart.Chart, dep *chart.Dependency) *chart.Chart {
for _, c := range charts {
if c == nil {
continue
}
if c.Name() != dep.Name {
continue
}
if !IsCompatibleRange(dep.Version, c.Metadata.Version) {
continue
}
out := *c
out.Metadata = copyMetadata(c.Metadata)
// empty dependencies and shallow copy all dependencies, otherwise parent info may be corrupted if
// there is more than one dependency aliasing this chart
out.SetDependencies()
for _, dependency := range c.Dependencies() {
cpy := *dependency
out.AddDependency(&cpy)
}
if dep.Alias != "" {
out.Metadata.Name = dep.Alias
}
return &out
}
return nil
}
func copyMetadata(metadata *chart.Metadata) *chart.Metadata {
md := *metadata
if md.Dependencies != nil {
dependencies := make([]*chart.Dependency, len(md.Dependencies))
for i := range md.Dependencies {
dependency := *md.Dependencies[i]
dependencies[i] = &dependency
}
md.Dependencies = dependencies
}
return &md
}
// processDependencyEnabled removes disabled charts from dependencies
func processDependencyEnabled(c *chart.Chart, v map[string]interface{}, path string) error {
if c.Metadata.Dependencies == nil {
return nil
}
var chartDependencies []*chart.Chart
// If any dependency is not a part of Chart.yaml
// then this should be added to chartDependencies.
// However, if the dependency is already specified in Chart.yaml
// we should not add it, as it would be processed from Chart.yaml anyway.
Loop:
for _, existing := range c.Dependencies() {
for _, req := range c.Metadata.Dependencies {
if existing.Name() == req.Name && IsCompatibleRange(req.Version, existing.Metadata.Version) {
continue Loop
}
}
chartDependencies = append(chartDependencies, existing)
}
for _, req := range c.Metadata.Dependencies {
if req == nil {
continue
}
if chartDependency := getAliasDependency(c.Dependencies(), req); chartDependency != nil {
chartDependencies = append(chartDependencies, chartDependency)
}
if req.Alias != "" {
req.Name = req.Alias
}
}
c.SetDependencies(chartDependencies...)
// set all to true
for _, lr := range c.Metadata.Dependencies {
lr.Enabled = true
}
cvals, err := util.CoalesceValues(c, v)
if err != nil {
return err
}
// flag dependencies as enabled/disabled
processDependencyTags(c.Metadata.Dependencies, cvals)
processDependencyConditions(c.Metadata.Dependencies, cvals, path)
// make a map of charts to remove
rm := map[string]struct{}{}
for _, r := range c.Metadata.Dependencies {
if !r.Enabled {
// remove disabled chart
rm[r.Name] = struct{}{}
}
}
// don't keep disabled charts in new slice
cd := []*chart.Chart{}
copy(cd, c.Dependencies()[:0])
for _, n := range c.Dependencies() {
if _, ok := rm[n.Metadata.Name]; !ok {
cd = append(cd, n)
}
}
// don't keep disabled charts in metadata
cdMetadata := []*chart.Dependency{}
copy(cdMetadata, c.Metadata.Dependencies[:0])
for _, n := range c.Metadata.Dependencies {
if _, ok := rm[n.Name]; !ok {
cdMetadata = append(cdMetadata, n)
}
}
// recursively call self to process sub dependencies
for _, t := range cd {
subpath := path + t.Metadata.Name + "."
if err := processDependencyEnabled(t, cvals, subpath); err != nil {
return err
}
}
// set the correct dependencies in metadata
c.Metadata.Dependencies = nil
c.Metadata.Dependencies = append(c.Metadata.Dependencies, cdMetadata...)
c.SetDependencies(cd...)
return nil
}
// pathToMap creates a nested map given a YAML path in dot notation.
func pathToMap(path string, data map[string]interface{}) map[string]interface{} {
if path == "." {
return data
}
return set(parsePath(path), data)
}
func parsePath(key string) []string { return strings.Split(key, ".") }
func set(path []string, data map[string]interface{}) map[string]interface{} {
if len(path) == 0 {
return nil
}
cur := data
for i := len(path) - 1; i >= 0; i-- {
cur = map[string]interface{}{path[i]: cur}
}
return cur
}
// processImportValues merges values from child to parent based on the chart's dependencies' ImportValues field.
func processImportValues(c *chart.Chart, merge bool) error {
if c.Metadata.Dependencies == nil {
return nil
}
// combine chart values and empty config to get Values
var cvals common.Values
var err error
if merge {
cvals, err = util.MergeValues(c, nil)
} else {
cvals, err = util.CoalesceValues(c, nil)
}
if err != nil {
return err
}
b := make(map[string]interface{})
// import values from each dependency if specified in import-values
for _, r := range c.Metadata.Dependencies {
var outiv []interface{}
for _, riv := range r.ImportValues {
switch iv := riv.(type) {
case map[string]interface{}:
child := fmt.Sprintf("%v", iv["child"])
parent := fmt.Sprintf("%v", iv["parent"])
outiv = append(outiv, map[string]string{
"child": child,
"parent": parent,
})
// get child table
vv, err := cvals.Table(r.Name + "." + child)
if err != nil {
slog.Warn(
"ImportValues missing table from chart",
slog.String("chart", r.Name),
slog.Any("error", err),
)
continue
}
// create value map from child to be merged into parent
if merge {
b = util.MergeTables(b, pathToMap(parent, vv.AsMap()))
} else {
b = util.CoalesceTables(b, pathToMap(parent, vv.AsMap()))
}
case string:
child := "exports." + iv
outiv = append(outiv, map[string]string{
"child": child,
"parent": ".",
})
vm, err := cvals.Table(r.Name + "." + child)
if err != nil {
slog.Warn("ImportValues missing table", slog.Any("error", err))
continue
}
if merge {
b = util.MergeTables(b, vm.AsMap())
} else {
b = util.CoalesceTables(b, vm.AsMap())
}
}
}
r.ImportValues = outiv
}
// Imported values from a child to a parent chart have a lower priority than
// the parents values. This enables parent charts to import a large section
// from a child and then override select parts. This is why b is merged into
// cvals in the code below and not the other way around.
if merge {
// deep copying the cvals as there are cases where pointers can end
// up in the cvals when they are copied onto b in ways that break things.
cvals = deepCopyMap(cvals)
c.Values = util.MergeTables(cvals, b)
} else {
// Trimming the nil values from cvals is needed for backwards compatibility.
// Previously, the b value had been populated with cvals along with some
// overrides. This caused the coalescing functionality to remove the
// nil/null values. This trimming is for backwards compat.
cvals = trimNilValues(cvals)
c.Values = util.CoalesceTables(cvals, b)
}
return nil
}
func deepCopyMap(vals map[string]interface{}) map[string]interface{} {
valsCopy, err := copystructure.Copy(vals)
if err != nil {
return vals
}
return valsCopy.(map[string]interface{})
}
func trimNilValues(vals map[string]interface{}) map[string]interface{} {
valsCopy, err := copystructure.Copy(vals)
if err != nil {
return vals
}
valsCopyMap := valsCopy.(map[string]interface{})
for key, val := range valsCopyMap {
if val == nil {
// Iterate over the values and remove nil keys
delete(valsCopyMap, key)
} else if istable(val) {
// Recursively call into ourselves to remove keys from inner tables
valsCopyMap[key] = trimNilValues(val.(map[string]interface{}))
}
}
return valsCopyMap
}
// istable is a special-purpose function to see if the present thing matches the definition of a YAML table.
func istable(v interface{}) bool {
_, ok := v.(map[string]interface{})
return ok
}
// processDependencyImportValues imports specified chart values from child to parent.
func processDependencyImportValues(c *chart.Chart, merge bool) error {
for _, d := range c.Dependencies() {
// recurse
if err := processDependencyImportValues(d, merge); err != nil {
return err
}
}
return processImportValues(c, merge)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/util/save.go | pkg/chart/v2/util/save.go | /*
Copyright The Helm 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 util
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"time"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
var headerBytes = []byte("+aHR0cHM6Ly95b3V0dS5iZS96OVV6MWljandyTQo=")
// SaveDir saves a chart as files in a directory.
//
// This takes the chart name, and creates a new subdirectory inside of the given dest
// directory, writing the chart's contents to that subdirectory.
func SaveDir(c *chart.Chart, dest string) error {
// Create the chart directory
err := validateName(c.Name())
if err != nil {
return err
}
outdir := filepath.Join(dest, c.Name())
if fi, err := os.Stat(outdir); err == nil && !fi.IsDir() {
return fmt.Errorf("file %s already exists and is not a directory", outdir)
}
if err := os.MkdirAll(outdir, 0755); err != nil {
return err
}
// Save the chart file.
if err := SaveChartfile(filepath.Join(outdir, ChartfileName), c.Metadata); err != nil {
return err
}
// Save values.yaml
for _, f := range c.Raw {
if f.Name == ValuesfileName {
vf := filepath.Join(outdir, ValuesfileName)
if err := writeFile(vf, f.Data); err != nil {
return err
}
}
}
// Save values.schema.json if it exists
if c.Schema != nil {
filename := filepath.Join(outdir, SchemafileName)
if err := writeFile(filename, c.Schema); err != nil {
return err
}
}
// Save templates and files
for _, o := range [][]*common.File{c.Templates, c.Files} {
for _, f := range o {
n := filepath.Join(outdir, f.Name)
if err := writeFile(n, f.Data); err != nil {
return err
}
}
}
// Save dependencies
base := filepath.Join(outdir, ChartsDir)
for _, dep := range c.Dependencies() {
// Here, we write each dependency as a tar file.
if _, err := Save(dep, base); err != nil {
return fmt.Errorf("saving %s: %w", dep.ChartFullPath(), err)
}
}
return nil
}
// Save creates an archived chart to the given directory.
//
// This takes an existing chart and a destination directory.
//
// If the directory is /foo, and the chart is named bar, with version 1.0.0, this
// will generate /foo/bar-1.0.0.tgz.
//
// This returns the absolute path to the chart archive file.
func Save(c *chart.Chart, outDir string) (string, error) {
if err := c.Validate(); err != nil {
return "", fmt.Errorf("chart validation: %w", err)
}
filename := fmt.Sprintf("%s-%s.tgz", c.Name(), c.Metadata.Version)
filename = filepath.Join(outDir, filename)
dir := filepath.Dir(filename)
if stat, err := os.Stat(dir); err != nil {
if errors.Is(err, fs.ErrNotExist) {
if err2 := os.MkdirAll(dir, 0755); err2 != nil {
return "", err2
}
} else {
return "", fmt.Errorf("stat %s: %w", dir, err)
}
} else if !stat.IsDir() {
return "", fmt.Errorf("is not a directory: %s", dir)
}
f, err := os.Create(filename)
if err != nil {
return "", err
}
// Wrap in gzip writer
zipper := gzip.NewWriter(f)
zipper.Extra = headerBytes
zipper.Comment = "Helm"
// Wrap in tar writer
twriter := tar.NewWriter(zipper)
rollback := false
defer func() {
twriter.Close()
zipper.Close()
f.Close()
if rollback {
os.Remove(filename)
}
}()
if err := writeTarContents(twriter, c, ""); err != nil {
rollback = true
return filename, err
}
return filename, nil
}
func writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {
err := validateName(c.Name())
if err != nil {
return err
}
base := filepath.Join(prefix, c.Name())
// Pull out the dependencies of a v1 Chart, since there's no way
// to tell the serializer to skip a field for just this use case
savedDependencies := c.Metadata.Dependencies
if c.Metadata.APIVersion == chart.APIVersionV1 {
c.Metadata.Dependencies = nil
}
// Save Chart.yaml
cdata, err := yaml.Marshal(c.Metadata)
if c.Metadata.APIVersion == chart.APIVersionV1 {
c.Metadata.Dependencies = savedDependencies
}
if err != nil {
return err
}
if err := writeToTar(out, filepath.Join(base, ChartfileName), cdata, c.ModTime); err != nil {
return err
}
// Save Chart.lock
// TODO: remove the APIVersion check when APIVersionV1 is not used anymore
if c.Metadata.APIVersion == chart.APIVersionV2 {
if c.Lock != nil {
ldata, err := yaml.Marshal(c.Lock)
if err != nil {
return err
}
if err := writeToTar(out, filepath.Join(base, "Chart.lock"), ldata, c.Lock.Generated); err != nil {
return err
}
}
}
// Save values.yaml
for _, f := range c.Raw {
if f.Name == ValuesfileName {
if err := writeToTar(out, filepath.Join(base, ValuesfileName), f.Data, f.ModTime); err != nil {
return err
}
}
}
// Save values.schema.json if it exists
if c.Schema != nil {
if !json.Valid(c.Schema) {
return errors.New("invalid JSON in " + SchemafileName)
}
if err := writeToTar(out, filepath.Join(base, SchemafileName), c.Schema, c.SchemaModTime); err != nil {
return err
}
}
// Save templates
for _, f := range c.Templates {
n := filepath.Join(base, f.Name)
if err := writeToTar(out, n, f.Data, f.ModTime); err != nil {
return err
}
}
// Save files
for _, f := range c.Files {
n := filepath.Join(base, f.Name)
if err := writeToTar(out, n, f.Data, f.ModTime); err != nil {
return err
}
}
// Save dependencies
for _, dep := range c.Dependencies() {
if err := writeTarContents(out, dep, filepath.Join(base, ChartsDir)); err != nil {
return err
}
}
return nil
}
// writeToTar writes a single file to a tar archive.
func writeToTar(out *tar.Writer, name string, body []byte, modTime time.Time) error {
// TODO: Do we need to create dummy parent directory names if none exist?
h := &tar.Header{
Name: filepath.ToSlash(name),
Mode: 0644,
Size: int64(len(body)),
ModTime: modTime,
}
if h.ModTime.IsZero() {
h.ModTime = time.Now()
}
if err := out.WriteHeader(h); err != nil {
return err
}
_, err := out.Write(body)
return err
}
// If the name has directory name has characters which would change the location
// they need to be removed.
func validateName(name string) error {
nname := filepath.Base(name)
if nname != name {
return common.ErrInvalidChartName{Name: name}
}
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/lint_test.go | pkg/chart/v2/lint/lint_test.go | /*
Copyright The Helm 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 lint
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
const namespace = "testNamespace"
const badChartDir = "rules/testdata/badchartfile"
const badValuesFileDir = "rules/testdata/badvaluesfile"
const badYamlFileDir = "rules/testdata/albatross"
const badCrdFileDir = "rules/testdata/badcrdfile"
const goodChartDir = "rules/testdata/goodone"
const subChartValuesDir = "rules/testdata/withsubchart"
const malformedTemplate = "rules/testdata/malformed-template"
const invalidChartFileDir = "rules/testdata/invalidchartfile"
func TestBadChart(t *testing.T) {
var values map[string]any
m := RunAll(badChartDir, values, namespace).Messages
if len(m) != 9 {
t.Errorf("Number of errors %v", len(m))
t.Errorf("All didn't fail with expected errors, got %#v", m)
}
// There should be one INFO, 2 WARNING and 2 ERROR messages, check for them
var i, w, w2, e, e2, e3, e4, e5, e6 bool
for _, msg := range m {
if msg.Severity == support.InfoSev {
if strings.Contains(msg.Err.Error(), "icon is recommended") {
i = true
}
}
if msg.Severity == support.WarningSev {
if strings.Contains(msg.Err.Error(), "does not exist") {
w = true
}
}
if msg.Severity == support.ErrorSev {
if strings.Contains(msg.Err.Error(), "version '0.0.0.0' is not a valid SemVer") {
e = true
}
if strings.Contains(msg.Err.Error(), "name is required") {
e2 = true
}
if strings.Contains(msg.Err.Error(), "apiVersion is required. The value must be either \"v1\" or \"v2\"") {
e3 = true
}
if strings.Contains(msg.Err.Error(), "chart type is not valid in apiVersion") {
e4 = true
}
if strings.Contains(msg.Err.Error(), "dependencies are not valid in the Chart file with apiVersion") {
e5 = true
}
// This comes from the dependency check, which loads dependency info from the Chart.yaml
if strings.Contains(msg.Err.Error(), "unable to load chart") {
e6 = true
}
}
if msg.Severity == support.WarningSev {
if strings.Contains(msg.Err.Error(), "version '0.0.0.0' is not a valid SemVerV2") {
w2 = true
}
}
}
if !e || !e2 || !e3 || !e4 || !e5 || !i || !e6 || !w || !w2 {
t.Errorf("Didn't find all the expected errors, got %#v", m)
}
}
func TestInvalidYaml(t *testing.T) {
var values map[string]any
m := RunAll(badYamlFileDir, values, namespace).Messages
if len(m) != 1 {
t.Fatalf("All didn't fail with expected errors, got %#v", m)
}
if !strings.Contains(m[0].Err.Error(), "deliberateSyntaxError") {
t.Errorf("All didn't have the error for deliberateSyntaxError")
}
}
func TestInvalidChartYaml(t *testing.T) {
var values map[string]any
m := RunAll(invalidChartFileDir, values, namespace).Messages
if len(m) != 2 {
t.Fatalf("All didn't fail with expected errors, got %#v", m)
}
if !strings.Contains(m[0].Err.Error(), "failed to strictly parse chart metadata file") {
t.Errorf("All didn't have the error for duplicate YAML keys")
}
}
func TestBadValues(t *testing.T) {
var values map[string]any
m := RunAll(badValuesFileDir, values, namespace).Messages
if len(m) < 1 {
t.Fatalf("All didn't fail with expected errors, got %#v", m)
}
if !strings.Contains(m[0].Err.Error(), "unable to parse YAML") {
t.Errorf("All didn't have the error for invalid key format: %s", m[0].Err)
}
}
func TestBadCrdFile(t *testing.T) {
var values map[string]any
m := RunAll(badCrdFileDir, values, namespace).Messages
assert.Lenf(t, m, 2, "All didn't fail with expected errors, got %#v", m)
assert.ErrorContains(t, m[0].Err, "apiVersion is not in 'apiextensions.k8s.io'")
assert.ErrorContains(t, m[1].Err, "object kind is not 'CustomResourceDefinition'")
}
func TestGoodChart(t *testing.T) {
var values map[string]any
m := RunAll(goodChartDir, values, namespace).Messages
if len(m) != 0 {
t.Error("All returned linter messages when it shouldn't have")
for i, msg := range m {
t.Logf("Message %d: %s", i, msg)
}
}
}
// TestHelmCreateChart tests that a `helm create` always passes a `helm lint` test.
//
// See https://github.com/helm/helm/issues/7923
func TestHelmCreateChart(t *testing.T) {
var values map[string]any
dir := t.TempDir()
createdChart, err := chartutil.Create("testhelmcreatepasseslint", dir)
if err != nil {
t.Error(err)
// Fatal is bad because of the defer.
return
}
// Note: we test with strict=true here, even though others have
// strict = false.
m := RunAll(createdChart, values, namespace, WithSkipSchemaValidation(true)).Messages
if ll := len(m); ll != 1 {
t.Errorf("All should have had exactly 1 error. Got %d", ll)
for i, msg := range m {
t.Logf("Message %d: %s", i, msg.Error())
}
} else if msg := m[0].Err.Error(); !strings.Contains(msg, "icon is recommended") {
t.Errorf("Unexpected lint error: %s", msg)
}
}
// TestHelmCreateChart_CheckDeprecatedWarnings checks if any default template created by `helm create` throws
// deprecated warnings in the linter check against the current Kubernetes version (provided using ldflags).
//
// See https://github.com/helm/helm/issues/11495
//
// Resources like hpa and ingress, which are disabled by default in values.yaml are enabled here using the equivalent
// of the `--set` flag.
func TestHelmCreateChart_CheckDeprecatedWarnings(t *testing.T) {
createdChart, err := chartutil.Create("checkdeprecatedwarnings", t.TempDir())
if err != nil {
t.Error(err)
return
}
// Add values to enable hpa, and ingress which are disabled by default.
// This is the equivalent of:
// helm lint checkdeprecatedwarnings --set 'autoscaling.enabled=true,ingress.enabled=true'
updatedValues := map[string]any{
"autoscaling": map[string]any{
"enabled": true,
},
"ingress": map[string]any{
"enabled": true,
},
}
linterRunDetails := RunAll(createdChart, updatedValues, namespace, WithSkipSchemaValidation(true))
for _, msg := range linterRunDetails.Messages {
if strings.HasPrefix(msg.Error(), "[WARNING]") &&
strings.Contains(msg.Error(), "deprecated") {
// When there is a deprecation warning for an object created
// by `helm create` for the current Kubernetes version, fail.
t.Errorf("Unexpected deprecation warning for %q: %s", msg.Path, msg.Error())
}
}
}
// lint ignores import-values
// See https://github.com/helm/helm/issues/9658
func TestSubChartValuesChart(t *testing.T) {
var values map[string]any
m := RunAll(subChartValuesDir, values, namespace).Messages
if len(m) != 0 {
t.Error("All returned linter messages when it shouldn't have")
for i, msg := range m {
t.Logf("Message %d: %s", i, msg)
}
}
}
// lint stuck with malformed template object
// See https://github.com/helm/helm/issues/11391
func TestMalformedTemplate(t *testing.T) {
var values map[string]any
c := time.After(3 * time.Second)
ch := make(chan int, 1)
var m []support.Message
go func() {
m = RunAll(malformedTemplate, values, namespace).Messages
ch <- 1
}()
select {
case <-c:
t.Fatalf("lint malformed template timeout")
case <-ch:
if len(m) != 1 {
t.Fatalf("All didn't fail with expected errors, got %#v", m)
}
if !strings.Contains(m[0].Err.Error(), "invalid character '{'") {
t.Errorf("All didn't have the error for invalid character '{'")
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/lint.go | pkg/chart/v2/lint/lint.go | /*
Copyright The Helm 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 lint // import "helm.sh/helm/v4/pkg/chart/v2/lint"
import (
"path/filepath"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/v2/lint/rules"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
)
type linterOptions struct {
KubeVersion *common.KubeVersion
SkipSchemaValidation bool
}
type LinterOption func(lo *linterOptions)
func WithKubeVersion(kubeVersion *common.KubeVersion) LinterOption {
return func(lo *linterOptions) {
lo.KubeVersion = kubeVersion
}
}
func WithSkipSchemaValidation(skipSchemaValidation bool) LinterOption {
return func(lo *linterOptions) {
lo.SkipSchemaValidation = skipSchemaValidation
}
}
func RunAll(baseDir string, values map[string]interface{}, namespace string, options ...LinterOption) support.Linter {
chartDir, _ := filepath.Abs(baseDir)
lo := linterOptions{}
for _, option := range options {
option(&lo)
}
result := support.Linter{
ChartDir: chartDir,
}
rules.Chartfile(&result)
rules.ValuesWithOverrides(&result, values, lo.SkipSchemaValidation)
rules.Templates(
&result,
namespace,
values,
rules.TemplateLinterKubeVersion(lo.KubeVersion),
rules.TemplateLinterSkipSchemaValidation(lo.SkipSchemaValidation))
rules.Dependencies(&result)
rules.Crds(&result)
return result
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/support/doc.go | pkg/chart/v2/lint/support/doc.go | /*
Copyright The Helm 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 support contains tools for linting charts.
Linting is the process of testing charts for errors or warnings regarding
formatting, compilation, or standards compliance.
*/
package support // import "helm.sh/helm/v4/pkg/chart/v2/lint/support"
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/support/message.go | pkg/chart/v2/lint/support/message.go | /*
Copyright The Helm 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 support
import "fmt"
// Severity indicates the severity of a Message.
const (
// UnknownSev indicates that the severity of the error is unknown, and should not stop processing.
UnknownSev = iota
// InfoSev indicates information, for example missing values.yaml file
InfoSev
// WarningSev indicates that something does not meet code standards, but will likely function.
WarningSev
// ErrorSev indicates that something will not likely function.
ErrorSev
)
// sev matches the *Sev states.
var sev = []string{"UNKNOWN", "INFO", "WARNING", "ERROR"}
// Linter encapsulates a linting run of a particular chart.
type Linter struct {
Messages []Message
// The highest severity of all the failing lint rules
HighestSeverity int
ChartDir string
}
// Message describes an error encountered while linting.
type Message struct {
// Severity is one of the *Sev constants
Severity int
Path string
Err error
}
func (m Message) Error() string {
return fmt.Sprintf("[%s] %s: %s", sev[m.Severity], m.Path, m.Err.Error())
}
// NewMessage creates a new Message struct
func NewMessage(severity int, path string, err error) Message {
return Message{Severity: severity, Path: path, Err: err}
}
// RunLinterRule returns true if the validation passed
func (l *Linter) RunLinterRule(severity int, path string, err error) bool {
// severity is out of bound
if severity < 0 || severity >= len(sev) {
return false
}
if err != nil {
l.Messages = append(l.Messages, NewMessage(severity, path, err))
if severity > l.HighestSeverity {
l.HighestSeverity = severity
}
}
return err == nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/support/message_test.go | pkg/chart/v2/lint/support/message_test.go | /*
Copyright The Helm 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 support
import (
"errors"
"testing"
)
var errLint = errors.New("lint failed")
func TestRunLinterRule(t *testing.T) {
var tests = []struct {
Severity int
LintError error
ExpectedMessages int
ExpectedReturn bool
ExpectedHighestSeverity int
}{
{InfoSev, errLint, 1, false, InfoSev},
{WarningSev, errLint, 2, false, WarningSev},
{ErrorSev, errLint, 3, false, ErrorSev},
// No error so it returns true
{ErrorSev, nil, 3, true, ErrorSev},
// Retains highest severity
{InfoSev, errLint, 4, false, ErrorSev},
// Invalid severity values
{4, errLint, 4, false, ErrorSev},
{22, errLint, 4, false, ErrorSev},
{-1, errLint, 4, false, ErrorSev},
}
linter := Linter{}
for _, test := range tests {
isValid := linter.RunLinterRule(test.Severity, "chart", test.LintError)
if len(linter.Messages) != test.ExpectedMessages {
t.Errorf("RunLinterRule(%d, \"chart\", %v), linter.Messages should now have %d message, we got %d", test.Severity, test.LintError, test.ExpectedMessages, len(linter.Messages))
}
if linter.HighestSeverity != test.ExpectedHighestSeverity {
t.Errorf("RunLinterRule(%d, \"chart\", %v), linter.HighestSeverity should be %d, we got %d", test.Severity, test.LintError, test.ExpectedHighestSeverity, linter.HighestSeverity)
}
if isValid != test.ExpectedReturn {
t.Errorf("RunLinterRule(%d, \"chart\", %v), should have returned %t but returned %t", test.Severity, test.LintError, test.ExpectedReturn, isValid)
}
}
}
func TestMessage(t *testing.T) {
m := Message{ErrorSev, "Chart.yaml", errors.New("Foo")}
if m.Error() != "[ERROR] Chart.yaml: Foo" {
t.Errorf("Unexpected output: %s", m.Error())
}
m = Message{WarningSev, "templates/", errors.New("Bar")}
if m.Error() != "[WARNING] templates/: Bar" {
t.Errorf("Unexpected output: %s", m.Error())
}
m = Message{InfoSev, "templates/rc.yaml", errors.New("FooBar")}
if m.Error() != "[INFO] templates/rc.yaml: FooBar" {
t.Errorf("Unexpected output: %s", m.Error())
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/chartfile.go | pkg/chart/v2/lint/rules/chartfile.go | /*
Copyright The Helm 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 rules // import "helm.sh/helm/v4/pkg/chart/v2/lint/rules"
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/Masterminds/semver/v3"
"github.com/asaskevich/govalidator"
"sigs.k8s.io/yaml"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
// Chartfile runs a set of linter rules related to Chart.yaml file
func Chartfile(linter *support.Linter) {
chartFileName := "Chart.yaml"
chartPath := filepath.Join(linter.ChartDir, chartFileName)
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlNotDirectory(chartPath))
chartFile, err := chartutil.LoadChartfile(chartPath)
validChartFile := linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartYamlFormat(err))
// Guard clause. Following linter rules require a parsable ChartFile
if !validChartFile {
return
}
_, err = chartutil.StrictLoadChartfile(chartPath)
linter.RunLinterRule(support.WarningSev, chartFileName, validateChartYamlStrictFormat(err))
// type check for Chart.yaml . ignoring error as any parse
// errors would already be caught in the above load function
chartFileForTypeCheck, _ := loadChartFileForTypeCheck(chartPath)
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartName(chartFile))
// Chart metadata
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartAPIVersion(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartVersionType(chartFileForTypeCheck))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartVersion(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartAppVersionType(chartFileForTypeCheck))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartMaintainer(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartSources(chartFile))
linter.RunLinterRule(support.InfoSev, chartFileName, validateChartIconPresence(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartIconURL(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartType(chartFile))
linter.RunLinterRule(support.ErrorSev, chartFileName, validateChartDependencies(chartFile))
linter.RunLinterRule(support.WarningSev, chartFileName, validateChartVersionStrictSemVerV2(chartFile))
}
func validateChartVersionType(data map[string]interface{}) error {
return isStringValue(data, "version")
}
func validateChartAppVersionType(data map[string]interface{}) error {
return isStringValue(data, "appVersion")
}
func isStringValue(data map[string]interface{}, key string) error {
value, ok := data[key]
if !ok {
return nil
}
valueType := fmt.Sprintf("%T", value)
if valueType != "string" {
return fmt.Errorf("%s should be of type string but it's of type %s", key, valueType)
}
return nil
}
func validateChartYamlNotDirectory(chartPath string) error {
fi, err := os.Stat(chartPath)
if err == nil && fi.IsDir() {
return errors.New("should be a file, not a directory")
}
return nil
}
func validateChartYamlFormat(chartFileError error) error {
if chartFileError != nil {
return fmt.Errorf("unable to parse YAML\n\t%w", chartFileError)
}
return nil
}
func validateChartYamlStrictFormat(chartFileError error) error {
if chartFileError != nil {
return fmt.Errorf("failed to strictly parse chart metadata file\n\t%w", chartFileError)
}
return nil
}
func validateChartName(cf *chart.Metadata) error {
if cf.Name == "" {
return errors.New("name is required")
}
name := filepath.Base(cf.Name)
if name != cf.Name {
return fmt.Errorf("chart name %q is invalid", cf.Name)
}
return nil
}
func validateChartAPIVersion(cf *chart.Metadata) error {
if cf.APIVersion == "" {
return errors.New("apiVersion is required. The value must be either \"v1\" or \"v2\"")
}
if cf.APIVersion != chart.APIVersionV1 && cf.APIVersion != chart.APIVersionV2 {
return fmt.Errorf("apiVersion '%s' is not valid. The value must be either \"v1\" or \"v2\"", cf.APIVersion)
}
return nil
}
func validateChartVersion(cf *chart.Metadata) error {
if cf.Version == "" {
return errors.New("version is required")
}
version, err := semver.NewVersion(cf.Version)
if err != nil {
return fmt.Errorf("version '%s' is not a valid SemVer", cf.Version)
}
c, err := semver.NewConstraint(">0.0.0-0")
if err != nil {
return err
}
valid, msg := c.Validate(version)
if !valid && len(msg) > 0 {
return fmt.Errorf("version %v", msg[0])
}
return nil
}
func validateChartVersionStrictSemVerV2(cf *chart.Metadata) error {
_, err := semver.StrictNewVersion(cf.Version)
if err != nil {
return fmt.Errorf("version '%s' is not a valid SemVerV2", cf.Version)
}
return nil
}
func validateChartMaintainer(cf *chart.Metadata) error {
for _, maintainer := range cf.Maintainers {
if maintainer == nil {
return errors.New("a maintainer entry is empty")
}
if maintainer.Name == "" {
return errors.New("each maintainer requires a name")
} else if maintainer.Email != "" && !govalidator.IsEmail(maintainer.Email) {
return fmt.Errorf("invalid email '%s' for maintainer '%s'", maintainer.Email, maintainer.Name)
} else if maintainer.URL != "" && !govalidator.IsURL(maintainer.URL) {
return fmt.Errorf("invalid url '%s' for maintainer '%s'", maintainer.URL, maintainer.Name)
}
}
return nil
}
func validateChartSources(cf *chart.Metadata) error {
for _, source := range cf.Sources {
if source == "" || !govalidator.IsRequestURL(source) {
return fmt.Errorf("invalid source URL '%s'", source)
}
}
return nil
}
func validateChartIconPresence(cf *chart.Metadata) error {
if cf.Icon == "" {
return errors.New("icon is recommended")
}
return nil
}
func validateChartIconURL(cf *chart.Metadata) error {
if cf.Icon != "" && !govalidator.IsRequestURL(cf.Icon) {
return fmt.Errorf("invalid icon URL '%s'", cf.Icon)
}
return nil
}
func validateChartDependencies(cf *chart.Metadata) error {
if len(cf.Dependencies) > 0 && cf.APIVersion != chart.APIVersionV2 {
return fmt.Errorf("dependencies are not valid in the Chart file with apiVersion '%s'. They are valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV2)
}
return nil
}
func validateChartType(cf *chart.Metadata) error {
if len(cf.Type) > 0 && cf.APIVersion != chart.APIVersionV2 {
return fmt.Errorf("chart type is not valid in apiVersion '%s'. It is valid in apiVersion '%s'", cf.APIVersion, chart.APIVersionV2)
}
return nil
}
// loadChartFileForTypeCheck loads the Chart.yaml
// in a generic form of a map[string]interface{}, so that the type
// of the values can be checked
func loadChartFileForTypeCheck(filename string) (map[string]interface{}, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
y := make(map[string]interface{})
err = yaml.Unmarshal(b, &y)
return y, err
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/deprecations_test.go | pkg/chart/v2/lint/rules/deprecations_test.go | /*
Copyright The Helm 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 rules // import "helm.sh/helm/v4/pkg/chart/v2/lint/rules"
import "testing"
func TestValidateNoDeprecations(t *testing.T) {
deprecated := &k8sYamlStruct{
APIVersion: "extensions/v1beta1",
Kind: "Deployment",
}
err := validateNoDeprecations(deprecated, nil)
if err == nil {
t.Fatal("Expected deprecated extension to be flagged")
}
depErr := err.(deprecatedAPIError)
if depErr.Message == "" {
t.Fatalf("Expected error message to be non-blank: %v", err)
}
if err := validateNoDeprecations(&k8sYamlStruct{
APIVersion: "v1",
Kind: "Pod",
}, nil); err != nil {
t.Errorf("Expected a v1 Pod to not be deprecated")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/deprecations.go | pkg/chart/v2/lint/rules/deprecations.go | /*
Copyright The Helm 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 rules // import "helm.sh/helm/v4/pkg/chart/v2/lint/rules"
import (
"fmt"
"strconv"
"helm.sh/helm/v4/pkg/chart/common"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/endpoints/deprecation"
kscheme "k8s.io/client-go/kubernetes/scheme"
)
// deprecatedAPIError indicates than an API is deprecated in Kubernetes
type deprecatedAPIError struct {
Deprecated string
Message string
}
func (e deprecatedAPIError) Error() string {
msg := e.Message
return msg
}
func validateNoDeprecations(resource *k8sYamlStruct, kubeVersion *common.KubeVersion) error {
// if `resource` does not have an APIVersion or Kind, we cannot test it for deprecation
if resource.APIVersion == "" {
return nil
}
if resource.Kind == "" {
return nil
}
if kubeVersion == nil {
kubeVersion = &common.DefaultCapabilities.KubeVersion
}
runtimeObject, err := resourceToRuntimeObject(resource)
if err != nil {
// do not error for non-kubernetes resources
if runtime.IsNotRegisteredError(err) {
return nil
}
return err
}
kubeVersionMajor, err := strconv.Atoi(kubeVersion.Major)
if err != nil {
return err
}
kubeVersionMinor, err := strconv.Atoi(kubeVersion.Minor)
if err != nil {
return err
}
if !deprecation.IsDeprecated(runtimeObject, kubeVersionMajor, kubeVersionMinor) {
return nil
}
gvk := fmt.Sprintf("%s %s", resource.APIVersion, resource.Kind)
return deprecatedAPIError{
Deprecated: gvk,
Message: deprecation.WarningMessage(runtimeObject),
}
}
func resourceToRuntimeObject(resource *k8sYamlStruct) (runtime.Object, error) {
scheme := runtime.NewScheme()
kscheme.AddToScheme(scheme)
gvk := schema.FromAPIVersionAndKind(resource.APIVersion, resource.Kind)
out, err := scheme.New(gvk)
if err != nil {
return nil, err
}
out.GetObjectKind().SetGroupVersionKind(gvk)
return out, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/crds_test.go | pkg/chart/v2/lint/rules/crds_test.go | /*
Copyright The Helm 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 rules
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
)
const invalidCrdsDir = "./testdata/invalidcrdsdir"
func TestInvalidCrdsDir(t *testing.T) {
linter := support.Linter{ChartDir: invalidCrdsDir}
Crds(&linter)
res := linter.Messages
assert.Len(t, res, 1)
assert.ErrorContains(t, res[0].Err, "not a directory")
}
// multi-document YAML with empty documents would panic
func TestCrdWithEmptyDocument(t *testing.T) {
chartDir := t.TempDir()
os.WriteFile(filepath.Join(chartDir, "Chart.yaml"), []byte(
`apiVersion: v1
name: test
version: 0.1.0
`), 0644)
// CRD with comments before --- (creates empty document)
crdsDir := filepath.Join(chartDir, "crds")
os.Mkdir(crdsDir, 0755)
os.WriteFile(filepath.Join(crdsDir, "test.yaml"), []byte(
`# Comments create empty document
---
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: test.example.io
`), 0644)
linter := support.Linter{ChartDir: chartDir}
Crds(&linter)
assert.Len(t, linter.Messages, 0)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/values.go | pkg/chart/v2/lint/rules/values.go | /*
Copyright The Helm 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 rules
import (
"fmt"
"os"
"path/filepath"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/common/util"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
)
// ValuesWithOverrides tests the values.yaml file.
//
// If a schema is present in the chart, values are tested against that. Otherwise,
// they are only tested for well-formedness.
//
// If additional values are supplied, they are coalesced into the values in values.yaml.
func ValuesWithOverrides(linter *support.Linter, valueOverrides map[string]interface{}, skipSchemaValidation bool) {
file := "values.yaml"
vf := filepath.Join(linter.ChartDir, file)
fileExists := linter.RunLinterRule(support.InfoSev, file, validateValuesFileExistence(vf))
if !fileExists {
return
}
linter.RunLinterRule(support.ErrorSev, file, validateValuesFile(vf, valueOverrides, skipSchemaValidation))
}
func validateValuesFileExistence(valuesPath string) error {
_, err := os.Stat(valuesPath)
if err != nil {
return fmt.Errorf("file does not exist")
}
return nil
}
func validateValuesFile(valuesPath string, overrides map[string]interface{}, skipSchemaValidation bool) error {
values, err := common.ReadValuesFile(valuesPath)
if err != nil {
return fmt.Errorf("unable to parse YAML: %w", err)
}
// Helm 3.0.0 carried over the values linting from Helm 2.x, which only tests the top
// level values against the top-level expectations. Subchart values are not linted.
// We could change that. For now, though, we retain that strategy, and thus can
// coalesce tables (like reuse-values does) instead of doing the full chart
// CoalesceValues
coalescedValues := util.CoalesceTables(make(map[string]interface{}, len(overrides)), overrides)
coalescedValues = util.CoalesceTables(coalescedValues, values)
ext := filepath.Ext(valuesPath)
schemaPath := valuesPath[:len(valuesPath)-len(ext)] + ".schema.json"
schema, err := os.ReadFile(schemaPath)
if len(schema) == 0 {
return nil
}
if err != nil {
return err
}
if !skipSchemaValidation {
return util.ValidateAgainstSingleSchema(coalescedValues, schema)
}
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/crds.go | pkg/chart/v2/lint/rules/crds.go | /*
Copyright The Helm 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 rules
import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"k8s.io/apimachinery/pkg/util/yaml"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
// Crds lints the CRDs in the Linter.
func Crds(linter *support.Linter) {
fpath := "crds/"
crdsPath := filepath.Join(linter.ChartDir, fpath)
// crds directory is optional
if _, err := os.Stat(crdsPath); errors.Is(err, fs.ErrNotExist) {
return
}
crdsDirValid := linter.RunLinterRule(support.ErrorSev, fpath, validateCrdsDir(crdsPath))
if !crdsDirValid {
return
}
// Load chart and parse CRDs
chart, err := loader.Load(linter.ChartDir)
chartLoaded := linter.RunLinterRule(support.ErrorSev, fpath, err)
if !chartLoaded {
return
}
/* Iterate over all the CRDs to check:
1. It is a YAML file and not a template
2. The API version is apiextensions.k8s.io
3. The kind is CustomResourceDefinition
*/
for _, crd := range chart.CRDObjects() {
fileName := crd.Name
fpath = fileName
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(crd.File.Data), 4096)
for {
var yamlStruct *k8sYamlStruct
err := decoder.Decode(&yamlStruct)
if errors.Is(err, io.EOF) {
break
}
// If YAML parsing fails here, it will always fail in the next block as well, so we should return here.
// This also confirms the YAML is not a template, since templates can't be decoded into a K8sYamlStruct.
if !linter.RunLinterRule(support.ErrorSev, fpath, validateYamlContent(err)) {
return
}
if yamlStruct != nil {
linter.RunLinterRule(support.ErrorSev, fpath, validateCrdAPIVersion(yamlStruct))
linter.RunLinterRule(support.ErrorSev, fpath, validateCrdKind(yamlStruct))
}
}
}
}
// Validation functions
func validateCrdsDir(crdsPath string) error {
fi, err := os.Stat(crdsPath)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New("not a directory")
}
return nil
}
func validateCrdAPIVersion(obj *k8sYamlStruct) error {
if !strings.HasPrefix(obj.APIVersion, "apiextensions.k8s.io") {
return fmt.Errorf("apiVersion is not in 'apiextensions.k8s.io'")
}
return nil
}
func validateCrdKind(obj *k8sYamlStruct) error {
if obj.Kind != "CustomResourceDefinition" {
return fmt.Errorf("object kind is not 'CustomResourceDefinition'")
}
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/chartfile_test.go | pkg/chart/v2/lint/rules/chartfile_test.go | /*
Copyright The Helm 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 rules
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
const (
badChartNameDir = "testdata/badchartname"
badChartDir = "testdata/badchartfile"
anotherBadChartDir = "testdata/anotherbadchartfile"
)
var (
badChartNamePath = filepath.Join(badChartNameDir, "Chart.yaml")
badChartFilePath = filepath.Join(badChartDir, "Chart.yaml")
nonExistingChartFilePath = filepath.Join(os.TempDir(), "Chart.yaml")
)
var badChart, _ = chartutil.LoadChartfile(badChartFilePath)
var badChartName, _ = chartutil.LoadChartfile(badChartNamePath)
// Validation functions Test
func TestValidateChartYamlNotDirectory(t *testing.T) {
_ = os.Mkdir(nonExistingChartFilePath, os.ModePerm)
defer os.Remove(nonExistingChartFilePath)
err := validateChartYamlNotDirectory(nonExistingChartFilePath)
if err == nil {
t.Errorf("validateChartYamlNotDirectory to return a linter error, got no error")
}
}
func TestValidateChartYamlFormat(t *testing.T) {
err := validateChartYamlFormat(errors.New("Read error"))
if err == nil {
t.Errorf("validateChartYamlFormat to return a linter error, got no error")
}
err = validateChartYamlFormat(nil)
if err != nil {
t.Errorf("validateChartYamlFormat to return no error, got a linter error")
}
}
func TestValidateChartName(t *testing.T) {
err := validateChartName(badChart)
if err == nil {
t.Errorf("validateChartName to return a linter error, got no error")
}
err = validateChartName(badChartName)
if err == nil {
t.Error("expected validateChartName to return a linter error for an invalid name, got no error")
}
}
func TestValidateChartVersion(t *testing.T) {
var failTest = []struct {
Version string
ErrorMsg string
}{
{"", "version is required"},
{"1.2.3.4", "version '1.2.3.4' is not a valid SemVer"},
{"waps", "'waps' is not a valid SemVer"},
{"-3", "'-3' is not a valid SemVer"},
}
var successTest = []string{"0.0.1", "0.0.1+build", "0.0.1-beta"}
for _, test := range failTest {
badChart.Version = test.Version
err := validateChartVersion(badChart)
if err == nil || !strings.Contains(err.Error(), test.ErrorMsg) {
t.Errorf("validateChartVersion(%s) to return \"%s\", got no error", test.Version, test.ErrorMsg)
}
}
for _, version := range successTest {
badChart.Version = version
err := validateChartVersion(badChart)
if err != nil {
t.Errorf("validateChartVersion(%s) to return no error, got a linter error", version)
}
}
}
func TestValidateChartVersionStrictSemVerV2(t *testing.T) {
var failTest = []struct {
Version string
ErrorMsg string
}{
{"", "version '' is not a valid SemVerV2"},
{"1", "version '1' is not a valid SemVerV2"},
{"1.1", "version '1.1' is not a valid SemVerV2"},
}
var successTest = []string{"1.1.1", "0.0.1+build", "0.0.1-beta"}
for _, test := range failTest {
badChart.Version = test.Version
err := validateChartVersionStrictSemVerV2(badChart)
if err == nil || !strings.Contains(err.Error(), test.ErrorMsg) {
t.Errorf("validateChartVersionStrictSemVerV2(%s) to return \"%s\", got no error", test.Version, test.ErrorMsg)
}
}
for _, version := range successTest {
badChart.Version = version
err := validateChartVersionStrictSemVerV2(badChart)
if err != nil {
t.Errorf("validateChartVersionStrictSemVerV2(%s) to return no error, got a linter error", version)
}
}
}
func TestValidateChartMaintainer(t *testing.T) {
var failTest = []struct {
Name string
Email string
ErrorMsg string
}{
{"", "", "each maintainer requires a name"},
{"", "test@test.com", "each maintainer requires a name"},
{"John Snow", "wrongFormatEmail.com", "invalid email"},
}
var successTest = []struct {
Name string
Email string
}{
{"John Snow", ""},
{"John Snow", "john@winterfell.com"},
}
for _, test := range failTest {
badChart.Maintainers = []*chart.Maintainer{{Name: test.Name, Email: test.Email}}
err := validateChartMaintainer(badChart)
if err == nil || !strings.Contains(err.Error(), test.ErrorMsg) {
t.Errorf("validateChartMaintainer(%s, %s) to return \"%s\", got no error", test.Name, test.Email, test.ErrorMsg)
}
}
for _, test := range successTest {
badChart.Maintainers = []*chart.Maintainer{{Name: test.Name, Email: test.Email}}
err := validateChartMaintainer(badChart)
if err != nil {
t.Errorf("validateChartMaintainer(%s, %s) to return no error, got %s", test.Name, test.Email, err.Error())
}
}
// Testing for an empty maintainer
badChart.Maintainers = []*chart.Maintainer{nil}
err := validateChartMaintainer(badChart)
if err == nil {
t.Errorf("validateChartMaintainer did not return error for nil maintainer as expected")
}
if err.Error() != "a maintainer entry is empty" {
t.Errorf("validateChartMaintainer returned unexpected error for nil maintainer: %s", err.Error())
}
}
func TestValidateChartSources(t *testing.T) {
var failTest = []string{"", "RiverRun", "john@winterfell", "riverrun.io"}
var successTest = []string{"http://riverrun.io", "https://riverrun.io", "https://riverrun.io/blackfish"}
for _, test := range failTest {
badChart.Sources = []string{test}
err := validateChartSources(badChart)
if err == nil || !strings.Contains(err.Error(), "invalid source URL") {
t.Errorf("validateChartSources(%s) to return \"invalid source URL\", got no error", test)
}
}
for _, test := range successTest {
badChart.Sources = []string{test}
err := validateChartSources(badChart)
if err != nil {
t.Errorf("validateChartSources(%s) to return no error, got %s", test, err.Error())
}
}
}
func TestValidateChartIconPresence(t *testing.T) {
t.Run("Icon absent", func(t *testing.T) {
testChart := &chart.Metadata{
Icon: "",
}
err := validateChartIconPresence(testChart)
if err == nil {
t.Errorf("validateChartIconPresence to return a linter error, got no error")
} else if !strings.Contains(err.Error(), "icon is recommended") {
t.Errorf("expected %q, got %q", "icon is recommended", err.Error())
}
})
t.Run("Icon present", func(t *testing.T) {
testChart := &chart.Metadata{
Icon: "http://example.org/icon.png",
}
err := validateChartIconPresence(testChart)
if err != nil {
t.Errorf("Unexpected error: %q", err.Error())
}
})
}
func TestValidateChartIconURL(t *testing.T) {
var failTest = []string{"RiverRun", "john@winterfell", "riverrun.io"}
var successTest = []string{"http://riverrun.io", "https://riverrun.io", "https://riverrun.io/blackfish.png"}
for _, test := range failTest {
badChart.Icon = test
err := validateChartIconURL(badChart)
if err == nil || !strings.Contains(err.Error(), "invalid icon URL") {
t.Errorf("validateChartIconURL(%s) to return \"invalid icon URL\", got no error", test)
}
}
for _, test := range successTest {
badChart.Icon = test
err := validateChartSources(badChart)
if err != nil {
t.Errorf("validateChartIconURL(%s) to return no error, got %s", test, err.Error())
}
}
}
func TestChartfile(t *testing.T) {
t.Run("Chart.yaml basic validity issues", func(t *testing.T) {
linter := support.Linter{ChartDir: badChartDir}
Chartfile(&linter)
msgs := linter.Messages
expectedNumberOfErrorMessages := 7
if len(msgs) != expectedNumberOfErrorMessages {
t.Errorf("Expected %d errors, got %d", expectedNumberOfErrorMessages, len(msgs))
return
}
if !strings.Contains(msgs[0].Err.Error(), "name is required") {
t.Errorf("Unexpected message 0: %s", msgs[0].Err)
}
if !strings.Contains(msgs[1].Err.Error(), "apiVersion is required. The value must be either \"v1\" or \"v2\"") {
t.Errorf("Unexpected message 1: %s", msgs[1].Err)
}
if !strings.Contains(msgs[2].Err.Error(), "version '0.0.0.0' is not a valid SemVer") {
t.Errorf("Unexpected message 2: %s", msgs[2].Err)
}
if !strings.Contains(msgs[3].Err.Error(), "icon is recommended") {
t.Errorf("Unexpected message 3: %s", msgs[3].Err)
}
if !strings.Contains(msgs[4].Err.Error(), "chart type is not valid in apiVersion") {
t.Errorf("Unexpected message 4: %s", msgs[4].Err)
}
if !strings.Contains(msgs[5].Err.Error(), "dependencies are not valid in the Chart file with apiVersion") {
t.Errorf("Unexpected message 5: %s", msgs[5].Err)
}
if !strings.Contains(msgs[6].Err.Error(), "version '0.0.0.0' is not a valid SemVerV2") {
t.Errorf("Unexpected message 6: %s", msgs[6].Err)
}
})
t.Run("Chart.yaml validity issues due to type mismatch", func(t *testing.T) {
linter := support.Linter{ChartDir: anotherBadChartDir}
Chartfile(&linter)
msgs := linter.Messages
expectedNumberOfErrorMessages := 4
if len(msgs) != expectedNumberOfErrorMessages {
t.Errorf("Expected %d errors, got %d", expectedNumberOfErrorMessages, len(msgs))
return
}
if !strings.Contains(msgs[0].Err.Error(), "version should be of type string") {
t.Errorf("Unexpected message 0: %s", msgs[0].Err)
}
if !strings.Contains(msgs[1].Err.Error(), "version '7.2445e+06' is not a valid SemVer") {
t.Errorf("Unexpected message 1: %s", msgs[1].Err)
}
if !strings.Contains(msgs[2].Err.Error(), "appVersion should be of type string") {
t.Errorf("Unexpected message 2: %s", msgs[2].Err)
}
if !strings.Contains(msgs[3].Err.Error(), "version '7.2445e+06' is not a valid SemVerV2") {
t.Errorf("Unexpected message 3: %s", msgs[3].Err)
}
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/values_test.go | pkg/chart/v2/lint/rules/values_test.go | /*
Copyright The Helm 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 rules
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/internal/test/ensure"
)
var nonExistingValuesFilePath = filepath.Join("/fake/dir", "values.yaml")
const testSchema = `
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "helm values test schema",
"type": "object",
"additionalProperties": false,
"required": [
"username",
"password"
],
"properties": {
"username": {
"description": "Your username",
"type": "string"
},
"password": {
"description": "Your password",
"type": "string"
}
}
}
`
func TestValidateValuesYamlNotDirectory(t *testing.T) {
_ = os.Mkdir(nonExistingValuesFilePath, os.ModePerm)
defer os.Remove(nonExistingValuesFilePath)
err := validateValuesFileExistence(nonExistingValuesFilePath)
if err == nil {
t.Errorf("validateValuesFileExistence to return a linter error, got no error")
}
}
func TestValidateValuesFileWellFormed(t *testing.T) {
badYaml := `
not:well[]{}formed
`
tmpdir := ensure.TempFile(t, "values.yaml", []byte(badYaml))
valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, map[string]interface{}{}, false); err == nil {
t.Fatal("expected values file to fail parsing")
}
}
func TestValidateValuesFileSchema(t *testing.T) {
yaml := "username: admin\npassword: swordfish"
tmpdir := ensure.TempFile(t, "values.yaml", []byte(yaml))
createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, map[string]interface{}{}, false); err != nil {
t.Fatalf("Failed validation with %s", err)
}
}
func TestValidateValuesFileSchemaFailure(t *testing.T) {
// 1234 is an int, not a string. This should fail.
yaml := "username: 1234\npassword: swordfish"
tmpdir := ensure.TempFile(t, "values.yaml", []byte(yaml))
createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml")
err := validateValuesFile(valfile, map[string]interface{}{}, false)
if err == nil {
t.Fatal("expected values file to fail parsing")
}
assert.Contains(t, err.Error(), "- at '/username': got number, want string")
}
func TestValidateValuesFileSchemaFailureButWithSkipSchemaValidation(t *testing.T) {
// 1234 is an int, not a string. This should fail normally but pass with skipSchemaValidation.
yaml := "username: 1234\npassword: swordfish"
tmpdir := ensure.TempFile(t, "values.yaml", []byte(yaml))
createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml")
err := validateValuesFile(valfile, map[string]interface{}{}, true)
if err != nil {
t.Fatal("expected values file to pass parsing because of skipSchemaValidation")
}
}
func TestValidateValuesFileSchemaOverrides(t *testing.T) {
yaml := "username: admin"
overrides := map[string]interface{}{
"password": "swordfish",
}
tmpdir := ensure.TempFile(t, "values.yaml", []byte(yaml))
createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml")
if err := validateValuesFile(valfile, overrides, false); err != nil {
t.Fatalf("Failed validation with %s", err)
}
}
func TestValidateValuesFile(t *testing.T) {
tests := []struct {
name string
yaml string
overrides map[string]interface{}
errorMessage string
}{
{
name: "value added",
yaml: "username: admin",
overrides: map[string]interface{}{"password": "swordfish"},
},
{
name: "value not overridden",
yaml: "username: admin\npassword:",
overrides: map[string]interface{}{"username": "anotherUser"},
errorMessage: "- at '/password': got null, want string",
},
{
name: "value overridden",
yaml: "username: admin\npassword:",
overrides: map[string]interface{}{"username": "anotherUser", "password": "swordfish"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpdir := ensure.TempFile(t, "values.yaml", []byte(tt.yaml))
createTestingSchema(t, tmpdir)
valfile := filepath.Join(tmpdir, "values.yaml")
err := validateValuesFile(valfile, tt.overrides, false)
switch {
case err != nil && tt.errorMessage == "":
t.Errorf("Failed validation with %s", err)
case err == nil && tt.errorMessage != "":
t.Error("expected values file to fail parsing")
case err != nil && tt.errorMessage != "":
assert.Contains(t, err.Error(), tt.errorMessage, "Failed with unexpected error")
}
})
}
}
func createTestingSchema(t *testing.T, dir string) string {
t.Helper()
schemafile := filepath.Join(dir, "values.schema.json")
if err := os.WriteFile(schemafile, []byte(testSchema), 0700); err != nil {
t.Fatalf("Failed to write schema to tmpdir: %s", err)
}
return schemafile
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/template_test.go | pkg/chart/v2/lint/rules/template_test.go | /*
Copyright The Helm 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 rules
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
const templateTestBasedir = "./testdata/albatross"
func TestValidateAllowedExtension(t *testing.T) {
var failTest = []string{"/foo", "/test.toml"}
for _, test := range failTest {
err := validateAllowedExtension(test)
if err == nil || !strings.Contains(err.Error(), "Valid extensions are .yaml, .yml, .tpl, or .txt") {
t.Errorf("validateAllowedExtension('%s') to return \"Valid extensions are .yaml, .yml, .tpl, or .txt\", got no error", test)
}
}
var successTest = []string{"/foo.yaml", "foo.yaml", "foo.tpl", "/foo/bar/baz.yaml", "NOTES.txt"}
for _, test := range successTest {
err := validateAllowedExtension(test)
if err != nil {
t.Errorf("validateAllowedExtension('%s') to return no error but got \"%s\"", test, err.Error())
}
}
}
var values = map[string]interface{}{"nameOverride": "", "httpPort": 80}
const namespace = "testNamespace"
func TestTemplateParsing(t *testing.T) {
linter := support.Linter{ChartDir: templateTestBasedir}
Templates(
&linter,
namespace,
values,
TemplateLinterSkipSchemaValidation(false))
res := linter.Messages
if len(res) != 1 {
t.Fatalf("Expected one error, got %d, %v", len(res), res)
}
if !strings.Contains(res[0].Err.Error(), "deliberateSyntaxError") {
t.Errorf("Unexpected error: %s", res[0])
}
}
var wrongTemplatePath = filepath.Join(templateTestBasedir, "templates", "fail.yaml")
var ignoredTemplatePath = filepath.Join(templateTestBasedir, "fail.yaml.ignored")
// Test a template with all the existing features:
// namespaces, partial templates
func TestTemplateIntegrationHappyPath(t *testing.T) {
// Rename file so it gets ignored by the linter
os.Rename(wrongTemplatePath, ignoredTemplatePath)
defer os.Rename(ignoredTemplatePath, wrongTemplatePath)
linter := support.Linter{ChartDir: templateTestBasedir}
Templates(
&linter,
namespace,
values,
TemplateLinterSkipSchemaValidation(false))
res := linter.Messages
if len(res) != 0 {
t.Fatalf("Expected no error, got %d, %v", len(res), res)
}
}
func TestMultiTemplateFail(t *testing.T) {
linter := support.Linter{ChartDir: "./testdata/multi-template-fail"}
Templates(
&linter,
namespace,
values,
TemplateLinterSkipSchemaValidation(false))
res := linter.Messages
if len(res) != 1 {
t.Fatalf("Expected 1 error, got %d, %v", len(res), res)
}
if !strings.Contains(res[0].Err.Error(), "object name does not conform to Kubernetes naming requirements") {
t.Errorf("Unexpected error: %s", res[0].Err)
}
}
func TestValidateMetadataName(t *testing.T) {
tests := []struct {
obj *k8sYamlStruct
wantErr bool
}{
// Most kinds use IsDNS1123Subdomain.
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: ""}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "foo.bar1234baz.seventyone"}}, false},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "FOO"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "foo.BAR.baz"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "one-two"}}, false},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "-two"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "one_two"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "a..b"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "%^&#$%*@^*@&#^"}}, true},
{&k8sYamlStruct{Kind: "Pod", Metadata: k8sYamlMetadata{Name: "operator:pod"}}, true},
{&k8sYamlStruct{Kind: "ServiceAccount", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "ServiceAccount", Metadata: k8sYamlMetadata{Name: "foo.bar1234baz.seventyone"}}, false},
{&k8sYamlStruct{Kind: "ServiceAccount", Metadata: k8sYamlMetadata{Name: "FOO"}}, true},
{&k8sYamlStruct{Kind: "ServiceAccount", Metadata: k8sYamlMetadata{Name: "operator:sa"}}, true},
// Service uses IsDNS1035Label.
{&k8sYamlStruct{Kind: "Service", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "Service", Metadata: k8sYamlMetadata{Name: "123baz"}}, true},
{&k8sYamlStruct{Kind: "Service", Metadata: k8sYamlMetadata{Name: "foo.bar"}}, true},
// Namespace uses IsDNS1123Label.
{&k8sYamlStruct{Kind: "Namespace", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "Namespace", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "Namespace", Metadata: k8sYamlMetadata{Name: "foo.bar"}}, true},
{&k8sYamlStruct{Kind: "Namespace", Metadata: k8sYamlMetadata{Name: "foo-bar"}}, false},
// CertificateSigningRequest has no validation.
{&k8sYamlStruct{Kind: "CertificateSigningRequest", Metadata: k8sYamlMetadata{Name: ""}}, false},
{&k8sYamlStruct{Kind: "CertificateSigningRequest", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "CertificateSigningRequest", Metadata: k8sYamlMetadata{Name: "%^&#$%*@^*@&#^"}}, false},
// RBAC uses path validation.
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "foo.bar"}}, false},
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "operator:role"}}, false},
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "operator/role"}}, true},
{&k8sYamlStruct{Kind: "Role", Metadata: k8sYamlMetadata{Name: "operator%role"}}, true},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "foo.bar"}}, false},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "operator:role"}}, false},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "operator/role"}}, true},
{&k8sYamlStruct{Kind: "ClusterRole", Metadata: k8sYamlMetadata{Name: "operator%role"}}, true},
{&k8sYamlStruct{Kind: "RoleBinding", Metadata: k8sYamlMetadata{Name: "operator:role"}}, false},
{&k8sYamlStruct{Kind: "ClusterRoleBinding", Metadata: k8sYamlMetadata{Name: "operator:role"}}, false},
// Unknown Kind
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: ""}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "foo.bar1234baz.seventyone"}}, false},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "FOO"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "123baz"}}, false},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "foo.BAR.baz"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "one-two"}}, false},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "-two"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "one_two"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "a..b"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "%^&#$%*@^*@&#^"}}, true},
{&k8sYamlStruct{Kind: "FutureKind", Metadata: k8sYamlMetadata{Name: "operator:pod"}}, true},
// No kind
{&k8sYamlStruct{Metadata: k8sYamlMetadata{Name: "foo"}}, false},
{&k8sYamlStruct{Metadata: k8sYamlMetadata{Name: "operator:pod"}}, true},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("%s/%s", tt.obj.Kind, tt.obj.Metadata.Name), func(t *testing.T) {
if err := validateMetadataName(tt.obj); (err != nil) != tt.wantErr {
t.Errorf("validateMetadataName() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestDeprecatedAPIFails(t *testing.T) {
modTime := time.Now()
mychart := chart.Chart{
Metadata: &chart.Metadata{
APIVersion: "v2",
Name: "failapi",
Version: "0.1.0",
Icon: "satisfy-the-linting-gods.gif",
},
Templates: []*common.File{
{
Name: "templates/baddeployment.yaml",
ModTime: modTime,
Data: []byte("apiVersion: apps/v1beta1\nkind: Deployment\nmetadata:\n name: baddep\nspec: {selector: {matchLabels: {foo: bar}}}"),
},
{
Name: "templates/goodsecret.yaml",
ModTime: modTime,
Data: []byte("apiVersion: v1\nkind: Secret\nmetadata:\n name: goodsecret"),
},
},
}
tmpdir := t.TempDir()
if err := chartutil.SaveDir(&mychart, tmpdir); err != nil {
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())}
Templates(
&linter,
namespace,
values,
TemplateLinterSkipSchemaValidation(false))
if l := len(linter.Messages); l != 1 {
for i, msg := range linter.Messages {
t.Logf("Message %d: %s", i, msg)
}
t.Fatalf("Expected 1 lint error, got %d", l)
}
err := linter.Messages[0].Err.(deprecatedAPIError)
if err.Deprecated != "apps/v1beta1 Deployment" {
t.Errorf("Surprised to learn that %q is deprecated", err.Deprecated)
}
}
const manifest = `apiVersion: v1
kind: ConfigMap
metadata:
name: foo
data:
myval1: {{default "val" .Values.mymap.key1 }}
myval2: {{default "val" .Values.mymap.key2 }}
`
// TestStrictTemplateParsingMapError is a regression test.
//
// The template engine should not produce an error when a map in values.yaml does
// not contain all possible keys.
//
// See https://github.com/helm/helm/issues/7483
func TestStrictTemplateParsingMapError(t *testing.T) {
ch := chart.Chart{
Metadata: &chart.Metadata{
Name: "regression7483",
APIVersion: "v2",
Version: "0.1.0",
},
Values: map[string]interface{}{
"mymap": map[string]string{
"key1": "val1",
},
},
Templates: []*common.File{
{
Name: "templates/configmap.yaml",
ModTime: time.Now(),
Data: []byte(manifest),
},
},
}
dir := t.TempDir()
if err := chartutil.SaveDir(&ch, dir); err != nil {
t.Fatal(err)
}
linter := &support.Linter{
ChartDir: filepath.Join(dir, ch.Metadata.Name),
}
Templates(
linter,
namespace,
ch.Values,
TemplateLinterSkipSchemaValidation(false))
if len(linter.Messages) != 0 {
t.Errorf("expected zero messages, got %d", len(linter.Messages))
for i, msg := range linter.Messages {
t.Logf("Message %d: %q", i, msg)
}
}
}
func TestValidateMatchSelector(t *testing.T) {
md := &k8sYamlStruct{
APIVersion: "apps/v1",
Kind: "Deployment",
Metadata: k8sYamlMetadata{
Name: "mydeployment",
},
}
manifest := `
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
`
if err := validateMatchSelector(md, manifest); err != nil {
t.Error(err)
}
manifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchExpressions:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
`
if err := validateMatchSelector(md, manifest); err != nil {
t.Error(err)
}
manifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
`
if err := validateMatchSelector(md, manifest); err == nil {
t.Error("expected Deployment with no selector to fail")
}
}
func TestValidateTopIndentLevel(t *testing.T) {
for doc, shouldFail := range map[string]bool{
// Should not fail
"\n\n\n\t\n \t\n": false,
"apiVersion:foo\n bar:baz": false,
"\n\n\napiVersion:foo\n\n\n": false,
// Should fail
" apiVersion:foo": true,
"\n\n apiVersion:foo\n\n": true,
} {
if err := validateTopIndentLevel(doc); (err == nil) == shouldFail {
t.Errorf("Expected %t for %q", shouldFail, doc)
}
}
}
// TestEmptyWithCommentsManifests checks the lint is not failing against empty manifests that contains only comments
// See https://github.com/helm/helm/issues/8621
func TestEmptyWithCommentsManifests(t *testing.T) {
mychart := chart.Chart{
Metadata: &chart.Metadata{
APIVersion: "v2",
Name: "emptymanifests",
Version: "0.1.0",
Icon: "satisfy-the-linting-gods.gif",
},
Templates: []*common.File{
{
Name: "templates/empty-with-comments.yaml",
ModTime: time.Now(),
Data: []byte("#@formatter:off\n"),
},
},
}
tmpdir := t.TempDir()
if err := chartutil.SaveDir(&mychart, tmpdir); err != nil {
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmpdir, mychart.Name())}
Templates(
&linter,
namespace,
values,
TemplateLinterSkipSchemaValidation(false))
if l := len(linter.Messages); l > 0 {
for i, msg := range linter.Messages {
t.Logf("Message %d: %s", i, msg)
}
t.Fatalf("Expected 0 lint errors, got %d", l)
}
}
func TestValidateListAnnotations(t *testing.T) {
md := &k8sYamlStruct{
APIVersion: "v1",
Kind: "List",
Metadata: k8sYamlMetadata{
Name: "list",
},
}
manifest := `
apiVersion: v1
kind: List
items:
- apiVersion: v1
kind: ConfigMap
metadata:
annotations:
helm.sh/resource-policy: keep
`
if err := validateListAnnotations(md, manifest); err == nil {
t.Fatal("expected list with nested keep annotations to fail")
}
manifest = `
apiVersion: v1
kind: List
metadata:
annotations:
helm.sh/resource-policy: keep
items:
- apiVersion: v1
kind: ConfigMap
`
if err := validateListAnnotations(md, manifest); err != nil {
t.Fatalf("List objects keep annotations should pass. got: %s", err)
}
}
func TestIsYamlFileExtension(t *testing.T) {
tests := []struct {
filename string
expected bool
}{
{"test.yaml", true},
{"test.yml", true},
{"test.txt", false},
{"test", false},
}
for _, test := range tests {
result := isYamlFileExtension(test.filename)
if result != test.expected {
t.Errorf("isYamlFileExtension(%s) = %v; want %v", test.filename, result, test.expected)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/dependencies_test.go | pkg/chart/v2/lint/rules/dependencies_test.go | /*
Copyright The Helm 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 rules
import (
"path/filepath"
"testing"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
func chartWithBadDependencies() chart.Chart {
badChartDeps := chart.Chart{
Metadata: &chart.Metadata{
Name: "badchart",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{
{
Name: "sub2",
},
{
Name: "sub3",
},
},
},
}
badChartDeps.SetDependencies(
&chart.Chart{
Metadata: &chart.Metadata{
Name: "sub1",
Version: "0.1.0",
APIVersion: "v2",
},
},
&chart.Chart{
Metadata: &chart.Metadata{
Name: "sub2",
Version: "0.1.0",
APIVersion: "v2",
},
},
)
return badChartDeps
}
func TestValidateDependencyInChartsDir(t *testing.T) {
c := chartWithBadDependencies()
if err := validateDependencyInChartsDir(&c); err == nil {
t.Error("chart should have been flagged for missing deps in chart directory")
}
}
func TestValidateDependencyInMetadata(t *testing.T) {
c := chartWithBadDependencies()
if err := validateDependencyInMetadata(&c); err == nil {
t.Errorf("chart should have been flagged for missing deps in chart metadata")
}
}
func TestValidateDependenciesUnique(t *testing.T) {
tests := []struct {
chart chart.Chart
}{
{chart.Chart{
Metadata: &chart.Metadata{
Name: "badchart",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{
{
Name: "foo",
},
{
Name: "foo",
},
},
},
}},
{chart.Chart{
Metadata: &chart.Metadata{
Name: "badchart",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{
{
Name: "foo",
Alias: "bar",
},
{
Name: "bar",
},
},
},
}},
{chart.Chart{
Metadata: &chart.Metadata{
Name: "badchart",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{
{
Name: "foo",
Alias: "baz",
},
{
Name: "bar",
Alias: "baz",
},
},
},
}},
}
for _, tt := range tests {
if err := validateDependenciesUnique(&tt.chart); err == nil {
t.Errorf("chart should have been flagged for dependency shadowing")
}
}
}
func TestDependencies(t *testing.T) {
tmp := t.TempDir()
c := chartWithBadDependencies()
err := chartutil.SaveDir(&c, tmp)
if err != nil {
t.Fatal(err)
}
linter := support.Linter{ChartDir: filepath.Join(tmp, c.Metadata.Name)}
Dependencies(&linter)
if l := len(linter.Messages); l != 2 {
t.Errorf("expected 2 linter errors for bad chart dependencies. Got %d.", l)
for i, msg := range linter.Messages {
t.Logf("Message: %d, Error: %#v", i, msg)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/dependencies.go | pkg/chart/v2/lint/rules/dependencies.go | /*
Copyright The Helm 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 rules // import "helm.sh/helm/v4/pkg/chart/v2/lint/rules"
import (
"fmt"
"strings"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
// Dependencies runs lints against a chart's dependencies
//
// See https://github.com/helm/helm/issues/7910
func Dependencies(linter *support.Linter) {
c, err := loader.LoadDir(linter.ChartDir)
if !linter.RunLinterRule(support.ErrorSev, "", validateChartFormat(err)) {
return
}
linter.RunLinterRule(support.ErrorSev, linter.ChartDir, validateDependencyInMetadata(c))
linter.RunLinterRule(support.ErrorSev, linter.ChartDir, validateDependenciesUnique(c))
linter.RunLinterRule(support.WarningSev, linter.ChartDir, validateDependencyInChartsDir(c))
}
func validateChartFormat(chartError error) error {
if chartError != nil {
return fmt.Errorf("unable to load chart\n\t%w", chartError)
}
return nil
}
func validateDependencyInChartsDir(c *chart.Chart) (err error) {
dependencies := map[string]struct{}{}
missing := []string{}
for _, dep := range c.Dependencies() {
dependencies[dep.Metadata.Name] = struct{}{}
}
for _, dep := range c.Metadata.Dependencies {
if _, ok := dependencies[dep.Name]; !ok {
missing = append(missing, dep.Name)
}
}
if len(missing) > 0 {
err = fmt.Errorf("chart directory is missing these dependencies: %s", strings.Join(missing, ","))
}
return err
}
func validateDependencyInMetadata(c *chart.Chart) (err error) {
dependencies := map[string]struct{}{}
missing := []string{}
for _, dep := range c.Metadata.Dependencies {
dependencies[dep.Name] = struct{}{}
}
for _, dep := range c.Dependencies() {
if _, ok := dependencies[dep.Metadata.Name]; !ok {
missing = append(missing, dep.Metadata.Name)
}
}
if len(missing) > 0 {
err = fmt.Errorf("chart metadata is missing these dependencies: %s", strings.Join(missing, ","))
}
return err
}
func validateDependenciesUnique(c *chart.Chart) (err error) {
dependencies := map[string]*chart.Dependency{}
shadowing := []string{}
for _, dep := range c.Metadata.Dependencies {
key := dep.Name
if dep.Alias != "" {
key = dep.Alias
}
if dependencies[key] != nil {
shadowing = append(shadowing, key)
}
dependencies[key] = dep
}
if len(shadowing) > 0 {
err = fmt.Errorf("multiple dependencies with name or alias: %s", strings.Join(shadowing, ","))
}
return err
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/lint/rules/template.go | pkg/chart/v2/lint/rules/template.go | /*
Copyright The Helm 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 rules
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"slices"
"strings"
"k8s.io/apimachinery/pkg/api/validation"
apipath "k8s.io/apimachinery/pkg/api/validation/path"
"k8s.io/apimachinery/pkg/util/validation/field"
"k8s.io/apimachinery/pkg/util/yaml"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/common/util"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
"helm.sh/helm/v4/pkg/chart/v2/loader"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/engine"
)
// Templates lints the templates in the Linter.
func Templates(linter *support.Linter, namespace string, values map[string]any, options ...TemplateLinterOption) {
templateLinter := newTemplateLinter(linter, namespace, values, options...)
templateLinter.Lint()
}
type TemplateLinterOption func(*templateLinter)
func TemplateLinterKubeVersion(kubeVersion *common.KubeVersion) TemplateLinterOption {
return func(tl *templateLinter) {
tl.kubeVersion = kubeVersion
}
}
func TemplateLinterSkipSchemaValidation(skipSchemaValidation bool) TemplateLinterOption {
return func(tl *templateLinter) {
tl.skipSchemaValidation = skipSchemaValidation
}
}
func newTemplateLinter(linter *support.Linter, namespace string, values map[string]any, options ...TemplateLinterOption) templateLinter {
result := templateLinter{
linter: linter,
values: values,
namespace: namespace,
}
for _, o := range options {
o(&result)
}
return result
}
type templateLinter struct {
linter *support.Linter
values map[string]any
namespace string
kubeVersion *common.KubeVersion
skipSchemaValidation bool
}
func (t *templateLinter) Lint() {
templatesDir := "templates/"
templatesPath := filepath.Join(t.linter.ChartDir, templatesDir)
templatesDirExists := t.linter.RunLinterRule(support.WarningSev, templatesDir, templatesDirExists(templatesPath))
if !templatesDirExists {
return
}
validTemplatesDir := t.linter.RunLinterRule(support.ErrorSev, templatesDir, validateTemplatesDir(templatesPath))
if !validTemplatesDir {
return
}
// Load chart and parse templates
chart, err := loader.Load(t.linter.ChartDir)
chartLoaded := t.linter.RunLinterRule(support.ErrorSev, templatesDir, err)
if !chartLoaded {
return
}
options := common.ReleaseOptions{
Name: "test-release",
Namespace: t.namespace,
}
caps := common.DefaultCapabilities.Copy()
if t.kubeVersion != nil {
caps.KubeVersion = *t.kubeVersion
}
// lint ignores import-values
// See https://github.com/helm/helm/issues/9658
if err := chartutil.ProcessDependencies(chart, t.values); err != nil {
return
}
cvals, err := util.CoalesceValues(chart, t.values)
if err != nil {
return
}
valuesToRender, err := util.ToRenderValuesWithSchemaValidation(chart, cvals, options, caps, t.skipSchemaValidation)
if err != nil {
t.linter.RunLinterRule(support.ErrorSev, templatesDir, err)
return
}
var e engine.Engine
e.LintMode = true
renderedContentMap, err := e.Render(chart, valuesToRender)
renderOk := t.linter.RunLinterRule(support.ErrorSev, templatesDir, err)
if !renderOk {
return
}
/* Iterate over all the templates to check:
- It is a .yaml file
- All the values in the template file is defined
- {{}} include | quote
- Generated content is a valid Yaml file
- Metadata.Namespace is not set
*/
for _, template := range chart.Templates {
fileName := template.Name
t.linter.RunLinterRule(support.ErrorSev, fileName, validateAllowedExtension(fileName))
// We only apply the following lint rules to yaml files
if !isYamlFileExtension(fileName) {
continue
}
// NOTE: disabled for now, Refs https://github.com/helm/helm/issues/1463
// Check that all the templates have a matching value
// linter.RunLinterRule(support.WarningSev, fpath, validateNoMissingValues(templatesPath, valuesToRender, preExecutedTemplate))
// NOTE: disabled for now, Refs https://github.com/helm/helm/issues/1037
// linter.RunLinterRule(support.WarningSev, fpath, validateQuotes(string(preExecutedTemplate)))
renderedContent := renderedContentMap[path.Join(chart.Name(), fileName)]
if strings.TrimSpace(renderedContent) != "" {
t.linter.RunLinterRule(support.WarningSev, fileName, validateTopIndentLevel(renderedContent))
decoder := yaml.NewYAMLOrJSONDecoder(strings.NewReader(renderedContent), 4096)
// Lint all resources if the file contains multiple documents separated by ---
for {
// Even though k8sYamlStruct only defines a few fields, an error in any other
// key will be raised as well
var yamlStruct *k8sYamlStruct
err := decoder.Decode(&yamlStruct)
if errors.Is(err, io.EOF) {
break
}
// If YAML linting fails here, it will always fail in the next block as well, so we should return here.
// fix https://github.com/helm/helm/issues/11391
if !t.linter.RunLinterRule(support.ErrorSev, fileName, validateYamlContent(err)) {
return
}
if yamlStruct != nil {
// NOTE: set to warnings to allow users to support out-of-date kubernetes
// Refs https://github.com/helm/helm/issues/8596
t.linter.RunLinterRule(support.WarningSev, fileName, validateMetadataName(yamlStruct))
t.linter.RunLinterRule(support.WarningSev, fileName, validateNoDeprecations(yamlStruct, t.kubeVersion))
t.linter.RunLinterRule(support.ErrorSev, fileName, validateMatchSelector(yamlStruct, renderedContent))
t.linter.RunLinterRule(support.ErrorSev, fileName, validateListAnnotations(yamlStruct, renderedContent))
}
}
}
}
}
// validateTopIndentLevel checks that the content does not start with an indent level > 0.
//
// This error can occur when a template accidentally inserts space. It can cause
// unpredictable errors depending on whether the text is normalized before being passed
// into the YAML parser. So we trap it here.
//
// See https://github.com/helm/helm/issues/8467
func validateTopIndentLevel(content string) error {
// Read lines until we get to a non-empty one
scanner := bufio.NewScanner(bytes.NewBufferString(content))
for scanner.Scan() {
line := scanner.Text()
// If line is empty, skip
if strings.TrimSpace(line) == "" {
continue
}
// If it starts with one or more spaces, this is an error
if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
return fmt.Errorf("document starts with an illegal indent: %q, which may cause parsing problems", line)
}
// Any other condition passes.
return nil
}
return scanner.Err()
}
// Validation functions
func templatesDirExists(templatesPath string) error {
_, err := os.Stat(templatesPath)
if errors.Is(err, os.ErrNotExist) {
return errors.New("directory does not exist")
}
return nil
}
func validateTemplatesDir(templatesPath string) error {
fi, err := os.Stat(templatesPath)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New("not a directory")
}
return nil
}
func validateAllowedExtension(fileName string) error {
ext := filepath.Ext(fileName)
validExtensions := []string{".yaml", ".yml", ".tpl", ".txt"}
if slices.Contains(validExtensions, ext) {
return nil
}
return fmt.Errorf("file extension '%s' not valid. Valid extensions are .yaml, .yml, .tpl, or .txt", ext)
}
func validateYamlContent(err error) error {
if err != nil {
return fmt.Errorf("unable to parse YAML: %w", err)
}
return nil
}
// validateMetadataName uses the correct validation function for the object
// Kind, or if not set, defaults to the standard definition of a subdomain in
// DNS (RFC 1123), used by most resources.
func validateMetadataName(obj *k8sYamlStruct) error {
fn := validateMetadataNameFunc(obj)
allErrs := field.ErrorList{}
for _, msg := range fn(obj.Metadata.Name, false) {
allErrs = append(allErrs, field.Invalid(field.NewPath("metadata").Child("name"), obj.Metadata.Name, msg))
}
if len(allErrs) > 0 {
return fmt.Errorf("object name does not conform to Kubernetes naming requirements: %q: %w", obj.Metadata.Name, allErrs.ToAggregate())
}
return nil
}
// validateMetadataNameFunc will return a name validation function for the
// object kind, if defined below.
//
// Rules should match those set in the various api validations:
// https://github.com/kubernetes/kubernetes/blob/v1.20.0/pkg/apis/core/validation/validation.go#L205-L274
// https://github.com/kubernetes/kubernetes/blob/v1.20.0/pkg/apis/apps/validation/validation.go#L39
// ...
//
// Implementing here to avoid importing k/k.
//
// If no mapping is defined, returns NameIsDNSSubdomain. This is used by object
// kinds that don't have special requirements, so is the most likely to work if
// new kinds are added.
func validateMetadataNameFunc(obj *k8sYamlStruct) validation.ValidateNameFunc {
switch strings.ToLower(obj.Kind) {
case "pod", "node", "secret", "endpoints", "resourcequota", // core
"controllerrevision", "daemonset", "deployment", "replicaset", "statefulset", // apps
"autoscaler", // autoscaler
"cronjob", "job", // batch
"lease", // coordination
"endpointslice", // discovery
"networkpolicy", "ingress", // networking
"podsecuritypolicy", // policy
"priorityclass", // scheduling
"podpreset", // settings
"storageclass", "volumeattachment", "csinode": // storage
return validation.NameIsDNSSubdomain
case "service":
return validation.NameIsDNS1035Label
case "namespace":
return validation.ValidateNamespaceName
case "serviceaccount":
return validation.ValidateServiceAccountName
case "certificatesigningrequest":
// No validation.
// https://github.com/kubernetes/kubernetes/blob/v1.20.0/pkg/apis/certificates/validation/validation.go#L137-L140
return func(_ string, _ bool) []string { return nil }
case "role", "clusterrole", "rolebinding", "clusterrolebinding":
// https://github.com/kubernetes/kubernetes/blob/v1.20.0/pkg/apis/rbac/validation/validation.go#L32-L34
return func(name string, _ bool) []string {
return apipath.IsValidPathSegmentName(name)
}
default:
return validation.NameIsDNSSubdomain
}
}
// validateMatchSelector ensures that template specs have a selector declared.
// See https://github.com/helm/helm/issues/1990
func validateMatchSelector(yamlStruct *k8sYamlStruct, manifest string) error {
switch yamlStruct.Kind {
case "Deployment", "ReplicaSet", "DaemonSet", "StatefulSet":
// verify that matchLabels or matchExpressions is present
if !strings.Contains(manifest, "matchLabels") && !strings.Contains(manifest, "matchExpressions") {
return fmt.Errorf("a %s must contain matchLabels or matchExpressions, and %q does not", yamlStruct.Kind, yamlStruct.Metadata.Name)
}
}
return nil
}
func validateListAnnotations(yamlStruct *k8sYamlStruct, manifest string) error {
if yamlStruct.Kind == "List" {
m := struct {
Items []struct {
Metadata struct {
Annotations map[string]string
}
}
}{}
if err := yaml.Unmarshal([]byte(manifest), &m); err != nil {
return validateYamlContent(err)
}
for _, i := range m.Items {
if _, ok := i.Metadata.Annotations["helm.sh/resource-policy"]; ok {
return errors.New("annotation 'helm.sh/resource-policy' within List objects are ignored")
}
}
}
return nil
}
func isYamlFileExtension(fileName string) bool {
ext := strings.ToLower(filepath.Ext(fileName))
return ext == ".yaml" || ext == ".yml"
}
// k8sYamlStruct stubs a Kubernetes YAML file.
type k8sYamlStruct struct {
APIVersion string `json:"apiVersion"`
Kind string
Metadata k8sYamlMetadata
}
type k8sYamlMetadata struct {
Namespace string
Name string
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/loader/archive.go | pkg/chart/v2/loader/archive.go | /*
Copyright The Helm 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 loader
import (
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"helm.sh/helm/v4/pkg/chart/loader/archive"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// FileLoader loads a chart from a file
type FileLoader string
// Load loads a chart
func (l FileLoader) Load() (*chart.Chart, error) {
return LoadFile(string(l))
}
// LoadFile loads from an archive file.
func LoadFile(name string) (*chart.Chart, error) {
if fi, err := os.Stat(name); err != nil {
return nil, err
} else if fi.IsDir() {
return nil, errors.New("cannot load a directory")
}
raw, err := os.Open(name)
if err != nil {
return nil, err
}
defer raw.Close()
err = archive.EnsureArchive(name, raw)
if err != nil {
return nil, err
}
c, err := LoadArchive(raw)
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return nil, fmt.Errorf("file '%s' does not appear to be a valid chart file (details: %w)", name, err)
}
}
return c, err
}
// LoadArchive loads from a reader containing a compressed tar archive.
func LoadArchive(in io.Reader) (*chart.Chart, error) {
files, err := archive.LoadArchiveFiles(in)
if err != nil {
return nil, err
}
return LoadFiles(files)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/loader/directory.go | pkg/chart/v2/loader/directory.go | /*
Copyright The Helm 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 loader
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"helm.sh/helm/v4/internal/sympath"
"helm.sh/helm/v4/pkg/chart/loader/archive"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/ignore"
)
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
// DirLoader loads a chart from a directory
type DirLoader string
// Load loads the chart
func (l DirLoader) Load() (*chart.Chart, error) {
return LoadDir(string(l))
}
// LoadDir loads from a directory.
//
// This loads charts only from directories.
func LoadDir(dir string) (*chart.Chart, error) {
topdir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
// Just used for errors.
c := &chart.Chart{}
rules := ignore.Empty()
ifile := filepath.Join(topdir, ignore.HelmIgnore)
if _, err := os.Stat(ifile); err == nil {
r, err := ignore.ParseFile(ifile)
if err != nil {
return c, err
}
rules = r
}
rules.AddDefaults()
files := []*archive.BufferedFile{}
topdir += string(filepath.Separator)
walk := func(name string, fi os.FileInfo, err error) error {
n := strings.TrimPrefix(name, topdir)
if n == "" {
// No need to process top level. Avoid bug with helmignore .* matching
// empty names. See issue 1779.
return nil
}
// Normalize to / since it will also work on Windows
n = filepath.ToSlash(n)
if err != nil {
return err
}
if fi.IsDir() {
// Directory-based ignore rules should involve skipping the entire
// contents of that directory.
if rules.Ignore(n, fi) {
return filepath.SkipDir
}
return nil
}
// If a .helmignore file matches, skip this file.
if rules.Ignore(n, fi) {
return nil
}
// Irregular files include devices, sockets, and other uses of files that
// are not regular files. In Go they have a file mode type bit set.
// See https://golang.org/pkg/os/#FileMode for examples.
if !fi.Mode().IsRegular() {
return fmt.Errorf("cannot load irregular file %s as it has file mode type bits set", name)
}
if fi.Size() > archive.MaxDecompressedFileSize {
return fmt.Errorf("chart file %q is larger than the maximum file size %d", fi.Name(), archive.MaxDecompressedFileSize)
}
data, err := os.ReadFile(name)
if err != nil {
return fmt.Errorf("error reading %s: %w", n, err)
}
data = bytes.TrimPrefix(data, utf8bom)
files = append(files, &archive.BufferedFile{Name: n, ModTime: fi.ModTime(), Data: data})
return nil
}
if err = sympath.Walk(topdir, walk); err != nil {
return c, err
}
return LoadFiles(files)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/loader/load.go | pkg/chart/v2/loader/load.go | /*
Copyright The Helm 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 loader
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"maps"
"os"
"path/filepath"
"strings"
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/loader/archive"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// ChartLoader loads a chart.
type ChartLoader interface {
Load() (*chart.Chart, error)
}
// Loader returns a new ChartLoader appropriate for the given chart name
func Loader(name string) (ChartLoader, error) {
fi, err := os.Stat(name)
if err != nil {
return nil, err
}
if fi.IsDir() {
return DirLoader(name), nil
}
return FileLoader(name), nil
}
// Load takes a string name, tries to resolve it to a file or directory, and then loads it.
//
// This is the preferred way to load a chart. It will discover the chart encoding
// and hand off to the appropriate chart reader.
//
// If a .helmignore file is present, the directory loader will skip loading any files
// matching it. But .helmignore is not evaluated when reading out of an archive.
func Load(name string) (*chart.Chart, error) {
l, err := Loader(name)
if err != nil {
return nil, err
}
return l.Load()
}
// LoadFiles loads from in-memory files.
func LoadFiles(files []*archive.BufferedFile) (*chart.Chart, error) {
c := new(chart.Chart)
subcharts := make(map[string][]*archive.BufferedFile)
// do not rely on assumed ordering of files in the chart and crash
// if Chart.yaml was not coming early enough to initialize metadata
for _, f := range files {
c.Raw = append(c.Raw, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
if f.Name == "Chart.yaml" {
if c.Metadata == nil {
c.Metadata = new(chart.Metadata)
}
if err := yaml.Unmarshal(f.Data, c.Metadata); err != nil {
return c, fmt.Errorf("cannot load Chart.yaml: %w", err)
}
// NOTE(bacongobbler): while the chart specification says that APIVersion must be set,
// Helm 2 accepted charts that did not provide an APIVersion in their chart metadata.
// Because of that, if APIVersion is unset, we should assume we're loading a v1 chart.
if c.Metadata.APIVersion == "" {
c.Metadata.APIVersion = chart.APIVersionV1
}
c.ModTime = f.ModTime
}
}
for _, f := range files {
switch {
case f.Name == "Chart.yaml":
// already processed
continue
case f.Name == "Chart.lock":
c.Lock = new(chart.Lock)
if err := yaml.Unmarshal(f.Data, &c.Lock); err != nil {
return c, fmt.Errorf("cannot load Chart.lock: %w", err)
}
case f.Name == "values.yaml":
values, err := LoadValues(bytes.NewReader(f.Data))
if err != nil {
return c, fmt.Errorf("cannot load values.yaml: %w", err)
}
c.Values = values
case f.Name == "values.schema.json":
c.Schema = f.Data
c.SchemaModTime = f.ModTime
// Deprecated: requirements.yaml is deprecated use Chart.yaml.
// We will handle it for you because we are nice people
case f.Name == "requirements.yaml":
if c.Metadata == nil {
c.Metadata = new(chart.Metadata)
}
if c.Metadata.APIVersion != chart.APIVersionV1 {
log.Printf("Warning: Dependencies are handled in Chart.yaml since apiVersion \"v2\". We recommend migrating dependencies to Chart.yaml.")
}
if err := yaml.Unmarshal(f.Data, c.Metadata); err != nil {
return c, fmt.Errorf("cannot load requirements.yaml: %w", err)
}
if c.Metadata.APIVersion == chart.APIVersionV1 {
c.Files = append(c.Files, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
}
// Deprecated: requirements.lock is deprecated use Chart.lock.
case f.Name == "requirements.lock":
c.Lock = new(chart.Lock)
if err := yaml.Unmarshal(f.Data, &c.Lock); err != nil {
return c, fmt.Errorf("cannot load requirements.lock: %w", err)
}
if c.Metadata == nil {
c.Metadata = new(chart.Metadata)
}
if c.Metadata.APIVersion != chart.APIVersionV1 {
log.Printf("Warning: Dependency locking is handled in Chart.lock since apiVersion \"v2\". We recommend migrating to Chart.lock.")
}
if c.Metadata.APIVersion == chart.APIVersionV1 {
c.Files = append(c.Files, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
}
case strings.HasPrefix(f.Name, "templates/"):
c.Templates = append(c.Templates, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
case strings.HasPrefix(f.Name, "charts/"):
if filepath.Ext(f.Name) == ".prov" {
c.Files = append(c.Files, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
continue
}
fname := strings.TrimPrefix(f.Name, "charts/")
cname := strings.SplitN(fname, "/", 2)[0]
subcharts[cname] = append(subcharts[cname], &archive.BufferedFile{Name: fname, ModTime: f.ModTime, Data: f.Data})
default:
c.Files = append(c.Files, &common.File{Name: f.Name, ModTime: f.ModTime, Data: f.Data})
}
}
if c.Metadata == nil {
return c, errors.New("Chart.yaml file is missing") //nolint:staticcheck
}
if err := c.Validate(); err != nil {
return c, err
}
for n, files := range subcharts {
var sc *chart.Chart
var err error
switch {
case strings.IndexAny(n, "_.") == 0:
continue
case filepath.Ext(n) == ".tgz":
file := files[0]
if file.Name != n {
return c, fmt.Errorf("error unpacking subchart tar in %s: expected %s, got %s", c.Name(), n, file.Name)
}
// Untar the chart and add to c.Dependencies
sc, err = LoadArchive(bytes.NewBuffer(file.Data))
default:
// We have to trim the prefix off of every file, and ignore any file
// that is in charts/, but isn't actually a chart.
buff := make([]*archive.BufferedFile, 0, len(files))
for _, f := range files {
parts := strings.SplitN(f.Name, "/", 2)
if len(parts) < 2 {
continue
}
f.Name = parts[1]
buff = append(buff, f)
}
sc, err = LoadFiles(buff)
}
if err != nil {
return c, fmt.Errorf("error unpacking subchart %s in %s: %w", n, c.Name(), err)
}
c.AddDependency(sc)
}
return c, nil
}
// LoadValues loads values from a reader.
//
// The reader is expected to contain one or more YAML documents, the values of which are merged.
// And the values can be either a chart's default values or user-supplied values.
func LoadValues(data io.Reader) (map[string]interface{}, error) {
values := map[string]interface{}{}
reader := utilyaml.NewYAMLReader(bufio.NewReader(data))
for {
currentMap := map[string]interface{}{}
raw, err := reader.Read()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("error reading yaml document: %w", err)
}
if err := yaml.Unmarshal(raw, ¤tMap); err != nil {
return nil, fmt.Errorf("cannot unmarshal yaml document: %w", err)
}
values = MergeMaps(values, currentMap)
}
return values, nil
}
// MergeMaps merges two maps. If a key exists in both maps, the value from b will be used.
// If the value is a map, the maps will be merged recursively.
func MergeMaps(a, b map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{}, len(a))
maps.Copy(out, a)
for k, v := range b {
if v, ok := v.(map[string]interface{}); ok {
if bv, ok := out[k]; ok {
if bv, ok := bv.(map[string]interface{}); ok {
out[k] = MergeMaps(bv, v)
continue
}
}
}
out[k] = v
}
return out
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/loader/load_test.go | pkg/chart/v2/loader/load_test.go | /*
Copyright The Helm 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 loader
import (
"archive/tar"
"bytes"
"compress/gzip"
"errors"
"io"
"log"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/loader/archive"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
func TestLoadDir(t *testing.T) {
l, err := Loader("testdata/frobnitz")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyFrobnitz(t, c)
verifyChart(t, c)
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
}
func TestLoadDirWithDevNull(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("test only works on unix systems with /dev/null present")
}
l, err := Loader("testdata/frobnitz_with_dev_null")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
if _, err := l.Load(); err == nil {
t.Errorf("packages with an irregular file (/dev/null) should not load")
}
}
func TestLoadDirWithSymlink(t *testing.T) {
sym := filepath.Join("..", "LICENSE")
link := filepath.Join("testdata", "frobnitz_with_symlink", "LICENSE")
if err := os.Symlink(sym, link); err != nil {
t.Fatal(err)
}
defer os.Remove(link)
l, err := Loader("testdata/frobnitz_with_symlink")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyFrobnitz(t, c)
verifyChart(t, c)
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
}
func TestBomTestData(t *testing.T) {
testFiles := []string{"frobnitz_with_bom/.helmignore", "frobnitz_with_bom/templates/template.tpl", "frobnitz_with_bom/Chart.yaml"}
for _, file := range testFiles {
data, err := os.ReadFile("testdata/" + file)
if err != nil || !bytes.HasPrefix(data, utf8bom) {
t.Errorf("Test file has no BOM or is invalid: testdata/%s", file)
}
}
archive, err := os.ReadFile("testdata/frobnitz_with_bom.tgz")
if err != nil {
t.Fatalf("Error reading archive frobnitz_with_bom.tgz: %s", err)
}
unzipped, err := gzip.NewReader(bytes.NewReader(archive))
if err != nil {
t.Fatalf("Error reading archive frobnitz_with_bom.tgz: %s", err)
}
defer unzipped.Close()
for _, testFile := range testFiles {
data := make([]byte, 3)
err := unzipped.Reset(bytes.NewReader(archive))
if err != nil {
t.Fatalf("Error reading archive frobnitz_with_bom.tgz: %s", err)
}
tr := tar.NewReader(unzipped)
for {
file, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
t.Fatalf("Error reading archive frobnitz_with_bom.tgz: %s", err)
}
if file != nil && strings.EqualFold(file.Name, testFile) {
_, err := tr.Read(data)
if err != nil {
t.Fatalf("Error reading archive frobnitz_with_bom.tgz: %s", err)
} else {
break
}
}
}
if !bytes.Equal(data, utf8bom) {
t.Fatalf("Test file has no BOM or is invalid: frobnitz_with_bom.tgz/%s", testFile)
}
}
}
func TestLoadDirWithUTFBOM(t *testing.T) {
l, err := Loader("testdata/frobnitz_with_bom")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyFrobnitz(t, c)
verifyChart(t, c)
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
verifyBomStripped(t, c.Files)
}
func TestLoadArchiveWithUTFBOM(t *testing.T) {
l, err := Loader("testdata/frobnitz_with_bom.tgz")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyFrobnitz(t, c)
verifyChart(t, c)
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
verifyBomStripped(t, c.Files)
}
func TestLoadV1(t *testing.T) {
l, err := Loader("testdata/frobnitz.v1")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
}
func TestLoadFileV1(t *testing.T) {
l, err := Loader("testdata/frobnitz.v1.tgz")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
}
func TestLoadFile(t *testing.T) {
l, err := Loader("testdata/frobnitz-1.2.3.tgz")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyFrobnitz(t, c)
verifyChart(t, c)
verifyDependencies(t, c)
}
func TestLoadFiles_BadCases(t *testing.T) {
for _, tt := range []struct {
name string
bufferedFiles []*archive.BufferedFile
expectError string
}{
{
name: "These files contain only requirements.lock",
bufferedFiles: []*archive.BufferedFile{
{
Name: "requirements.lock",
ModTime: time.Now(),
Data: []byte(""),
},
},
expectError: "validation: chart.metadata.apiVersion is required"},
} {
_, err := LoadFiles(tt.bufferedFiles)
if err == nil {
t.Fatal("expected error when load illegal files")
}
if !strings.Contains(err.Error(), tt.expectError) {
t.Errorf("Expected error to contain %q, got %q for %s", tt.expectError, err.Error(), tt.name)
}
}
}
func TestLoadFiles(t *testing.T) {
modTime := time.Now()
goodFiles := []*archive.BufferedFile{
{
Name: "Chart.yaml",
ModTime: modTime,
Data: []byte(`apiVersion: v1
name: frobnitz
description: This is a frobnitz.
version: "1.2.3"
keywords:
- frobnitz
- sprocket
- dodad
maintainers:
- name: The Helm Team
email: helm@example.com
- name: Someone Else
email: nobody@example.com
sources:
- https://example.com/foo/bar
home: http://example.com
icon: https://example.com/64x64.png
`),
},
{
Name: "values.yaml",
ModTime: modTime,
Data: []byte("var: some values"),
},
{
Name: "values.schema.json",
ModTime: modTime,
Data: []byte("type: Values"),
},
{
Name: "templates/deployment.yaml",
ModTime: modTime,
Data: []byte("some deployment"),
},
{
Name: "templates/service.yaml",
ModTime: modTime,
Data: []byte("some service"),
},
}
c, err := LoadFiles(goodFiles)
if err != nil {
t.Errorf("Expected good files to be loaded, got %v", err)
}
if c.Name() != "frobnitz" {
t.Errorf("Expected chart name to be 'frobnitz', got %s", c.Name())
}
if c.Values["var"] != "some values" {
t.Error("Expected chart values to be populated with default values")
}
if len(c.Raw) != 5 {
t.Errorf("Expected %d files, got %d", 5, len(c.Raw))
}
if !bytes.Equal(c.Schema, []byte("type: Values")) {
t.Error("Expected chart schema to be populated with default values")
}
if len(c.Templates) != 2 {
t.Errorf("Expected number of templates == 2, got %d", len(c.Templates))
}
if _, err = LoadFiles([]*archive.BufferedFile{}); err == nil {
t.Fatal("Expected err to be non-nil")
}
if err.Error() != "Chart.yaml file is missing" {
t.Errorf("Expected chart metadata missing error, got '%s'", err.Error())
}
}
// Test the order of file loading. The Chart.yaml file needs to come first for
// later comparison checks. See https://github.com/helm/helm/pull/8948
func TestLoadFilesOrder(t *testing.T) {
modTime := time.Now()
goodFiles := []*archive.BufferedFile{
{
Name: "requirements.yaml",
ModTime: modTime,
Data: []byte("dependencies:"),
},
{
Name: "values.yaml",
ModTime: modTime,
Data: []byte("var: some values"),
},
{
Name: "templates/deployment.yaml",
ModTime: modTime,
Data: []byte("some deployment"),
},
{
Name: "templates/service.yaml",
ModTime: modTime,
Data: []byte("some service"),
},
{
Name: "Chart.yaml",
ModTime: modTime,
Data: []byte(`apiVersion: v1
name: frobnitz
description: This is a frobnitz.
version: "1.2.3"
keywords:
- frobnitz
- sprocket
- dodad
maintainers:
- name: The Helm Team
email: helm@example.com
- name: Someone Else
email: nobody@example.com
sources:
- https://example.com/foo/bar
home: http://example.com
icon: https://example.com/64x64.png
`),
},
}
// Capture stderr to make sure message about Chart.yaml handle dependencies
// is not present
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("Unable to create pipe: %s", err)
}
stderr := log.Writer()
log.SetOutput(w)
defer func() {
log.SetOutput(stderr)
}()
_, err = LoadFiles(goodFiles)
if err != nil {
t.Errorf("Expected good files to be loaded, got %v", err)
}
w.Close()
var text bytes.Buffer
io.Copy(&text, r)
if text.String() != "" {
t.Errorf("Expected no message to Stderr, got %s", text.String())
}
}
// Packaging the chart on a Windows machine will produce an
// archive that has \\ as delimiters. Test that we support these archives
func TestLoadFileBackslash(t *testing.T) {
c, err := Load("testdata/frobnitz_backslash-1.2.3.tgz")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyChartFileAndTemplate(t, c, "frobnitz_backslash")
verifyChart(t, c)
verifyDependencies(t, c)
}
func TestLoadV2WithReqs(t *testing.T) {
l, err := Loader("testdata/frobnitz.v2.reqs")
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
c, err := l.Load()
if err != nil {
t.Fatalf("Failed to load testdata: %s", err)
}
verifyDependencies(t, c)
verifyDependenciesLock(t, c)
}
func TestLoadInvalidArchive(t *testing.T) {
tmpdir := t.TempDir()
writeTar := func(filename, internalPath string, body []byte) {
dest, err := os.Create(filename)
if err != nil {
t.Fatal(err)
}
zipper := gzip.NewWriter(dest)
tw := tar.NewWriter(zipper)
h := &tar.Header{
Name: internalPath,
Mode: 0755,
Size: int64(len(body)),
ModTime: time.Now(),
}
if err := tw.WriteHeader(h); err != nil {
t.Fatal(err)
}
if _, err := tw.Write(body); err != nil {
t.Fatal(err)
}
tw.Close()
zipper.Close()
dest.Close()
}
for _, tt := range []struct {
chartname string
internal string
expectError string
}{
{"illegal-dots.tgz", "../../malformed-helm-test", "chart illegally references parent directory"},
{"illegal-dots2.tgz", "/foo/../../malformed-helm-test", "chart illegally references parent directory"},
{"illegal-dots3.tgz", "/../../malformed-helm-test", "chart illegally references parent directory"},
{"illegal-dots4.tgz", "./../../malformed-helm-test", "chart illegally references parent directory"},
{"illegal-name.tgz", "./.", "chart illegally contains content outside the base directory"},
{"illegal-name2.tgz", "/./.", "chart illegally contains content outside the base directory"},
{"illegal-name3.tgz", "missing-leading-slash", "chart illegally contains content outside the base directory"},
{"illegal-name4.tgz", "/missing-leading-slash", "Chart.yaml file is missing"},
{"illegal-abspath.tgz", "//foo", "chart illegally contains absolute paths"},
{"illegal-abspath2.tgz", "///foo", "chart illegally contains absolute paths"},
{"illegal-abspath3.tgz", "\\\\foo", "chart illegally contains absolute paths"},
{"illegal-abspath3.tgz", "\\..\\..\\foo", "chart illegally references parent directory"},
// Under special circumstances, this can get normalized to things that look like absolute Windows paths
{"illegal-abspath4.tgz", "\\.\\c:\\\\foo", "chart contains illegally named files"},
{"illegal-abspath5.tgz", "/./c://foo", "chart contains illegally named files"},
{"illegal-abspath6.tgz", "\\\\?\\Some\\windows\\magic", "chart illegally contains absolute paths"},
} {
illegalChart := filepath.Join(tmpdir, tt.chartname)
writeTar(illegalChart, tt.internal, []byte("hello: world"))
_, err := Load(illegalChart)
if err == nil {
t.Fatal("expected error when unpacking illegal files")
}
if !strings.Contains(err.Error(), tt.expectError) {
t.Errorf("Expected error to contain %q, got %q for %s", tt.expectError, err.Error(), tt.chartname)
}
}
// Make sure that absolute path gets interpreted as relative
illegalChart := filepath.Join(tmpdir, "abs-path.tgz")
writeTar(illegalChart, "/Chart.yaml", []byte("hello: world"))
_, err := Load(illegalChart)
if err.Error() != "validation: chart.metadata.name is required" {
t.Error(err)
}
// And just to validate that the above was not spurious
illegalChart = filepath.Join(tmpdir, "abs-path2.tgz")
writeTar(illegalChart, "files/whatever.yaml", []byte("hello: world"))
_, err = Load(illegalChart)
if err.Error() != "Chart.yaml file is missing" {
t.Errorf("Unexpected error message: %s", err)
}
// Finally, test that drive letter gets stripped off on Windows
illegalChart = filepath.Join(tmpdir, "abs-winpath.tgz")
writeTar(illegalChart, "c:\\Chart.yaml", []byte("hello: world"))
_, err = Load(illegalChart)
if err.Error() != "validation: chart.metadata.name is required" {
t.Error(err)
}
}
func TestLoadValues(t *testing.T) {
testCases := map[string]struct {
data []byte
expctedValues map[string]interface{}
}{
"It should load values correctly": {
data: []byte(`
foo:
image: foo:v1
bar:
version: v2
`),
expctedValues: map[string]interface{}{
"foo": map[string]interface{}{
"image": "foo:v1",
},
"bar": map[string]interface{}{
"version": "v2",
},
},
},
"It should load values correctly with multiple documents in one file": {
data: []byte(`
foo:
image: foo:v1
bar:
version: v2
---
foo:
image: foo:v2
`),
expctedValues: map[string]interface{}{
"foo": map[string]interface{}{
"image": "foo:v2",
},
"bar": map[string]interface{}{
"version": "v2",
},
},
},
}
for testName, testCase := range testCases {
t.Run(testName, func(tt *testing.T) {
values, err := LoadValues(bytes.NewReader(testCase.data))
if err != nil {
tt.Fatal(err)
}
if !reflect.DeepEqual(values, testCase.expctedValues) {
tt.Errorf("Expected values: %v, got %v", testCase.expctedValues, values)
}
})
}
}
func TestMergeValuesV2(t *testing.T) {
nestedMap := map[string]interface{}{
"foo": "bar",
"baz": map[string]string{
"cool": "stuff",
},
}
anotherNestedMap := map[string]interface{}{
"foo": "bar",
"baz": map[string]string{
"cool": "things",
"awesome": "stuff",
},
}
flatMap := map[string]interface{}{
"foo": "bar",
"baz": "stuff",
}
anotherFlatMap := map[string]interface{}{
"testing": "fun",
}
testMap := MergeMaps(flatMap, nestedMap)
equal := reflect.DeepEqual(testMap, nestedMap)
if !equal {
t.Errorf("Expected a nested map to overwrite a flat value. Expected: %v, got %v", nestedMap, testMap)
}
testMap = MergeMaps(nestedMap, flatMap)
equal = reflect.DeepEqual(testMap, flatMap)
if !equal {
t.Errorf("Expected a flat value to overwrite a map. Expected: %v, got %v", flatMap, testMap)
}
testMap = MergeMaps(nestedMap, anotherNestedMap)
equal = reflect.DeepEqual(testMap, anotherNestedMap)
if !equal {
t.Errorf("Expected a nested map to overwrite another nested map. Expected: %v, got %v", anotherNestedMap, testMap)
}
testMap = MergeMaps(anotherFlatMap, anotherNestedMap)
expectedMap := map[string]interface{}{
"testing": "fun",
"foo": "bar",
"baz": map[string]string{
"cool": "things",
"awesome": "stuff",
},
}
equal = reflect.DeepEqual(testMap, expectedMap)
if !equal {
t.Errorf("Expected a map with different keys to merge properly with another map. Expected: %v, got %v", expectedMap, testMap)
}
}
func verifyChart(t *testing.T, c *chart.Chart) {
t.Helper()
if c.Name() == "" {
t.Fatalf("No chart metadata found on %v", c)
}
t.Logf("Verifying chart %s", c.Name())
if len(c.Templates) != 1 {
t.Errorf("Expected 1 template, got %d", len(c.Templates))
}
numfiles := 6
if len(c.Files) != numfiles {
t.Errorf("Expected %d extra files, got %d", numfiles, len(c.Files))
for _, n := range c.Files {
t.Logf("\t%s", n.Name)
}
}
if len(c.Dependencies()) != 2 {
t.Errorf("Expected 2 dependencies, got %d (%v)", len(c.Dependencies()), c.Dependencies())
for _, d := range c.Dependencies() {
t.Logf("\tSubchart: %s\n", d.Name())
}
}
expect := map[string]map[string]string{
"alpine": {
"version": "0.1.0",
},
"mariner": {
"version": "4.3.2",
},
}
for _, dep := range c.Dependencies() {
if dep.Metadata == nil {
t.Fatalf("expected metadata on dependency: %v", dep)
}
exp, ok := expect[dep.Name()]
if !ok {
t.Fatalf("Unknown dependency %s", dep.Name())
}
if exp["version"] != dep.Metadata.Version {
t.Errorf("Expected %s version %s, got %s", dep.Name(), exp["version"], dep.Metadata.Version)
}
}
}
func verifyDependencies(t *testing.T, c *chart.Chart) {
t.Helper()
if len(c.Metadata.Dependencies) != 2 {
t.Errorf("Expected 2 dependencies, got %d", len(c.Metadata.Dependencies))
}
tests := []*chart.Dependency{
{Name: "alpine", Version: "0.1.0", Repository: "https://example.com/charts"},
{Name: "mariner", Version: "4.3.2", Repository: "https://example.com/charts"},
}
for i, tt := range tests {
d := c.Metadata.Dependencies[i]
if d.Name != tt.Name {
t.Errorf("Expected dependency named %q, got %q", tt.Name, d.Name)
}
if d.Version != tt.Version {
t.Errorf("Expected dependency named %q to have version %q, got %q", tt.Name, tt.Version, d.Version)
}
if d.Repository != tt.Repository {
t.Errorf("Expected dependency named %q to have repository %q, got %q", tt.Name, tt.Repository, d.Repository)
}
}
}
func verifyDependenciesLock(t *testing.T, c *chart.Chart) {
t.Helper()
if len(c.Metadata.Dependencies) != 2 {
t.Errorf("Expected 2 dependencies, got %d", len(c.Metadata.Dependencies))
}
tests := []*chart.Dependency{
{Name: "alpine", Version: "0.1.0", Repository: "https://example.com/charts"},
{Name: "mariner", Version: "4.3.2", Repository: "https://example.com/charts"},
}
for i, tt := range tests {
d := c.Metadata.Dependencies[i]
if d.Name != tt.Name {
t.Errorf("Expected dependency named %q, got %q", tt.Name, d.Name)
}
if d.Version != tt.Version {
t.Errorf("Expected dependency named %q to have version %q, got %q", tt.Name, tt.Version, d.Version)
}
if d.Repository != tt.Repository {
t.Errorf("Expected dependency named %q to have repository %q, got %q", tt.Name, tt.Repository, d.Repository)
}
}
}
func verifyFrobnitz(t *testing.T, c *chart.Chart) {
t.Helper()
verifyChartFileAndTemplate(t, c, "frobnitz")
}
func verifyChartFileAndTemplate(t *testing.T, c *chart.Chart, name string) {
t.Helper()
if c.Metadata == nil {
t.Fatal("Metadata is nil")
}
if c.Name() != name {
t.Errorf("Expected %s, got %s", name, c.Name())
}
if len(c.Templates) != 1 {
t.Fatalf("Expected 1 template, got %d", len(c.Templates))
}
if c.Templates[0].Name != "templates/template.tpl" {
t.Errorf("Unexpected template: %s", c.Templates[0].Name)
}
if len(c.Templates[0].Data) == 0 {
t.Error("No template data.")
}
if len(c.Files) != 6 {
t.Fatalf("Expected 6 Files, got %d", len(c.Files))
}
if len(c.Dependencies()) != 2 {
t.Fatalf("Expected 2 Dependency, got %d", len(c.Dependencies()))
}
if len(c.Metadata.Dependencies) != 2 {
t.Fatalf("Expected 2 Dependencies.Dependency, got %d", len(c.Metadata.Dependencies))
}
if len(c.Lock.Dependencies) != 2 {
t.Fatalf("Expected 2 Lock.Dependency, got %d", len(c.Lock.Dependencies))
}
for _, dep := range c.Dependencies() {
switch dep.Name() {
case "mariner":
case "alpine":
if len(dep.Templates) != 1 {
t.Fatalf("Expected 1 template, got %d", len(dep.Templates))
}
if dep.Templates[0].Name != "templates/alpine-pod.yaml" {
t.Errorf("Unexpected template: %s", dep.Templates[0].Name)
}
if len(dep.Templates[0].Data) == 0 {
t.Error("No template data.")
}
if len(dep.Files) != 1 {
t.Fatalf("Expected 1 Files, got %d", len(dep.Files))
}
if len(dep.Dependencies()) != 2 {
t.Fatalf("Expected 2 Dependency, got %d", len(dep.Dependencies()))
}
default:
t.Errorf("Unexpected dependency %s", dep.Name())
}
}
}
func verifyBomStripped(t *testing.T, files []*common.File) {
t.Helper()
for _, file := range files {
if bytes.HasPrefix(file.Data, utf8bom) {
t.Errorf("Byte Order Mark still present in processed file %s", file.Name)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cli/environment_test.go | pkg/cli/environment_test.go | /*
Copyright The Helm 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 cli
import (
"os"
"reflect"
"strings"
"testing"
"github.com/spf13/pflag"
"helm.sh/helm/v4/internal/version"
)
func TestSetNamespace(t *testing.T) {
settings := New()
if settings.namespace != "" {
t.Errorf("Expected empty namespace, got %s", settings.namespace)
}
settings.SetNamespace("testns")
if settings.namespace != "testns" {
t.Errorf("Expected namespace testns, got %s", settings.namespace)
}
}
func TestEnvSettings(t *testing.T) {
tests := []struct {
name string
// input
args string
envvars map[string]string
// expected values
ns, kcontext string
debug bool
maxhistory int
kubeAsUser string
kubeAsGroups []string
kubeCaFile string
kubeInsecure bool
kubeTLSServer string
burstLimit int
qps float32
}{
{
name: "defaults",
ns: "default",
maxhistory: defaultMaxHistory,
burstLimit: defaultBurstLimit,
qps: defaultQPS,
},
{
name: "with flags set",
args: "--debug --namespace=myns --kube-as-user=poro --kube-as-group=admins --kube-as-group=teatime --kube-as-group=snackeaters --kube-ca-file=/tmp/ca.crt --burst-limit 100 --qps 50.12 --kube-insecure-skip-tls-verify=true --kube-tls-server-name=example.org",
ns: "myns",
debug: true,
maxhistory: defaultMaxHistory,
burstLimit: 100,
qps: 50.12,
kubeAsUser: "poro",
kubeAsGroups: []string{"admins", "teatime", "snackeaters"},
kubeCaFile: "/tmp/ca.crt",
kubeTLSServer: "example.org",
kubeInsecure: true,
},
{
name: "with envvars set",
envvars: map[string]string{"HELM_DEBUG": "1", "HELM_NAMESPACE": "yourns", "HELM_KUBEASUSER": "pikachu", "HELM_KUBEASGROUPS": ",,,operators,snackeaters,partyanimals", "HELM_MAX_HISTORY": "5", "HELM_KUBECAFILE": "/tmp/ca.crt", "HELM_BURST_LIMIT": "150", "HELM_KUBEINSECURE_SKIP_TLS_VERIFY": "true", "HELM_KUBETLS_SERVER_NAME": "example.org", "HELM_QPS": "60.34"},
ns: "yourns",
maxhistory: 5,
burstLimit: 150,
qps: 60.34,
debug: true,
kubeAsUser: "pikachu",
kubeAsGroups: []string{"operators", "snackeaters", "partyanimals"},
kubeCaFile: "/tmp/ca.crt",
kubeTLSServer: "example.org",
kubeInsecure: true,
},
{
name: "with flags and envvars set",
args: "--debug --namespace=myns --kube-as-user=poro --kube-as-group=admins --kube-as-group=teatime --kube-as-group=snackeaters --kube-ca-file=/my/ca.crt --burst-limit 175 --qps 70 --kube-insecure-skip-tls-verify=true --kube-tls-server-name=example.org",
envvars: map[string]string{"HELM_DEBUG": "1", "HELM_NAMESPACE": "yourns", "HELM_KUBEASUSER": "pikachu", "HELM_KUBEASGROUPS": ",,,operators,snackeaters,partyanimals", "HELM_MAX_HISTORY": "5", "HELM_KUBECAFILE": "/tmp/ca.crt", "HELM_BURST_LIMIT": "200", "HELM_KUBEINSECURE_SKIP_TLS_VERIFY": "true", "HELM_KUBETLS_SERVER_NAME": "example.org", "HELM_QPS": "40"},
ns: "myns",
debug: true,
maxhistory: 5,
burstLimit: 175,
qps: 70,
kubeAsUser: "poro",
kubeAsGroups: []string{"admins", "teatime", "snackeaters"},
kubeCaFile: "/my/ca.crt",
kubeTLSServer: "example.org",
kubeInsecure: true,
},
{
name: "invalid kubeconfig",
ns: "testns",
args: "--namespace=testns --kubeconfig=/path/to/fake/file",
maxhistory: defaultMaxHistory,
burstLimit: defaultBurstLimit,
qps: defaultQPS,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer resetEnv()()
for k, v := range tt.envvars {
t.Setenv(k, v)
}
flags := pflag.NewFlagSet("testing", pflag.ContinueOnError)
settings := New()
settings.AddFlags(flags)
flags.Parse(strings.Split(tt.args, " "))
if settings.Debug != tt.debug {
t.Errorf("expected debug %t, got %t", tt.debug, settings.Debug)
}
if settings.Namespace() != tt.ns {
t.Errorf("expected namespace %q, got %q", tt.ns, settings.Namespace())
}
if settings.KubeContext != tt.kcontext {
t.Errorf("expected kube-context %q, got %q", tt.kcontext, settings.KubeContext)
}
if settings.MaxHistory != tt.maxhistory {
t.Errorf("expected maxHistory %d, got %d", tt.maxhistory, settings.MaxHistory)
}
if tt.kubeAsUser != settings.KubeAsUser {
t.Errorf("expected kAsUser %q, got %q", tt.kubeAsUser, settings.KubeAsUser)
}
if !reflect.DeepEqual(tt.kubeAsGroups, settings.KubeAsGroups) {
t.Errorf("expected kAsGroups %+v, got %+v", len(tt.kubeAsGroups), len(settings.KubeAsGroups))
}
if tt.kubeCaFile != settings.KubeCaFile {
t.Errorf("expected kCaFile %q, got %q", tt.kubeCaFile, settings.KubeCaFile)
}
if tt.burstLimit != settings.BurstLimit {
t.Errorf("expected BurstLimit %d, got %d", tt.burstLimit, settings.BurstLimit)
}
if tt.kubeInsecure != settings.KubeInsecureSkipTLSVerify {
t.Errorf("expected kubeInsecure %t, got %t", tt.kubeInsecure, settings.KubeInsecureSkipTLSVerify)
}
if tt.kubeTLSServer != settings.KubeTLSServerName {
t.Errorf("expected kubeTLSServer %q, got %q", tt.kubeTLSServer, settings.KubeTLSServerName)
}
})
}
}
func TestEnvOrBool(t *testing.T) {
const envName = "TEST_ENV_OR_BOOL"
tests := []struct {
name string
env string
val string
def bool
expected bool
}{
{
name: "unset with default false",
def: false,
expected: false,
},
{
name: "unset with default true",
def: true,
expected: true,
},
{
name: "blank env with default false",
env: envName,
def: false,
expected: false,
},
{
name: "blank env with default true",
env: envName,
def: true,
expected: true,
},
{
name: "env true with default false",
env: envName,
val: "true",
def: false,
expected: true,
},
{
name: "env false with default true",
env: envName,
val: "false",
def: true,
expected: false,
},
{
name: "env fails parsing with default true",
env: envName,
val: "NOT_A_BOOL",
def: true,
expected: true,
},
{
name: "env fails parsing with default false",
env: envName,
val: "NOT_A_BOOL",
def: false,
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.env != "" {
t.Setenv(tt.env, tt.val)
}
actual := envBoolOr(tt.env, tt.def)
if actual != tt.expected {
t.Errorf("expected result %t, got %t", tt.expected, actual)
}
})
}
}
func TestUserAgentHeaderInK8sRESTClientConfig(t *testing.T) {
defer resetEnv()()
settings := New()
restConfig, err := settings.RESTClientGetter().ToRESTConfig()
if err != nil {
t.Fatal(err)
}
expectedUserAgent := version.GetUserAgent()
if restConfig.UserAgent != expectedUserAgent {
t.Errorf("expected User-Agent header %q in K8s REST client config, got %q", expectedUserAgent, restConfig.UserAgent)
}
}
func resetEnv() func() {
origEnv := os.Environ()
// ensure any local envvars do not hose us
for e := range New().EnvVars() {
os.Unsetenv(e)
}
return func() {
for _, pair := range origEnv {
kv := strings.SplitN(pair, "=", 2)
os.Setenv(kv[0], kv[1])
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cli/environment.go | pkg/cli/environment.go | /*
Copyright The Helm 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 cli describes the operating environment for the Helm CLI.
Helm's environment encapsulates all of the service dependencies Helm has.
These dependencies are expressed as interfaces so that alternate implementations
(mocks, etc.) can be easily generated.
*/
package cli
import (
"fmt"
"net/http"
"os"
"strconv"
"strings"
"github.com/spf13/pflag"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/rest"
"helm.sh/helm/v4/internal/version"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/kube"
)
// defaultMaxHistory sets the maximum number of releases to 0: unlimited
const defaultMaxHistory = 10
// defaultBurstLimit sets the default client-side throttling limit
const defaultBurstLimit = 100
// defaultQPS sets the default QPS value to 0 to use library defaults unless specified
const defaultQPS = float32(0)
// EnvSettings describes all of the environment settings.
type EnvSettings struct {
namespace string
config *genericclioptions.ConfigFlags
// KubeConfig is the path to the kubeconfig file
KubeConfig string
// KubeContext is the name of the kubeconfig context.
KubeContext string
// Bearer KubeToken used for authentication
KubeToken string
// Username to impersonate for the operation
KubeAsUser string
// Groups to impersonate for the operation, multiple groups parsed from a comma delimited list
KubeAsGroups []string
// Kubernetes API Server Endpoint for authentication
KubeAPIServer string
// Custom certificate authority file.
KubeCaFile string
// KubeInsecureSkipTLSVerify indicates if server's certificate will not be checked for validity.
// This makes the HTTPS connections insecure
KubeInsecureSkipTLSVerify bool
// KubeTLSServerName overrides the name to use for server certificate validation.
// If it is not provided, the hostname used to contact the server is used
KubeTLSServerName string
// Debug indicates whether or not Helm is running in Debug mode.
Debug bool
// RegistryConfig is the path to the registry config file.
RegistryConfig string
// RepositoryConfig is the path to the repositories file.
RepositoryConfig string
// RepositoryCache is the path to the repository cache directory.
RepositoryCache string
// PluginsDirectory is the path to the plugins directory.
PluginsDirectory string
// MaxHistory is the max release history maintained.
MaxHistory int
// BurstLimit is the default client-side throttling limit.
BurstLimit int
// QPS is queries per second which may be used to avoid throttling.
QPS float32
// ColorMode controls colorized output (never, auto, always)
ColorMode string
// ContentCache is the location where cached charts are stored
ContentCache string
}
func New() *EnvSettings {
env := &EnvSettings{
namespace: os.Getenv("HELM_NAMESPACE"),
MaxHistory: envIntOr("HELM_MAX_HISTORY", defaultMaxHistory),
KubeConfig: os.Getenv("KUBECONFIG"),
KubeContext: os.Getenv("HELM_KUBECONTEXT"),
KubeToken: os.Getenv("HELM_KUBETOKEN"),
KubeAsUser: os.Getenv("HELM_KUBEASUSER"),
KubeAsGroups: envCSV("HELM_KUBEASGROUPS"),
KubeAPIServer: os.Getenv("HELM_KUBEAPISERVER"),
KubeCaFile: os.Getenv("HELM_KUBECAFILE"),
KubeTLSServerName: os.Getenv("HELM_KUBETLS_SERVER_NAME"),
KubeInsecureSkipTLSVerify: envBoolOr("HELM_KUBEINSECURE_SKIP_TLS_VERIFY", false),
PluginsDirectory: envOr("HELM_PLUGINS", helmpath.DataPath("plugins")),
RegistryConfig: envOr("HELM_REGISTRY_CONFIG", helmpath.ConfigPath("registry/config.json")),
RepositoryConfig: envOr("HELM_REPOSITORY_CONFIG", helmpath.ConfigPath("repositories.yaml")),
RepositoryCache: envOr("HELM_REPOSITORY_CACHE", helmpath.CachePath("repository")),
ContentCache: envOr("HELM_CONTENT_CACHE", helmpath.CachePath("content")),
BurstLimit: envIntOr("HELM_BURST_LIMIT", defaultBurstLimit),
QPS: envFloat32Or("HELM_QPS", defaultQPS),
ColorMode: envColorMode(),
}
env.Debug, _ = strconv.ParseBool(os.Getenv("HELM_DEBUG"))
// bind to kubernetes config flags
config := &genericclioptions.ConfigFlags{
Namespace: &env.namespace,
Context: &env.KubeContext,
BearerToken: &env.KubeToken,
APIServer: &env.KubeAPIServer,
CAFile: &env.KubeCaFile,
KubeConfig: &env.KubeConfig,
Impersonate: &env.KubeAsUser,
Insecure: &env.KubeInsecureSkipTLSVerify,
TLSServerName: &env.KubeTLSServerName,
ImpersonateGroup: &env.KubeAsGroups,
WrapConfigFn: func(config *rest.Config) *rest.Config {
config.Burst = env.BurstLimit
config.QPS = env.QPS
config.Wrap(func(rt http.RoundTripper) http.RoundTripper {
return &kube.RetryingRoundTripper{Wrapped: rt}
})
config.UserAgent = version.GetUserAgent()
return config
},
}
if env.BurstLimit != defaultBurstLimit {
config = config.WithDiscoveryBurst(env.BurstLimit)
}
env.config = config
return env
}
// AddFlags binds flags to the given flagset.
func (s *EnvSettings) AddFlags(fs *pflag.FlagSet) {
fs.StringVarP(&s.namespace, "namespace", "n", s.namespace, "namespace scope for this request")
fs.StringVar(&s.KubeConfig, "kubeconfig", "", "path to the kubeconfig file")
fs.StringVar(&s.KubeContext, "kube-context", s.KubeContext, "name of the kubeconfig context to use")
fs.StringVar(&s.KubeToken, "kube-token", s.KubeToken, "bearer token used for authentication")
fs.StringVar(&s.KubeAsUser, "kube-as-user", s.KubeAsUser, "username to impersonate for the operation")
fs.StringArrayVar(&s.KubeAsGroups, "kube-as-group", s.KubeAsGroups, "group to impersonate for the operation, this flag can be repeated to specify multiple groups.")
fs.StringVar(&s.KubeAPIServer, "kube-apiserver", s.KubeAPIServer, "the address and the port for the Kubernetes API server")
fs.StringVar(&s.KubeCaFile, "kube-ca-file", s.KubeCaFile, "the certificate authority file for the Kubernetes API server connection")
fs.StringVar(&s.KubeTLSServerName, "kube-tls-server-name", s.KubeTLSServerName, "server name to use for Kubernetes API server certificate validation. If it is not provided, the hostname used to contact the server is used")
fs.BoolVar(&s.KubeInsecureSkipTLSVerify, "kube-insecure-skip-tls-verify", s.KubeInsecureSkipTLSVerify, "if true, the Kubernetes API server's certificate will not be checked for validity. This will make your HTTPS connections insecure")
fs.BoolVar(&s.Debug, "debug", s.Debug, "enable verbose output")
fs.StringVar(&s.RegistryConfig, "registry-config", s.RegistryConfig, "path to the registry config file")
fs.StringVar(&s.RepositoryConfig, "repository-config", s.RepositoryConfig, "path to the file containing repository names and URLs")
fs.StringVar(&s.RepositoryCache, "repository-cache", s.RepositoryCache, "path to the directory containing cached repository indexes")
fs.StringVar(&s.ContentCache, "content-cache", s.ContentCache, "path to the directory containing cached content (e.g. charts)")
fs.IntVar(&s.BurstLimit, "burst-limit", s.BurstLimit, "client-side default throttling limit")
fs.Float32Var(&s.QPS, "qps", s.QPS, "queries per second used when communicating with the Kubernetes API, not including bursting")
fs.StringVar(&s.ColorMode, "color", s.ColorMode, "use colored output (never, auto, always)")
fs.StringVar(&s.ColorMode, "colour", s.ColorMode, "use colored output (never, auto, always)")
}
func envOr(name, def string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
return def
}
func envBoolOr(name string, def bool) bool {
if name == "" {
return def
}
envVal := envOr(name, strconv.FormatBool(def))
ret, err := strconv.ParseBool(envVal)
if err != nil {
return def
}
return ret
}
func envIntOr(name string, def int) int {
if name == "" {
return def
}
envVal := envOr(name, strconv.Itoa(def))
ret, err := strconv.Atoi(envVal)
if err != nil {
return def
}
return ret
}
func envFloat32Or(name string, def float32) float32 {
if name == "" {
return def
}
envVal := envOr(name, strconv.FormatFloat(float64(def), 'f', 2, 32))
ret, err := strconv.ParseFloat(envVal, 32)
if err != nil {
return def
}
return float32(ret)
}
func envCSV(name string) (ls []string) {
trimmed := strings.Trim(os.Getenv(name), ", ")
if trimmed != "" {
ls = strings.Split(trimmed, ",")
}
return
}
func envColorMode() string {
// Check NO_COLOR environment variable first (standard)
if v, ok := os.LookupEnv("NO_COLOR"); ok && v != "" {
return "never"
}
// Check HELM_COLOR environment variable
if v, ok := os.LookupEnv("HELM_COLOR"); ok {
v = strings.ToLower(v)
switch v {
case "never", "auto", "always":
return v
}
}
// Default to auto
return "auto"
}
func (s *EnvSettings) EnvVars() map[string]string {
envvars := map[string]string{
"HELM_BIN": os.Args[0],
"HELM_CACHE_HOME": helmpath.CachePath(""),
"HELM_CONFIG_HOME": helmpath.ConfigPath(""),
"HELM_DATA_HOME": helmpath.DataPath(""),
"HELM_DEBUG": fmt.Sprint(s.Debug),
"HELM_PLUGINS": s.PluginsDirectory,
"HELM_REGISTRY_CONFIG": s.RegistryConfig,
"HELM_REPOSITORY_CACHE": s.RepositoryCache,
"HELM_CONTENT_CACHE": s.ContentCache,
"HELM_REPOSITORY_CONFIG": s.RepositoryConfig,
"HELM_NAMESPACE": s.Namespace(),
"HELM_MAX_HISTORY": strconv.Itoa(s.MaxHistory),
"HELM_BURST_LIMIT": strconv.Itoa(s.BurstLimit),
"HELM_QPS": strconv.FormatFloat(float64(s.QPS), 'f', 2, 32),
// broken, these are populated from helm flags and not kubeconfig.
"HELM_KUBECONTEXT": s.KubeContext,
"HELM_KUBETOKEN": s.KubeToken,
"HELM_KUBEASUSER": s.KubeAsUser,
"HELM_KUBEASGROUPS": strings.Join(s.KubeAsGroups, ","),
"HELM_KUBEAPISERVER": s.KubeAPIServer,
"HELM_KUBECAFILE": s.KubeCaFile,
"HELM_KUBEINSECURE_SKIP_TLS_VERIFY": strconv.FormatBool(s.KubeInsecureSkipTLSVerify),
"HELM_KUBETLS_SERVER_NAME": s.KubeTLSServerName,
}
if s.KubeConfig != "" {
envvars["KUBECONFIG"] = s.KubeConfig
}
return envvars
}
// Namespace gets the namespace from the configuration
func (s *EnvSettings) Namespace() string {
if ns, _, err := s.config.ToRawKubeConfigLoader().Namespace(); err == nil {
return ns
}
if s.namespace != "" {
return s.namespace
}
return "default"
}
// SetNamespace sets the namespace in the configuration
func (s *EnvSettings) SetNamespace(namespace string) {
s.namespace = namespace
}
// RESTClientGetter gets the kubeconfig from EnvSettings
func (s *EnvSettings) RESTClientGetter() genericclioptions.RESTClientGetter {
return s.config
}
// ShouldDisableColor returns true if color output should be disabled
func (s *EnvSettings) ShouldDisableColor() bool {
return s.ColorMode == "never"
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cli/values/options_test.go | pkg/cli/values/options_test.go | /*
Copyright The Helm 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 values
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"helm.sh/helm/v4/pkg/getter"
)
// mockGetter implements getter.Getter for testing
type mockGetter struct {
content []byte
err error
}
func (m *mockGetter) Get(_ string, _ ...getter.Option) (*bytes.Buffer, error) {
if m.err != nil {
return nil, m.err
}
return bytes.NewBuffer(m.content), nil
}
// mockProvider creates a test provider
func mockProvider(schemes []string, content []byte, err error) getter.Provider {
return getter.Provider{
Schemes: schemes,
New: func(_ ...getter.Option) (getter.Getter, error) {
return &mockGetter{content: content, err: err}, nil
},
}
}
func TestReadFile(t *testing.T) {
tests := []struct {
name string
filePath string
providers getter.Providers
setupFunc func(*testing.T) (string, func()) // setup temp files, return cleanup
expectError bool
expectStdin bool
expectedData []byte
}{
{
name: "stdin input with dash",
filePath: "-",
providers: getter.Providers{},
expectStdin: true,
expectError: false,
},
{
name: "stdin input with whitespace",
filePath: " - ",
providers: getter.Providers{},
expectStdin: true,
expectError: false,
},
{
name: "invalid URL parsing",
filePath: "://invalid-url",
providers: getter.Providers{},
expectError: true,
},
{
name: "local file - existing",
filePath: "test.txt",
providers: getter.Providers{},
setupFunc: func(t *testing.T) (string, func()) {
t.Helper()
tmpDir := t.TempDir()
filePath := filepath.Join(tmpDir, "test.txt")
content := []byte("local file content")
err := os.WriteFile(filePath, content, 0644)
if err != nil {
t.Fatal(err)
}
return filePath, func() {} // cleanup handled by t.TempDir()
},
expectError: false,
expectedData: []byte("local file content"),
},
{
name: "local file - non-existent",
filePath: "/non/existent/file.txt",
providers: getter.Providers{},
expectError: true,
},
{
name: "remote file with http scheme - success",
filePath: "http://example.com/values.yaml",
providers: getter.Providers{
mockProvider([]string{"http", "https"}, []byte("remote content"), nil),
},
expectError: false,
expectedData: []byte("remote content"),
},
{
name: "remote file with https scheme - success",
filePath: "https://example.com/values.yaml",
providers: getter.Providers{
mockProvider([]string{"http", "https"}, []byte("https content"), nil),
},
expectError: false,
expectedData: []byte("https content"),
},
{
name: "remote file with custom scheme - success",
filePath: "oci://registry.example.com/chart",
providers: getter.Providers{
mockProvider([]string{"oci"}, []byte("oci content"), nil),
},
expectError: false,
expectedData: []byte("oci content"),
},
{
name: "remote file - getter error",
filePath: "http://example.com/values.yaml",
providers: getter.Providers{
mockProvider([]string{"http"}, nil, errors.New("network error")),
},
expectError: true,
},
{
name: "unsupported scheme fallback to local file",
filePath: "ftp://example.com/file.txt",
providers: getter.Providers{
mockProvider([]string{"http"}, []byte("should not be used"), nil),
},
setupFunc: func(t *testing.T) (string, func()) {
t.Helper()
// Create a local file named "ftp://example.com/file.txt"
// This tests the fallback behavior when scheme is not supported
tmpDir := t.TempDir()
fileName := "ftp_file.txt" // Valid filename for filesystem
filePath := filepath.Join(tmpDir, fileName)
content := []byte("local fallback content")
err := os.WriteFile(filePath, content, 0644)
if err != nil {
t.Fatal(err)
}
return filePath, func() {}
},
expectError: false,
expectedData: []byte("local fallback content"),
},
{
name: "empty file path",
filePath: "",
providers: getter.Providers{},
expectError: true, // Empty path should cause error
},
{
name: "multiple providers - correct selection",
filePath: "custom://example.com/resource",
providers: getter.Providers{
mockProvider([]string{"http", "https"}, []byte("wrong content"), nil),
mockProvider([]string{"custom"}, []byte("correct content"), nil),
mockProvider([]string{"oci"}, []byte("also wrong"), nil),
},
expectError: false,
expectedData: []byte("correct content"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var actualFilePath string
var cleanup func()
if tt.setupFunc != nil {
actualFilePath, cleanup = tt.setupFunc(t)
defer cleanup()
} else {
actualFilePath = tt.filePath
}
// Handle stdin test case
if tt.expectStdin {
// Save original stdin
originalStdin := os.Stdin
defer func() { os.Stdin = originalStdin }()
// Create a pipe for stdin
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer r.Close()
defer w.Close()
// Replace stdin with our pipe
os.Stdin = r
// Write test data to stdin
testData := []byte("stdin test data")
go func() {
defer w.Close()
w.Write(testData)
}()
// Test the function
got, err := readFile(actualFilePath, tt.providers)
if err != nil {
t.Errorf("readFile() error = %v, expected no error for stdin", err)
return
}
if !bytes.Equal(got, testData) {
t.Errorf("readFile() = %v, want %v", got, testData)
}
return
}
// Regular test cases
got, err := readFile(actualFilePath, tt.providers)
if (err != nil) != tt.expectError {
t.Errorf("readFile() error = %v, expectError %v", err, tt.expectError)
return
}
if !tt.expectError && tt.expectedData != nil {
if !bytes.Equal(got, tt.expectedData) {
t.Errorf("readFile() = %v, want %v", got, tt.expectedData)
}
}
})
}
}
// TestReadFileErrorMessages tests specific error scenarios and their messages
func TestReadFileErrorMessages(t *testing.T) {
tests := []struct {
name string
filePath string
providers getter.Providers
wantErr string
}{
{
name: "URL parse error",
filePath: "://invalid",
providers: getter.Providers{},
wantErr: "missing protocol scheme",
},
{
name: "getter error with message",
filePath: "http://example.com/file",
providers: getter.Providers{mockProvider([]string{"http"}, nil, fmt.Errorf("connection refused"))},
wantErr: "connection refused",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := readFile(tt.filePath, tt.providers)
if err == nil {
t.Errorf("readFile() expected error containing %q, got nil", tt.wantErr)
return
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("readFile() error = %v, want error containing %q", err, tt.wantErr)
}
})
}
}
// Original test case - keeping for backward compatibility
func TestReadFileOriginal(t *testing.T) {
var p getter.Providers
filePath := "%a.txt"
_, err := readFile(filePath, p)
if err == nil {
t.Errorf("Expected error when has special strings")
}
}
func TestMergeValuesCLI(t *testing.T) {
tests := []struct {
name string
opts Options
expected map[string]interface{}
wantErr bool
}{
{
name: "set-json object",
opts: Options{
JSONValues: []string{`{"foo": {"bar": "baz"}}`},
},
expected: map[string]interface{}{
"foo": map[string]interface{}{
"bar": "baz",
},
},
},
{
name: "set-json key=value",
opts: Options{
JSONValues: []string{"foo.bar=[1,2,3]"},
},
expected: map[string]interface{}{
"foo": map[string]interface{}{
"bar": []interface{}{1.0, 2.0, 3.0},
},
},
},
{
name: "set regular value",
opts: Options{
Values: []string{"foo=bar"},
},
expected: map[string]interface{}{
"foo": "bar",
},
},
{
name: "set string value",
opts: Options{
StringValues: []string{"foo=123"},
},
expected: map[string]interface{}{
"foo": "123",
},
},
{
name: "set literal value",
opts: Options{
LiteralValues: []string{"foo=true"},
},
expected: map[string]interface{}{
"foo": "true",
},
},
{
name: "multiple options",
opts: Options{
Values: []string{"a=foo"},
StringValues: []string{"b=bar"},
JSONValues: []string{`{"c": "foo1"}`},
LiteralValues: []string{"d=bar1"},
},
expected: map[string]interface{}{
"a": "foo",
"b": "bar",
"c": "foo1",
"d": "bar1",
},
},
{
name: "invalid json",
opts: Options{
JSONValues: []string{`{invalid`},
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := tt.opts.MergeValues(getter.Providers{})
if (err != nil) != tt.wantErr {
t.Errorf("MergeValues() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && !reflect.DeepEqual(got, tt.expected) {
t.Errorf("MergeValues() = %v, want %v", got, tt.expected)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cli/values/options.go | pkg/cli/values/options.go | /*
Copyright The Helm 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 values
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/url"
"os"
"strings"
"helm.sh/helm/v4/pkg/chart/v2/loader"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/strvals"
)
// Options captures the different ways to specify values
type Options struct {
ValueFiles []string // -f/--values
StringValues []string // --set-string
Values []string // --set
FileValues []string // --set-file
JSONValues []string // --set-json
LiteralValues []string // --set-literal
}
// MergeValues merges values from files specified via -f/--values and directly
// via --set-json, --set, --set-string, or --set-file, marshaling them to YAML
func (opts *Options) MergeValues(p getter.Providers) (map[string]interface{}, error) {
base := map[string]interface{}{}
// User specified a values files via -f/--values
for _, filePath := range opts.ValueFiles {
raw, err := readFile(filePath, p)
if err != nil {
return nil, err
}
currentMap, err := loader.LoadValues(bytes.NewReader(raw))
if err != nil {
return nil, fmt.Errorf("failed to parse %s: %w", filePath, err)
}
// Merge with the previous map
base = loader.MergeMaps(base, currentMap)
}
// User specified a value via --set-json
for _, value := range opts.JSONValues {
trimmedValue := strings.TrimSpace(value)
if len(trimmedValue) > 0 && trimmedValue[0] == '{' {
// If value is JSON object format, parse it as map
var jsonMap map[string]interface{}
if err := json.Unmarshal([]byte(trimmedValue), &jsonMap); err != nil {
return nil, fmt.Errorf("failed parsing --set-json data JSON: %s", value)
}
base = loader.MergeMaps(base, jsonMap)
} else {
// Otherwise, parse it as key=value format
if err := strvals.ParseJSON(value, base); err != nil {
return nil, fmt.Errorf("failed parsing --set-json data %s", value)
}
}
}
// User specified a value via --set
for _, value := range opts.Values {
if err := strvals.ParseInto(value, base); err != nil {
return nil, fmt.Errorf("failed parsing --set data: %w", err)
}
}
// User specified a value via --set-string
for _, value := range opts.StringValues {
if err := strvals.ParseIntoString(value, base); err != nil {
return nil, fmt.Errorf("failed parsing --set-string data: %w", err)
}
}
// User specified a value via --set-file
for _, value := range opts.FileValues {
reader := func(rs []rune) (interface{}, error) {
bytes, err := readFile(string(rs), p)
if err != nil {
return nil, err
}
return string(bytes), err
}
if err := strvals.ParseIntoFile(value, base, reader); err != nil {
return nil, fmt.Errorf("failed parsing --set-file data: %w", err)
}
}
// User specified a value via --set-literal
for _, value := range opts.LiteralValues {
if err := strvals.ParseLiteralInto(value, base); err != nil {
return nil, fmt.Errorf("failed parsing --set-literal data: %w", err)
}
}
return base, nil
}
// readFile load a file from stdin, the local directory, or a remote file with a url.
func readFile(filePath string, p getter.Providers) ([]byte, error) {
if strings.TrimSpace(filePath) == "-" {
return io.ReadAll(os.Stdin)
}
u, err := url.Parse(filePath)
if err != nil {
return nil, err
}
// FIXME: maybe someone handle other protocols like ftp.
g, err := p.ByScheme(u.Scheme)
if err != nil {
return os.ReadFile(filePath)
}
data, err := g.Get(filePath, getter.WithURL(filePath))
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/cli/output/output.go | pkg/cli/output/output.go | /*
Copyright The Helm 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 output
import (
"encoding/json"
"fmt"
"io"
"github.com/gosuri/uitable"
"sigs.k8s.io/yaml"
)
// Format is a type for capturing supported output formats
type Format string
const (
Table Format = "table"
JSON Format = "json"
YAML Format = "yaml"
)
// Formats returns a list of the string representation of the supported formats
func Formats() []string {
return []string{Table.String(), JSON.String(), YAML.String()}
}
// FormatsWithDesc returns a list of the string representation of the supported formats
// including a description
func FormatsWithDesc() map[string]string {
return map[string]string{
Table.String(): "Output result in human-readable format",
JSON.String(): "Output result in JSON format",
YAML.String(): "Output result in YAML format",
}
}
// ErrInvalidFormatType is returned when an unsupported format type is used
var ErrInvalidFormatType = fmt.Errorf("invalid format type")
// String returns the string representation of the Format
func (o Format) String() string {
return string(o)
}
// Write the output in the given format to the io.Writer. Unsupported formats
// will return an error
func (o Format) Write(out io.Writer, w Writer) error {
switch o {
case Table:
return w.WriteTable(out)
case JSON:
return w.WriteJSON(out)
case YAML:
return w.WriteYAML(out)
}
return ErrInvalidFormatType
}
// ParseFormat takes a raw string and returns the matching Format.
// If the format does not exist, ErrInvalidFormatType is returned
func ParseFormat(s string) (out Format, err error) {
switch s {
case Table.String():
out, err = Table, nil
case JSON.String():
out, err = JSON, nil
case YAML.String():
out, err = YAML, nil
default:
out, err = "", ErrInvalidFormatType
}
return
}
// Writer is an interface that any type can implement to write supported formats
type Writer interface {
// WriteTable will write tabular output into the given io.Writer, returning
// an error if any occur
WriteTable(out io.Writer) error
// WriteJSON will write JSON formatted output into the given io.Writer,
// returning an error if any occur
WriteJSON(out io.Writer) error
// WriteYAML will write YAML formatted output into the given io.Writer,
// returning an error if any occur
WriteYAML(out io.Writer) error
}
// EncodeJSON is a helper function to decorate any error message with a bit more
// context and avoid writing the same code over and over for printers.
func EncodeJSON(out io.Writer, obj interface{}) error {
enc := json.NewEncoder(out)
err := enc.Encode(obj)
if err != nil {
return fmt.Errorf("unable to write JSON output: %w", err)
}
return nil
}
// EncodeYAML is a helper function to decorate any error message with a bit more
// context and avoid writing the same code over and over for printers
func EncodeYAML(out io.Writer, obj interface{}) error {
raw, err := yaml.Marshal(obj)
if err != nil {
return fmt.Errorf("unable to write YAML output: %w", err)
}
_, err = out.Write(raw)
if err != nil {
return fmt.Errorf("unable to write YAML output: %w", err)
}
return nil
}
// EncodeTable is a helper function to decorate any error message with a bit
// more context and avoid writing the same code over and over for printers
func EncodeTable(out io.Writer, table *uitable.Table) error {
raw := table.Bytes()
raw = append(raw, []byte("\n")...)
_, err := out.Write(raw)
if err != nil {
return fmt.Errorf("unable to write table output: %w", err)
}
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/files_test.go | pkg/engine/files_test.go | /*
Copyright The Helm 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 engine
import (
"testing"
"github.com/stretchr/testify/assert"
)
var cases = []struct {
path, data string
}{
{"ship/captain.txt", "The Captain"},
{"ship/stowaway.txt", "Legatt"},
{"story/name.txt", "The Secret Sharer"},
{"story/author.txt", "Joseph Conrad"},
{"multiline/test.txt", "bar\nfoo\n"},
{"multiline/test_with_blank_lines.txt", "bar\nfoo\n\n\n"},
}
func getTestFiles() files {
a := make(files, len(cases))
for _, c := range cases {
a[c.path] = []byte(c.data)
}
return a
}
func TestNewFiles(t *testing.T) {
files := getTestFiles()
if len(files) != len(cases) {
t.Errorf("Expected len() = %d, got %d", len(cases), len(files))
}
for i, f := range cases {
if got := string(files.GetBytes(f.path)); got != f.data {
t.Errorf("%d: expected %q, got %q", i, f.data, got)
}
if got := files.Get(f.path); got != f.data {
t.Errorf("%d: expected %q, got %q", i, f.data, got)
}
}
}
func TestFileGlob(t *testing.T) {
as := assert.New(t)
f := getTestFiles()
matched := f.Glob("story/**")
as.Len(matched, 2, "Should be two files in glob story/**")
as.Equal("Joseph Conrad", matched.Get("story/author.txt"))
}
func TestToConfig(t *testing.T) {
as := assert.New(t)
f := getTestFiles()
out := f.Glob("**/captain.txt").AsConfig()
as.Equal("captain.txt: The Captain", out)
out = f.Glob("ship/**").AsConfig()
as.Equal("captain.txt: The Captain\nstowaway.txt: Legatt", out)
}
func TestToSecret(t *testing.T) {
as := assert.New(t)
f := getTestFiles()
out := f.Glob("ship/**").AsSecrets()
as.Equal("captain.txt: VGhlIENhcHRhaW4=\nstowaway.txt: TGVnYXR0", out)
}
func TestLines(t *testing.T) {
as := assert.New(t)
f := getTestFiles()
out := f.Lines("multiline/test.txt")
as.Len(out, 2)
as.Equal("bar", out[0])
}
func TestBlankLines(t *testing.T) {
as := assert.New(t)
f := getTestFiles()
out := f.Lines("multiline/test_with_blank_lines.txt")
as.Len(out, 4)
as.Equal("bar", out[0])
as.Equal("", out[3])
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/funcs_test.go | pkg/engine/funcs_test.go | /*
Copyright The Helm 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 engine
import (
"strings"
"testing"
"text/template"
"github.com/stretchr/testify/assert"
)
func TestFuncs(t *testing.T) {
//TODO write tests for failure cases
tests := []struct {
tpl, expect string
vars interface{}
}{{
tpl: `{{ toYaml . }}`,
expect: `foo: bar`,
vars: map[string]interface{}{"foo": "bar"},
}, {
tpl: `{{ toYamlPretty . }}`,
expect: "baz:\n - 1\n - 2\n - 3",
vars: map[string]interface{}{"baz": []int{1, 2, 3}},
}, {
tpl: `{{ toToml . }}`,
expect: "foo = \"bar\"\n",
vars: map[string]interface{}{"foo": "bar"},
}, {
tpl: `{{ fromToml . }}`,
expect: "map[hello:world]",
vars: `hello = "world"`,
}, {
tpl: `{{ fromToml . }}`,
expect: "map[table:map[keyInTable:valueInTable subtable:map[keyInSubtable:valueInSubTable]]]",
vars: `
[table]
keyInTable = "valueInTable"
[table.subtable]
keyInSubtable = "valueInSubTable"`,
}, {
tpl: `{{ fromToml . }}`,
expect: "map[tableArray:[map[keyInElement0:valueInElement0] map[keyInElement1:valueInElement1]]]",
vars: `
[[tableArray]]
keyInElement0 = "valueInElement0"
[[tableArray]]
keyInElement1 = "valueInElement1"`,
}, {
tpl: `{{ fromToml . }}`,
expect: "map[Error:toml: line 1: unexpected EOF; expected key separator '=']",
vars: "one",
}, {
tpl: `{{ toJson . }}`,
expect: `{"foo":"bar"}`,
vars: map[string]interface{}{"foo": "bar"},
}, {
tpl: `{{ fromYaml . }}`,
expect: "map[hello:world]",
vars: `hello: world`,
}, {
tpl: `{{ fromYamlArray . }}`,
expect: "[one 2 map[name:helm]]",
vars: "- one\n- 2\n- name: helm\n",
}, {
tpl: `{{ fromYamlArray . }}`,
expect: "[one 2 map[name:helm]]",
vars: `["one", 2, { "name": "helm" }]`,
}, {
// Regression for https://github.com/helm/helm/issues/2271
tpl: `{{ toToml . }}`,
expect: "[mast]\n sail = \"white\"\n",
vars: map[string]map[string]string{"mast": {"sail": "white"}},
}, {
tpl: `{{ fromYaml . }}`,
expect: "map[Error:error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array into Go value of type map[string]interface {}]",
vars: "- one\n- two\n",
}, {
tpl: `{{ fromJson .}}`,
expect: `map[hello:world]`,
vars: `{"hello":"world"}`,
}, {
tpl: `{{ fromJson . }}`,
expect: `map[Error:json: cannot unmarshal array into Go value of type map[string]interface {}]`,
vars: `["one", "two"]`,
}, {
tpl: `{{ fromJsonArray . }}`,
expect: `[one 2 map[name:helm]]`,
vars: `["one", 2, { "name": "helm" }]`,
}, {
tpl: `{{ fromJsonArray . }}`,
expect: `[json: cannot unmarshal object into Go value of type []interface {}]`,
vars: `{"hello": "world"}`,
}, {
tpl: `{{ merge .dict (fromYaml .yaml) }}`,
expect: `map[a:map[b:c]]`,
vars: map[string]interface{}{"dict": map[string]interface{}{"a": map[string]interface{}{"b": "c"}}, "yaml": `{"a":{"b":"d"}}`},
}, {
tpl: `{{ merge (fromYaml .yaml) .dict }}`,
expect: `map[a:map[b:d]]`,
vars: map[string]interface{}{"dict": map[string]interface{}{"a": map[string]interface{}{"b": "c"}}, "yaml": `{"a":{"b":"d"}}`},
}, {
tpl: `{{ fromYaml . }}`,
expect: `map[Error:error unmarshaling JSON: while decoding JSON: json: cannot unmarshal array into Go value of type map[string]interface {}]`,
vars: `["one", "two"]`,
}, {
tpl: `{{ fromYamlArray . }}`,
expect: `[error unmarshaling JSON: while decoding JSON: json: cannot unmarshal object into Go value of type []interface {}]`,
vars: `hello: world`,
}, {
// This should never result in a network lookup. Regression for #7955
tpl: `{{ lookup "v1" "Namespace" "" "unlikelynamespace99999999" }}`,
expect: `map[]`,
vars: `["one", "two"]`,
}}
for _, tt := range tests {
var b strings.Builder
err := template.Must(template.New("test").Funcs(funcMap()).Parse(tt.tpl)).Execute(&b, tt.vars)
assert.NoError(t, err)
assert.Equal(t, tt.expect, b.String(), tt.tpl)
}
loopMap := map[string]interface{}{
"foo": "bar",
}
loopMap["loop"] = []interface{}{loopMap}
mustFuncsTests := []struct {
tpl string
expect interface{}
vars interface{}
}{{
tpl: `{{ mustToYaml . }}`,
vars: loopMap,
}, {
tpl: `{{ mustToJson . }}`,
vars: loopMap,
}, {
tpl: `{{ toYaml . }}`,
expect: "", // should return empty string and swallow error
vars: loopMap,
}, {
tpl: `{{ toJson . }}`,
expect: "", // should return empty string and swallow error
vars: loopMap,
},
}
for _, tt := range mustFuncsTests {
var b strings.Builder
err := template.Must(template.New("test").Funcs(funcMap()).Parse(tt.tpl)).Execute(&b, tt.vars)
if tt.expect != nil {
assert.NoError(t, err)
assert.Equal(t, tt.expect, b.String(), tt.tpl)
} else {
assert.Error(t, err)
}
}
}
// This test to check a function provided by sprig is due to a change in a
// dependency of sprig. mergo in v0.3.9 changed the way it merges and only does
// public fields (i.e. those starting with a capital letter). This test, from
// sprig, fails in the new version. This is a behavior change for mergo that
// impacts sprig and Helm users. This test will help us to not update to a
// version of mergo (even accidentally) that causes a breaking change. See
// sprig changelog and notes for more details.
// Note, Go modules assume semver is never broken. So, there is no way to tell
// the tooling to not update to a minor or patch version. `go install` could
// be used to accidentally update mergo. This test and message should catch
// the problem and explain why it's happening.
func TestMerge(t *testing.T) {
dict := map[string]interface{}{
"src2": map[string]interface{}{
"h": 10,
"i": "i",
"j": "j",
},
"src1": map[string]interface{}{
"a": 1,
"b": 2,
"d": map[string]interface{}{
"e": "four",
},
"g": []int{6, 7},
"i": "aye",
"j": "jay",
"k": map[string]interface{}{
"l": false,
},
},
"dst": map[string]interface{}{
"a": "one",
"c": 3,
"d": map[string]interface{}{
"f": 5,
},
"g": []int{8, 9},
"i": "eye",
"k": map[string]interface{}{
"l": true,
},
},
}
tpl := `{{merge .dst .src1 .src2}}`
var b strings.Builder
err := template.Must(template.New("test").Funcs(funcMap()).Parse(tpl)).Execute(&b, dict)
assert.NoError(t, err)
expected := map[string]interface{}{
"a": "one", // key overridden
"b": 2, // merged from src1
"c": 3, // merged from dst
"d": map[string]interface{}{ // deep merge
"e": "four",
"f": 5,
},
"g": []int{8, 9}, // overridden - arrays are not merged
"h": 10, // merged from src2
"i": "eye", // overridden twice
"j": "jay", // overridden and merged
"k": map[string]interface{}{
"l": true, // overridden
},
}
assert.Equal(t, expected, dict["dst"])
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/lookup_func.go | pkg/engine/lookup_func.go | /*
Copyright The Helm 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 engine
import (
"context"
"fmt"
"log/slog"
"strings"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
)
type lookupFunc = func(apiversion string, resource string, namespace string, name string) (map[string]interface{}, error)
// NewLookupFunction returns a function for looking up objects in the cluster.
//
// If the resource does not exist, no error is raised.
func NewLookupFunction(config *rest.Config) lookupFunc { //nolint:revive
return newLookupFunction(clientProviderFromConfig{config: config})
}
type ClientProvider interface {
// GetClientFor returns a dynamic.NamespaceableResourceInterface suitable for interacting with resources
// corresponding to the provided apiVersion and kind, as well as a boolean indicating whether the resources
// are namespaced.
GetClientFor(apiVersion, kind string) (dynamic.NamespaceableResourceInterface, bool, error)
}
type clientProviderFromConfig struct {
config *rest.Config
}
func (c clientProviderFromConfig) GetClientFor(apiVersion, kind string) (dynamic.NamespaceableResourceInterface, bool, error) {
return getDynamicClientOnKind(apiVersion, kind, c.config)
}
func newLookupFunction(clientProvider ClientProvider) lookupFunc {
return func(apiversion string, kind string, namespace string, name string) (map[string]interface{}, error) {
var client dynamic.ResourceInterface
c, namespaced, err := clientProvider.GetClientFor(apiversion, kind)
if err != nil {
return map[string]interface{}{}, err
}
if namespaced && namespace != "" {
client = c.Namespace(namespace)
} else {
client = c
}
if name != "" {
// this will return a single object
obj, err := client.Get(context.Background(), name, metav1.GetOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
// Just return an empty interface when the object was not found.
// That way, users can use `if not (lookup ...)` in their templates.
return map[string]interface{}{}, nil
}
return map[string]interface{}{}, err
}
return obj.UnstructuredContent(), nil
}
// this will return a list
obj, err := client.List(context.Background(), metav1.ListOptions{})
if err != nil {
if apierrors.IsNotFound(err) {
// Just return an empty interface when the object was not found.
// That way, users can use `if not (lookup ...)` in their templates.
return map[string]interface{}{}, nil
}
return map[string]interface{}{}, err
}
return obj.UnstructuredContent(), nil
}
}
// getDynamicClientOnKind returns a dynamic client on an Unstructured type. This client can be further namespaced.
func getDynamicClientOnKind(apiversion string, kind string, config *rest.Config) (dynamic.NamespaceableResourceInterface, bool, error) {
gvk := schema.FromAPIVersionAndKind(apiversion, kind)
apiRes, err := getAPIResourceForGVK(gvk, config)
if err != nil {
slog.Error(
"unable to get apiresource",
slog.String("groupVersionKind", gvk.String()),
slog.Any("error", err),
)
return nil, false, fmt.Errorf("unable to get apiresource from unstructured: %s: %w", gvk.String(), err)
}
gvr := schema.GroupVersionResource{
Group: apiRes.Group,
Version: apiRes.Version,
Resource: apiRes.Name,
}
intf, err := dynamic.NewForConfig(config)
if err != nil {
slog.Error("unable to get dynamic client", slog.Any("error", err))
return nil, false, err
}
res := intf.Resource(gvr)
return res, apiRes.Namespaced, nil
}
func getAPIResourceForGVK(gvk schema.GroupVersionKind, config *rest.Config) (metav1.APIResource, error) {
res := metav1.APIResource{}
discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
if err != nil {
slog.Error("unable to create discovery client", slog.Any("error", err))
return res, err
}
resList, err := discoveryClient.ServerResourcesForGroupVersion(gvk.GroupVersion().String())
if err != nil {
slog.Error(
"unable to retrieve resource list",
slog.String("GroupVersion", gvk.GroupVersion().String()),
slog.Any("error", err),
)
return res, err
}
for _, resource := range resList.APIResources {
// if a resource contains a "/" it's referencing a subresource. we don't support subresource for now.
if resource.Kind == gvk.Kind && !strings.Contains(resource.Name, "/") {
res = resource
res.Group = gvk.Group
res.Version = gvk.Version
break
}
}
return res, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/files.go | pkg/engine/files.go | /*
Copyright The Helm 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 engine
import (
"encoding/base64"
"path"
"strings"
"github.com/gobwas/glob"
"helm.sh/helm/v4/pkg/chart/common"
)
// files is a map of files in a chart that can be accessed from a template.
type files map[string][]byte
// NewFiles creates a new files from chart files.
// Given an []*chart.File (the format for files in a chart.Chart), extract a map of files.
func newFiles(from []*common.File) files {
files := make(map[string][]byte)
for _, f := range from {
files[f.Name] = f.Data
}
return files
}
// GetBytes gets a file by path.
//
// The returned data is raw. In a template context, this is identical to calling
// {{index .Files $path}}.
//
// This is intended to be accessed from within a template, so a missed key returns
// an empty []byte.
func (f files) GetBytes(name string) []byte {
if v, ok := f[name]; ok {
return v
}
return []byte{}
}
// Get returns a string representation of the given file.
//
// Fetch the contents of a file as a string. It is designed to be called in a
// template.
//
// {{.Files.Get "foo"}}
func (f files) Get(name string) string {
return string(f.GetBytes(name))
}
// Glob takes a glob pattern and returns another files object only containing
// matched files.
//
// This is designed to be called from a template.
//
// {{ range $name, $content := .Files.Glob("foo/**") }}
// {{ $name }}: |
// {{ .Files.Get($name) | indent 4 }}{{ end }}
func (f files) Glob(pattern string) files {
g, err := glob.Compile(pattern, '/')
if err != nil {
g, _ = glob.Compile("**")
}
nf := newFiles(nil)
for name, contents := range f {
if g.Match(name) {
nf[name] = contents
}
}
return nf
}
// AsConfig turns a Files group and flattens it to a YAML map suitable for
// including in the 'data' section of a Kubernetes ConfigMap definition.
// Duplicate keys will be overwritten, so be aware that your file names
// (regardless of path) should be unique.
//
// This is designed to be called from a template, and will return empty string
// (via toYAML function) if it cannot be serialized to YAML, or if the Files
// object is nil.
//
// The output will not be indented, so you will want to pipe this to the
// 'indent' template function.
//
// data:
//
// {{ .Files.Glob("config/**").AsConfig() | indent 4 }}
func (f files) AsConfig() string {
if f == nil {
return ""
}
m := make(map[string]string)
// Explicitly convert to strings, and file names
for k, v := range f {
m[path.Base(k)] = string(v)
}
return toYAML(m)
}
// AsSecrets returns the base64-encoded value of a Files object suitable for
// including in the 'data' section of a Kubernetes Secret definition.
// Duplicate keys will be overwritten, so be aware that your file names
// (regardless of path) should be unique.
//
// This is designed to be called from a template, and will return empty string
// (via toYAML function) if it cannot be serialized to YAML, or if the Files
// object is nil.
//
// The output will not be indented, so you will want to pipe this to the
// 'indent' template function.
//
// data:
//
// {{ .Files.Glob("secrets/*").AsSecrets() | indent 4 }}
func (f files) AsSecrets() string {
if f == nil {
return ""
}
m := make(map[string]string)
for k, v := range f {
m[path.Base(k)] = base64.StdEncoding.EncodeToString(v)
}
return toYAML(m)
}
// Lines returns each line of a named file (split by "\n") as a slice, so it can
// be ranged over in your templates.
//
// This is designed to be called from a template.
//
// {{ range .Files.Lines "foo/bar.html" }}
// {{ . }}{{ end }}
func (f files) Lines(path string) []string {
if f == nil || f[path] == nil {
return []string{}
}
s := string(f[path])
if s[len(s)-1] == '\n' {
s = s[:len(s)-1]
}
return strings.Split(s, "\n")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/engine_test.go | pkg/engine/engine_test.go | /*
Copyright The Helm 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 engine
import (
"fmt"
"path"
"strings"
"sync"
"testing"
"text/template"
"time"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/fake"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/common/util"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
func TestSortTemplates(t *testing.T) {
tpls := map[string]renderable{
"/mychart/templates/foo.tpl": {},
"/mychart/templates/charts/foo/charts/bar/templates/foo.tpl": {},
"/mychart/templates/bar.tpl": {},
"/mychart/templates/charts/foo/templates/bar.tpl": {},
"/mychart/templates/_foo.tpl": {},
"/mychart/templates/charts/foo/templates/foo.tpl": {},
"/mychart/templates/charts/bar/templates/foo.tpl": {},
}
got := sortTemplates(tpls)
if len(got) != len(tpls) {
t.Fatal("Sorted results are missing templates")
}
expect := []string{
"/mychart/templates/charts/foo/charts/bar/templates/foo.tpl",
"/mychart/templates/charts/foo/templates/foo.tpl",
"/mychart/templates/charts/foo/templates/bar.tpl",
"/mychart/templates/charts/bar/templates/foo.tpl",
"/mychart/templates/foo.tpl",
"/mychart/templates/bar.tpl",
"/mychart/templates/_foo.tpl",
}
for i, e := range expect {
if got[i] != e {
t.Fatalf("\n\tExp:\n%s\n\tGot:\n%s",
strings.Join(expect, "\n"),
strings.Join(got, "\n"),
)
}
}
}
func TestFuncMap(t *testing.T) {
fns := funcMap()
forbidden := []string{"env", "expandenv"}
for _, f := range forbidden {
if _, ok := fns[f]; ok {
t.Errorf("Forbidden function %s exists in FuncMap.", f)
}
}
// Test for Engine-specific template functions.
expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "fromToml", "toJson", "fromJson", "lookup"}
for _, f := range expect {
if _, ok := fns[f]; !ok {
t.Errorf("Expected add-on function %q", f)
}
}
}
func TestRender(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "moby",
Version: "1.2.3",
},
Templates: []*common.File{
{Name: "templates/test1", ModTime: modTime, Data: []byte("{{.Values.outer | title }} {{.Values.inner | title}}")},
{Name: "templates/test2", ModTime: modTime, Data: []byte("{{.Values.global.callme | lower }}")},
{Name: "templates/test3", ModTime: modTime, Data: []byte("{{.noValue}}")},
{Name: "templates/test4", ModTime: modTime, Data: []byte("{{toJson .Values}}")},
{Name: "templates/test5", ModTime: modTime, Data: []byte("{{getHostByName \"helm.sh\"}}")},
},
Values: map[string]interface{}{"outer": "DEFAULT", "inner": "DEFAULT"},
}
vals := map[string]interface{}{
"Values": map[string]interface{}{
"outer": "spouter",
"inner": "inn",
"global": map[string]interface{}{
"callme": "Ishmael",
},
},
}
v, err := util.CoalesceValues(c, vals)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}
out, err := Render(c, v)
if err != nil {
t.Errorf("Failed to render templates: %s", err)
}
expect := map[string]string{
"moby/templates/test1": "Spouter Inn",
"moby/templates/test2": "ishmael",
"moby/templates/test3": "",
"moby/templates/test4": `{"global":{"callme":"Ishmael"},"inner":"inn","outer":"spouter"}`,
"moby/templates/test5": "",
}
for name, data := range expect {
if out[name] != data {
t.Errorf("Expected %q, got %q", data, out[name])
}
}
}
func TestRenderRefsOrdering(t *testing.T) {
modTime := time.Now()
parentChart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "parent",
Version: "1.2.3",
},
Templates: []*common.File{
{Name: "templates/_helpers.tpl", ModTime: modTime, Data: []byte(`{{- define "test" -}}parent value{{- end -}}`)},
{Name: "templates/test.yaml", ModTime: modTime, Data: []byte(`{{ tpl "{{ include \"test\" . }}" . }}`)},
},
}
childChart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "child",
Version: "1.2.3",
},
Templates: []*common.File{
{Name: "templates/_helpers.tpl", ModTime: modTime, Data: []byte(`{{- define "test" -}}child value{{- end -}}`)},
},
}
parentChart.AddDependency(childChart)
expect := map[string]string{
"parent/templates/test.yaml": "parent value",
}
for i := range 100 {
out, err := Render(parentChart, common.Values{})
if err != nil {
t.Fatalf("Failed to render templates: %s", err)
}
for name, data := range expect {
if out[name] != data {
t.Fatalf("Expected %q, got %q (iteration %d)", data, out[name], i+1)
}
}
}
}
func TestRenderInternals(t *testing.T) {
// Test the internals of the rendering tool.
vals := common.Values{"Name": "one", "Value": "two"}
tpls := map[string]renderable{
"one": {tpl: `Hello {{title .Name}}`, vals: vals},
"two": {tpl: `Goodbye {{upper .Value}}`, vals: vals},
// Test whether a template can reliably reference another template
// without regard for ordering.
"three": {tpl: `{{template "two" dict "Value" "three"}}`, vals: vals},
}
out, err := new(Engine).render(tpls)
if err != nil {
t.Fatalf("Failed template rendering: %s", err)
}
if len(out) != 3 {
t.Fatalf("Expected 3 templates, got %d", len(out))
}
if out["one"] != "Hello One" {
t.Errorf("Expected 'Hello One', got %q", out["one"])
}
if out["two"] != "Goodbye TWO" {
t.Errorf("Expected 'Goodbye TWO'. got %q", out["two"])
}
if out["three"] != "Goodbye THREE" {
t.Errorf("Expected 'Goodbye THREE'. got %q", out["two"])
}
}
func TestRenderWithDNS(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "moby",
Version: "1.2.3",
},
Templates: []*common.File{
{Name: "templates/test1", ModTime: time.Now(), Data: []byte("{{getHostByName \"helm.sh\"}}")},
},
Values: map[string]interface{}{},
}
vals := map[string]interface{}{
"Values": map[string]interface{}{},
}
v, err := util.CoalesceValues(c, vals)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}
var e Engine
e.EnableDNS = true
out, err := e.Render(c, v)
if err != nil {
t.Errorf("Failed to render templates: %s", err)
}
for _, val := range c.Templates {
fp := path.Join("moby", val.Name)
if out[fp] == "" {
t.Errorf("Expected IP address, got %q", out[fp])
}
}
}
type kindProps struct {
shouldErr error
gvr schema.GroupVersionResource
namespaced bool
}
type testClientProvider struct {
t *testing.T
scheme map[string]kindProps
objects []runtime.Object
}
func (p *testClientProvider) GetClientFor(apiVersion, kind string) (dynamic.NamespaceableResourceInterface, bool, error) {
props := p.scheme[path.Join(apiVersion, kind)]
if props.shouldErr != nil {
return nil, false, props.shouldErr
}
return fake.NewSimpleDynamicClient(runtime.NewScheme(), p.objects...).Resource(props.gvr), props.namespaced, nil
}
var _ ClientProvider = &testClientProvider{}
// makeUnstructured is a convenience function for single-line creation of Unstructured objects.
func makeUnstructured(apiVersion, kind, name, namespace string) *unstructured.Unstructured {
ret := &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": apiVersion,
"kind": kind,
"metadata": map[string]interface{}{
"name": name,
},
}}
if namespace != "" {
ret.Object["metadata"].(map[string]interface{})["namespace"] = namespace
}
return ret
}
func TestRenderWithClientProvider(t *testing.T) {
provider := &testClientProvider{
t: t,
scheme: map[string]kindProps{
"v1/Namespace": {
gvr: schema.GroupVersionResource{
Version: "v1",
Resource: "namespaces",
},
},
"v1/Pod": {
gvr: schema.GroupVersionResource{
Version: "v1",
Resource: "pods",
},
namespaced: true,
},
},
objects: []runtime.Object{
makeUnstructured("v1", "Namespace", "default", ""),
makeUnstructured("v1", "Pod", "pod1", "default"),
makeUnstructured("v1", "Pod", "pod2", "ns1"),
makeUnstructured("v1", "Pod", "pod3", "ns1"),
},
}
type testCase struct {
template string
output string
}
cases := map[string]testCase{
"ns-single": {
template: `{{ (lookup "v1" "Namespace" "" "default").metadata.name }}`,
output: "default",
},
"ns-list": {
template: `{{ (lookup "v1" "Namespace" "" "").items | len }}`,
output: "1",
},
"ns-missing": {
template: `{{ (lookup "v1" "Namespace" "" "absent") }}`,
output: "map[]",
},
"pod-single": {
template: `{{ (lookup "v1" "Pod" "default" "pod1").metadata.name }}`,
output: "pod1",
},
"pod-list": {
template: `{{ (lookup "v1" "Pod" "ns1" "").items | len }}`,
output: "2",
},
"pod-all": {
template: `{{ (lookup "v1" "Pod" "" "").items | len }}`,
output: "3",
},
"pod-missing": {
template: `{{ (lookup "v1" "Pod" "" "ns2") }}`,
output: "map[]",
},
}
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "moby",
Version: "1.2.3",
},
Values: map[string]interface{}{},
}
modTime := time.Now()
for name, exp := range cases {
c.Templates = append(c.Templates, &common.File{
Name: path.Join("templates", name),
ModTime: modTime,
Data: []byte(exp.template),
})
}
vals := map[string]interface{}{
"Values": map[string]interface{}{},
}
v, err := util.CoalesceValues(c, vals)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}
out, err := RenderWithClientProvider(c, v, provider)
if err != nil {
t.Errorf("Failed to render templates: %s", err)
}
for name, want := range cases {
t.Run(name, func(t *testing.T) {
key := path.Join("moby/templates", name)
if out[key] != want.output {
t.Errorf("Expected %q, got %q", want, out[key])
}
})
}
}
func TestRenderWithClientProvider_error(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "moby",
Version: "1.2.3",
},
Templates: []*common.File{
{Name: "templates/error", ModTime: time.Now(), Data: []byte(`{{ lookup "v1" "Error" "" "" }}`)},
},
Values: map[string]interface{}{},
}
vals := map[string]interface{}{
"Values": map[string]interface{}{},
}
v, err := util.CoalesceValues(c, vals)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}
provider := &testClientProvider{
t: t,
scheme: map[string]kindProps{
"v1/Error": {
shouldErr: fmt.Errorf("kaboom"),
},
},
}
_, err = RenderWithClientProvider(c, v, provider)
if err == nil || !strings.Contains(err.Error(), "kaboom") {
t.Errorf("Expected error from client provider when rendering, got %q", err)
}
}
func TestParallelRenderInternals(t *testing.T) {
// Make sure that we can use one Engine to run parallel template renders.
e := new(Engine)
var wg sync.WaitGroup
for i := range 20 {
wg.Add(1)
go func(i int) {
tt := fmt.Sprintf("expect-%d", i)
tpls := map[string]renderable{
"t": {
tpl: `{{.val}}`,
vals: map[string]interface{}{"val": tt},
},
}
out, err := e.render(tpls)
if err != nil {
t.Errorf("Failed to render %s: %s", tt, err)
}
if out["t"] != tt {
t.Errorf("Expected %q, got %q", tt, out["t"])
}
wg.Done()
}(i)
}
wg.Wait()
}
func TestParseErrors(t *testing.T) {
vals := common.Values{"Values": map[string]interface{}{}}
tplsUndefinedFunction := map[string]renderable{
"undefined_function": {tpl: `{{foo}}`, vals: vals},
}
_, err := new(Engine).render(tplsUndefinedFunction)
if err == nil {
t.Fatalf("Expected failures while rendering: %s", err)
}
expected := `parse error at (undefined_function:1): function "foo" not defined`
if err.Error() != expected {
t.Errorf("Expected '%s', got %q", expected, err.Error())
}
}
func TestExecErrors(t *testing.T) {
vals := common.Values{"Values": map[string]interface{}{}}
cases := []struct {
name string
tpls map[string]renderable
expected string
}{
{
name: "MissingRequired",
tpls: map[string]renderable{
"missing_required": {tpl: `{{required "foo is required" .Values.foo}}`, vals: vals},
},
expected: `execution error at (missing_required:1:2): foo is required`,
},
{
name: "MissingRequiredWithColons",
tpls: map[string]renderable{
"missing_required_with_colons": {tpl: `{{required ":this: message: has many: colons:" .Values.foo}}`, vals: vals},
},
expected: `execution error at (missing_required_with_colons:1:2): :this: message: has many: colons:`,
},
{
name: "Issue6044",
tpls: map[string]renderable{
"issue6044": {
vals: vals,
tpl: `{{ $someEmptyValue := "" }}
{{ $myvar := "abc" }}
{{- required (printf "%s: something is missing" $myvar) $someEmptyValue | repeat 0 }}`,
},
},
expected: `execution error at (issue6044:3:4): abc: something is missing`,
},
{
name: "MissingRequiredWithNewlines",
tpls: map[string]renderable{
"issue9981": {tpl: `{{required "foo is required\nmore info after the break" .Values.foo}}`, vals: vals},
},
expected: `execution error at (issue9981:1:2): foo is required
more info after the break`,
},
{
name: "FailWithNewlines",
tpls: map[string]renderable{
"issue9981": {tpl: `{{fail "something is wrong\nlinebreak"}}`, vals: vals},
},
expected: `execution error at (issue9981:1:2): something is wrong
linebreak`,
},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
_, err := new(Engine).render(tt.tpls)
if err == nil {
t.Fatalf("Expected failures while rendering: %s", err)
}
if err.Error() != tt.expected {
t.Errorf("Expected %q, got %q", tt.expected, err.Error())
}
})
}
}
func TestFailErrors(t *testing.T) {
vals := common.Values{"Values": map[string]interface{}{}}
failtpl := `All your base are belong to us{{ fail "This is an error" }}`
tplsFailed := map[string]renderable{
"failtpl": {tpl: failtpl, vals: vals},
}
_, err := new(Engine).render(tplsFailed)
if err == nil {
t.Fatalf("Expected failures while rendering: %s", err)
}
expected := `execution error at (failtpl:1:33): This is an error`
if err.Error() != expected {
t.Errorf("Expected '%s', got %q", expected, err.Error())
}
var e Engine
e.LintMode = true
out, err := e.render(tplsFailed)
if err != nil {
t.Fatal(err)
}
expectStr := "All your base are belong to us"
if gotStr := out["failtpl"]; gotStr != expectStr {
t.Errorf("Expected %q, got %q (%v)", expectStr, gotStr, out)
}
}
func TestAllTemplates(t *testing.T) {
modTime := time.Now()
ch1 := &chart.Chart{
Metadata: &chart.Metadata{Name: "ch1"},
Templates: []*common.File{
{Name: "templates/foo", ModTime: modTime, Data: []byte("foo")},
{Name: "templates/bar", ModTime: modTime, Data: []byte("bar")},
},
}
dep1 := &chart.Chart{
Metadata: &chart.Metadata{Name: "laboratory mice"},
Templates: []*common.File{
{Name: "templates/pinky", ModTime: modTime, Data: []byte("pinky")},
{Name: "templates/brain", ModTime: modTime, Data: []byte("brain")},
},
}
ch1.AddDependency(dep1)
dep2 := &chart.Chart{
Metadata: &chart.Metadata{Name: "same thing we do every night"},
Templates: []*common.File{
{Name: "templates/innermost", ModTime: modTime, Data: []byte("innermost")},
},
}
dep1.AddDependency(dep2)
tpls := allTemplates(ch1, common.Values{})
if len(tpls) != 5 {
t.Errorf("Expected 5 charts, got %d", len(tpls))
}
}
func TestChartValuesContainsIsRoot(t *testing.T) {
modTime := time.Now()
ch1 := &chart.Chart{
Metadata: &chart.Metadata{Name: "parent"},
Templates: []*common.File{
{Name: "templates/isroot", ModTime: modTime, Data: []byte("{{.Chart.IsRoot}}")},
},
}
dep1 := &chart.Chart{
Metadata: &chart.Metadata{Name: "child"},
Templates: []*common.File{
{Name: "templates/isroot", ModTime: modTime, Data: []byte("{{.Chart.IsRoot}}")},
},
}
ch1.AddDependency(dep1)
out, err := Render(ch1, common.Values{})
if err != nil {
t.Fatalf("failed to render templates: %s", err)
}
expects := map[string]string{
"parent/charts/child/templates/isroot": "false",
"parent/templates/isroot": "true",
}
for file, expect := range expects {
if out[file] != expect {
t.Errorf("Expected %q, got %q", expect, out[file])
}
}
}
func TestRenderDependency(t *testing.T) {
deptpl := `{{define "myblock"}}World{{end}}`
toptpl := `Hello {{template "myblock"}}`
modTime := time.Now()
ch := &chart.Chart{
Metadata: &chart.Metadata{Name: "outerchart"},
Templates: []*common.File{
{Name: "templates/outer", ModTime: modTime, Data: []byte(toptpl)},
},
}
ch.AddDependency(&chart.Chart{
Metadata: &chart.Metadata{Name: "innerchart"},
Templates: []*common.File{
{Name: "templates/inner", ModTime: modTime, Data: []byte(deptpl)},
},
})
out, err := Render(ch, map[string]interface{}{})
if err != nil {
t.Fatalf("failed to render chart: %s", err)
}
if len(out) != 2 {
t.Errorf("Expected 2, got %d", len(out))
}
expect := "Hello World"
if out["outerchart/templates/outer"] != expect {
t.Errorf("Expected %q, got %q", expect, out["outer"])
}
}
func TestRenderNestedValues(t *testing.T) {
innerpath := "templates/inner.tpl"
outerpath := "templates/outer.tpl"
// Ensure namespacing rules are working.
deepestpath := "templates/inner.tpl"
checkrelease := "templates/release.tpl"
// Ensure subcharts scopes are working.
subchartspath := "templates/subcharts.tpl"
modTime := time.Now()
deepest := &chart.Chart{
Metadata: &chart.Metadata{Name: "deepest"},
Templates: []*common.File{
{Name: deepestpath, ModTime: modTime, Data: []byte(`And this same {{.Values.what}} that smiles {{.Values.global.when}}`)},
{Name: checkrelease, ModTime: modTime, Data: []byte(`Tomorrow will be {{default "happy" .Release.Name }}`)},
},
Values: map[string]interface{}{"what": "milkshake", "where": "here"},
}
inner := &chart.Chart{
Metadata: &chart.Metadata{Name: "herrick"},
Templates: []*common.File{
{Name: innerpath, ModTime: modTime, Data: []byte(`Old {{.Values.who}} is still a-flyin'`)},
},
Values: map[string]interface{}{"who": "Robert", "what": "glasses"},
}
inner.AddDependency(deepest)
outer := &chart.Chart{
Metadata: &chart.Metadata{Name: "top"},
Templates: []*common.File{
{Name: outerpath, ModTime: modTime, Data: []byte(`Gather ye {{.Values.what}} while ye may`)},
{Name: subchartspath, ModTime: modTime, Data: []byte(`The glorious Lamp of {{.Subcharts.herrick.Subcharts.deepest.Values.where}}, the {{.Subcharts.herrick.Values.what}}`)},
},
Values: map[string]interface{}{
"what": "stinkweed",
"who": "me",
"herrick": map[string]interface{}{
"who": "time",
"what": "Sun",
},
},
}
outer.AddDependency(inner)
injValues := map[string]interface{}{
"what": "rosebuds",
"herrick": map[string]interface{}{
"deepest": map[string]interface{}{
"what": "flower",
"where": "Heaven",
},
},
"global": map[string]interface{}{
"when": "to-day",
},
}
tmp, err := util.CoalesceValues(outer, injValues)
if err != nil {
t.Fatalf("Failed to coalesce values: %s", err)
}
inject := common.Values{
"Values": tmp,
"Chart": outer.Metadata,
"Release": common.Values{
"Name": "dyin",
},
}
t.Logf("Calculated values: %v", inject)
out, err := Render(outer, inject)
if err != nil {
t.Fatalf("failed to render templates: %s", err)
}
fullouterpath := "top/" + outerpath
if out[fullouterpath] != "Gather ye rosebuds while ye may" {
t.Errorf("Unexpected outer: %q", out[fullouterpath])
}
fullinnerpath := "top/charts/herrick/" + innerpath
if out[fullinnerpath] != "Old time is still a-flyin'" {
t.Errorf("Unexpected inner: %q", out[fullinnerpath])
}
fulldeepestpath := "top/charts/herrick/charts/deepest/" + deepestpath
if out[fulldeepestpath] != "And this same flower that smiles to-day" {
t.Errorf("Unexpected deepest: %q", out[fulldeepestpath])
}
fullcheckrelease := "top/charts/herrick/charts/deepest/" + checkrelease
if out[fullcheckrelease] != "Tomorrow will be dyin" {
t.Errorf("Unexpected release: %q", out[fullcheckrelease])
}
fullchecksubcharts := "top/" + subchartspath
if out[fullchecksubcharts] != "The glorious Lamp of Heaven, the Sun" {
t.Errorf("Unexpected subcharts: %q", out[fullchecksubcharts])
}
}
func TestRenderBuiltinValues(t *testing.T) {
modTime := time.Now()
inner := &chart.Chart{
Metadata: &chart.Metadata{Name: "Latium", APIVersion: chart.APIVersionV2},
Templates: []*common.File{
{Name: "templates/Lavinia", ModTime: modTime, Data: []byte(`{{.Template.Name}}{{.Chart.Name}}{{.Release.Name}}`)},
{Name: "templates/From", ModTime: modTime, Data: []byte(`{{.Files.author | printf "%s"}} {{.Files.Get "book/title.txt"}}`)},
},
Files: []*common.File{
{Name: "author", ModTime: modTime, Data: []byte("Virgil")},
{Name: "book/title.txt", ModTime: modTime, Data: []byte("Aeneid")},
},
}
outer := &chart.Chart{
Metadata: &chart.Metadata{Name: "Troy", APIVersion: chart.APIVersionV2},
Templates: []*common.File{
{Name: "templates/Aeneas", ModTime: modTime, Data: []byte(`{{.Template.Name}}{{.Chart.Name}}{{.Release.Name}}`)},
{Name: "templates/Amata", ModTime: modTime, Data: []byte(`{{.Subcharts.Latium.Chart.Name}} {{.Subcharts.Latium.Files.author | printf "%s"}}`)},
},
}
outer.AddDependency(inner)
inject := common.Values{
"Values": "",
"Chart": outer.Metadata,
"Release": common.Values{
"Name": "Aeneid",
},
}
t.Logf("Calculated values: %v", outer)
out, err := Render(outer, inject)
if err != nil {
t.Fatalf("failed to render templates: %s", err)
}
expects := map[string]string{
"Troy/charts/Latium/templates/Lavinia": "Troy/charts/Latium/templates/LaviniaLatiumAeneid",
"Troy/templates/Aeneas": "Troy/templates/AeneasTroyAeneid",
"Troy/templates/Amata": "Latium Virgil",
"Troy/charts/Latium/templates/From": "Virgil Aeneid",
}
for file, expect := range expects {
if out[file] != expect {
t.Errorf("Expected %q, got %q", expect, out[file])
}
}
}
func TestAlterFuncMap_include(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "conrad"},
Templates: []*common.File{
{Name: "templates/quote", ModTime: modTime, Data: []byte(`{{include "conrad/templates/_partial" . | indent 2}} dead.`)},
{Name: "templates/_partial", ModTime: modTime, Data: []byte(`{{.Release.Name}} - he`)},
},
}
// Check nested reference in include FuncMap
d := &chart.Chart{
Metadata: &chart.Metadata{Name: "nested"},
Templates: []*common.File{
{Name: "templates/quote", ModTime: modTime, Data: []byte(`{{include "nested/templates/quote" . | indent 2}} dead.`)},
{Name: "templates/_partial", ModTime: modTime, Data: []byte(`{{.Release.Name}} - he`)},
},
}
v := common.Values{
"Values": "",
"Chart": c.Metadata,
"Release": common.Values{
"Name": "Mistah Kurtz",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := " Mistah Kurtz - he dead."
if got := out["conrad/templates/quote"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
_, err = Render(d, v)
expectErrName := "nested/templates/quote"
if err == nil {
t.Errorf("Expected err of nested reference name: %v", expectErrName)
}
}
func TestAlterFuncMap_require(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "conan"},
Templates: []*common.File{
{Name: "templates/quote", ModTime: modTime, Data: []byte(`All your base are belong to {{ required "A valid 'who' is required" .Values.who }}`)},
{Name: "templates/bases", ModTime: modTime, Data: []byte(`All {{ required "A valid 'bases' is required" .Values.bases }} of them!`)},
},
}
v := common.Values{
"Values": common.Values{
"who": "us",
"bases": 2,
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "That 90s meme",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expectStr := "All your base are belong to us"
if gotStr := out["conan/templates/quote"]; gotStr != expectStr {
t.Errorf("Expected %q, got %q (%v)", expectStr, gotStr, out)
}
expectNum := "All 2 of them!"
if gotNum := out["conan/templates/bases"]; gotNum != expectNum {
t.Errorf("Expected %q, got %q (%v)", expectNum, gotNum, out)
}
// test required without passing in needed values with lint mode on
// verifies lint replaces required with an empty string (should not fail)
lintValues := common.Values{
"Values": common.Values{
"who": "us",
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "That 90s meme",
},
}
var e Engine
e.LintMode = true
out, err = e.Render(c, lintValues)
if err != nil {
t.Fatal(err)
}
expectStr = "All your base are belong to us"
if gotStr := out["conan/templates/quote"]; gotStr != expectStr {
t.Errorf("Expected %q, got %q (%v)", expectStr, gotStr, out)
}
expectNum = "All of them!"
if gotNum := out["conan/templates/bases"]; gotNum != expectNum {
t.Errorf("Expected %q, got %q (%v)", expectNum, gotNum, out)
}
}
func TestAlterFuncMap_tpl(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplFunction"},
Templates: []*common.File{
{Name: "templates/base", ModTime: time.Now(), Data: []byte(`Evaluate tpl {{tpl "Value: {{ .Values.value}}" .}}`)},
},
}
v := common.Values{
"Values": common.Values{
"value": "myvalue",
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := "Evaluate tpl Value: myvalue"
if got := out["TplFunction/templates/base"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
}
func TestAlterFuncMap_tplfunc(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplFunction"},
Templates: []*common.File{
{Name: "templates/base", ModTime: time.Now(), Data: []byte(`Evaluate tpl {{tpl "Value: {{ .Values.value | quote}}" .}}`)},
},
}
v := common.Values{
"Values": common.Values{
"value": "myvalue",
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := "Evaluate tpl Value: \"myvalue\""
if got := out["TplFunction/templates/base"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
}
func TestAlterFuncMap_tplinclude(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplFunction"},
Templates: []*common.File{
{Name: "templates/base", ModTime: modTime, Data: []byte(`{{ tpl "{{include ` + "`" + `TplFunction/templates/_partial` + "`" + ` . | quote }}" .}}`)},
{Name: "templates/_partial", ModTime: modTime, Data: []byte(`{{.Template.Name}}`)},
},
}
v := common.Values{
"Values": common.Values{
"value": "myvalue",
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := "\"TplFunction/templates/base\""
if got := out["TplFunction/templates/base"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
}
func TestRenderRecursionLimit(t *testing.T) {
modTime := time.Now()
// endless recursion should produce an error
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "bad"},
Templates: []*common.File{
{Name: "templates/base", ModTime: modTime, Data: []byte(`{{include "recursion" . }}`)},
{Name: "templates/recursion", ModTime: modTime, Data: []byte(`{{define "recursion"}}{{include "recursion" . }}{{end}}`)},
},
}
v := common.Values{
"Values": "",
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
expectErr := "rendering template has a nested reference name: recursion: unable to execute template"
_, err := Render(c, v)
if err == nil || !strings.HasSuffix(err.Error(), expectErr) {
t.Errorf("Expected err with suffix: %s", expectErr)
}
// calling the same function many times is ok
times := 4000
phrase := "All work and no play makes Jack a dull boy"
printFunc := `{{define "overlook"}}{{printf "` + phrase + `\n"}}{{end}}`
var repeatedIncl strings.Builder
for range times {
repeatedIncl.WriteString(`{{include "overlook" . }}`)
}
d := &chart.Chart{
Metadata: &chart.Metadata{Name: "overlook"},
Templates: []*common.File{
{Name: "templates/quote", ModTime: modTime, Data: []byte(repeatedIncl.String())},
{Name: "templates/_function", ModTime: modTime, Data: []byte(printFunc)},
},
}
out, err := Render(d, v)
if err != nil {
t.Fatal(err)
}
var expect string
for range times {
expect += phrase + "\n"
}
if got := out["overlook/templates/quote"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
}
func TestRenderLoadTemplateForTplFromFile(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplLoadFromFile"},
Templates: []*common.File{
{Name: "templates/base", ModTime: modTime, Data: []byte(`{{ tpl (.Files.Get .Values.filename) . }}`)},
{Name: "templates/_function", ModTime: modTime, Data: []byte(`{{define "test-function"}}test-function{{end}}`)},
},
Files: []*common.File{
{Name: "test", ModTime: modTime, Data: []byte(`{{ tpl (.Files.Get .Values.filename2) .}}`)},
{Name: "test2", ModTime: modTime, Data: []byte(`{{include "test-function" .}}{{define "nested-define"}}nested-define-content{{end}} {{include "nested-define" .}}`)},
},
}
v := common.Values{
"Values": common.Values{
"filename": "test",
"filename2": "test2",
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := "test-function nested-define-content"
if got := out["TplLoadFromFile/templates/base"]; got != expect {
t.Fatalf("Expected %q, got %q", expect, got)
}
}
func TestRenderTplEmpty(t *testing.T) {
modTime := time.Now()
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplEmpty"},
Templates: []*common.File{
{Name: "templates/empty-string", ModTime: modTime, Data: []byte(`{{tpl "" .}}`)},
{Name: "templates/empty-action", ModTime: modTime, Data: []byte(`{{tpl "{{ \"\"}}" .}}`)},
{Name: "templates/only-defines", ModTime: modTime, Data: []byte(`{{tpl "{{define \"not-invoked\"}}not-rendered{{end}}" .}}`)},
},
}
v := common.Values{
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
if err != nil {
t.Fatal(err)
}
expects := map[string]string{
"TplEmpty/templates/empty-string": "",
"TplEmpty/templates/empty-action": "",
"TplEmpty/templates/only-defines": "",
}
for file, expect := range expects {
if out[file] != expect {
t.Errorf("Expected %q, got %q", expect, out[file])
}
}
}
func TestRenderTplTemplateNames(t *testing.T) {
modTime := time.Now()
// .Template.BasePath and .Name make it through
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplTemplateNames"},
Templates: []*common.File{
{Name: "templates/default-basepath", ModTime: modTime, Data: []byte(`{{tpl "{{ .Template.BasePath }}" .}}`)},
{Name: "templates/default-name", ModTime: modTime, Data: []byte(`{{tpl "{{ .Template.Name }}" .}}`)},
{Name: "templates/modified-basepath", ModTime: modTime, Data: []byte(`{{tpl "{{ .Template.BasePath }}" .Values.dot}}`)},
{Name: "templates/modified-name", ModTime: modTime, Data: []byte(`{{tpl "{{ .Template.Name }}" .Values.dot}}`)},
{Name: "templates/modified-field", ModTime: modTime, Data: []byte(`{{tpl "{{ .Template.Field }}" .Values.dot}}`)},
},
}
v := common.Values{
"Values": common.Values{
"dot": common.Values{
"Template": common.Values{
"BasePath": "path/to/template",
"Name": "name-of-template",
"Field": "extra-field",
},
},
},
"Chart": c.Metadata,
"Release": common.Values{
"Name": "TestRelease",
},
}
out, err := Render(c, v)
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | true |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/engine.go | pkg/engine/engine.go | /*
Copyright The Helm 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 engine
import (
"errors"
"fmt"
"log/slog"
"maps"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"k8s.io/client-go/rest"
ci "helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/common"
)
// Engine is an implementation of the Helm rendering implementation for templates.
type Engine struct {
// If strict is enabled, template rendering will fail if a template references
// a value that was not passed in.
Strict bool
// In LintMode, some 'required' template values may be missing, so don't fail
LintMode bool
// optional provider of clients to talk to the Kubernetes API
clientProvider *ClientProvider
// EnableDNS tells the engine to allow DNS lookups when rendering templates
EnableDNS bool
// CustomTemplateFuncs is defined by users to provide custom template funcs
CustomTemplateFuncs template.FuncMap
}
// New creates a new instance of Engine using the passed in rest config.
func New(config *rest.Config) Engine {
var clientProvider ClientProvider = clientProviderFromConfig{config}
return Engine{
clientProvider: &clientProvider,
}
}
// Render takes a chart, optional values, and value overrides, and attempts to render the Go templates.
//
// Render can be called repeatedly on the same engine.
//
// This will look in the chart's 'templates' data (e.g. the 'templates/' directory)
// and attempt to render the templates there using the values passed in.
//
// Values are scoped to their templates. A dependency template will not have
// access to the values set for its parent. If chart "foo" includes chart "bar",
// "bar" will not have access to the values for "foo".
//
// Values should be prepared with something like `chartutils.ReadValues`.
//
// Values are passed through the templates according to scope. If the top layer
// chart includes the chart foo, which includes the chart bar, the values map
// will be examined for a table called "foo". If "foo" is found in vals,
// that section of the values will be passed into the "foo" chart. And if that
// section contains a value named "bar", that value will be passed on to the
// bar chart during render time.
func (e Engine) Render(chrt ci.Charter, values common.Values) (map[string]string, error) {
tmap := allTemplates(chrt, values)
return e.render(tmap)
}
// Render takes a chart, optional values, and value overrides, and attempts to
// render the Go templates using the default options.
func Render(chrt ci.Charter, values common.Values) (map[string]string, error) {
return new(Engine).Render(chrt, values)
}
// RenderWithClient takes a chart, optional values, and value overrides, and attempts to
// render the Go templates using the default options. This engine is client aware and so can have template
// functions that interact with the client.
func RenderWithClient(chrt ci.Charter, values common.Values, config *rest.Config) (map[string]string, error) {
var clientProvider ClientProvider = clientProviderFromConfig{config}
return Engine{
clientProvider: &clientProvider,
}.Render(chrt, values)
}
// RenderWithClientProvider takes a chart, optional values, and value overrides, and attempts to
// render the Go templates using the default options. This engine is client aware and so can have template
// functions that interact with the client.
// This function differs from RenderWithClient in that it lets you customize the way a dynamic client is constructed.
func RenderWithClientProvider(chrt ci.Charter, values common.Values, clientProvider ClientProvider) (map[string]string, error) {
return Engine{
clientProvider: &clientProvider,
}.Render(chrt, values)
}
// renderable is an object that can be rendered.
type renderable struct {
// tpl is the current template.
tpl string
// vals are the values to be supplied to the template.
vals common.Values
// namespace prefix to the templates of the current chart
basePath string
}
const warnStartDelim = "HELM_ERR_START"
const warnEndDelim = "HELM_ERR_END"
const recursionMaxNums = 1000
var warnRegex = regexp.MustCompile(warnStartDelim + `((?s).*)` + warnEndDelim)
func warnWrap(warn string) string {
return warnStartDelim + warn + warnEndDelim
}
// 'include' needs to be defined in the scope of a 'tpl' template as
// well as regular file-loaded templates.
func includeFun(t *template.Template, includedNames map[string]int) func(string, interface{}) (string, error) {
return func(name string, data interface{}) (string, error) {
var buf strings.Builder
if v, ok := includedNames[name]; ok {
if v > recursionMaxNums {
return "", fmt.Errorf(
"rendering template has a nested reference name: %s: %w",
name, errors.New("unable to execute template"))
}
includedNames[name]++
} else {
includedNames[name] = 1
}
err := t.ExecuteTemplate(&buf, name, data)
includedNames[name]--
return buf.String(), err
}
}
// As does 'tpl', so that nested calls to 'tpl' see the templates
// defined by their enclosing contexts.
func tplFun(parent *template.Template, includedNames map[string]int, strict bool) func(string, interface{}) (string, error) {
return func(tpl string, vals interface{}) (string, error) {
t, err := parent.Clone()
if err != nil {
return "", fmt.Errorf("cannot clone template: %w", err)
}
// Re-inject the missingkey option, see text/template issue https://github.com/golang/go/issues/43022
// We have to go by strict from our engine configuration, as the option fields are private in Template.
// TODO: Remove workaround (and the strict parameter) once we build only with golang versions with a fix.
if strict {
t.Option("missingkey=error")
} else {
t.Option("missingkey=zero")
}
// Re-inject 'include' so that it can close over our clone of t;
// this lets any 'define's inside tpl be 'include'd.
t.Funcs(template.FuncMap{
"include": includeFun(t, includedNames),
"tpl": tplFun(t, includedNames, strict),
})
// We need a .New template, as template text which is just blanks
// or comments after parsing out defines just adds new named
// template definitions without changing the main template.
// https://pkg.go.dev/text/template#Template.Parse
// Use the parent's name for lack of a better way to identify the tpl
// text string. (Maybe we could use a hash appended to the name?)
t, err = t.New(parent.Name()).Parse(tpl)
if err != nil {
return "", fmt.Errorf("cannot parse template %q: %w", tpl, err)
}
var buf strings.Builder
if err := t.Execute(&buf, vals); err != nil {
return "", fmt.Errorf("error during tpl function execution for %q: %w", tpl, err)
}
// See comment in renderWithReferences explaining the <no value> hack.
return strings.ReplaceAll(buf.String(), "<no value>", ""), nil
}
}
// initFunMap creates the Engine's FuncMap and adds context-specific functions.
func (e Engine) initFunMap(t *template.Template) {
funcMap := funcMap()
includedNames := make(map[string]int)
// Add the template-rendering functions here so we can close over t.
funcMap["include"] = includeFun(t, includedNames)
funcMap["tpl"] = tplFun(t, includedNames, e.Strict)
// Add the `required` function here so we can use lintMode
funcMap["required"] = func(warn string, val interface{}) (interface{}, error) {
if val == nil {
if e.LintMode {
// Don't fail on missing required values when linting
slog.Warn("missing required value", "message", warn)
return "", nil
}
return val, errors.New(warnWrap(warn))
} else if _, ok := val.(string); ok {
if val == "" {
if e.LintMode {
// Don't fail on missing required values when linting
slog.Warn("missing required values", "message", warn)
return "", nil
}
return val, errors.New(warnWrap(warn))
}
}
return val, nil
}
// Override sprig fail function for linting and wrapping message
funcMap["fail"] = func(msg string) (string, error) {
if e.LintMode {
// Don't fail when linting
slog.Info("funcMap fail", "message", msg)
return "", nil
}
return "", errors.New(warnWrap(msg))
}
// If we are not linting and have a cluster connection, provide a Kubernetes-backed
// implementation.
if !e.LintMode && e.clientProvider != nil {
funcMap["lookup"] = newLookupFunction(*e.clientProvider)
}
// When DNS lookups are not enabled override the sprig function and return
// an empty string.
if !e.EnableDNS {
funcMap["getHostByName"] = func(_ string) string {
return ""
}
}
// Set custom template funcs
maps.Copy(funcMap, e.CustomTemplateFuncs)
t.Funcs(funcMap)
}
// render takes a map of templates/values and renders them.
func (e Engine) render(tpls map[string]renderable) (rendered map[string]string, err error) {
// Basically, what we do here is start with an empty parent template and then
// build up a list of templates -- one for each file. Once all of the templates
// have been parsed, we loop through again and execute every template.
//
// The idea with this process is to make it possible for more complex templates
// to share common blocks, but to make the entire thing feel like a file-based
// template engine.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("rendering template failed: %v", r)
}
}()
t := template.New("gotpl")
if e.Strict {
t.Option("missingkey=error")
} else {
// Not that zero will attempt to add default values for types it knows,
// but will still emit <no value> for others. We mitigate that later.
t.Option("missingkey=zero")
}
e.initFunMap(t)
// We want to parse the templates in a predictable order. The order favors
// higher-level (in file system) templates over deeply nested templates.
keys := sortTemplates(tpls)
for _, filename := range keys {
r := tpls[filename]
if _, err := t.New(filename).Parse(r.tpl); err != nil {
return map[string]string{}, cleanupParseError(filename, err)
}
}
rendered = make(map[string]string, len(keys))
for _, filename := range keys {
// Don't render partials. We don't care out the direct output of partials.
// They are only included from other templates.
if strings.HasPrefix(path.Base(filename), "_") {
continue
}
// At render time, add information about the template that is being rendered.
vals := tpls[filename].vals
vals["Template"] = common.Values{"Name": filename, "BasePath": tpls[filename].basePath}
var buf strings.Builder
if err := t.ExecuteTemplate(&buf, filename, vals); err != nil {
return map[string]string{}, reformatExecErrorMsg(filename, err)
}
// Work around the issue where Go will emit "<no value>" even if Options(missing=zero)
// is set. Since missing=error will never get here, we do not need to handle
// the Strict case.
rendered[filename] = strings.ReplaceAll(buf.String(), "<no value>", "")
}
return rendered, nil
}
func cleanupParseError(filename string, err error) error {
tokens := strings.Split(err.Error(), ": ")
if len(tokens) == 1 {
// This might happen if a non-templating error occurs
return fmt.Errorf("parse error in (%s): %s", filename, err)
}
// The first token is "template"
// The second token is either "filename:lineno" or "filename:lineNo:columnNo"
location := tokens[1]
// The remaining tokens make up a stacktrace-like chain, ending with the relevant error
errMsg := tokens[len(tokens)-1]
return fmt.Errorf("parse error at (%s): %s", location, errMsg)
}
type TraceableError struct {
location string
message string
executedFunction string
}
func (t TraceableError) String() string {
var errorString strings.Builder
if t.location != "" {
_, _ = fmt.Fprintf(&errorString, "%s\n ", t.location)
}
if t.executedFunction != "" {
_, _ = fmt.Fprintf(&errorString, "%s\n ", t.executedFunction)
}
if t.message != "" {
_, _ = fmt.Fprintf(&errorString, "%s\n", t.message)
}
return errorString.String()
}
// parseTemplateExecErrorString parses a template execution error string from text/template
// without using regular expressions. It returns a TraceableError and true if parsing succeeded.
func parseTemplateExecErrorString(s string) (TraceableError, bool) {
const prefix = "template: "
if !strings.HasPrefix(s, prefix) {
return TraceableError{}, false
}
remainder := s[len(prefix):]
// Special case: "template: no template %q associated with template %q"
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=191
traceableError, done := parseTemplateNoTemplateError(s, remainder)
if done {
return traceableError, true
}
// Executing form: "<templateName>: executing \"<funcName>\" at <<location>>: <errMsg>[ template:...]"
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=141
traceableError, done = parseTemplateExecutingAtErrorType(remainder)
if done {
return traceableError, true
}
// Simple form: "<templateName>: <errMsg>"
// Use LastIndex to avoid splitting colons within line:col info.
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=138
traceableError, done = parseTemplateSimpleErrorString(remainder)
if done {
return traceableError, true
}
return TraceableError{}, false
}
// Special case: "template: no template %q associated with template %q"
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=191
func parseTemplateNoTemplateError(s string, remainder string) (TraceableError, bool) {
if strings.HasPrefix(remainder, "no template ") {
return TraceableError{message: s}, true
}
return TraceableError{}, false
}
// Simple form: "<templateName>: <errMsg>"
// Use LastIndex to avoid splitting colons within line:col info.
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=138
func parseTemplateSimpleErrorString(remainder string) (TraceableError, bool) {
if sep := strings.LastIndex(remainder, ": "); sep != -1 {
templateName := remainder[:sep]
errMsg := remainder[sep+2:]
if cut := strings.Index(errMsg, " template:"); cut != -1 {
errMsg = errMsg[:cut]
}
return TraceableError{location: templateName, message: errMsg}, true
}
return TraceableError{}, false
}
// Executing form: "<templateName>: executing \"<funcName>\" at <<location>>: <errMsg>[ template:...]"
// Matches https://cs.opensource.google/go/go/+/refs/tags/go1.23.6:src/text/template/exec.go;l=141
func parseTemplateExecutingAtErrorType(remainder string) (TraceableError, bool) {
if idx := strings.Index(remainder, ": executing "); idx != -1 {
templateName := remainder[:idx]
after := remainder[idx+len(": executing "):]
if len(after) == 0 || after[0] != '"' {
return TraceableError{}, false
}
// find closing quote for function name
endQuote := strings.IndexByte(after[1:], '"')
if endQuote == -1 {
return TraceableError{}, false
}
endQuote++ // account for offset we started at 1
functionName := after[1:endQuote]
afterFunc := after[endQuote+1:]
// expect: " at <" then location then ">: " then message
const atPrefix = " at <"
if !strings.HasPrefix(afterFunc, atPrefix) {
return TraceableError{}, false
}
afterAt := afterFunc[len(atPrefix):]
endLoc := strings.Index(afterAt, ">: ")
if endLoc == -1 {
return TraceableError{}, false
}
locationName := afterAt[:endLoc]
errMsg := afterAt[endLoc+len(">: "):]
// trim chained next error starting with space + "template:" if present
if cut := strings.Index(errMsg, " template:"); cut != -1 {
errMsg = errMsg[:cut]
}
return TraceableError{
location: templateName,
message: errMsg,
executedFunction: "executing \"" + functionName + "\" at <" + locationName + ">:",
}, true
}
return TraceableError{}, false
}
// reformatExecErrorMsg takes an error message for template rendering and formats it into a formatted
// multi-line error string
func reformatExecErrorMsg(filename string, err error) error {
// This function parses the error message produced by text/template package.
// If it can parse out details from that error message such as the line number, template it failed on,
// and error description, then it will construct a new error that displays these details in a structured way.
// If there are issues with parsing the error message, the err passed into the function should return instead.
var execError template.ExecError
if !errors.As(err, &execError) {
return err
}
tokens := strings.SplitN(err.Error(), ": ", 3)
if len(tokens) != 3 {
// This might happen if a non-templating error occurs
return fmt.Errorf("execution error in (%s): %s", filename, err)
}
// The first token is "template"
// The second token is either "filename:lineno" or "filename:lineNo:columnNo"
location := tokens[1]
parts := warnRegex.FindStringSubmatch(tokens[2])
if len(parts) >= 2 {
return fmt.Errorf("execution error at (%s): %s", location, parts[1])
}
current := err
var fileLocations []TraceableError
for current != nil {
if tr, ok := parseTemplateExecErrorString(current.Error()); ok {
if len(fileLocations) == 0 || fileLocations[len(fileLocations)-1] != tr {
fileLocations = append(fileLocations, tr)
}
} else {
return err
}
current = errors.Unwrap(current)
}
var finalErrorString strings.Builder
for _, fileLocation := range fileLocations {
_, _ = fmt.Fprintf(&finalErrorString, "%s", fileLocation.String())
}
return errors.New(strings.TrimSpace(finalErrorString.String()))
}
func sortTemplates(tpls map[string]renderable) []string {
keys := make([]string, len(tpls))
i := 0
for key := range tpls {
keys[i] = key
i++
}
sort.Sort(sort.Reverse(byPathLen(keys)))
return keys
}
type byPathLen []string
func (p byPathLen) Len() int { return len(p) }
func (p byPathLen) Swap(i, j int) { p[j], p[i] = p[i], p[j] }
func (p byPathLen) Less(i, j int) bool {
a, b := p[i], p[j]
ca, cb := strings.Count(a, "/"), strings.Count(b, "/")
if ca == cb {
return strings.Compare(a, b) == -1
}
return ca < cb
}
// allTemplates returns all templates for a chart and its dependencies.
//
// As it goes, it also prepares the values in a scope-sensitive manner.
func allTemplates(c ci.Charter, vals common.Values) map[string]renderable {
templates := make(map[string]renderable)
recAllTpls(c, templates, vals)
return templates
}
// recAllTpls recurses through the templates in a chart.
//
// As it recurses, it also sets the values to be appropriate for the template
// scope.
func recAllTpls(c ci.Charter, templates map[string]renderable, values common.Values) map[string]interface{} {
vals := values.AsMap()
subCharts := make(map[string]interface{})
accessor, err := ci.NewAccessor(c)
if err != nil {
slog.Error("error accessing chart", "error", err)
}
chartMetaData := accessor.MetadataAsMap()
chartMetaData["IsRoot"] = accessor.IsRoot()
next := map[string]interface{}{
"Chart": chartMetaData,
"Files": newFiles(accessor.Files()),
"Release": vals["Release"],
"Capabilities": vals["Capabilities"],
"Values": make(common.Values),
"Subcharts": subCharts,
}
// If there is a {{.Values.ThisChart}} in the parent metadata,
// copy that into the {{.Values}} for this template.
if accessor.IsRoot() {
next["Values"] = vals["Values"]
} else if vs, err := values.Table("Values." + accessor.Name()); err == nil {
next["Values"] = vs
}
for _, child := range accessor.Dependencies() {
// TODO: Handle error
sub, _ := ci.NewAccessor(child)
subCharts[sub.Name()] = recAllTpls(child, templates, next)
}
newParentID := accessor.ChartFullPath()
for _, t := range accessor.Templates() {
if t == nil {
continue
}
if !isTemplateValid(accessor, t.Name) {
continue
}
templates[path.Join(newParentID, t.Name)] = renderable{
tpl: string(t.Data),
vals: next,
basePath: path.Join(newParentID, "templates"),
}
}
return next
}
// isTemplateValid returns true if the template is valid for the chart type
func isTemplateValid(accessor ci.Accessor, templateName string) bool {
if accessor.IsLibraryChart() {
return strings.HasPrefix(filepath.Base(templateName), "_")
}
return true
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/funcs.go | pkg/engine/funcs.go | /*
Copyright The Helm 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 engine
import (
"bytes"
"encoding/json"
"maps"
"strings"
"text/template"
"github.com/BurntSushi/toml"
"github.com/Masterminds/sprig/v3"
"sigs.k8s.io/yaml"
goYaml "sigs.k8s.io/yaml/goyaml.v3"
)
// funcMap returns a mapping of all of the functions that Engine has.
//
// Because some functions are late-bound (e.g. contain context-sensitive
// data), the functions may not all perform identically outside of an Engine
// as they will inside of an Engine.
//
// Known late-bound functions:
//
// - "include"
// - "tpl"
//
// These are late-bound in Engine.Render(). The
// version included in the FuncMap is a placeholder.
func funcMap() template.FuncMap {
f := sprig.TxtFuncMap()
delete(f, "env")
delete(f, "expandenv")
// Add some extra functionality
extra := template.FuncMap{
"toToml": toTOML,
"fromToml": fromTOML,
"toYaml": toYAML,
"mustToYaml": mustToYAML,
"toYamlPretty": toYAMLPretty,
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
"mustToJson": mustToJSON,
"fromJson": fromJSON,
"fromJsonArray": fromJSONArray,
// This is a placeholder for the "include" function, which is
// late-bound to a template. By declaring it here, we preserve the
// integrity of the linter.
"include": func(string, interface{}) string { return "not implemented" },
"tpl": func(string, interface{}) interface{} { return "not implemented" },
"required": func(string, interface{}) (interface{}, error) { return "not implemented", nil },
// Provide a placeholder for the "lookup" function, which requires a kubernetes
// connection.
"lookup": func(string, string, string, string) (map[string]interface{}, error) {
return map[string]interface{}{}, nil
},
}
maps.Copy(f, extra)
return f
}
// toYAML takes an interface, marshals it to yaml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toYAML(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return strings.TrimSuffix(string(data), "\n")
}
// mustToYAML takes an interface, marshals it to yaml, and returns a string.
// It will panic if there is an error.
//
// This is designed to be called from a template when need to ensure that the
// output YAML is valid.
func mustToYAML(v interface{}) string {
data, err := yaml.Marshal(v)
if err != nil {
panic(err)
}
return strings.TrimSuffix(string(data), "\n")
}
func toYAMLPretty(v interface{}) string {
var data bytes.Buffer
encoder := goYaml.NewEncoder(&data)
encoder.SetIndent(2)
err := encoder.Encode(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return strings.TrimSuffix(data.String(), "\n")
}
// fromYAML converts a YAML document into a map[string]interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid
// YAML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["Error"] in the returned map.
func fromYAML(str string) map[string]interface{} {
m := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}
// fromYAMLArray converts a YAML array into a []interface{}.
//
// This is not a general-purpose YAML parser, and will not parse all valid
// YAML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string as
// the first and only item in the returned array.
func fromYAMLArray(str string) []interface{} {
a := []interface{}{}
if err := yaml.Unmarshal([]byte(str), &a); err != nil {
a = []interface{}{err.Error()}
}
return a
}
// toTOML takes an interface, marshals it to toml, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toTOML(v interface{}) string {
b := bytes.NewBuffer(nil)
e := toml.NewEncoder(b)
err := e.Encode(v)
if err != nil {
return err.Error()
}
return b.String()
}
// fromTOML converts a TOML document into a map[string]interface{}.
//
// This is not a general-purpose TOML parser, and will not parse all valid
// TOML documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["Error"] in the returned map.
func fromTOML(str string) map[string]interface{} {
m := make(map[string]interface{})
if err := toml.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}
// toJSON takes an interface, marshals it to json, and returns a string. It will
// always return a string, even on marshal error (empty string).
//
// This is designed to be called from a template.
func toJSON(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}
// mustToJSON takes an interface, marshals it to json, and returns a string.
// It will panic if there is an error.
//
// This is designed to be called from a template when need to ensure that the
// output JSON is valid.
func mustToJSON(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
panic(err)
}
return string(data)
}
// fromJSON converts a JSON document into a map[string]interface{}.
//
// This is not a general-purpose JSON parser, and will not parse all valid
// JSON documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string into
// m["Error"] in the returned map.
func fromJSON(str string) map[string]interface{} {
m := make(map[string]interface{})
if err := json.Unmarshal([]byte(str), &m); err != nil {
m["Error"] = err.Error()
}
return m
}
// fromJSONArray converts a JSON array into a []interface{}.
//
// This is not a general-purpose JSON parser, and will not parse all valid
// JSON documents. Additionally, because its intended use is within templates
// it tolerates errors. It will insert the returned error message string as
// the first and only item in the returned array.
func fromJSONArray(str string) []interface{} {
a := []interface{}{}
if err := json.Unmarshal([]byte(str), &a); err != nil {
a = []interface{}{err.Error()}
}
return a
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/engine/doc.go | pkg/engine/doc.go | /*
Copyright The Helm 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 engine implements the Go text template engine as needed for Helm.
When Helm renders templates it does so with additional functions and different
modes (e.g., strict, lint mode). This package handles the helm specific
implementation.
*/
package engine // import "helm.sh/helm/v4/pkg/engine"
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/httpgetter.go | pkg/getter/httpgetter.go | /*
Copyright The Helm 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 getter
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"helm.sh/helm/v4/internal/tlsutil"
"helm.sh/helm/v4/internal/version"
)
// HTTPGetter is the default HTTP(/S) backend handler
type HTTPGetter struct {
opts getterOptions
transport *http.Transport
once sync.Once
}
// Get performs a Get from repo.Getter and returns the body.
func (g *HTTPGetter) Get(href string, options ...Option) (*bytes.Buffer, error) {
for _, opt := range options {
opt(&g.opts)
}
return g.get(href)
}
func (g *HTTPGetter) get(href string) (*bytes.Buffer, error) {
// Set a helm specific user agent so that a repo server and metrics can
// separate helm calls from other tools interacting with repos.
req, err := http.NewRequest(http.MethodGet, href, nil)
if err != nil {
return nil, err
}
if g.opts.acceptHeader != "" {
req.Header.Set("Accept", g.opts.acceptHeader)
}
req.Header.Set("User-Agent", version.GetUserAgent())
if g.opts.userAgent != "" {
req.Header.Set("User-Agent", g.opts.userAgent)
}
// Before setting the basic auth credentials, make sure the URL associated
// with the basic auth is the one being fetched.
u1, err := url.Parse(g.opts.url)
if err != nil {
return nil, fmt.Errorf("unable to parse getter URL: %w", err)
}
u2, err := url.Parse(href)
if err != nil {
return nil, fmt.Errorf("unable to parse URL getting from: %w", err)
}
// Host on URL (returned from url.Parse) contains the port if present.
// This check ensures credentials are not passed between different
// services on different ports.
if g.opts.passCredentialsAll || (u1.Scheme == u2.Scheme && u1.Host == u2.Host) {
if g.opts.username != "" && g.opts.password != "" {
req.SetBasicAuth(g.opts.username, g.opts.password)
}
}
client, err := g.httpClient()
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch %s : %s", href, resp.Status)
}
buf := bytes.NewBuffer(nil)
_, err = io.Copy(buf, resp.Body)
return buf, err
}
// NewHTTPGetter constructs a valid http/https client as a Getter
func NewHTTPGetter(options ...Option) (Getter, error) {
var client HTTPGetter
for _, opt := range options {
opt(&client.opts)
}
return &client, nil
}
func (g *HTTPGetter) httpClient() (*http.Client, error) {
if g.opts.transport != nil {
return &http.Client{
Transport: g.opts.transport,
Timeout: g.opts.timeout,
}, nil
}
g.once.Do(func() {
g.transport = &http.Transport{
DisableCompression: true,
Proxy: http.ProxyFromEnvironment,
// Being nil would cause the tls.Config default to be used
// "NewTLSConfig" modifies an empty TLS config, not the default one
TLSClientConfig: &tls.Config{},
}
})
if (g.opts.certFile != "" && g.opts.keyFile != "") || g.opts.caFile != "" || g.opts.insecureSkipVerifyTLS {
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(g.opts.insecureSkipVerifyTLS),
tlsutil.WithCertKeyPairFiles(g.opts.certFile, g.opts.keyFile),
tlsutil.WithCAFile(g.opts.caFile),
)
if err != nil {
return nil, fmt.Errorf("can't create TLS config for client: %w", err)
}
g.transport.TLSClientConfig = tlsConf
}
if g.opts.insecureSkipVerifyTLS {
if g.transport.TLSClientConfig == nil {
g.transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
} else {
g.transport.TLSClientConfig.InsecureSkipVerify = true
}
}
client := &http.Client{
Transport: g.transport,
Timeout: g.opts.timeout,
}
return client, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/httpgetter_test.go | pkg/getter/httpgetter_test.go | /*
Copyright The Helm 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 getter
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"helm.sh/helm/v4/internal/tlsutil"
"helm.sh/helm/v4/internal/version"
"helm.sh/helm/v4/pkg/cli"
)
func TestHTTPGetter(t *testing.T) {
g, err := NewHTTPGetter(WithURL("http://example.com"))
if err != nil {
t.Fatal(err)
}
if _, ok := g.(*HTTPGetter); !ok {
t.Fatal("Expected NewHTTPGetter to produce an *HTTPGetter")
}
cd := "../../testdata"
join := filepath.Join
ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem")
insecure := false
timeout := time.Second * 5
transport := &http.Transport{}
// Test with getterOptions
g, err = NewHTTPGetter(
WithBasicAuth("I", "Am"),
WithPassCredentialsAll(false),
WithUserAgent("Groot"),
WithTLSClientConfig(pub, priv, ca),
WithInsecureSkipVerifyTLS(insecure),
WithTimeout(timeout),
WithTransport(transport),
)
if err != nil {
t.Fatal(err)
}
hg, ok := g.(*HTTPGetter)
if !ok {
t.Fatal("expected NewHTTPGetter to produce an *HTTPGetter")
}
if hg.opts.username != "I" {
t.Errorf("Expected NewHTTPGetter to contain %q as the username, got %q", "I", hg.opts.username)
}
if hg.opts.password != "Am" {
t.Errorf("Expected NewHTTPGetter to contain %q as the password, got %q", "Am", hg.opts.password)
}
if hg.opts.passCredentialsAll != false {
t.Errorf("Expected NewHTTPGetter to contain %t as PassCredentialsAll, got %t", false, hg.opts.passCredentialsAll)
}
if hg.opts.userAgent != "Groot" {
t.Errorf("Expected NewHTTPGetter to contain %q as the user agent, got %q", "Groot", hg.opts.userAgent)
}
if hg.opts.certFile != pub {
t.Errorf("Expected NewHTTPGetter to contain %q as the public key file, got %q", pub, hg.opts.certFile)
}
if hg.opts.keyFile != priv {
t.Errorf("Expected NewHTTPGetter to contain %q as the private key file, got %q", priv, hg.opts.keyFile)
}
if hg.opts.caFile != ca {
t.Errorf("Expected NewHTTPGetter to contain %q as the CA file, got %q", ca, hg.opts.caFile)
}
if hg.opts.insecureSkipVerifyTLS != insecure {
t.Errorf("Expected NewHTTPGetter to contain %t as InsecureSkipVerifyTLs flag, got %t", false, hg.opts.insecureSkipVerifyTLS)
}
if hg.opts.timeout != timeout {
t.Errorf("Expected NewHTTPGetter to contain %s as Timeout flag, got %s", timeout, hg.opts.timeout)
}
if hg.opts.transport != transport {
t.Errorf("Expected NewHTTPGetter to contain %p as Transport, got %p", transport, hg.opts.transport)
}
// Test if setting insecureSkipVerifyTLS is being passed to the ops
insecure = true
g, err = NewHTTPGetter(
WithInsecureSkipVerifyTLS(insecure),
)
if err != nil {
t.Fatal(err)
}
hg, ok = g.(*HTTPGetter)
if !ok {
t.Fatal("expected NewHTTPGetter to produce an *HTTPGetter")
}
if hg.opts.insecureSkipVerifyTLS != insecure {
t.Errorf("Expected NewHTTPGetter to contain %t as InsecureSkipVerifyTLs flag, got %t", insecure, hg.opts.insecureSkipVerifyTLS)
}
// Checking false by default
if hg.opts.passCredentialsAll != false {
t.Errorf("Expected NewHTTPGetter to contain %t as PassCredentialsAll, got %t", false, hg.opts.passCredentialsAll)
}
// Test setting PassCredentialsAll
g, err = NewHTTPGetter(
WithBasicAuth("I", "Am"),
WithPassCredentialsAll(true),
)
if err != nil {
t.Fatal(err)
}
hg, ok = g.(*HTTPGetter)
if !ok {
t.Fatal("expected NewHTTPGetter to produce an *HTTPGetter")
}
if hg.opts.passCredentialsAll != true {
t.Errorf("Expected NewHTTPGetter to contain %t as PassCredentialsAll, got %t", true, hg.opts.passCredentialsAll)
}
}
func TestDownload(t *testing.T) {
expect := "Call me Ishmael"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defaultUserAgent := version.GetUserAgent()
if r.UserAgent() != defaultUserAgent {
t.Errorf("Expected '%s', got '%s'", defaultUserAgent, r.UserAgent())
}
fmt.Fprint(w, expect)
}))
defer srv.Close()
g, err := All(cli.New()).ByScheme("http")
if err != nil {
t.Fatal(err)
}
got, err := g.Get(srv.URL, WithURL(srv.URL))
if err != nil {
t.Fatal(err)
}
if got.String() != expect {
t.Errorf("Expected %q, got %q", expect, got.String())
}
// test with http server
const expectedUserAgent = "I am Groot"
basicAuthSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || username != "username" || password != "password" {
t.Errorf("Expected request to use basic auth and for username == 'username' and password == 'password', got '%v', '%s', '%s'", ok, username, password)
}
if r.UserAgent() != expectedUserAgent {
t.Errorf("Expected '%s', got '%s'", expectedUserAgent, r.UserAgent())
}
fmt.Fprint(w, expect)
}))
defer basicAuthSrv.Close()
u, _ := url.ParseRequestURI(basicAuthSrv.URL)
httpgetter, err := NewHTTPGetter(
WithURL(u.String()),
WithBasicAuth("username", "password"),
WithPassCredentialsAll(false),
WithUserAgent(expectedUserAgent),
)
if err != nil {
t.Fatal(err)
}
got, err = httpgetter.Get(u.String())
if err != nil {
t.Fatal(err)
}
if got.String() != expect {
t.Errorf("Expected %q, got %q", expect, got.String())
}
// test with Get URL differing from withURL
crossAuthSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if ok || username == "username" || password == "password" {
t.Errorf("Expected request to not include but got '%v', '%s', '%s'", ok, username, password)
}
fmt.Fprint(w, expect)
}))
defer crossAuthSrv.Close()
u, _ = url.ParseRequestURI(crossAuthSrv.URL)
// A different host is provided for the WithURL from the one used for Get
u2, _ := url.ParseRequestURI(crossAuthSrv.URL)
host := strings.Split(u2.Host, ":")
host[0] = host[0] + "a"
u2.Host = strings.Join(host, ":")
httpgetter, err = NewHTTPGetter(
WithURL(u2.String()),
WithBasicAuth("username", "password"),
WithPassCredentialsAll(false),
)
if err != nil {
t.Fatal(err)
}
got, err = httpgetter.Get(u.String())
if err != nil {
t.Fatal(err)
}
if got.String() != expect {
t.Errorf("Expected %q, got %q", expect, got.String())
}
// test with Get URL differing from withURL and should pass creds
crossAuthSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || username != "username" || password != "password" {
t.Errorf("Expected request to use basic auth and for username == 'username' and password == 'password', got '%v', '%s', '%s'", ok, username, password)
}
fmt.Fprint(w, expect)
}))
defer crossAuthSrv.Close()
u, _ = url.ParseRequestURI(crossAuthSrv.URL)
// A different host is provided for the WithURL from the one used for Get
u2, _ = url.ParseRequestURI(crossAuthSrv.URL)
host = strings.Split(u2.Host, ":")
host[0] = host[0] + "a"
u2.Host = strings.Join(host, ":")
httpgetter, err = NewHTTPGetter(
WithURL(u2.String()),
WithBasicAuth("username", "password"),
WithPassCredentialsAll(true),
)
if err != nil {
t.Fatal(err)
}
got, err = httpgetter.Get(u.String())
if err != nil {
t.Fatal(err)
}
if got.String() != expect {
t.Errorf("Expected %q, got %q", expect, got.String())
}
// test server with varied Accept Header
const expectedAcceptHeader = "application/gzip,application/octet-stream"
acceptHeaderSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept") != expectedAcceptHeader {
t.Errorf("Expected '%s', got '%s'", expectedAcceptHeader, r.Header.Get("Accept"))
}
fmt.Fprint(w, expect)
}))
defer acceptHeaderSrv.Close()
u, _ = url.ParseRequestURI(acceptHeaderSrv.URL)
httpgetter, err = NewHTTPGetter(
WithAcceptHeader(expectedAcceptHeader),
)
if err != nil {
t.Fatal(err)
}
_, err = httpgetter.Get(u.String())
if err != nil {
t.Fatal(err)
}
}
func TestDownloadTLS(t *testing.T) {
cd := "../../testdata"
ca, pub, priv := filepath.Join(cd, "rootca.crt"), filepath.Join(cd, "crt.pem"), filepath.Join(cd, "key.pem")
insecureSkipTLSVerify := false
tlsSrv := httptest.NewUnstartedServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(insecureSkipTLSVerify),
tlsutil.WithCertKeyPairFiles(pub, priv),
tlsutil.WithCAFile(ca),
)
if err != nil {
t.Fatal(fmt.Errorf("can't create TLS config for client: %w", err))
}
tlsConf.ServerName = "helm.sh"
tlsSrv.TLS = tlsConf
tlsSrv.StartTLS()
defer tlsSrv.Close()
u, _ := url.ParseRequestURI(tlsSrv.URL)
g, err := NewHTTPGetter(
WithURL(u.String()),
WithTLSClientConfig(pub, priv, ca),
)
if err != nil {
t.Fatal(err)
}
if _, err := g.Get(u.String()); err != nil {
t.Error(err)
}
// now test with TLS config being passed along in .Get (see #6635)
g, err = NewHTTPGetter()
if err != nil {
t.Fatal(err)
}
if _, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig(pub, priv, ca)); err != nil {
t.Error(err)
}
// test with only the CA file (see also #6635)
g, err = NewHTTPGetter()
if err != nil {
t.Fatal(err)
}
if _, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig("", "", ca)); err != nil {
t.Error(err)
}
}
func TestDownloadTLSWithRedirect(t *testing.T) {
cd := "../../testdata"
srv2Resp := "hello"
insecureSkipTLSVerify := false
// Server 2 that will actually fulfil the request.
ca, pub, priv := filepath.Join(cd, "rootca.crt"), filepath.Join(cd, "localhost-crt.pem"), filepath.Join(cd, "key.pem")
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithCAFile(ca),
tlsutil.WithCertKeyPairFiles(pub, priv),
tlsutil.WithInsecureSkipVerify(insecureSkipTLSVerify),
)
if err != nil {
t.Fatal(fmt.Errorf("can't create TLS config for client: %w", err))
}
tlsSrv2 := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
rw.Header().Set("Content-Type", "text/plain")
rw.Write([]byte(srv2Resp))
}))
tlsSrv2.TLS = tlsConf
tlsSrv2.StartTLS()
defer tlsSrv2.Close()
// Server 1 responds with a redirect to Server 2.
ca, pub, priv = filepath.Join(cd, "rootca.crt"), filepath.Join(cd, "crt.pem"), filepath.Join(cd, "key.pem")
tlsConf, err = tlsutil.NewTLSConfig(
tlsutil.WithCAFile(ca),
tlsutil.WithCertKeyPairFiles(pub, priv),
tlsutil.WithInsecureSkipVerify(insecureSkipTLSVerify),
)
if err != nil {
t.Fatal(fmt.Errorf("can't create TLS config for client: %w", err))
}
tlsSrv1 := httptest.NewUnstartedServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
u, _ := url.ParseRequestURI(tlsSrv2.URL)
// Make the request using the hostname 'localhost' (to which 'localhost-crt.pem' is issued)
// to verify that a successful TLS connection is made even if the client doesn't specify
// the hostname (SNI) in `tls.Config.ServerName`. By default the hostname is derived from the
// request URL for every request (including redirects). Setting `tls.Config.ServerName` on the
// client just overrides the remote endpoint's hostname.
// See https://github.com/golang/go/blob/3979fb9/src/net/http/transport.go#L1505-L1513.
u.Host = fmt.Sprintf("localhost:%s", u.Port())
http.Redirect(rw, r, u.String(), http.StatusTemporaryRedirect)
}))
tlsSrv1.TLS = tlsConf
tlsSrv1.StartTLS()
defer tlsSrv1.Close()
u, _ := url.ParseRequestURI(tlsSrv1.URL)
t.Run("Test with TLS", func(t *testing.T) {
g, err := NewHTTPGetter(
WithURL(u.String()),
WithTLSClientConfig(pub, priv, ca),
)
if err != nil {
t.Fatal(err)
}
buf, err := g.Get(u.String())
if err != nil {
t.Error(err)
}
b, err := io.ReadAll(buf)
if err != nil {
t.Error(err)
}
if string(b) != srv2Resp {
t.Errorf("expected response from Server2 to be '%s', instead got: %s", srv2Resp, string(b))
}
})
t.Run("Test with TLS config being passed along in .Get (see #6635)", func(t *testing.T) {
g, err := NewHTTPGetter()
if err != nil {
t.Fatal(err)
}
buf, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig(pub, priv, ca))
if err != nil {
t.Error(err)
}
b, err := io.ReadAll(buf)
if err != nil {
t.Error(err)
}
if string(b) != srv2Resp {
t.Errorf("expected response from Server2 to be '%s', instead got: %s", srv2Resp, string(b))
}
})
t.Run("Test with only the CA file (see also #6635)", func(t *testing.T) {
g, err := NewHTTPGetter()
if err != nil {
t.Fatal(err)
}
buf, err := g.Get(u.String(), WithURL(u.String()), WithTLSClientConfig("", "", ca))
if err != nil {
t.Error(err)
}
b, err := io.ReadAll(buf)
if err != nil {
t.Error(err)
}
if string(b) != srv2Resp {
t.Errorf("expected response from Server2 to be '%s', instead got: %s", srv2Resp, string(b))
}
})
}
func TestDownloadInsecureSkipTLSVerify(t *testing.T) {
ts := httptest.NewTLSServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
defer ts.Close()
u, _ := url.ParseRequestURI(ts.URL)
// Ensure the default behavior did not change
g, err := NewHTTPGetter(
WithURL(u.String()),
)
if err != nil {
t.Error(err)
}
if _, err := g.Get(u.String()); err == nil {
t.Errorf("Expected Getter to throw an error, got %s", err)
}
// Test certificate check skip
g, err = NewHTTPGetter(
WithURL(u.String()),
WithInsecureSkipVerifyTLS(true),
)
if err != nil {
t.Error(err)
}
if _, err = g.Get(u.String()); err != nil {
t.Error(err)
}
}
func TestHTTPGetterTarDownload(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
f, _ := os.Open("testdata/empty-0.0.1.tgz")
defer f.Close()
b := make([]byte, 512)
f.Read(b)
// Get the file size
FileStat, _ := f.Stat()
FileSize := strconv.FormatInt(FileStat.Size(), 10)
// Simulating improper header values from bitbucket
w.Header().Set("Content-Type", "application/x-tar")
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Length", FileSize)
f.Seek(0, 0)
io.Copy(w, f)
}))
defer srv.Close()
g, err := NewHTTPGetter(WithURL(srv.URL))
if err != nil {
t.Fatal(err)
}
data, _ := g.Get(srv.URL)
mimeType := http.DetectContentType(data.Bytes())
expectedMimeType := "application/x-gzip"
if mimeType != expectedMimeType {
t.Fatalf("Expected response with MIME type %s, but got %s", expectedMimeType, mimeType)
}
}
func TestHttpClientInsecureSkipVerify(t *testing.T) {
g := HTTPGetter{}
g.opts.url = "https://localhost"
verifyInsecureSkipVerify(t, &g, "Blank HTTPGetter", false)
g = HTTPGetter{}
g.opts.url = "https://localhost"
g.opts.caFile = "testdata/ca.crt"
verifyInsecureSkipVerify(t, &g, "HTTPGetter with ca file", false)
g = HTTPGetter{}
g.opts.url = "https://localhost"
g.opts.insecureSkipVerifyTLS = true
verifyInsecureSkipVerify(t, &g, "HTTPGetter with skip cert verification only", true)
g = HTTPGetter{}
g.opts.url = "https://localhost"
g.opts.certFile = "testdata/client.crt"
g.opts.keyFile = "testdata/client.key"
g.opts.insecureSkipVerifyTLS = true
transport := verifyInsecureSkipVerify(t, &g, "HTTPGetter with 2 way ssl", true)
if len(transport.TLSClientConfig.Certificates) <= 0 {
t.Fatal("transport.TLSClientConfig.Certificates is not present")
}
}
func verifyInsecureSkipVerify(t *testing.T, g *HTTPGetter, caseName string, expectedValue bool) *http.Transport {
t.Helper()
returnVal, err := g.httpClient()
if err != nil {
t.Fatal(err)
}
if returnVal == nil { //nolint:staticcheck
t.Fatalf("Expected non nil value for http client")
}
transport := (returnVal.Transport).(*http.Transport) //nolint:staticcheck
gotValue := false
if transport.TLSClientConfig != nil {
gotValue = transport.TLSClientConfig.InsecureSkipVerify
}
if gotValue != expectedValue {
t.Fatalf("Case Name = %s\nInsecureSkipVerify did not come as expected. Expected = %t; Got = %v",
caseName, expectedValue, gotValue)
}
return transport
}
func TestDefaultHTTPTransportReuse(t *testing.T) {
g := HTTPGetter{}
httpClient1, err := g.httpClient()
if err != nil {
t.Fatal(err)
}
if httpClient1 == nil { //nolint:staticcheck
t.Fatalf("Expected non nil value for http client")
}
transport1 := (httpClient1.Transport).(*http.Transport) //nolint:staticcheck
httpClient2, err := g.httpClient()
if err != nil {
t.Fatal(err)
}
if httpClient2 == nil { //nolint:staticcheck
t.Fatalf("Expected non nil value for http client")
}
transport2 := (httpClient2.Transport).(*http.Transport) //nolint:staticcheck
if transport1 != transport2 {
t.Fatalf("Expected default transport to be reused")
}
}
func TestHTTPTransportOption(t *testing.T) {
transport := &http.Transport{}
g := HTTPGetter{}
g.opts.transport = transport
httpClient1, err := g.httpClient()
if err != nil {
t.Fatal(err)
}
if httpClient1 == nil { //nolint:staticcheck
t.Fatalf("Expected non nil value for http client")
}
transport1 := (httpClient1.Transport).(*http.Transport) //nolint:staticcheck
if transport1 != transport {
t.Fatalf("Expected transport option to be applied")
}
httpClient2, err := g.httpClient()
if err != nil {
t.Fatal(err)
}
if httpClient2 == nil { //nolint:staticcheck
t.Fatalf("Expected non nil value for http client")
}
transport2 := (httpClient2.Transport).(*http.Transport) //nolint:staticcheck
if transport1 != transport2 {
t.Fatalf("Expected applied transport to be reused")
}
g = HTTPGetter{}
g.opts.url = "https://localhost"
g.opts.certFile = "testdata/client.crt"
g.opts.keyFile = "testdata/client.key"
g.opts.insecureSkipVerifyTLS = true
g.opts.transport = transport
usedTransport := verifyInsecureSkipVerify(t, &g, "HTTPGetter with 2 way ssl", false)
if usedTransport.TLSClientConfig != nil {
t.Fatal("transport.TLSClientConfig should not be set")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/getter.go | pkg/getter/getter.go | /*
Copyright The Helm 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 getter
import (
"bytes"
"fmt"
"net/http"
"slices"
"time"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/registry"
)
// getterOptions are generic parameters to be provided to the getter during instantiation.
//
// Getters may or may not ignore these parameters as they are passed in.
// TODO what is the difference between this and schema.GetterOptionsV1?
type getterOptions struct {
url string
certFile string
keyFile string
caFile string
unTar bool
insecureSkipVerifyTLS bool
plainHTTP bool
acceptHeader string
username string
password string
passCredentialsAll bool
userAgent string
version string
registryClient *registry.Client
timeout time.Duration
transport *http.Transport
artifactType string
}
// Option allows specifying various settings configurable by the user for overriding the defaults
// used when performing Get operations with the Getter.
type Option func(*getterOptions)
// WithURL informs the getter the server name that will be used when fetching objects. Used in conjunction with
// WithTLSClientConfig to set the TLSClientConfig's server name.
func WithURL(url string) Option {
return func(opts *getterOptions) {
opts.url = url
}
}
// WithAcceptHeader sets the request's Accept header as some REST APIs serve multiple content types
func WithAcceptHeader(header string) Option {
return func(opts *getterOptions) {
opts.acceptHeader = header
}
}
// WithBasicAuth sets the request's Authorization header to use the provided credentials
func WithBasicAuth(username, password string) Option {
return func(opts *getterOptions) {
opts.username = username
opts.password = password
}
}
func WithPassCredentialsAll(pass bool) Option {
return func(opts *getterOptions) {
opts.passCredentialsAll = pass
}
}
// WithUserAgent sets the request's User-Agent header to use the provided agent name.
func WithUserAgent(userAgent string) Option {
return func(opts *getterOptions) {
opts.userAgent = userAgent
}
}
// WithInsecureSkipVerifyTLS determines if a TLS Certificate will be checked
func WithInsecureSkipVerifyTLS(insecureSkipVerifyTLS bool) Option {
return func(opts *getterOptions) {
opts.insecureSkipVerifyTLS = insecureSkipVerifyTLS
}
}
// WithTLSClientConfig sets the client auth with the provided credentials.
func WithTLSClientConfig(certFile, keyFile, caFile string) Option {
return func(opts *getterOptions) {
opts.certFile = certFile
opts.keyFile = keyFile
opts.caFile = caFile
}
}
func WithPlainHTTP(plainHTTP bool) Option {
return func(opts *getterOptions) {
opts.plainHTTP = plainHTTP
}
}
// WithTimeout sets the timeout for requests
func WithTimeout(timeout time.Duration) Option {
return func(opts *getterOptions) {
opts.timeout = timeout
}
}
func WithTagName(tagname string) Option {
return func(opts *getterOptions) {
opts.version = tagname
}
}
func WithRegistryClient(client *registry.Client) Option {
return func(opts *getterOptions) {
opts.registryClient = client
}
}
func WithUntar() Option {
return func(opts *getterOptions) {
opts.unTar = true
}
}
// WithTransport sets the http.Transport to allow overwriting the HTTPGetter default.
func WithTransport(transport *http.Transport) Option {
return func(opts *getterOptions) {
opts.transport = transport
}
}
// WithArtifactType sets the type of OCI artifact ("chart" or "plugin")
func WithArtifactType(artifactType string) Option {
return func(opts *getterOptions) {
opts.artifactType = artifactType
}
}
// Getter is an interface to support GET to the specified URL.
type Getter interface {
// Get file content by url string
Get(url string, options ...Option) (*bytes.Buffer, error)
}
// Constructor is the function for every getter which creates a specific instance
// according to the configuration
type Constructor func(options ...Option) (Getter, error)
// Provider represents any getter and the schemes that it supports.
//
// For example, an HTTP provider may provide one getter that handles both
// 'http' and 'https' schemes.
type Provider struct {
Schemes []string
New Constructor
}
// Provides returns true if the given scheme is supported by this Provider.
func (p Provider) Provides(scheme string) bool {
return slices.Contains(p.Schemes, scheme)
}
// Providers is a collection of Provider objects.
type Providers []Provider
// ByScheme returns a Provider that handles the given scheme.
//
// If no provider handles this scheme, this will return an error.
func (p Providers) ByScheme(scheme string) (Getter, error) {
for _, pp := range p {
if pp.Provides(scheme) {
return pp.New()
}
}
return nil, fmt.Errorf("scheme %q not supported", scheme)
}
const (
// The cost timeout references curl's default connection timeout.
// https://github.com/curl/curl/blob/master/lib/connect.h#L40C21-L40C21
// The helm commands are usually executed manually. Considering the acceptable waiting time, we reduced the entire request time to 120s.
DefaultHTTPTimeout = 120
)
var defaultOptions = []Option{WithTimeout(time.Second * DefaultHTTPTimeout)}
func Getters(extraOpts ...Option) Providers {
return Providers{
Provider{
Schemes: []string{"http", "https"},
New: func(options ...Option) (Getter, error) {
options = append(options, defaultOptions...)
options = append(options, extraOpts...)
return NewHTTPGetter(options...)
},
},
Provider{
Schemes: []string{registry.OCIScheme},
New: func(options ...Option) (Getter, error) {
options = append(options, defaultOptions...)
options = append(options, extraOpts...)
return NewOCIGetter(options...)
},
},
}
}
// All finds all of the registered getters as a list of Provider instances.
// Currently, the built-in getters and the discovered plugins with downloader
// notations are collected.
func All(settings *cli.EnvSettings, opts ...Option) Providers {
result := Getters(opts...)
pluginDownloaders, _ := collectGetterPlugins(settings)
result = append(result, pluginDownloaders...)
return result
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/ocigetter.go | pkg/getter/ocigetter.go | /*
Copyright The Helm 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 getter
import (
"bytes"
"crypto/tls"
"fmt"
"net"
"net/http"
"path"
"strings"
"sync"
"time"
"helm.sh/helm/v4/internal/tlsutil"
"helm.sh/helm/v4/internal/urlutil"
"helm.sh/helm/v4/pkg/registry"
)
// OCIGetter is the default HTTP(/S) backend handler
type OCIGetter struct {
opts getterOptions
transport *http.Transport
once sync.Once
}
// Get performs a Get from repo.Getter and returns the body.
func (g *OCIGetter) Get(href string, options ...Option) (*bytes.Buffer, error) {
for _, opt := range options {
opt(&g.opts)
}
return g.get(href)
}
func (g *OCIGetter) get(href string) (*bytes.Buffer, error) {
client := g.opts.registryClient
// if the user has already provided a configured registry client, use it,
// this is particularly true when user has his own way of handling the client credentials.
if client == nil {
c, err := g.newRegistryClient()
if err != nil {
return nil, err
}
client = c
}
ref := strings.TrimPrefix(href, fmt.Sprintf("%s://", registry.OCIScheme))
if version := g.opts.version; version != "" && !strings.Contains(path.Base(ref), ":") {
ref = fmt.Sprintf("%s:%s", ref, version)
}
// Check if this is a plugin request
if g.opts.artifactType == "plugin" {
return g.getPlugin(client, ref)
}
// Default to chart behavior for backward compatibility
var pullOpts []registry.PullOption
requestingProv := strings.HasSuffix(ref, ".prov")
if requestingProv {
ref = strings.TrimSuffix(ref, ".prov")
pullOpts = append(pullOpts,
registry.PullOptWithChart(false),
registry.PullOptWithProv(true))
}
result, err := client.Pull(ref, pullOpts...)
if err != nil {
return nil, err
}
if requestingProv {
return bytes.NewBuffer(result.Prov.Data), nil
}
return bytes.NewBuffer(result.Chart.Data), nil
}
// NewOCIGetter constructs a valid http/https client as a Getter
func NewOCIGetter(ops ...Option) (Getter, error) {
var client OCIGetter
for _, opt := range ops {
opt(&client.opts)
}
return &client, nil
}
func (g *OCIGetter) newRegistryClient() (*registry.Client, error) {
if g.opts.transport != nil {
client, err := registry.NewClient(
registry.ClientOptHTTPClient(&http.Client{
Transport: g.opts.transport,
Timeout: g.opts.timeout,
}),
)
if err != nil {
return nil, err
}
return client, nil
}
g.once.Do(func() {
g.transport = &http.Transport{
// From https://github.com/google/go-containerregistry/blob/31786c6cbb82d6ec4fb8eb79cd9387905130534e/pkg/v1/remote/options.go#L87
DisableCompression: true,
DialContext: (&net.Dialer{
// By default we wrap the transport in retries, so reduce the
// default dial timeout to 5s to avoid 5x 30s of connection
// timeouts when doing the "ping" on certain http registries.
Timeout: 5 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
Proxy: http.ProxyFromEnvironment,
// Being nil would cause the tls.Config default to be used
// "NewTLSConfig" modifies an empty TLS config, not the default one
TLSClientConfig: &tls.Config{},
}
})
if (g.opts.certFile != "" && g.opts.keyFile != "") || g.opts.caFile != "" || g.opts.insecureSkipVerifyTLS {
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(g.opts.insecureSkipVerifyTLS),
tlsutil.WithCertKeyPairFiles(g.opts.certFile, g.opts.keyFile),
tlsutil.WithCAFile(g.opts.caFile),
)
if err != nil {
return nil, fmt.Errorf("can't create TLS config for client: %w", err)
}
sni, err := urlutil.ExtractHostname(g.opts.url)
if err != nil {
return nil, err
}
tlsConf.ServerName = sni
g.transport.TLSClientConfig = tlsConf
}
opts := []registry.ClientOption{registry.ClientOptHTTPClient(&http.Client{
Transport: g.transport,
Timeout: g.opts.timeout,
})}
if g.opts.plainHTTP {
opts = append(opts, registry.ClientOptPlainHTTP())
}
client, err := registry.NewClient(opts...)
if err != nil {
return nil, err
}
return client, nil
}
// getPlugin handles plugin-specific OCI pulls
func (g *OCIGetter) getPlugin(client *registry.Client, ref string) (*bytes.Buffer, error) {
// Check if this is a provenance file request
requestingProv := strings.HasSuffix(ref, ".prov")
if requestingProv {
ref = strings.TrimSuffix(ref, ".prov")
}
// Extract plugin name from the reference
// e.g., "ghcr.io/user/plugin-name:v1.0.0" -> "plugin-name"
parts := strings.Split(ref, "/")
if len(parts) < 2 {
return nil, fmt.Errorf("invalid OCI reference: %s", ref)
}
lastPart := parts[len(parts)-1]
pluginName := lastPart
if idx := strings.LastIndex(lastPart, ":"); idx > 0 {
pluginName = lastPart[:idx]
}
if idx := strings.LastIndex(lastPart, "@"); idx > 0 {
pluginName = lastPart[:idx]
}
var pullOpts []registry.PluginPullOption
if requestingProv {
pullOpts = append(pullOpts, registry.PullPluginOptWithProv(true))
}
result, err := client.PullPlugin(ref, pluginName, pullOpts...)
if err != nil {
return nil, err
}
if requestingProv {
return bytes.NewBuffer(result.Prov.Data), nil
}
return bytes.NewBuffer(result.PluginData), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/plugingetter_test.go | pkg/getter/plugingetter_test.go | /*
Copyright The Helm 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 getter
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/internal/plugin/schema"
"helm.sh/helm/v4/pkg/cli"
)
func TestCollectPlugins(t *testing.T) {
env := cli.New()
env.PluginsDirectory = pluginDir
p, err := collectGetterPlugins(env)
if err != nil {
t.Fatal(err)
}
if len(p) != 2 {
t.Errorf("Expected 2 plugins, got %d: %v", len(p), p)
}
if _, err := p.ByScheme("test2"); err != nil {
t.Error(err)
}
if _, err := p.ByScheme("test"); err != nil {
t.Error(err)
}
if _, err := p.ByScheme("nosuchthing"); err == nil {
t.Fatal("did not expect protocol handler for nosuchthing")
}
}
func TestConvertOptions(t *testing.T) {
opts := convertOptions(
[]Option{
WithURL("example://foo"),
WithAcceptHeader("Accept-Header"),
WithBasicAuth("username", "password"),
WithPassCredentialsAll(true),
WithUserAgent("User-agent"),
WithInsecureSkipVerifyTLS(true),
WithTLSClientConfig("certFile.pem", "keyFile.pem", "caFile.pem"),
WithPlainHTTP(true),
WithTimeout(10),
WithTagName("1.2.3"),
WithUntar(),
},
[]Option{
WithTimeout(20),
},
)
expected := schema.GetterOptionsV1{
URL: "example://foo",
CertFile: "certFile.pem",
KeyFile: "keyFile.pem",
CAFile: "caFile.pem",
UNTar: true,
Timeout: 20,
InsecureSkipVerifyTLS: true,
PlainHTTP: true,
AcceptHeader: "Accept-Header",
Username: "username",
Password: "password",
PassCredentialsAll: true,
UserAgent: "User-agent",
Version: "1.2.3",
}
assert.Equal(t, expected, opts)
}
type testPlugin struct {
t *testing.T
dir string
}
func (t *testPlugin) Dir() string {
return t.dir
}
func (t *testPlugin) Metadata() plugin.Metadata {
return plugin.Metadata{
Name: "fake-plugin",
Type: "cli/v1",
APIVersion: "v1",
Runtime: "subprocess",
Config: &schema.ConfigCLIV1{},
RuntimeConfig: &plugin.RuntimeConfigSubprocess{
PlatformCommand: []plugin.PlatformCommand{
{
Command: "echo fake-plugin",
},
},
},
}
}
func (t *testPlugin) Invoke(_ context.Context, _ *plugin.Input) (*plugin.Output, error) {
// Simulate a plugin invocation
output := &plugin.Output{
Message: schema.OutputMessageGetterV1{
Data: []byte("fake-plugin output"),
},
}
return output, nil
}
var _ plugin.Plugin = (*testPlugin)(nil)
func TestGetterPlugin(t *testing.T) {
gp := getterPlugin{
options: []Option{},
plg: &testPlugin{t: t, dir: "fake/dir"},
}
buf, err := gp.Get("test://example.com", WithTimeout(5*time.Second))
require.NoError(t, err)
assert.Equal(t, "fake-plugin output", buf.String())
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/ocigetter_test.go | pkg/getter/ocigetter_test.go | /*
Copyright The Helm 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 getter
import (
"net/http"
"path/filepath"
"testing"
"time"
"helm.sh/helm/v4/pkg/registry"
)
func TestOCIGetter(t *testing.T) {
g, err := NewOCIGetter(WithURL("oci://example.com"))
if err != nil {
t.Fatal(err)
}
if _, ok := g.(*OCIGetter); !ok {
t.Fatal("Expected NewOCIGetter to produce an *OCIGetter")
}
cd := "../../testdata"
join := filepath.Join
ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem")
timeout := time.Second * 5
transport := &http.Transport{}
insecureSkipVerifyTLS := false
plainHTTP := false
// Test with getterOptions
g, err = NewOCIGetter(
WithBasicAuth("I", "Am"),
WithTLSClientConfig(pub, priv, ca),
WithTimeout(timeout),
WithTransport(transport),
WithInsecureSkipVerifyTLS(insecureSkipVerifyTLS),
WithPlainHTTP(plainHTTP),
)
if err != nil {
t.Fatal(err)
}
og, ok := g.(*OCIGetter)
if !ok {
t.Fatal("expected NewOCIGetter to produce an *OCIGetter")
}
if og.opts.username != "I" {
t.Errorf("Expected NewOCIGetter to contain %q as the username, got %q", "I", og.opts.username)
}
if og.opts.password != "Am" {
t.Errorf("Expected NewOCIGetter to contain %q as the password, got %q", "Am", og.opts.password)
}
if og.opts.certFile != pub {
t.Errorf("Expected NewOCIGetter to contain %q as the public key file, got %q", pub, og.opts.certFile)
}
if og.opts.keyFile != priv {
t.Errorf("Expected NewOCIGetter to contain %q as the private key file, got %q", priv, og.opts.keyFile)
}
if og.opts.caFile != ca {
t.Errorf("Expected NewOCIGetter to contain %q as the CA file, got %q", ca, og.opts.caFile)
}
if og.opts.timeout != timeout {
t.Errorf("Expected NewOCIGetter to contain %s as Timeout flag, got %s", timeout, og.opts.timeout)
}
if og.opts.transport != transport {
t.Errorf("Expected NewOCIGetter to contain %p as Transport, got %p", transport, og.opts.transport)
}
if og.opts.plainHTTP != plainHTTP {
t.Errorf("Expected NewOCIGetter to have plainHTTP as %t, got %t", plainHTTP, og.opts.plainHTTP)
}
if og.opts.insecureSkipVerifyTLS != insecureSkipVerifyTLS {
t.Errorf("Expected NewOCIGetter to have insecureSkipVerifyTLS as %t, got %t", insecureSkipVerifyTLS, og.opts.insecureSkipVerifyTLS)
}
// Test if setting registryClient is being passed to the ops
registryClient, err := registry.NewClient()
if err != nil {
t.Fatal(err)
}
g, err = NewOCIGetter(
WithRegistryClient(registryClient),
)
if err != nil {
t.Fatal(err)
}
og, ok = g.(*OCIGetter)
if !ok {
t.Fatal("expected NewOCIGetter to produce an *OCIGetter")
}
if og.opts.registryClient != registryClient {
t.Errorf("Expected NewOCIGetter to contain %p as RegistryClient, got %p", registryClient, og.opts.registryClient)
}
}
func TestOCIHTTPTransportReuse(t *testing.T) {
g := OCIGetter{}
_, err := g.newRegistryClient()
if err != nil {
t.Fatal(err)
}
if g.transport == nil {
t.Fatalf("Expected non nil value for transport")
}
transport1 := g.transport
_, err = g.newRegistryClient()
if err != nil {
t.Fatal(err)
}
if g.transport == nil {
t.Fatalf("Expected non nil value for transport")
}
transport2 := g.transport
if transport1 != transport2 {
t.Fatalf("Expected default transport to be reused")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/plugingetter.go | pkg/getter/plugingetter.go | /*
Copyright The Helm 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 getter
import (
"bytes"
"context"
"fmt"
"net/url"
"helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/internal/plugin/schema"
"helm.sh/helm/v4/pkg/cli"
)
// collectGetterPlugins scans for getter plugins.
// This will load plugins according to the cli.
func collectGetterPlugins(settings *cli.EnvSettings) (Providers, error) {
d := plugin.Descriptor{
Type: "getter/v1",
}
plgs, err := plugin.FindPlugins([]string{settings.PluginsDirectory}, d)
if err != nil {
return nil, err
}
pluginConstructorBuilder := func(plg plugin.Plugin) Constructor {
return func(option ...Option) (Getter, error) {
return &getterPlugin{
options: append([]Option{}, option...),
plg: plg,
}, nil
}
}
results := make([]Provider, 0, len(plgs))
for _, plg := range plgs {
if c, ok := plg.Metadata().Config.(*schema.ConfigGetterV1); ok {
results = append(results, Provider{
Schemes: c.Protocols,
New: pluginConstructorBuilder(plg),
})
}
}
return results, nil
}
func convertOptions(globalOptions, options []Option) schema.GetterOptionsV1 {
opts := getterOptions{}
for _, opt := range globalOptions {
opt(&opts)
}
for _, opt := range options {
opt(&opts)
}
result := schema.GetterOptionsV1{
URL: opts.url,
CertFile: opts.certFile,
KeyFile: opts.keyFile,
CAFile: opts.caFile,
UNTar: opts.unTar,
InsecureSkipVerifyTLS: opts.insecureSkipVerifyTLS,
PlainHTTP: opts.plainHTTP,
AcceptHeader: opts.acceptHeader,
Username: opts.username,
Password: opts.password,
PassCredentialsAll: opts.passCredentialsAll,
UserAgent: opts.userAgent,
Version: opts.version,
Timeout: opts.timeout,
}
return result
}
type getterPlugin struct {
options []Option
plg plugin.Plugin
}
func (g *getterPlugin) Get(href string, options ...Option) (*bytes.Buffer, error) {
opts := convertOptions(g.options, options)
// TODO optimization: pass this along to Get() instead of re-parsing here
u, err := url.Parse(href)
if err != nil {
return nil, err
}
input := &plugin.Input{
Message: schema.InputMessageGetterV1{
Href: href,
Options: opts,
Protocol: u.Scheme,
},
// TODO should we pass Stdin, Stdout, and Stderr through Input here to getter plugins?
// Stdout: os.Stdout,
}
output, err := g.plg.Invoke(context.Background(), input)
if err != nil {
return nil, fmt.Errorf("plugin %q failed to invoke: %w", g.plg, err)
}
outputMessage, ok := output.Message.(schema.OutputMessageGetterV1)
if !ok {
return nil, fmt.Errorf("invalid output message type from plugin %q", g.plg.Metadata().Name)
}
return bytes.NewBuffer(outputMessage.Data), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/getter_test.go | pkg/getter/getter_test.go | /*
Copyright The Helm 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 getter
import (
"testing"
"time"
"helm.sh/helm/v4/pkg/cli"
)
const pluginDir = "testdata/plugins"
func TestProvider(t *testing.T) {
p := Provider{
[]string{"one", "three"},
func(_ ...Option) (Getter, error) { return nil, nil },
}
if !p.Provides("three") {
t.Error("Expected provider to provide three")
}
}
func TestProviders(t *testing.T) {
ps := Providers{
{[]string{"one", "three"}, func(_ ...Option) (Getter, error) { return nil, nil }},
{[]string{"two", "four"}, func(_ ...Option) (Getter, error) { return nil, nil }},
}
if _, err := ps.ByScheme("one"); err != nil {
t.Error(err)
}
if _, err := ps.ByScheme("four"); err != nil {
t.Error(err)
}
if _, err := ps.ByScheme("five"); err == nil {
t.Error("Did not expect handler for five")
}
}
func TestProvidersWithTimeout(t *testing.T) {
want := time.Hour
getters := Getters(WithTimeout(want))
getter, err := getters.ByScheme("http")
if err != nil {
t.Error(err)
}
client, err := getter.(*HTTPGetter).httpClient()
if err != nil {
t.Error(err)
}
got := client.Timeout
if got != want {
t.Errorf("Expected %q, got %q", want, got)
}
}
func TestAll(t *testing.T) {
env := cli.New()
env.PluginsDirectory = pluginDir
all := All(env)
if len(all) != 4 {
t.Errorf("expected 4 providers (default plus three plugins), got %d", len(all))
}
if _, err := all.ByScheme("test2"); err != nil {
t.Error(err)
}
}
func TestByScheme(t *testing.T) {
env := cli.New()
env.PluginsDirectory = pluginDir
g := All(env)
if _, err := g.ByScheme("test"); err != nil {
t.Error(err)
}
if _, err := g.ByScheme("https"); err != nil {
t.Error(err)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/getter/doc.go | pkg/getter/doc.go | /*
Copyright The Helm 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 getter provides a generalize tool for fetching data by scheme.
This provides a method by which the plugin system can load arbitrary protocol
handlers based upon a URL scheme.
*/
package getter
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/wait_test.go | pkg/kube/wait_test.go | /*
Copyright The Helm 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 kube
import (
"fmt"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/resource"
)
func TestSelectorsForObject(t *testing.T) {
tests := []struct {
name string
object interface{}
expectError bool
errorContains string
expectedLabels map[string]string
}{
{
name: "appsv1 ReplicaSet",
object: &appsv1.ReplicaSet{
Spec: appsv1.ReplicaSetSpec{
Selector: &metav1.LabelSelector{
MatchLabels: map[string]string{"app": "test"},
},
},
},
expectError: false,
expectedLabels: map[string]string{"app": "test"},
},
{
name: "extensionsv1beta1 ReplicaSet",
object: &extensionsv1beta1.ReplicaSet{
Spec: extensionsv1beta1.ReplicaSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "ext-rs"}},
},
},
expectedLabels: map[string]string{"app": "ext-rs"},
},
{
name: "appsv1beta2 ReplicaSet",
object: &appsv1beta2.ReplicaSet{
Spec: appsv1beta2.ReplicaSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "beta2-rs"}},
},
},
expectedLabels: map[string]string{"app": "beta2-rs"},
},
{
name: "corev1 ReplicationController",
object: &corev1.ReplicationController{
Spec: corev1.ReplicationControllerSpec{
Selector: map[string]string{"rc": "test"},
},
},
expectError: false,
expectedLabels: map[string]string{"rc": "test"},
},
{
name: "appsv1 StatefulSet",
object: &appsv1.StatefulSet{
Spec: appsv1.StatefulSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "statefulset-v1"}},
},
},
expectedLabels: map[string]string{"app": "statefulset-v1"},
},
{
name: "appsv1beta1 StatefulSet",
object: &appsv1beta1.StatefulSet{
Spec: appsv1beta1.StatefulSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "statefulset-beta1"}},
},
},
expectedLabels: map[string]string{"app": "statefulset-beta1"},
},
{
name: "appsv1beta2 StatefulSet",
object: &appsv1beta2.StatefulSet{
Spec: appsv1beta2.StatefulSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "statefulset-beta2"}},
},
},
expectedLabels: map[string]string{"app": "statefulset-beta2"},
},
{
name: "extensionsv1beta1 DaemonSet",
object: &extensionsv1beta1.DaemonSet{
Spec: extensionsv1beta1.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "daemonset-ext-beta1"}},
},
},
expectedLabels: map[string]string{"app": "daemonset-ext-beta1"},
},
{
name: "appsv1 DaemonSet",
object: &appsv1.DaemonSet{
Spec: appsv1.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "daemonset-v1"}},
},
},
expectedLabels: map[string]string{"app": "daemonset-v1"},
},
{
name: "appsv1beta2 DaemonSet",
object: &appsv1beta2.DaemonSet{
Spec: appsv1beta2.DaemonSetSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "daemonset-beta2"}},
},
},
expectedLabels: map[string]string{"app": "daemonset-beta2"},
},
{
name: "extensionsv1beta1 Deployment",
object: &extensionsv1beta1.Deployment{
Spec: extensionsv1beta1.DeploymentSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "deployment-ext-beta1"}},
},
},
expectedLabels: map[string]string{"app": "deployment-ext-beta1"},
},
{
name: "appsv1 Deployment",
object: &appsv1.Deployment{
Spec: appsv1.DeploymentSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "deployment-v1"}},
},
},
expectedLabels: map[string]string{"app": "deployment-v1"},
},
{
name: "appsv1beta1 Deployment",
object: &appsv1beta1.Deployment{
Spec: appsv1beta1.DeploymentSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "deployment-beta1"}},
},
},
expectedLabels: map[string]string{"app": "deployment-beta1"},
},
{
name: "appsv1beta2 Deployment",
object: &appsv1beta2.Deployment{
Spec: appsv1beta2.DeploymentSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "deployment-beta2"}},
},
},
expectedLabels: map[string]string{"app": "deployment-beta2"},
},
{
name: "batchv1 Job",
object: &batchv1.Job{
Spec: batchv1.JobSpec{
Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"job": "batch-job"}},
},
},
expectedLabels: map[string]string{"job": "batch-job"},
},
{
name: "corev1 Service with selector",
object: &corev1.Service{
ObjectMeta: metav1.ObjectMeta{Name: "svc"},
Spec: corev1.ServiceSpec{
Selector: map[string]string{"svc": "yes"},
},
},
expectError: false,
expectedLabels: map[string]string{"svc": "yes"},
},
{
name: "corev1 Service without selector",
object: &corev1.Service{
ObjectMeta: metav1.ObjectMeta{Name: "svc"},
Spec: corev1.ServiceSpec{Selector: map[string]string{}},
},
expectError: true,
errorContains: "invalid service 'svc': Service is defined without a selector",
},
{
name: "invalid label selector",
object: &appsv1.ReplicaSet{
Spec: appsv1.ReplicaSetSpec{
Selector: &metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{
{
Key: "foo",
Operator: "InvalidOperator",
Values: []string{"bar"},
},
},
},
},
},
expectError: true,
errorContains: "invalid label selector:",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
selector, err := SelectorsForObject(tt.object.(runtime.Object))
if tt.expectError {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.errorContains)
} else {
assert.NoError(t, err)
expected := labels.Set(tt.expectedLabels)
assert.True(t, selector.Matches(expected), "expected selector to match")
}
})
}
}
func TestLegacyWaiter_waitForPodSuccess(t *testing.T) {
lw := &legacyWaiter{}
tests := []struct {
name string
obj runtime.Object
wantDone bool
wantErr bool
errMessage string
}{
{
name: "pod succeeded",
obj: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pod1"},
Status: corev1.PodStatus{Phase: corev1.PodSucceeded},
},
wantDone: true,
wantErr: false,
},
{
name: "pod failed",
obj: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pod2"},
Status: corev1.PodStatus{Phase: corev1.PodFailed},
},
wantDone: true,
wantErr: true,
errMessage: "pod pod2 failed",
},
{
name: "pod pending",
obj: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pod3"},
Status: corev1.PodStatus{Phase: corev1.PodPending},
},
wantDone: false,
wantErr: false,
},
{
name: "pod running",
obj: &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "pod4"},
Status: corev1.PodStatus{Phase: corev1.PodRunning},
},
wantDone: false,
wantErr: false,
},
{
name: "wrong object type",
obj: &metav1.Status{},
wantDone: true,
wantErr: true,
errMessage: "expected foo to be a *v1.Pod, got *v1.Status",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
done, err := lw.waitForPodSuccess(tt.obj, "foo")
if tt.wantErr {
if err == nil {
t.Errorf("expected error, got none")
} else if !strings.Contains(err.Error(), tt.errMessage) {
t.Errorf("expected error to contain %q, got %q", tt.errMessage, err.Error())
}
} else if err != nil {
t.Errorf("unexpected error: %v", err)
}
if done != tt.wantDone {
t.Errorf("got done=%v, want %v", done, tt.wantDone)
}
})
}
}
func TestLegacyWaiter_waitForJob(t *testing.T) {
lw := &legacyWaiter{}
tests := []struct {
name string
obj runtime.Object
wantDone bool
wantErr bool
errMessage string
}{
{
name: "job complete",
obj: &batchv1.Job{
Status: batchv1.JobStatus{
Conditions: []batchv1.JobCondition{
{
Type: batchv1.JobComplete,
Status: "True",
},
},
},
},
wantDone: true,
wantErr: false,
},
{
name: "job failed",
obj: &batchv1.Job{
Status: batchv1.JobStatus{
Conditions: []batchv1.JobCondition{
{
Type: batchv1.JobFailed,
Status: "True",
Reason: "FailedReason",
},
},
},
},
wantDone: true,
wantErr: true,
errMessage: "job test-job failed: FailedReason",
},
{
name: "job in progress",
obj: &batchv1.Job{
Status: batchv1.JobStatus{
Active: 1,
Failed: 0,
Succeeded: 0,
Conditions: []batchv1.JobCondition{
{
Type: batchv1.JobComplete,
Status: "False",
},
{
Type: batchv1.JobFailed,
Status: "False",
},
},
},
},
wantDone: false,
wantErr: false,
},
{
name: "wrong object type",
obj: &metav1.Status{},
wantDone: true,
wantErr: true,
errMessage: "expected test-job to be a *batch.Job, got *v1.Status",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
done, err := lw.waitForJob(tt.obj, "test-job")
if tt.wantErr {
if err == nil {
t.Errorf("expected error, got none")
} else if !strings.Contains(err.Error(), tt.errMessage) {
t.Errorf("expected error to contain %q, got %q", tt.errMessage, err.Error())
}
} else if err != nil {
t.Errorf("unexpected error: %v", err)
}
if done != tt.wantDone {
t.Errorf("got done=%v, want %v", done, tt.wantDone)
}
})
}
}
func TestLegacyWaiter_isRetryableError(t *testing.T) {
lw := &legacyWaiter{}
info := &resource.Info{
Name: "test-resource",
}
tests := []struct {
name string
err error
wantRetry bool
description string
}{
{
name: "nil error",
err: nil,
wantRetry: false,
},
{
name: "status error - 0 code",
err: &apierrors.StatusError{ErrStatus: metav1.Status{Code: 0}},
wantRetry: true,
},
{
name: "status error - 429 (TooManyRequests)",
err: &apierrors.StatusError{ErrStatus: metav1.Status{Code: http.StatusTooManyRequests}},
wantRetry: true,
},
{
name: "status error - 503",
err: &apierrors.StatusError{ErrStatus: metav1.Status{Code: http.StatusServiceUnavailable}},
wantRetry: true,
},
{
name: "status error - 501 (NotImplemented)",
err: &apierrors.StatusError{ErrStatus: metav1.Status{Code: http.StatusNotImplemented}},
wantRetry: false,
},
{
name: "status error - 400 (Bad Request)",
err: &apierrors.StatusError{ErrStatus: metav1.Status{Code: http.StatusBadRequest}},
wantRetry: false,
},
{
name: "non-status error",
err: fmt.Errorf("some generic error"),
wantRetry: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := lw.isRetryableError(tt.err, info)
if got != tt.wantRetry {
t.Errorf("isRetryableError() = %v, want %v", got, tt.wantRetry)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/resource_policy.go | pkg/kube/resource_policy.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
// ResourcePolicyAnno is the annotation name for a resource policy
const ResourcePolicyAnno = "helm.sh/resource-policy"
// KeepPolicy is the resource policy type for keep
//
// This resource policy type allows resources to skip being deleted
//
// during an uninstallRelease action.
const KeepPolicy = "keep"
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/ready.go | pkg/kube/ready.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"context"
"fmt"
"log/slog"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
deploymentutil "helm.sh/helm/v4/internal/third_party/k8s.io/kubernetes/deployment/util"
)
// ReadyCheckerOption is a function that configures a ReadyChecker.
type ReadyCheckerOption func(*ReadyChecker)
// PausedAsReady returns a ReadyCheckerOption that configures a ReadyChecker
// to consider paused resources to be ready. For example a Deployment
// with spec.paused equal to true would be considered ready.
func PausedAsReady(pausedAsReady bool) ReadyCheckerOption {
return func(c *ReadyChecker) {
c.pausedAsReady = pausedAsReady
}
}
// CheckJobs returns a ReadyCheckerOption that configures a ReadyChecker
// to consider readiness of Job resources.
func CheckJobs(checkJobs bool) ReadyCheckerOption {
return func(c *ReadyChecker) {
c.checkJobs = checkJobs
}
}
// NewReadyChecker creates a new checker. Passed ReadyCheckerOptions can
// be used to override defaults.
func NewReadyChecker(cl kubernetes.Interface, opts ...ReadyCheckerOption) ReadyChecker {
c := ReadyChecker{
client: cl,
}
for _, opt := range opts {
opt(&c)
}
return c
}
// ReadyChecker is a type that can check core Kubernetes types for readiness.
type ReadyChecker struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
// IsReady checks if v is ready. It supports checking readiness for pods,
// deployments, persistent volume claims, services, daemon sets, custom
// resource definitions, stateful sets, replication controllers, jobs (optional),
// and replica sets. All other resource kinds are always considered ready.
//
// IsReady will fetch the latest state of the object from the server prior to
// performing readiness checks, and it will return any error encountered.
func (c *ReadyChecker) IsReady(ctx context.Context, v *resource.Info) (bool, error) {
switch value := AsVersioned(v).(type) {
case *corev1.Pod:
pod, err := c.client.CoreV1().Pods(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil || !c.isPodReady(pod) {
return false, err
}
case *batchv1.Job:
if c.checkJobs {
job, err := c.client.BatchV1().Jobs(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
ready, err := c.jobReady(job)
return ready, err
}
case *appsv1.Deployment:
currentDeployment, err := c.client.AppsV1().Deployments(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
// If paused deployment will never be ready
if currentDeployment.Spec.Paused {
return c.pausedAsReady, nil
}
// Find RS associated with deployment
newReplicaSet, err := deploymentutil.GetNewReplicaSet(currentDeployment, c.client.AppsV1())
if err != nil || newReplicaSet == nil {
return false, err
}
if !c.deploymentReady(newReplicaSet, currentDeployment) {
return false, nil
}
case *corev1.PersistentVolumeClaim:
claim, err := c.client.CoreV1().PersistentVolumeClaims(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.volumeReady(claim) {
return false, nil
}
case *corev1.Service:
svc, err := c.client.CoreV1().Services(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.serviceReady(svc) {
return false, nil
}
case *appsv1.DaemonSet:
ds, err := c.client.AppsV1().DaemonSets(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.daemonSetReady(ds) {
return false, nil
}
case *apiextv1beta1.CustomResourceDefinition:
if err := v.Get(); err != nil {
return false, err
}
crd := &apiextv1beta1.CustomResourceDefinition{}
if err := scheme.Scheme.Convert(v.Object, crd, nil); err != nil {
return false, err
}
if !c.crdBetaReady(*crd) {
return false, nil
}
case *apiextv1.CustomResourceDefinition:
if err := v.Get(); err != nil {
return false, err
}
crd := &apiextv1.CustomResourceDefinition{}
if err := scheme.Scheme.Convert(v.Object, crd, nil); err != nil {
return false, err
}
if !c.crdReady(*crd) {
return false, nil
}
case *appsv1.StatefulSet:
sts, err := c.client.AppsV1().StatefulSets(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.statefulSetReady(sts) {
return false, nil
}
case *corev1.ReplicationController:
rc, err := c.client.CoreV1().ReplicationControllers(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.replicationControllerReady(rc) {
return false, nil
}
ready, err := c.podsReadyForObject(ctx, v.Namespace, value)
if !ready || err != nil {
return false, err
}
case *appsv1.ReplicaSet:
rs, err := c.client.AppsV1().ReplicaSets(v.Namespace).Get(ctx, v.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
if !c.replicaSetReady(rs) {
return false, nil
}
ready, err := c.podsReadyForObject(ctx, v.Namespace, value)
if !ready || err != nil {
return false, err
}
}
return true, nil
}
func (c *ReadyChecker) podsReadyForObject(ctx context.Context, namespace string, obj runtime.Object) (bool, error) {
pods, err := c.podsforObject(ctx, namespace, obj)
if err != nil {
return false, err
}
for _, pod := range pods {
if !c.isPodReady(&pod) {
return false, nil
}
}
return true, nil
}
func (c *ReadyChecker) podsforObject(ctx context.Context, namespace string, obj runtime.Object) ([]corev1.Pod, error) {
selector, err := SelectorsForObject(obj)
if err != nil {
return nil, err
}
list, err := getPods(ctx, c.client, namespace, selector.String())
return list, err
}
// isPodReady returns true if a pod is ready; false otherwise.
func (c *ReadyChecker) isPodReady(pod *corev1.Pod) bool {
for _, c := range pod.Status.Conditions {
if c.Type == corev1.PodReady && c.Status == corev1.ConditionTrue {
return true
}
}
slog.Debug("Pod is not ready", "namespace", pod.GetNamespace(), "name", pod.GetName())
return false
}
func (c *ReadyChecker) jobReady(job *batchv1.Job) (bool, error) {
if job.Status.Failed > *job.Spec.BackoffLimit {
slog.Debug("Job is failed", "namespace", job.GetNamespace(), "name", job.GetName())
// If a job is failed, it can't recover, so throw an error
return false, fmt.Errorf("job is failed: %s/%s", job.GetNamespace(), job.GetName())
}
if job.Spec.Completions != nil && job.Status.Succeeded < *job.Spec.Completions {
slog.Debug("Job is not completed", "namespace", job.GetNamespace(), "name", job.GetName())
return false, nil
}
slog.Debug("Job is completed", "namespace", job.GetNamespace(), "name", job.GetName())
return true, nil
}
func (c *ReadyChecker) serviceReady(s *corev1.Service) bool {
// ExternalName Services are external to cluster so helm shouldn't be checking to see if they're 'ready' (i.e. have an IP Set)
if s.Spec.Type == corev1.ServiceTypeExternalName {
return true
}
// Ensure that the service cluster IP is not empty
if s.Spec.ClusterIP == "" {
slog.Debug("Service does not have cluster IP address", "namespace", s.GetNamespace(), "name", s.GetName())
return false
}
// This checks if the service has a LoadBalancer and that balancer has an Ingress defined
if s.Spec.Type == corev1.ServiceTypeLoadBalancer {
// do not wait when at least 1 external IP is set
if len(s.Spec.ExternalIPs) > 0 {
slog.Debug("Service has external IP addresses", "namespace", s.GetNamespace(), "name", s.GetName(), "externalIPs", s.Spec.ExternalIPs)
return true
}
if s.Status.LoadBalancer.Ingress == nil {
slog.Debug("Service does not have load balancer ingress IP address", "namespace", s.GetNamespace(), "name", s.GetName())
return false
}
}
slog.Debug("Service is ready", "namespace", s.GetNamespace(), "name", s.GetName(), "clusterIP", s.Spec.ClusterIP, "externalIPs", s.Spec.ExternalIPs)
return true
}
func (c *ReadyChecker) volumeReady(v *corev1.PersistentVolumeClaim) bool {
if v.Status.Phase != corev1.ClaimBound {
slog.Debug("PersistentVolumeClaim is not bound", "namespace", v.GetNamespace(), "name", v.GetName())
return false
}
slog.Debug("PersistentVolumeClaim is bound", "namespace", v.GetNamespace(), "name", v.GetName(), "phase", v.Status.Phase)
return true
}
func (c *ReadyChecker) deploymentReady(rs *appsv1.ReplicaSet, dep *appsv1.Deployment) bool {
// Verify the replicaset readiness
if !c.replicaSetReady(rs) {
return false
}
// Verify the generation observed by the deployment controller matches the spec generation
if dep.Status.ObservedGeneration != dep.Generation {
slog.Debug("Deployment is not ready, observedGeneration does not match spec generation", "namespace", dep.GetNamespace(), "name", dep.GetName(), "actualGeneration", dep.Status.ObservedGeneration, "expectedGeneration", dep.Generation)
return false
}
expectedReady := *dep.Spec.Replicas - deploymentutil.MaxUnavailable(*dep)
if rs.Status.ReadyReplicas < expectedReady {
slog.Debug("Deployment does not have enough pods ready", "namespace", dep.GetNamespace(), "name", dep.GetName(), "readyPods", rs.Status.ReadyReplicas, "totalPods", expectedReady)
return false
}
slog.Debug("Deployment is ready", "namespace", dep.GetNamespace(), "name", dep.GetName(), "readyPods", rs.Status.ReadyReplicas, "totalPods", expectedReady)
return true
}
func (c *ReadyChecker) daemonSetReady(ds *appsv1.DaemonSet) bool {
// Verify the generation observed by the daemonSet controller matches the spec generation
if ds.Status.ObservedGeneration != ds.Generation {
slog.Debug("DaemonSet is not ready, observedGeneration does not match spec generation", "namespace", ds.GetNamespace(), "name", ds.GetName(), "observedGeneration", ds.Status.ObservedGeneration, "expectedGeneration", ds.Generation)
return false
}
// If the update strategy is not a rolling update, there will be nothing to wait for
if ds.Spec.UpdateStrategy.Type != appsv1.RollingUpdateDaemonSetStrategyType {
return true
}
// Make sure all the updated pods have been scheduled
if ds.Status.UpdatedNumberScheduled != ds.Status.DesiredNumberScheduled {
slog.Debug("DaemonSet does not have enough Pods scheduled", "namespace", ds.GetNamespace(), "name", ds.GetName(), "scheduledPods", ds.Status.UpdatedNumberScheduled, "totalPods", ds.Status.DesiredNumberScheduled)
return false
}
maxUnavailable, err := intstr.GetScaledValueFromIntOrPercent(ds.Spec.UpdateStrategy.RollingUpdate.MaxUnavailable, int(ds.Status.DesiredNumberScheduled), true)
if err != nil {
// If for some reason the value is invalid, set max unavailable to the
// number of desired replicas. This is the same behavior as the
// `MaxUnavailable` function in deploymentutil
maxUnavailable = int(ds.Status.DesiredNumberScheduled)
}
expectedReady := int(ds.Status.DesiredNumberScheduled) - maxUnavailable
if int(ds.Status.NumberReady) < expectedReady {
slog.Debug("DaemonSet does not have enough Pods ready", "namespace", ds.GetNamespace(), "name", ds.GetName(), "readyPods", ds.Status.NumberReady, "totalPods", expectedReady)
return false
}
slog.Debug("DaemonSet is ready", "namespace", ds.GetNamespace(), "name", ds.GetName(), "readyPods", ds.Status.NumberReady, "totalPods", expectedReady)
return true
}
// Because the v1 extensions API is not available on all supported k8s versions
// yet and because Go doesn't support generics, we need to have a duplicate
// function to support the v1beta1 types
func (c *ReadyChecker) crdBetaReady(crd apiextv1beta1.CustomResourceDefinition) bool {
for _, cond := range crd.Status.Conditions {
switch cond.Type {
case apiextv1beta1.Established:
if cond.Status == apiextv1beta1.ConditionTrue {
return true
}
case apiextv1beta1.NamesAccepted:
if cond.Status == apiextv1beta1.ConditionFalse {
// This indicates a naming conflict, but it's probably not the
// job of this function to fail because of that. Instead,
// we treat it as a success, since the process should be able to
// continue.
return true
}
default:
// intentionally left empty
}
}
return false
}
func (c *ReadyChecker) crdReady(crd apiextv1.CustomResourceDefinition) bool {
for _, cond := range crd.Status.Conditions {
switch cond.Type {
case apiextv1.Established:
if cond.Status == apiextv1.ConditionTrue {
return true
}
case apiextv1.NamesAccepted:
if cond.Status == apiextv1.ConditionFalse {
// This indicates a naming conflict, but it's probably not the
// job of this function to fail because of that. Instead,
// we treat it as a success, since the process should be able to
// continue.
return true
}
default:
// intentionally left empty
}
}
return false
}
func (c *ReadyChecker) statefulSetReady(sts *appsv1.StatefulSet) bool {
// Verify the generation observed by the statefulSet controller matches the spec generation
if sts.Status.ObservedGeneration != sts.Generation {
slog.Debug("StatefulSet is not ready, observedGeneration doest not match spec generation", "namespace", sts.GetNamespace(), "name", sts.GetName(), "actualGeneration", sts.Status.ObservedGeneration, "expectedGeneration", sts.Generation)
return false
}
// If the update strategy is not a rolling update, there will be nothing to wait for
if sts.Spec.UpdateStrategy.Type != appsv1.RollingUpdateStatefulSetStrategyType {
slog.Debug("StatefulSet skipped ready check", "namespace", sts.GetNamespace(), "name", sts.GetName(), "updateStrategy", sts.Spec.UpdateStrategy.Type)
return true
}
// Dereference all the pointers because StatefulSets like them
var partition int
// 1 is the default for replicas if not set
replicas := 1
// For some reason, even if the update strategy is a rolling update, the
// actual rollingUpdate field can be nil. If it is, we can safely assume
// there is no partition value
if sts.Spec.UpdateStrategy.RollingUpdate != nil && sts.Spec.UpdateStrategy.RollingUpdate.Partition != nil {
partition = int(*sts.Spec.UpdateStrategy.RollingUpdate.Partition)
}
if sts.Spec.Replicas != nil {
replicas = int(*sts.Spec.Replicas)
}
// Because an update strategy can use partitioning, we need to calculate the
// number of updated replicas we should have. For example, if the replicas
// is set to 3 and the partition is 2, we'd expect only one pod to be
// updated
expectedReplicas := replicas - partition
// Make sure all the updated pods have been scheduled
if int(sts.Status.UpdatedReplicas) < expectedReplicas {
slog.Debug("StatefulSet does not have enough Pods scheduled", "namespace", sts.GetNamespace(), "name", sts.GetName(), "readyPods", sts.Status.UpdatedReplicas, "totalPods", expectedReplicas)
return false
}
if int(sts.Status.ReadyReplicas) != replicas {
slog.Debug("StatefulSet does not have enough Pods ready", "namespace", sts.GetNamespace(), "name", sts.GetName(), "readyPods", sts.Status.ReadyReplicas, "totalPods", replicas)
return false
}
// This check only makes sense when all partitions are being upgraded otherwise during a
// partitioned rolling upgrade, this condition will never evaluate to true, leading to
// error.
if partition == 0 && sts.Status.CurrentRevision != sts.Status.UpdateRevision {
slog.Debug("StatefulSet is not ready, currentRevision does not match updateRevision", "namespace", sts.GetNamespace(), "name", sts.GetName(), "currentRevision", sts.Status.CurrentRevision, "updateRevision", sts.Status.UpdateRevision)
return false
}
slog.Debug("StatefulSet is ready", "namespace", sts.GetNamespace(), "name", sts.GetName(), "readyPods", sts.Status.ReadyReplicas, "totalPods", replicas)
return true
}
func (c *ReadyChecker) replicationControllerReady(rc *corev1.ReplicationController) bool {
// Verify the generation observed by the replicationController controller matches the spec generation
if rc.Status.ObservedGeneration != rc.Generation {
slog.Debug("ReplicationController is not ready, observedGeneration doest not match spec generation", "namespace", rc.GetNamespace(), "name", rc.GetName(), "actualGeneration", rc.Status.ObservedGeneration, "expectedGeneration", rc.Generation)
return false
}
return true
}
func (c *ReadyChecker) replicaSetReady(rs *appsv1.ReplicaSet) bool {
// Verify the generation observed by the replicaSet controller matches the spec generation
if rs.Status.ObservedGeneration != rs.Generation {
slog.Debug("ReplicaSet is not ready, observedGeneration doest not match spec generation", "namespace", rs.GetNamespace(), "name", rs.GetName(), "actualGeneration", rs.Status.ObservedGeneration, "expectedGeneration", rs.Generation)
return false
}
return true
}
func getPods(ctx context.Context, client kubernetes.Interface, namespace, selector string) ([]corev1.Pod, error) {
list, err := client.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
LabelSelector: selector,
})
if err != nil {
return nil, fmt.Errorf("failed to list pods: %w", err)
}
return list.Items, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/client.go | pkg/kube/client.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
jsonpatch "github.com/evanphx/json-patch/v5"
v1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
"helm.sh/helm/v4/internal/logging"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/jsonmergepatch"
"k8s.io/apimachinery/pkg/util/mergepatch"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest"
"k8s.io/client-go/util/csaupgrade"
"k8s.io/client-go/util/retry"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
)
// ErrNoObjectsVisited indicates that during a visit operation, no matching objects were found.
var ErrNoObjectsVisited = errors.New("no objects visited")
var metadataAccessor = meta.NewAccessor()
// ManagedFieldsManager is the name of the manager of Kubernetes managedFields
// first introduced in Kubernetes 1.18
var ManagedFieldsManager string
// Client represents a client capable of communicating with the Kubernetes API.
type Client struct {
// Factory provides a minimal version of the kubectl Factory interface. If
// you need the full Factory you can type switch to the full interface.
// Since Kubernetes Go API does not provide backwards compatibility across
// minor versions, this API does not follow Helm backwards compatibility.
// Helm is exposing Kubernetes in this property and cannot guarantee this
// will not change. The minimal interface only has the functions that Helm
// needs. The smaller surface area of the interface means there is a lower
// chance of it changing.
Factory Factory
// Namespace allows to bypass the kubeconfig file for the choice of the namespace
Namespace string
// WaitContext is an optional context to use for wait operations.
// If not set, a context will be created internally using the
// timeout provided to the wait functions.
WaitContext context.Context
Waiter
kubeClient kubernetes.Interface
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
var _ Interface = (*Client)(nil)
// WaitStrategy represents the algorithm used to wait for Kubernetes
// resources to reach their desired state.
type WaitStrategy string
const (
// StatusWatcherStrategy: event-driven waits using kstatus (watches + aggregated readers).
// Default for --wait. More accurate and responsive; waits CRs and full reconciliation.
// Requires: reachable API server, list+watch RBAC on deployed resources, and a non-zero timeout.
StatusWatcherStrategy WaitStrategy = "watcher"
// LegacyStrategy: Helm 3-style periodic polling until ready or timeout.
// Use when watches aren’t available/reliable, or for compatibility/simple CI.
// Requires only list RBAC for polled resources.
LegacyStrategy WaitStrategy = "legacy"
// HookOnlyStrategy: wait only for hook Pods/Jobs to complete; does not wait for general chart resources.
HookOnlyStrategy WaitStrategy = "hookOnly"
)
type FieldValidationDirective string
const (
FieldValidationDirectiveIgnore FieldValidationDirective = "Ignore"
FieldValidationDirectiveWarn FieldValidationDirective = "Warn"
FieldValidationDirectiveStrict FieldValidationDirective = "Strict"
)
type CreateApplyFunc func(target *resource.Info) error
type UpdateApplyFunc func(original, target *resource.Info) error
func init() {
// Add CRDs to the scheme. They are missing by default.
if err := apiextv1.AddToScheme(scheme.Scheme); err != nil {
// This should never happen.
panic(err)
}
if err := apiextv1beta1.AddToScheme(scheme.Scheme); err != nil {
panic(err)
}
}
func (c *Client) newStatusWatcher() (*statusWaiter, error) {
cfg, err := c.Factory.ToRESTConfig()
if err != nil {
return nil, err
}
dynamicClient, err := c.Factory.DynamicClient()
if err != nil {
return nil, err
}
httpClient, err := rest.HTTPClientFor(cfg)
if err != nil {
return nil, err
}
restMapper, err := apiutil.NewDynamicRESTMapper(cfg, httpClient)
if err != nil {
return nil, err
}
return &statusWaiter{
restMapper: restMapper,
client: dynamicClient,
ctx: c.WaitContext,
}, nil
}
func (c *Client) GetWaiter(strategy WaitStrategy) (Waiter, error) {
switch strategy {
case LegacyStrategy:
kc, err := c.Factory.KubernetesClientSet()
if err != nil {
return nil, err
}
return &legacyWaiter{kubeClient: kc, ctx: c.WaitContext}, nil
case StatusWatcherStrategy:
return c.newStatusWatcher()
case HookOnlyStrategy:
sw, err := c.newStatusWatcher()
if err != nil {
return nil, err
}
return &hookOnlyWaiter{sw: sw}, nil
case "":
return nil, errors.New("wait strategy not set. Choose one of: " + string(StatusWatcherStrategy) + ", " + string(HookOnlyStrategy) + ", " + string(LegacyStrategy))
default:
return nil, errors.New("unknown wait strategy (s" + string(strategy) + "). Valid values are: " + string(StatusWatcherStrategy) + ", " + string(HookOnlyStrategy) + ", " + string(LegacyStrategy))
}
}
func (c *Client) SetWaiter(ws WaitStrategy) error {
var err error
c.Waiter, err = c.GetWaiter(ws)
if err != nil {
return err
}
return nil
}
// New creates a new Client.
func New(getter genericclioptions.RESTClientGetter) *Client {
if getter == nil {
getter = genericclioptions.NewConfigFlags(true)
}
factory := cmdutil.NewFactory(getter)
c := &Client{
Factory: factory,
}
c.SetLogger(slog.Default().Handler())
return c
}
// getKubeClient get or create a new KubernetesClientSet
func (c *Client) getKubeClient() (kubernetes.Interface, error) {
var err error
if c.kubeClient == nil {
c.kubeClient, err = c.Factory.KubernetesClientSet()
}
return c.kubeClient, err
}
// IsReachable tests connectivity to the cluster.
func (c *Client) IsReachable() error {
client, err := c.getKubeClient()
if err == genericclioptions.ErrEmptyConfig {
// re-replace kubernetes ErrEmptyConfig error with a friendly error
// moar workarounds for Kubernetes API breaking.
return errors.New("kubernetes cluster unreachable")
}
if err != nil {
return fmt.Errorf("kubernetes cluster unreachable: %w", err)
}
if _, err := client.Discovery().ServerVersion(); err != nil {
return fmt.Errorf("kubernetes cluster unreachable: %w", err)
}
return nil
}
type clientCreateOptions struct {
serverSideApply bool
forceConflicts bool
dryRun bool
fieldValidationDirective FieldValidationDirective
}
type ClientCreateOption func(*clientCreateOptions) error
// ClientCreateOptionServerSideApply enables performing object apply server-side
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/
//
// `forceConflicts` forces conflicts to be resolved (may be when serverSideApply enabled only)
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts
func ClientCreateOptionServerSideApply(serverSideApply, forceConflicts bool) ClientCreateOption {
return func(o *clientCreateOptions) error {
if !serverSideApply && forceConflicts {
return fmt.Errorf("forceConflicts enabled when serverSideApply disabled")
}
o.serverSideApply = serverSideApply
o.forceConflicts = forceConflicts
return nil
}
}
// ClientCreateOptionDryRun requests the server to perform non-mutating operations only
func ClientCreateOptionDryRun(dryRun bool) ClientCreateOption {
return func(o *clientCreateOptions) error {
o.dryRun = dryRun
return nil
}
}
// ClientCreateOptionFieldValidationDirective specifies how API operations validate object's schema
// - For client-side apply: this is ignored
// - For server-side apply: the directive is sent to the server to perform the validation
//
// Defaults to `FieldValidationDirectiveStrict`
func ClientCreateOptionFieldValidationDirective(fieldValidationDirective FieldValidationDirective) ClientCreateOption {
return func(o *clientCreateOptions) error {
o.fieldValidationDirective = fieldValidationDirective
return nil
}
}
func (c *Client) makeCreateApplyFunc(serverSideApply, forceConflicts, dryRun bool, fieldValidationDirective FieldValidationDirective) CreateApplyFunc {
if serverSideApply {
c.Logger().Debug(
"using server-side apply for resource creation",
slog.Bool("forceConflicts", forceConflicts),
slog.Bool("dryRun", dryRun),
slog.String("fieldValidationDirective", string(fieldValidationDirective)))
return func(target *resource.Info) error {
err := patchResourceServerSide(target, dryRun, forceConflicts, fieldValidationDirective)
logger := c.Logger().With(
slog.String("namespace", target.Namespace),
slog.String("name", target.Name),
slog.String("gvk", target.Mapping.GroupVersionKind.String()))
if err != nil {
logger.Debug("Error creating resource via patch", slog.Any("error", err))
return err
}
logger.Debug("Created resource via patch")
return nil
}
}
c.Logger().Debug("using client-side apply for resource creation")
return createResource
}
// Create creates Kubernetes resources specified in the resource list.
func (c *Client) Create(resources ResourceList, options ...ClientCreateOption) (*Result, error) {
c.Logger().Debug("creating resource(s)", "resources", len(resources))
createOptions := clientCreateOptions{
serverSideApply: true, // Default to server-side apply
fieldValidationDirective: FieldValidationDirectiveStrict,
}
errs := make([]error, 0, len(options))
for _, o := range options {
errs = append(errs, o(&createOptions))
}
if err := errors.Join(errs...); err != nil {
return nil, fmt.Errorf("invalid client create option(s): %w", err)
}
createApplyFunc := c.makeCreateApplyFunc(
createOptions.serverSideApply,
createOptions.forceConflicts,
createOptions.dryRun,
createOptions.fieldValidationDirective)
if err := perform(resources, createApplyFunc); err != nil {
return nil, err
}
return &Result{Created: resources}, nil
}
func transformRequests(req *rest.Request) {
tableParam := strings.Join([]string{
fmt.Sprintf("application/json;as=Table;v=%s;g=%s", metav1.SchemeGroupVersion.Version, metav1.GroupName),
fmt.Sprintf("application/json;as=Table;v=%s;g=%s", metav1beta1.SchemeGroupVersion.Version, metav1beta1.GroupName),
"application/json",
}, ",")
req.SetHeader("Accept", tableParam)
// if sorting, ensure we receive the full object in order to introspect its fields via jsonpath
req.Param("includeObject", "Object")
}
// Get retrieves the resource objects supplied. If related is set to true the
// related pods are fetched as well. If the passed in resources are a table kind
// the related resources will also be fetched as kind=table.
func (c *Client) Get(resources ResourceList, related bool) (map[string][]runtime.Object, error) {
buf := new(bytes.Buffer)
objs := make(map[string][]runtime.Object)
podSelectors := []map[string]string{}
err := resources.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
gvk := info.ResourceMapping().GroupVersionKind
vk := gvk.Version + "/" + gvk.Kind
obj, err := getResource(info)
if err != nil {
fmt.Fprintf(buf, "Get resource %s failed, err:%v\n", info.Name, err)
} else {
objs[vk] = append(objs[vk], obj)
// Only fetch related pods if they are requested
if related {
// Discover if the existing object is a table. If it is, request
// the pods as Tables. Otherwise request them normally.
objGVK := obj.GetObjectKind().GroupVersionKind()
var isTable bool
if objGVK.Kind == "Table" {
isTable = true
}
objs, err = c.getSelectRelationPod(info, objs, isTable, &podSelectors)
if err != nil {
c.Logger().Warn("get the relation pod is failed", slog.Any("error", err))
}
}
}
return nil
})
if err != nil {
return nil, err
}
return objs, nil
}
func (c *Client) getSelectRelationPod(info *resource.Info, objs map[string][]runtime.Object, table bool, podSelectors *[]map[string]string) (map[string][]runtime.Object, error) {
if info == nil {
return objs, nil
}
c.Logger().Debug("get relation pod of object", "namespace", info.Namespace, "name", info.Name, "kind", info.Mapping.GroupVersionKind.Kind)
selector, ok, _ := getSelectorFromObject(info.Object)
if !ok {
return objs, nil
}
for index := range *podSelectors {
if reflect.DeepEqual((*podSelectors)[index], selector) {
// check if pods for selectors are already added. This avoids duplicate printing of pods
return objs, nil
}
}
*podSelectors = append(*podSelectors, selector)
var infos []*resource.Info
var err error
if table {
infos, err = c.Factory.NewBuilder().
Unstructured().
ContinueOnError().
NamespaceParam(info.Namespace).
DefaultNamespace().
ResourceTypes("pods").
LabelSelector(labels.Set(selector).AsSelector().String()).
TransformRequests(transformRequests).
Do().Infos()
if err != nil {
return objs, err
}
} else {
infos, err = c.Factory.NewBuilder().
Unstructured().
ContinueOnError().
NamespaceParam(info.Namespace).
DefaultNamespace().
ResourceTypes("pods").
LabelSelector(labels.Set(selector).AsSelector().String()).
Do().Infos()
if err != nil {
return objs, err
}
}
vk := "v1/Pod(related)"
for _, info := range infos {
objs[vk] = append(objs[vk], info.Object)
}
return objs, nil
}
func getSelectorFromObject(obj runtime.Object) (map[string]string, bool, error) {
typed := obj.(*unstructured.Unstructured)
kind := typed.Object["kind"]
switch kind {
case "ReplicaSet", "Deployment", "StatefulSet", "DaemonSet", "Job":
return unstructured.NestedStringMap(typed.Object, "spec", "selector", "matchLabels")
case "ReplicationController":
return unstructured.NestedStringMap(typed.Object, "spec", "selector")
default:
return nil, false, nil
}
}
func getResource(info *resource.Info) (runtime.Object, error) {
obj, err := resource.NewHelper(info.Client, info.Mapping).Get(info.Namespace, info.Name)
if err != nil {
return nil, err
}
return obj, nil
}
func (c *Client) namespace() string {
if c.Namespace != "" {
return c.Namespace
}
if ns, _, err := c.Factory.ToRawKubeConfigLoader().Namespace(); err == nil {
return ns
}
return v1.NamespaceDefault
}
func determineFieldValidationDirective(validate bool) FieldValidationDirective {
if validate {
return FieldValidationDirectiveStrict
}
return FieldValidationDirectiveIgnore
}
func buildResourceList(f Factory, namespace string, validationDirective FieldValidationDirective, reader io.Reader, transformRequest resource.RequestTransform) (ResourceList, error) {
schema, err := f.Validator(string(validationDirective))
if err != nil {
return nil, err
}
builder := f.NewBuilder().
ContinueOnError().
NamespaceParam(namespace).
DefaultNamespace().
Flatten().
Unstructured().
Schema(schema).
Stream(reader, "")
if transformRequest != nil {
builder.TransformRequests(transformRequest)
}
result, err := builder.Do().Infos()
return result, scrubValidationError(err)
}
// Build validates for Kubernetes objects and returns unstructured infos.
func (c *Client) Build(reader io.Reader, validate bool) (ResourceList, error) {
return buildResourceList(
c.Factory,
c.namespace(),
determineFieldValidationDirective(validate),
reader,
nil)
}
// BuildTable validates for Kubernetes objects and returns unstructured infos.
// The returned kind is a Table.
func (c *Client) BuildTable(reader io.Reader, validate bool) (ResourceList, error) {
return buildResourceList(
c.Factory,
c.namespace(),
determineFieldValidationDirective(validate),
reader,
transformRequests)
}
func (c *Client) update(originals, targets ResourceList, createApplyFunc CreateApplyFunc, updateApplyFunc UpdateApplyFunc) (*Result, error) {
updateErrors := []error{}
res := &Result{}
c.Logger().Debug("checking resources for changes", "resources", len(targets))
err := targets.Visit(func(target *resource.Info, err error) error {
if err != nil {
return err
}
helper := resource.NewHelper(target.Client, target.Mapping).WithFieldManager(getManagedFieldsManager())
if _, err := helper.Get(target.Namespace, target.Name); err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("could not get information about the resource: %w", err)
}
// Append the created resource to the results, even if something fails
res.Created = append(res.Created, target)
// Since the resource does not exist, create it.
if err := createApplyFunc(target); err != nil {
return fmt.Errorf("failed to create resource: %w", err)
}
kind := target.Mapping.GroupVersionKind.Kind
c.Logger().Debug(
"created a new resource",
slog.String("namespace", target.Namespace),
slog.String("name", target.Name),
slog.String("kind", kind),
)
return nil
}
original := originals.Get(target)
if original == nil {
kind := target.Mapping.GroupVersionKind.Kind
return fmt.Errorf("original object %s with the name %q not found", kind, target.Name)
}
if err := updateApplyFunc(original, target); err != nil {
updateErrors = append(updateErrors, err)
}
// Because we check for errors later, append the info regardless
res.Updated = append(res.Updated, target)
return nil
})
switch {
case err != nil:
return res, err
case len(updateErrors) != 0:
return res, joinErrors(updateErrors, " && ")
}
for _, info := range originals.Difference(targets) {
c.Logger().Debug("deleting resource", "namespace", info.Namespace, "name", info.Name, "kind", info.Mapping.GroupVersionKind.Kind)
if err := info.Get(); err != nil {
c.Logger().Debug(
"unable to get object",
slog.String("namespace", info.Namespace),
slog.String("name", info.Name),
slog.String("kind", info.Mapping.GroupVersionKind.Kind),
slog.Any("error", err),
)
continue
}
annotations, err := metadataAccessor.Annotations(info.Object)
if err != nil {
c.Logger().Debug(
"unable to get annotations",
slog.String("namespace", info.Namespace),
slog.String("name", info.Name),
slog.String("kind", info.Mapping.GroupVersionKind.Kind),
slog.Any("error", err),
)
}
if annotations != nil && annotations[ResourcePolicyAnno] == KeepPolicy {
c.Logger().Debug("skipping delete due to annotation", "namespace", info.Namespace, "name", info.Name, "kind", info.Mapping.GroupVersionKind.Kind, "annotation", ResourcePolicyAnno, "value", KeepPolicy)
continue
}
if err := deleteResource(info, metav1.DeletePropagationBackground); err != nil {
c.Logger().Debug(
"failed to delete resource",
slog.String("namespace", info.Namespace),
slog.String("name", info.Name),
slog.String("kind", info.Mapping.GroupVersionKind.Kind),
slog.Any("error", err),
)
if !apierrors.IsNotFound(err) {
updateErrors = append(updateErrors, fmt.Errorf("failed to delete resource %s: %w", info.Name, err))
}
continue
}
res.Deleted = append(res.Deleted, info)
}
if len(updateErrors) != 0 {
return res, joinErrors(updateErrors, " && ")
}
return res, nil
}
type clientUpdateOptions struct {
threeWayMergeForUnstructured bool
serverSideApply bool
forceReplace bool
forceConflicts bool
dryRun bool
fieldValidationDirective FieldValidationDirective
upgradeClientSideFieldManager bool
}
type ClientUpdateOption func(*clientUpdateOptions) error
// ClientUpdateOptionThreeWayMergeForUnstructured enables performing three-way merge for unstructured objects
// Must not be enabled when ClientUpdateOptionServerSideApply is enabled
func ClientUpdateOptionThreeWayMergeForUnstructured(threeWayMergeForUnstructured bool) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
o.threeWayMergeForUnstructured = threeWayMergeForUnstructured
return nil
}
}
// ClientUpdateOptionServerSideApply enables performing object apply server-side (default)
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/
// Must not be enabled when ClientUpdateOptionThreeWayMerge is enabled
//
// `forceConflicts` forces conflicts to be resolved (may be enabled when serverSideApply enabled only)
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts
func ClientUpdateOptionServerSideApply(serverSideApply, forceConflicts bool) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
if !serverSideApply && forceConflicts {
return fmt.Errorf("forceConflicts enabled when serverSideApply disabled")
}
o.serverSideApply = serverSideApply
o.forceConflicts = forceConflicts
return nil
}
}
// ClientUpdateOptionForceReplace forces objects to be replaced rather than updated via patch
// Must not be enabled when ClientUpdateOptionForceConflicts is enabled
func ClientUpdateOptionForceReplace(forceReplace bool) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
o.forceReplace = forceReplace
return nil
}
}
// ClientUpdateOptionDryRun requests the server to perform non-mutating operations only
func ClientUpdateOptionDryRun(dryRun bool) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
o.dryRun = dryRun
return nil
}
}
// ClientUpdateOptionFieldValidationDirective specifies how API operations validate object's schema
// - For client-side apply: this is ignored
// - For server-side apply: the directive is sent to the server to perform the validation
//
// Defaults to `FieldValidationDirectiveStrict`
func ClientUpdateOptionFieldValidationDirective(fieldValidationDirective FieldValidationDirective) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
o.fieldValidationDirective = fieldValidationDirective
return nil
}
}
// ClientUpdateOptionUpgradeClientSideFieldManager specifies that resources client-side field manager should be upgraded to server-side apply
// (before applying the object server-side)
// This is required when upgrading a chart from client-side to server-side apply, otherwise the client-side field management remains. Conflicting with server-side applied updates.
//
// Note:
// if this option is specified, but the object is not managed by client-side field manager, it will be a no-op. However, the cost of fetching the objects will be incurred.
//
// see:
// - https://github.com/kubernetes/kubernetes/pull/112905
// - `UpgradeManagedFields` / https://github.com/kubernetes/kubernetes/blob/f47e9696d7237f1011d23c9b55f6947e60526179/staging/src/k8s.io/client-go/util/csaupgrade/upgrade.go#L81
func ClientUpdateOptionUpgradeClientSideFieldManager(upgradeClientSideFieldManager bool) ClientUpdateOption {
return func(o *clientUpdateOptions) error {
o.upgradeClientSideFieldManager = upgradeClientSideFieldManager
return nil
}
}
// Update takes the current list of objects and target list of objects and
// creates resources that don't already exist, updates resources that have been
// modified in the target configuration, and deletes resources from the current
// configuration that are not present in the target configuration. If an error
// occurs, a Result will still be returned with the error, containing all
// resource updates, creations, and deletions that were attempted. These can be
// used for cleanup or other logging purposes.
//
// The default is to use server-side apply, equivalent to: `ClientUpdateOptionServerSideApply(true)`
func (c *Client) Update(originals, targets ResourceList, options ...ClientUpdateOption) (*Result, error) {
updateOptions := clientUpdateOptions{
serverSideApply: true, // Default to server-side apply
fieldValidationDirective: FieldValidationDirectiveStrict,
}
errs := make([]error, 0, len(options))
for _, o := range options {
errs = append(errs, o(&updateOptions))
}
if err := errors.Join(errs...); err != nil {
return &Result{}, fmt.Errorf("invalid client update option(s): %w", err)
}
if updateOptions.threeWayMergeForUnstructured && updateOptions.serverSideApply {
return &Result{}, fmt.Errorf("invalid operation: cannot use three-way merge for unstructured and server-side apply together")
}
if updateOptions.forceConflicts && updateOptions.forceReplace {
return &Result{}, fmt.Errorf("invalid operation: cannot use force conflicts and force replace together")
}
if updateOptions.serverSideApply && updateOptions.forceReplace {
return &Result{}, fmt.Errorf("invalid operation: cannot use server-side apply and force replace together")
}
createApplyFunc := c.makeCreateApplyFunc(
updateOptions.serverSideApply,
updateOptions.forceConflicts,
updateOptions.dryRun,
updateOptions.fieldValidationDirective)
makeUpdateApplyFunc := func() UpdateApplyFunc {
if updateOptions.forceReplace {
c.Logger().Debug(
"using resource replace update strategy",
slog.String("fieldValidationDirective", string(updateOptions.fieldValidationDirective)))
return func(original, target *resource.Info) error {
if err := replaceResource(target, updateOptions.fieldValidationDirective); err != nil {
c.Logger().With(
slog.String("namespace", target.Namespace),
slog.String("name", target.Name),
slog.String("gvk", target.Mapping.GroupVersionKind.String()),
).Debug(
"error replacing the resource", slog.Any("error", err),
)
return err
}
originalObject := original.Object
kind := target.Mapping.GroupVersionKind.Kind
c.Logger().Debug("replace succeeded", "name", original.Name, "initialKind", originalObject.GetObjectKind().GroupVersionKind().Kind, "kind", kind)
return nil
}
} else if updateOptions.serverSideApply {
c.Logger().Debug(
"using server-side apply for resource update",
slog.Bool("forceConflicts", updateOptions.forceConflicts),
slog.Bool("dryRun", updateOptions.dryRun),
slog.String("fieldValidationDirective", string(updateOptions.fieldValidationDirective)),
slog.Bool("upgradeClientSideFieldManager", updateOptions.upgradeClientSideFieldManager))
return func(original, target *resource.Info) error {
logger := c.Logger().With(
slog.String("namespace", target.Namespace),
slog.String("name", target.Name),
slog.String("gvk", target.Mapping.GroupVersionKind.String()))
if updateOptions.upgradeClientSideFieldManager {
patched, err := upgradeClientSideFieldManager(original, updateOptions.dryRun, updateOptions.fieldValidationDirective)
if err != nil {
c.Logger().Debug("Error patching resource to replace CSA field management", slog.Any("error", err))
return err
}
if patched {
logger.Debug("Upgraded object client-side field management with server-side apply field management")
}
}
if err := patchResourceServerSide(target, updateOptions.dryRun, updateOptions.forceConflicts, updateOptions.fieldValidationDirective); err != nil {
logger.Debug("Error patching resource", slog.Any("error", err))
return err
}
logger.Debug("Patched resource")
return nil
}
}
c.Logger().Debug("using client-side apply for resource update", slog.Bool("threeWayMergeForUnstructured", updateOptions.threeWayMergeForUnstructured))
return func(original, target *resource.Info) error {
return patchResourceClientSide(original.Object, target, updateOptions.threeWayMergeForUnstructured)
}
}
return c.update(originals, targets, createApplyFunc, makeUpdateApplyFunc())
}
// Delete deletes Kubernetes resources specified in the resources list with
// given deletion propagation policy. It will attempt to delete all resources even
// if one or more fail and collect any errors. All successfully deleted items
// will be returned in the `Deleted` ResourceList that is part of the result.
func (c *Client) Delete(resources ResourceList, policy metav1.DeletionPropagation) (*Result, []error) {
var errs []error
res := &Result{}
mtx := sync.Mutex{}
err := perform(resources, func(target *resource.Info) error {
c.Logger().Debug("starting delete resource", "namespace", target.Namespace, "name", target.Name, "kind", target.Mapping.GroupVersionKind.Kind)
err := deleteResource(target, policy)
if err == nil || apierrors.IsNotFound(err) {
if err != nil {
c.Logger().Debug(
"ignoring delete failure",
slog.String("namespace", target.Namespace),
slog.String("name", target.Name),
slog.String("kind", target.Mapping.GroupVersionKind.Kind),
slog.Any("error", err))
}
mtx.Lock()
defer mtx.Unlock()
res.Deleted = append(res.Deleted, target)
return nil
}
mtx.Lock()
defer mtx.Unlock()
// Collect the error and continue on
errs = append(errs, err)
return nil
})
if err != nil {
if errors.Is(err, ErrNoObjectsVisited) {
err = fmt.Errorf("object not found, skipping delete: %w", err)
}
errs = append(errs, err)
}
if errs != nil {
return nil, errs
}
return res, nil
}
// https://github.com/kubernetes/kubectl/blob/197123726db24c61aa0f78d1f0ba6e91a2ec2f35/pkg/cmd/apply/apply.go#L439
func isIncompatibleServerError(err error) bool {
// 415: Unsupported media type means we're talking to a server which doesn't
// support server-side apply.
if _, ok := err.(*apierrors.StatusError); !ok {
// Non-StatusError means the error isn't because the server is incompatible.
return false
}
return err.(*apierrors.StatusError).Status().Code == http.StatusUnsupportedMediaType
}
// getManagedFieldsManager returns the manager string. If one was set it will be returned.
// Otherwise, one is calculated based on the name of the binary.
func getManagedFieldsManager() string {
// When a manager is explicitly set use it
if ManagedFieldsManager != "" {
return ManagedFieldsManager
}
// When no manager is set and no calling application can be found it is unknown
if len(os.Args[0]) == 0 {
return "unknown"
}
// When there is an application that can be determined and no set manager
// use the base name. This is one of the ways Kubernetes libs handle figuring
// names out.
return filepath.Base(os.Args[0])
}
func perform(infos ResourceList, fn func(*resource.Info) error) error {
var result error
if len(infos) == 0 {
return ErrNoObjectsVisited
}
errs := make(chan error)
go batchPerform(infos, fn, errs)
for range infos {
err := <-errs
if err != nil {
result = errors.Join(result, err)
}
}
return result
}
func batchPerform(infos ResourceList, fn func(*resource.Info) error, errs chan<- error) {
var kind string
var wg sync.WaitGroup
defer wg.Wait()
for _, info := range infos {
currentKind := info.Object.GetObjectKind().GroupVersionKind().Kind
if kind != currentKind {
wg.Wait()
kind = currentKind
}
wg.Add(1)
go func(info *resource.Info) {
errs <- fn(info)
wg.Done()
}(info)
}
}
var createMutex sync.Mutex
func createResource(info *resource.Info) error {
return retry.RetryOnConflict(
retry.DefaultRetry,
func() error {
createMutex.Lock()
defer createMutex.Unlock()
obj, err := resource.NewHelper(info.Client, info.Mapping).WithFieldManager(getManagedFieldsManager()).Create(info.Namespace, true, info.Object)
if err != nil {
return err
}
return info.Refresh(obj, true)
})
}
func deleteResource(info *resource.Info, policy metav1.DeletionPropagation) error {
return retry.RetryOnConflict(
retry.DefaultRetry,
func() error {
opts := &metav1.DeleteOptions{PropagationPolicy: &policy}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | true |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/statuswait_test.go | pkg/kube/statuswait_test.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v3/pkg/kube"
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/fluxcd/cli-utils/pkg/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/apimachinery/pkg/watch"
dynamicfake "k8s.io/client-go/dynamic/fake"
clienttesting "k8s.io/client-go/testing"
"k8s.io/kubectl/pkg/scheme"
)
var podCurrentManifest = `
apiVersion: v1
kind: Pod
metadata:
name: current-pod
namespace: ns
status:
conditions:
- type: Ready
status: "True"
phase: Running
`
var podNoStatusManifest = `
apiVersion: v1
kind: Pod
metadata:
name: in-progress-pod
namespace: ns
`
var jobNoStatusManifest = `
apiVersion: batch/v1
kind: Job
metadata:
name: test
namespace: qual
generation: 1
`
var jobReadyManifest = `
apiVersion: batch/v1
kind: Job
metadata:
name: ready-not-complete
namespace: default
generation: 1
status:
startTime: 2025-02-06T16:34:20-05:00
active: 1
ready: 1
`
var jobCompleteManifest = `
apiVersion: batch/v1
kind: Job
metadata:
name: test
namespace: qual
generation: 1
status:
succeeded: 1
active: 0
conditions:
- type: Complete
status: "True"
`
var podCompleteManifest = `
apiVersion: v1
kind: Pod
metadata:
name: good-pod
namespace: ns
status:
phase: Succeeded
`
var pausedDeploymentManifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: paused
namespace: ns-1
generation: 1
spec:
paused: true
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.19.6
ports:
- containerPort: 80
`
var notReadyDeploymentManifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
name: not-ready
namespace: ns-1
generation: 1
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.19.6
ports:
- containerPort: 80
`
var podNamespace1Manifest = `
apiVersion: v1
kind: Pod
metadata:
name: pod-ns1
namespace: namespace-1
status:
conditions:
- type: Ready
status: "True"
phase: Running
`
var podNamespace2Manifest = `
apiVersion: v1
kind: Pod
metadata:
name: pod-ns2
namespace: namespace-2
status:
conditions:
- type: Ready
status: "True"
phase: Running
`
var podNamespace1NoStatusManifest = `
apiVersion: v1
kind: Pod
metadata:
name: pod-ns1
namespace: namespace-1
`
var jobNamespace1CompleteManifest = `
apiVersion: batch/v1
kind: Job
metadata:
name: job-ns1
namespace: namespace-1
generation: 1
status:
succeeded: 1
active: 0
conditions:
- type: Complete
status: "True"
`
var podNamespace2SucceededManifest = `
apiVersion: v1
kind: Pod
metadata:
name: pod-ns2
namespace: namespace-2
status:
phase: Succeeded
`
var clusterRoleManifest = `
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: test-cluster-role
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
`
var namespaceManifest = `
apiVersion: v1
kind: Namespace
metadata:
name: test-namespace
`
func getGVR(t *testing.T, mapper meta.RESTMapper, obj *unstructured.Unstructured) schema.GroupVersionResource {
t.Helper()
gvk := obj.GroupVersionKind()
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
require.NoError(t, err)
return mapping.Resource
}
func getRuntimeObjFromManifests(t *testing.T, manifests []string) []runtime.Object {
t.Helper()
objects := []runtime.Object{}
for _, manifest := range manifests {
m := make(map[string]interface{})
err := yaml.Unmarshal([]byte(manifest), &m)
assert.NoError(t, err)
resource := &unstructured.Unstructured{Object: m}
objects = append(objects, resource)
}
return objects
}
func getResourceListFromRuntimeObjs(t *testing.T, c *Client, objs []runtime.Object) ResourceList {
t.Helper()
resourceList := ResourceList{}
for _, obj := range objs {
list, err := c.Build(objBody(obj), false)
assert.NoError(t, err)
resourceList = append(resourceList, list...)
}
return resourceList
}
func TestStatusWaitForDelete(t *testing.T) {
t.Parallel()
tests := []struct {
name string
manifestsToCreate []string
manifestsToDelete []string
expectErrs []error
}{
{
name: "wait for pod to be deleted",
manifestsToCreate: []string{podCurrentManifest},
manifestsToDelete: []string{podCurrentManifest},
expectErrs: nil,
},
{
name: "error when not all objects are deleted",
manifestsToCreate: []string{jobCompleteManifest, podCurrentManifest},
manifestsToDelete: []string{jobCompleteManifest},
expectErrs: []error{errors.New("resource still exists, name: current-pod, kind: Pod, status: Current"), errors.New("context deadline exceeded")},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
timeout := time.Second
timeUntilPodDelete := time.Millisecond * 500
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
batchv1.SchemeGroupVersion.WithKind("Job"),
)
statusWaiter := statusWaiter{
restMapper: fakeMapper,
client: fakeClient,
}
objsToCreate := getRuntimeObjFromManifests(t, tt.manifestsToCreate)
for _, objToCreate := range objsToCreate {
u := objToCreate.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := fakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
objsToDelete := getRuntimeObjFromManifests(t, tt.manifestsToDelete)
for _, objToDelete := range objsToDelete {
u := objToDelete.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
go func(gvr schema.GroupVersionResource, u *unstructured.Unstructured) {
time.Sleep(timeUntilPodDelete)
err := fakeClient.Tracker().Delete(gvr, u.GetNamespace(), u.GetName())
assert.NoError(t, err)
}(gvr, u)
}
resourceList := getResourceListFromRuntimeObjs(t, c, objsToCreate)
err := statusWaiter.WaitForDelete(resourceList, timeout)
if tt.expectErrs != nil {
assert.EqualError(t, err, errors.Join(tt.expectErrs...).Error())
return
}
assert.NoError(t, err)
})
}
}
func TestStatusWaitForDeleteNonExistentObject(t *testing.T) {
t.Parallel()
c := newTestClient(t)
timeout := time.Second
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
)
statusWaiter := statusWaiter{
restMapper: fakeMapper,
client: fakeClient,
}
// Don't create the object to test that the wait for delete works when the object doesn't exist
objManifest := getRuntimeObjFromManifests(t, []string{podCurrentManifest})
resourceList := getResourceListFromRuntimeObjs(t, c, objManifest)
err := statusWaiter.WaitForDelete(resourceList, timeout)
assert.NoError(t, err)
}
func TestStatusWait(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
expectErrs []error
waitForJobs bool
}{
{
name: "Job is not complete",
objManifests: []string{jobNoStatusManifest},
expectErrs: []error{errors.New("resource not ready, name: test, kind: Job, status: InProgress"), errors.New("context deadline exceeded")},
waitForJobs: true,
},
{
name: "Job is ready but not complete",
objManifests: []string{jobReadyManifest},
expectErrs: nil,
waitForJobs: false,
},
{
name: "Pod is ready",
objManifests: []string{podCurrentManifest},
expectErrs: nil,
},
{
name: "one of the pods never becomes ready",
objManifests: []string{podNoStatusManifest, podCurrentManifest},
expectErrs: []error{errors.New("resource not ready, name: in-progress-pod, kind: Pod, status: InProgress"), errors.New("context deadline exceeded")},
},
{
name: "paused deployment passes",
objManifests: []string{pausedDeploymentManifest},
expectErrs: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
appsv1.SchemeGroupVersion.WithKind("Deployment"),
batchv1.SchemeGroupVersion.WithKind("Job"),
)
statusWaiter := statusWaiter{
client: fakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := fakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := statusWaiter.Wait(resourceList, time.Second*3)
if tt.expectErrs != nil {
assert.EqualError(t, err, errors.Join(tt.expectErrs...).Error())
return
}
assert.NoError(t, err)
})
}
}
func TestWaitForJobComplete(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
expectErrs []error
}{
{
name: "Job is complete",
objManifests: []string{jobCompleteManifest},
},
{
name: "Job is not ready",
objManifests: []string{jobNoStatusManifest},
expectErrs: []error{errors.New("resource not ready, name: test, kind: Job, status: InProgress"), errors.New("context deadline exceeded")},
},
{
name: "Job is ready but not complete",
objManifests: []string{jobReadyManifest},
expectErrs: []error{errors.New("resource not ready, name: ready-not-complete, kind: Job, status: InProgress"), errors.New("context deadline exceeded")},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
batchv1.SchemeGroupVersion.WithKind("Job"),
)
statusWaiter := statusWaiter{
client: fakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := fakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := statusWaiter.WaitWithJobs(resourceList, time.Second*3)
if tt.expectErrs != nil {
assert.EqualError(t, err, errors.Join(tt.expectErrs...).Error())
return
}
assert.NoError(t, err)
})
}
}
func TestWatchForReady(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
expectErrs []error
}{
{
name: "succeeds if pod and job are complete",
objManifests: []string{jobCompleteManifest, podCompleteManifest},
},
{
name: "succeeds when a resource that's not a pod or job is not ready",
objManifests: []string{notReadyDeploymentManifest},
},
{
name: "Fails if job is not complete",
objManifests: []string{jobReadyManifest},
expectErrs: []error{errors.New("resource not ready, name: ready-not-complete, kind: Job, status: InProgress"), errors.New("context deadline exceeded")},
},
{
name: "Fails if pod is not complete",
objManifests: []string{podCurrentManifest},
expectErrs: []error{errors.New("resource not ready, name: current-pod, kind: Pod, status: InProgress"), errors.New("context deadline exceeded")},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
appsv1.SchemeGroupVersion.WithKind("Deployment"),
batchv1.SchemeGroupVersion.WithKind("Job"),
)
statusWaiter := statusWaiter{
client: fakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := fakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := statusWaiter.WatchUntilReady(resourceList, time.Second*3)
if tt.expectErrs != nil {
assert.EqualError(t, err, errors.Join(tt.expectErrs...).Error())
return
}
assert.NoError(t, err)
})
}
}
func TestStatusWaitMultipleNamespaces(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
expectErrs []error
testFunc func(statusWaiter, ResourceList, time.Duration) error
}{
{
name: "pods in multiple namespaces",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "hooks in multiple namespaces",
objManifests: []string{jobNamespace1CompleteManifest, podNamespace2SucceededManifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WatchUntilReady(rl, timeout)
},
},
{
name: "error when resource not ready in one namespace",
objManifests: []string{podNamespace1NoStatusManifest, podNamespace2Manifest},
expectErrs: []error{errors.New("resource not ready, name: pod-ns1, kind: Pod, status: InProgress"), errors.New("context deadline exceeded")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "delete resources in multiple namespaces",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WaitForDelete(rl, timeout)
},
},
{
name: "cluster-scoped resources work correctly with unrestricted permissions",
objManifests: []string{podNamespace1Manifest, clusterRoleManifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "namespace-scoped and cluster-scoped resources work together",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest, clusterRoleManifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "delete cluster-scoped resources works correctly",
objManifests: []string{podNamespace1Manifest, namespaceManifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WaitForDelete(rl, timeout)
},
},
{
name: "watch cluster-scoped resources works correctly",
objManifests: []string{clusterRoleManifest},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WatchUntilReady(rl, timeout)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
fakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
batchv1.SchemeGroupVersion.WithKind("Job"),
schema.GroupVersion{Group: "rbac.authorization.k8s.io", Version: "v1"}.WithKind("ClusterRole"),
v1.SchemeGroupVersion.WithKind("Namespace"),
)
sw := statusWaiter{
client: fakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := fakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
if strings.Contains(tt.name, "delete") {
timeUntilDelete := time.Millisecond * 500
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
go func(gvr schema.GroupVersionResource, u *unstructured.Unstructured) {
time.Sleep(timeUntilDelete)
err := fakeClient.Tracker().Delete(gvr, u.GetNamespace(), u.GetName())
assert.NoError(t, err)
}(gvr, u)
}
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := tt.testFunc(sw, resourceList, time.Second*3)
if tt.expectErrs != nil {
assert.EqualError(t, err, errors.Join(tt.expectErrs...).Error())
return
}
assert.NoError(t, err)
})
}
}
// restrictedClientConfig holds the configuration for RBAC simulation on a fake dynamic client
type restrictedClientConfig struct {
allowedNamespaces map[string]bool
clusterScopedListAttempted bool
}
// setupRestrictedClient configures a fake dynamic client to simulate RBAC restrictions
// by using PrependReactor and PrependWatchReactor to intercept list/watch operations.
func setupRestrictedClient(fakeClient *dynamicfake.FakeDynamicClient, allowedNamespaces []string) *restrictedClientConfig {
allowed := make(map[string]bool)
for _, ns := range allowedNamespaces {
allowed[ns] = true
}
config := &restrictedClientConfig{
allowedNamespaces: allowed,
}
// Intercept list operations
fakeClient.PrependReactor("list", "*", func(action clienttesting.Action) (bool, runtime.Object, error) {
listAction := action.(clienttesting.ListAction)
ns := listAction.GetNamespace()
if ns == "" {
// Cluster-scoped list
config.clusterScopedListAttempted = true
return true, nil, apierrors.NewForbidden(
action.GetResource().GroupResource(),
"",
fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources"),
)
}
if !config.allowedNamespaces[ns] {
return true, nil, apierrors.NewForbidden(
action.GetResource().GroupResource(),
"",
fmt.Errorf("user does not have LIST permissions in namespace %q", ns),
)
}
// Fall through to the default handler
return false, nil, nil
})
// Intercept watch operations
fakeClient.PrependWatchReactor("*", func(action clienttesting.Action) (bool, watch.Interface, error) {
watchAction := action.(clienttesting.WatchAction)
ns := watchAction.GetNamespace()
if ns == "" {
// Cluster-scoped watch
config.clusterScopedListAttempted = true
return true, nil, apierrors.NewForbidden(
action.GetResource().GroupResource(),
"",
fmt.Errorf("user does not have cluster-wide WATCH permissions for cluster-scoped resources"),
)
}
if !config.allowedNamespaces[ns] {
return true, nil, apierrors.NewForbidden(
action.GetResource().GroupResource(),
"",
fmt.Errorf("user does not have WATCH permissions in namespace %q", ns),
)
}
// Fall through to the default handler
return false, nil, nil
})
return config
}
func TestStatusWaitRestrictedRBAC(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
allowedNamespaces []string
expectErrs []error
testFunc func(statusWaiter, ResourceList, time.Duration) error
}{
{
name: "pods in multiple namespaces with namespace permissions",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
allowedNamespaces: []string{"namespace-1", "namespace-2"},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "delete pods in multiple namespaces with namespace permissions",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
allowedNamespaces: []string{"namespace-1", "namespace-2"},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WaitForDelete(rl, timeout)
},
},
{
name: "hooks in multiple namespaces with namespace permissions",
objManifests: []string{jobNamespace1CompleteManifest, podNamespace2SucceededManifest},
allowedNamespaces: []string{"namespace-1", "namespace-2"},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WatchUntilReady(rl, timeout)
},
},
{
name: "error when cluster-scoped resource included",
objManifests: []string{podNamespace1Manifest, clusterRoleManifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "error when deleting cluster-scoped resource",
objManifests: []string{podNamespace1Manifest, namespaceManifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WaitForDelete(rl, timeout)
},
},
{
name: "error when accessing disallowed namespace",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have LIST permissions in namespace %q", "namespace-2")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
baseFakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
batchv1.SchemeGroupVersion.WithKind("Job"),
schema.GroupVersion{Group: "rbac.authorization.k8s.io", Version: "v1"}.WithKind("ClusterRole"),
v1.SchemeGroupVersion.WithKind("Namespace"),
)
restrictedConfig := setupRestrictedClient(baseFakeClient, tt.allowedNamespaces)
sw := statusWaiter{
client: baseFakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := baseFakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
if strings.Contains(tt.name, "delet") {
timeUntilDelete := time.Millisecond * 500
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
go func(gvr schema.GroupVersionResource, u *unstructured.Unstructured) {
time.Sleep(timeUntilDelete)
err := baseFakeClient.Tracker().Delete(gvr, u.GetNamespace(), u.GetName())
assert.NoError(t, err)
}(gvr, u)
}
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := tt.testFunc(sw, resourceList, time.Second*3)
if tt.expectErrs != nil {
require.Error(t, err)
for _, expectedErr := range tt.expectErrs {
assert.Contains(t, err.Error(), expectedErr.Error())
}
return
}
assert.NoError(t, err)
assert.False(t, restrictedConfig.clusterScopedListAttempted)
})
}
}
func TestStatusWaitMixedResources(t *testing.T) {
t.Parallel()
tests := []struct {
name string
objManifests []string
allowedNamespaces []string
expectErrs []error
testFunc func(statusWaiter, ResourceList, time.Duration) error
}{
{
name: "wait succeeds with namespace-scoped resources only",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
allowedNamespaces: []string{"namespace-1", "namespace-2"},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "wait fails when cluster-scoped resource included",
objManifests: []string{podNamespace1Manifest, clusterRoleManifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "waitForDelete fails when cluster-scoped resource included",
objManifests: []string{podNamespace1Manifest, clusterRoleManifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.WaitForDelete(rl, timeout)
},
},
{
name: "wait fails when namespace resource included",
objManifests: []string{podNamespace1Manifest, namespaceManifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have cluster-wide LIST permissions for cluster-scoped resources")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
{
name: "error when accessing disallowed namespace",
objManifests: []string{podNamespace1Manifest, podNamespace2Manifest},
allowedNamespaces: []string{"namespace-1"},
expectErrs: []error{fmt.Errorf("user does not have LIST permissions in namespace %q", "namespace-2")},
testFunc: func(sw statusWaiter, rl ResourceList, timeout time.Duration) error {
return sw.Wait(rl, timeout)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
c := newTestClient(t)
baseFakeClient := dynamicfake.NewSimpleDynamicClient(scheme.Scheme)
fakeMapper := testutil.NewFakeRESTMapper(
v1.SchemeGroupVersion.WithKind("Pod"),
batchv1.SchemeGroupVersion.WithKind("Job"),
schema.GroupVersion{Group: "rbac.authorization.k8s.io", Version: "v1"}.WithKind("ClusterRole"),
v1.SchemeGroupVersion.WithKind("Namespace"),
)
restrictedConfig := setupRestrictedClient(baseFakeClient, tt.allowedNamespaces)
sw := statusWaiter{
client: baseFakeClient,
restMapper: fakeMapper,
}
objs := getRuntimeObjFromManifests(t, tt.objManifests)
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
err := baseFakeClient.Tracker().Create(gvr, u, u.GetNamespace())
assert.NoError(t, err)
}
if strings.Contains(tt.name, "delet") {
timeUntilDelete := time.Millisecond * 500
for _, obj := range objs {
u := obj.(*unstructured.Unstructured)
gvr := getGVR(t, fakeMapper, u)
go func(gvr schema.GroupVersionResource, u *unstructured.Unstructured) {
time.Sleep(timeUntilDelete)
err := baseFakeClient.Tracker().Delete(gvr, u.GetNamespace(), u.GetName())
assert.NoError(t, err)
}(gvr, u)
}
}
resourceList := getResourceListFromRuntimeObjs(t, c, objs)
err := tt.testFunc(sw, resourceList, time.Second*3)
if tt.expectErrs != nil {
require.Error(t, err)
for _, expectedErr := range tt.expectErrs {
assert.Contains(t, err.Error(), expectedErr.Error())
}
return
}
assert.NoError(t, err)
assert.False(t, restrictedConfig.clusterScopedListAttempted)
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/wait.go | pkg/kube/wait.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"context"
"fmt"
"log/slog"
"net/http"
"time"
appsv1 "k8s.io/api/apps/v1"
appsv1beta1 "k8s.io/api/apps/v1beta1"
appsv1beta2 "k8s.io/api/apps/v1beta2"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
extensionsv1beta1 "k8s.io/api/extensions/v1beta1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
cachetools "k8s.io/client-go/tools/cache"
watchtools "k8s.io/client-go/tools/watch"
"k8s.io/apimachinery/pkg/util/wait"
)
// legacyWaiter is the legacy implementation of the Waiter interface. This logic was used by default in Helm 3
// Helm 4 now uses the StatusWaiter implementation instead
type legacyWaiter struct {
c ReadyChecker
kubeClient *kubernetes.Clientset
ctx context.Context
}
func (hw *legacyWaiter) Wait(resources ResourceList, timeout time.Duration) error {
hw.c = NewReadyChecker(hw.kubeClient, PausedAsReady(true))
return hw.waitForResources(resources, timeout)
}
func (hw *legacyWaiter) WaitWithJobs(resources ResourceList, timeout time.Duration) error {
hw.c = NewReadyChecker(hw.kubeClient, PausedAsReady(true), CheckJobs(true))
return hw.waitForResources(resources, timeout)
}
// waitForResources polls to get the current status of all pods, PVCs, Services and
// Jobs(optional) until all are ready or a timeout is reached
func (hw *legacyWaiter) waitForResources(created ResourceList, timeout time.Duration) error {
slog.Debug("beginning wait for resources", "count", len(created), "timeout", timeout)
ctx, cancel := hw.contextWithTimeout(timeout)
defer cancel()
numberOfErrors := make([]int, len(created))
for i := range numberOfErrors {
numberOfErrors[i] = 0
}
return wait.PollUntilContextCancel(ctx, 2*time.Second, true, func(ctx context.Context) (bool, error) {
waitRetries := 30
for i, v := range created {
ready, err := hw.c.IsReady(ctx, v)
if waitRetries > 0 && hw.isRetryableError(err, v) {
numberOfErrors[i]++
if numberOfErrors[i] > waitRetries {
slog.Debug("max number of retries reached", "resource", v.Name, "retries", numberOfErrors[i])
return false, err
}
slog.Debug("retrying resource readiness", "resource", v.Name, "currentRetries", numberOfErrors[i]-1, "maxRetries", waitRetries)
return false, nil
}
numberOfErrors[i] = 0
if !ready {
return false, err
}
}
return true, nil
})
}
func (hw *legacyWaiter) isRetryableError(err error, resource *resource.Info) bool {
if err == nil {
return false
}
slog.Debug(
"error received when checking resource status",
slog.String("resource", resource.Name),
slog.Any("error", err),
)
if ev, ok := err.(*apierrors.StatusError); ok {
statusCode := ev.Status().Code
retryable := hw.isRetryableHTTPStatusCode(statusCode)
slog.Debug(
"status code received",
slog.String("resource", resource.Name),
slog.Int("statusCode", int(statusCode)),
slog.Bool("retryable", retryable),
)
return retryable
}
slog.Debug("retryable error assumed", "resource", resource.Name)
return true
}
func (hw *legacyWaiter) isRetryableHTTPStatusCode(httpStatusCode int32) bool {
return httpStatusCode == 0 || httpStatusCode == http.StatusTooManyRequests || (httpStatusCode >= 500 && httpStatusCode != http.StatusNotImplemented)
}
// WaitForDelete polls to check if all the resources are deleted or a timeout is reached
func (hw *legacyWaiter) WaitForDelete(deleted ResourceList, timeout time.Duration) error {
slog.Debug("beginning wait for resources to be deleted", "count", len(deleted), "timeout", timeout)
startTime := time.Now()
ctx, cancel := hw.contextWithTimeout(timeout)
defer cancel()
err := wait.PollUntilContextCancel(ctx, 2*time.Second, true, func(_ context.Context) (bool, error) {
for _, v := range deleted {
err := v.Get()
if err == nil || !apierrors.IsNotFound(err) {
return false, err
}
}
return true, nil
})
elapsed := time.Since(startTime).Round(time.Second)
if err != nil {
slog.Debug("wait for resources failed", slog.Duration("elapsed", elapsed), slog.Any("error", err))
} else {
slog.Debug("wait for resources succeeded", slog.Duration("elapsed", elapsed))
}
return err
}
// SelectorsForObject returns the pod label selector for a given object
//
// Modified version of https://github.com/kubernetes/kubernetes/blob/v1.14.1/pkg/kubectl/polymorphichelpers/helpers.go#L84
func SelectorsForObject(object runtime.Object) (selector labels.Selector, err error) {
switch t := object.(type) {
case *extensionsv1beta1.ReplicaSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1.ReplicaSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta2.ReplicaSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *corev1.ReplicationController:
selector = labels.SelectorFromSet(t.Spec.Selector)
case *appsv1.StatefulSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta1.StatefulSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta2.StatefulSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *extensionsv1beta1.DaemonSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1.DaemonSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta2.DaemonSet:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *extensionsv1beta1.Deployment:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1.Deployment:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta1.Deployment:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *appsv1beta2.Deployment:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *batchv1.Job:
selector, err = metav1.LabelSelectorAsSelector(t.Spec.Selector)
case *corev1.Service:
if len(t.Spec.Selector) == 0 {
return nil, fmt.Errorf("invalid service '%s': Service is defined without a selector", t.Name)
}
selector = labels.SelectorFromSet(t.Spec.Selector)
default:
return nil, fmt.Errorf("selector for %T not implemented", object)
}
if err != nil {
return selector, fmt.Errorf("invalid label selector: %w", err)
}
return selector, nil
}
func (hw *legacyWaiter) watchTimeout(t time.Duration) func(*resource.Info) error {
return func(info *resource.Info) error {
return hw.watchUntilReady(t, info)
}
}
// WatchUntilReady watches the resources given and waits until it is ready.
//
// This method is mainly for hook implementations. It watches for a resource to
// hit a particular milestone. The milestone depends on the Kind.
//
// For most kinds, it checks to see if the resource is marked as Added or Modified
// by the Kubernetes event stream. For some kinds, it does more:
//
// - Jobs: A job is marked "Ready" when it has successfully completed. This is
// ascertained by watching the Status fields in a job's output.
// - Pods: A pod is marked "Ready" when it has successfully completed. This is
// ascertained by watching the status.phase field in a pod's output.
//
// Handling for other kinds will be added as necessary.
func (hw *legacyWaiter) WatchUntilReady(resources ResourceList, timeout time.Duration) error {
// For jobs, there's also the option to do poll c.Jobs(namespace).Get():
// https://github.com/adamreese/kubernetes/blob/master/test/e2e/job.go#L291-L300
return perform(resources, hw.watchTimeout(timeout))
}
func (hw *legacyWaiter) watchUntilReady(timeout time.Duration, info *resource.Info) error {
kind := info.Mapping.GroupVersionKind.Kind
switch kind {
case "Job", "Pod":
default:
return nil
}
slog.Debug("watching for resource changes", "kind", kind, "resource", info.Name, "timeout", timeout)
// Use a selector on the name of the resource. This should be unique for the
// given version and kind
selector, err := fields.ParseSelector(fmt.Sprintf("metadata.name=%s", info.Name))
if err != nil {
return err
}
lw := cachetools.NewListWatchFromClient(info.Client, info.Mapping.Resource.Resource, info.Namespace, selector)
// What we watch for depends on the Kind.
// - For a Job, we watch for completion.
// - For all else, we watch until Ready.
// In the future, we might want to add some special logic for types
// like Ingress, Volume, etc.
ctx, cancel := hw.contextWithTimeout(timeout)
defer cancel()
_, err = watchtools.UntilWithSync(ctx, lw, &unstructured.Unstructured{}, nil, func(e watch.Event) (bool, error) {
// Make sure the incoming object is versioned as we use unstructured
// objects when we build manifests
obj := convertWithMapper(e.Object, info.Mapping)
switch e.Type {
case watch.Added, watch.Modified:
// For things like a secret or a config map, this is the best indicator
// we get. We care mostly about jobs, where what we want to see is
// the status go into a good state. For other types, like ReplicaSet
// we don't really do anything to support these as hooks.
slog.Debug("add/modify event received", "resource", info.Name, "eventType", e.Type)
switch kind {
case "Job":
return hw.waitForJob(obj, info.Name)
case "Pod":
return hw.waitForPodSuccess(obj, info.Name)
}
return true, nil
case watch.Deleted:
slog.Debug("deleted event received", "resource", info.Name)
return true, nil
case watch.Error:
// Handle error and return with an error.
slog.Error("error event received", "resource", info.Name)
return true, fmt.Errorf("failed to deploy %s", info.Name)
default:
return false, nil
}
})
return err
}
// waitForJob is a helper that waits for a job to complete.
//
// This operates on an event returned from a watcher.
func (hw *legacyWaiter) waitForJob(obj runtime.Object, name string) (bool, error) {
o, ok := obj.(*batchv1.Job)
if !ok {
return true, fmt.Errorf("expected %s to be a *batch.Job, got %T", name, obj)
}
for _, c := range o.Status.Conditions {
if c.Type == batchv1.JobComplete && c.Status == "True" {
return true, nil
} else if c.Type == batchv1.JobFailed && c.Status == "True" {
slog.Error("job failed", "job", name, "reason", c.Reason)
return true, fmt.Errorf("job %s failed: %s", name, c.Reason)
}
}
slog.Debug("job status update", "job", name, "active", o.Status.Active, "failed", o.Status.Failed, "succeeded", o.Status.Succeeded)
return false, nil
}
// waitForPodSuccess is a helper that waits for a pod to complete.
//
// This operates on an event returned from a watcher.
func (hw *legacyWaiter) waitForPodSuccess(obj runtime.Object, name string) (bool, error) {
o, ok := obj.(*corev1.Pod)
if !ok {
return true, fmt.Errorf("expected %s to be a *v1.Pod, got %T", name, obj)
}
switch o.Status.Phase {
case corev1.PodSucceeded:
slog.Debug("pod succeeded", "pod", o.Name)
return true, nil
case corev1.PodFailed:
slog.Error("pod failed", "pod", o.Name)
return true, fmt.Errorf("pod %s failed", o.Name)
case corev1.PodPending:
slog.Debug("pod pending", "pod", o.Name)
case corev1.PodRunning:
slog.Debug("pod running", "pod", o.Name)
case corev1.PodUnknown:
slog.Debug("pod unknown", "pod", o.Name)
}
return false, nil
}
func (hw *legacyWaiter) contextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc) {
return contextWithTimeout(hw.ctx, timeout)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/result.go | pkg/kube/result.go | /*
Copyright The Helm 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 kube
// Result contains the information of created, updated, and deleted resources
// for various kube API calls along with helper methods for using those
// resources
type Result struct {
Created ResourceList
Updated ResourceList
Deleted ResourceList
}
// If needed, we can add methods to the Result type for things like diffing
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/interface.go | pkg/kube/interface.go | /*
Copyright The Helm 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 kube
import (
"io"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
)
// Interface represents a client capable of communicating with the Kubernetes API.
//
// A KubernetesClient must be concurrency safe.
type Interface interface {
// Get details of deployed resources.
// The first argument is a list of resources to get. The second argument
// specifies if related pods should be fetched. For example, the pods being
// managed by a deployment.
Get(resources ResourceList, related bool) (map[string][]runtime.Object, error)
// Create creates one or more resources.
Create(resources ResourceList, options ...ClientCreateOption) (*Result, error)
// Delete destroys one or more resources using the specified deletion propagation policy.
// The 'policy' parameter determines how child resources are handled during deletion.
Delete(resources ResourceList, policy metav1.DeletionPropagation) (*Result, []error)
// Update updates one or more resources or creates the resource
// if it doesn't exist.
Update(original, target ResourceList, options ...ClientUpdateOption) (*Result, error)
// Build creates a resource list from a Reader.
//
// Reader must contain a YAML stream (one or more YAML documents separated
// by "\n---\n")
//
// Validates against OpenAPI schema if validate is true.
Build(reader io.Reader, validate bool) (ResourceList, error)
// IsReachable checks whether the client is able to connect to the cluster.
IsReachable() error
// Get Waiter gets the Kube.Waiter
GetWaiter(ws WaitStrategy) (Waiter, error)
// GetPodList lists all pods that match the specified listOptions
GetPodList(namespace string, listOptions metav1.ListOptions) (*v1.PodList, error)
// OutputContainerLogsForPodList outputs the logs for a pod list
OutputContainerLogsForPodList(podList *v1.PodList, namespace string, writerFunc func(namespace, pod, container string) io.Writer) error
// BuildTable creates a resource list from a Reader. This differs from
// Interface.Build() in that a table kind is returned. A table is useful
// if you want to use a printer to display the information.
//
// Reader must contain a YAML stream (one or more YAML documents separated
// by "\n---\n")
//
// Validates against OpenAPI schema if validate is true.
// TODO Helm 4: Integrate into Build with an argument
BuildTable(reader io.Reader, validate bool) (ResourceList, error)
}
// Waiter defines methods related to waiting for resource states.
type Waiter interface {
// Wait waits up to the given timeout for the specified resources to be ready.
Wait(resources ResourceList, timeout time.Duration) error
// WaitWithJobs wait up to the given timeout for the specified resources to be ready, including jobs.
WaitWithJobs(resources ResourceList, timeout time.Duration) error
// WaitForDelete wait up to the given timeout for the specified resources to be deleted.
WaitForDelete(resources ResourceList, timeout time.Duration) error
// WatchUntilReady watches the resources given and waits until it is ready.
//
// This method is mainly for hook implementations. It watches for a resource to
// hit a particular milestone. The milestone depends on the Kind.
//
// For Jobs, "ready" means the Job ran to completion (exited without error).
// For Pods, "ready" means the Pod phase is marked "succeeded".
// For all other kinds, it means the kind was created or modified without
// error.
WatchUntilReady(resources ResourceList, timeout time.Duration) error
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/statuswait.go | pkg/kube/statuswait.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v3/pkg/kube"
import (
"context"
"errors"
"fmt"
"log/slog"
"sort"
"time"
"github.com/fluxcd/cli-utils/pkg/kstatus/polling/aggregator"
"github.com/fluxcd/cli-utils/pkg/kstatus/polling/collector"
"github.com/fluxcd/cli-utils/pkg/kstatus/polling/engine"
"github.com/fluxcd/cli-utils/pkg/kstatus/polling/event"
"github.com/fluxcd/cli-utils/pkg/kstatus/polling/statusreaders"
"github.com/fluxcd/cli-utils/pkg/kstatus/status"
"github.com/fluxcd/cli-utils/pkg/kstatus/watcher"
"github.com/fluxcd/cli-utils/pkg/object"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/dynamic"
watchtools "k8s.io/client-go/tools/watch"
helmStatusReaders "helm.sh/helm/v4/internal/statusreaders"
)
type statusWaiter struct {
client dynamic.Interface
restMapper meta.RESTMapper
ctx context.Context
}
// DefaultStatusWatcherTimeout is the timeout used by the status waiter when a
// zero timeout is provided. This prevents callers from accidentally passing a
// zero value (which would immediately cancel the context) and getting
// "context deadline exceeded" errors. SDK callers can rely on this default
// when they don't set a timeout.
var DefaultStatusWatcherTimeout = 30 * time.Second
func alwaysReady(_ *unstructured.Unstructured) (*status.Result, error) {
return &status.Result{
Status: status.CurrentStatus,
Message: "Resource is current",
}, nil
}
func (w *statusWaiter) WatchUntilReady(resourceList ResourceList, timeout time.Duration) error {
if timeout == 0 {
timeout = DefaultStatusWatcherTimeout
}
ctx, cancel := w.contextWithTimeout(timeout)
defer cancel()
slog.Debug("waiting for resources", "count", len(resourceList), "timeout", timeout)
sw := watcher.NewDefaultStatusWatcher(w.client, w.restMapper)
jobSR := helmStatusReaders.NewCustomJobStatusReader(w.restMapper)
podSR := helmStatusReaders.NewCustomPodStatusReader(w.restMapper)
// We don't want to wait on any other resources as watchUntilReady is only for Helm hooks
genericSR := statusreaders.NewGenericStatusReader(w.restMapper, alwaysReady)
sr := &statusreaders.DelegatingStatusReader{
StatusReaders: []engine.StatusReader{
jobSR,
podSR,
genericSR,
},
}
sw.StatusReader = sr
return w.wait(ctx, resourceList, sw)
}
func (w *statusWaiter) Wait(resourceList ResourceList, timeout time.Duration) error {
if timeout == 0 {
timeout = DefaultStatusWatcherTimeout
}
ctx, cancel := w.contextWithTimeout(timeout)
defer cancel()
slog.Debug("waiting for resources", "count", len(resourceList), "timeout", timeout)
sw := watcher.NewDefaultStatusWatcher(w.client, w.restMapper)
return w.wait(ctx, resourceList, sw)
}
func (w *statusWaiter) WaitWithJobs(resourceList ResourceList, timeout time.Duration) error {
if timeout == 0 {
timeout = DefaultStatusWatcherTimeout
}
ctx, cancel := w.contextWithTimeout(timeout)
defer cancel()
slog.Debug("waiting for resources", "count", len(resourceList), "timeout", timeout)
sw := watcher.NewDefaultStatusWatcher(w.client, w.restMapper)
newCustomJobStatusReader := helmStatusReaders.NewCustomJobStatusReader(w.restMapper)
customSR := statusreaders.NewStatusReader(w.restMapper, newCustomJobStatusReader)
sw.StatusReader = customSR
return w.wait(ctx, resourceList, sw)
}
func (w *statusWaiter) WaitForDelete(resourceList ResourceList, timeout time.Duration) error {
if timeout == 0 {
timeout = DefaultStatusWatcherTimeout
}
ctx, cancel := w.contextWithTimeout(timeout)
defer cancel()
slog.Debug("waiting for resources to be deleted", "count", len(resourceList), "timeout", timeout)
sw := watcher.NewDefaultStatusWatcher(w.client, w.restMapper)
return w.waitForDelete(ctx, resourceList, sw)
}
func (w *statusWaiter) waitForDelete(ctx context.Context, resourceList ResourceList, sw watcher.StatusWatcher) error {
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
resources := []object.ObjMetadata{}
for _, resource := range resourceList {
obj, err := object.RuntimeToObjMeta(resource.Object)
if err != nil {
return err
}
resources = append(resources, obj)
}
eventCh := sw.Watch(cancelCtx, resources, watcher.Options{
RESTScopeStrategy: watcher.RESTScopeNamespace,
})
statusCollector := collector.NewResourceStatusCollector(resources)
done := statusCollector.ListenWithObserver(eventCh, statusObserver(cancel, status.NotFoundStatus))
<-done
if statusCollector.Error != nil {
return statusCollector.Error
}
// Only check parent context error, otherwise we would error when desired status is achieved.
if ctx.Err() != nil {
errs := []error{}
for _, id := range resources {
rs := statusCollector.ResourceStatuses[id]
if rs.Status == status.NotFoundStatus {
continue
}
errs = append(errs, fmt.Errorf("resource still exists, name: %s, kind: %s, status: %s", rs.Identifier.Name, rs.Identifier.GroupKind.Kind, rs.Status))
}
errs = append(errs, ctx.Err())
return errors.Join(errs...)
}
return nil
}
func (w *statusWaiter) wait(ctx context.Context, resourceList ResourceList, sw watcher.StatusWatcher) error {
cancelCtx, cancel := context.WithCancel(ctx)
defer cancel()
resources := []object.ObjMetadata{}
for _, resource := range resourceList {
switch value := AsVersioned(resource).(type) {
case *appsv1.Deployment:
if value.Spec.Paused {
continue
}
}
obj, err := object.RuntimeToObjMeta(resource.Object)
if err != nil {
return err
}
resources = append(resources, obj)
}
eventCh := sw.Watch(cancelCtx, resources, watcher.Options{
RESTScopeStrategy: watcher.RESTScopeNamespace,
})
statusCollector := collector.NewResourceStatusCollector(resources)
done := statusCollector.ListenWithObserver(eventCh, statusObserver(cancel, status.CurrentStatus))
<-done
if statusCollector.Error != nil {
return statusCollector.Error
}
// Only check parent context error, otherwise we would error when desired status is achieved.
if ctx.Err() != nil {
errs := []error{}
for _, id := range resources {
rs := statusCollector.ResourceStatuses[id]
if rs.Status == status.CurrentStatus {
continue
}
errs = append(errs, fmt.Errorf("resource not ready, name: %s, kind: %s, status: %s", rs.Identifier.Name, rs.Identifier.GroupKind.Kind, rs.Status))
}
errs = append(errs, ctx.Err())
return errors.Join(errs...)
}
return nil
}
func (w *statusWaiter) contextWithTimeout(timeout time.Duration) (context.Context, context.CancelFunc) {
return contextWithTimeout(w.ctx, timeout)
}
func contextWithTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc) {
if ctx == nil {
ctx = context.Background()
}
return watchtools.ContextWithOptionalTimeout(ctx, timeout)
}
func statusObserver(cancel context.CancelFunc, desired status.Status) collector.ObserverFunc {
return func(statusCollector *collector.ResourceStatusCollector, _ event.Event) {
var rss []*event.ResourceStatus
var nonDesiredResources []*event.ResourceStatus
for _, rs := range statusCollector.ResourceStatuses {
if rs == nil {
continue
}
// If a resource is already deleted before waiting has started, it will show as unknown
// this check ensures we don't wait forever for a resource that is already deleted
if rs.Status == status.UnknownStatus && desired == status.NotFoundStatus {
continue
}
rss = append(rss, rs)
if rs.Status != desired {
nonDesiredResources = append(nonDesiredResources, rs)
}
}
if aggregator.AggregateStatus(rss, desired) == desired {
slog.Debug("all resources achieved desired status", "desiredStatus", desired, "resourceCount", len(rss))
cancel()
return
}
if len(nonDesiredResources) > 0 {
// Log a single resource so the user knows what they're waiting for without an overwhelming amount of output
sort.Slice(nonDesiredResources, func(i, j int) bool {
return nonDesiredResources[i].Identifier.Name < nonDesiredResources[j].Identifier.Name
})
first := nonDesiredResources[0]
slog.Debug("waiting for resource", "namespace", first.Identifier.Namespace, "name", first.Identifier.Name, "kind", first.Identifier.GroupKind.Kind, "expectedStatus", desired, "actualStatus", first.Status)
}
}
}
type hookOnlyWaiter struct {
sw *statusWaiter
}
func (w *hookOnlyWaiter) WatchUntilReady(resourceList ResourceList, timeout time.Duration) error {
return w.sw.WatchUntilReady(resourceList, timeout)
}
func (w *hookOnlyWaiter) Wait(_ ResourceList, _ time.Duration) error {
return nil
}
func (w *hookOnlyWaiter) WaitWithJobs(_ ResourceList, _ time.Duration) error {
return nil
}
func (w *hookOnlyWaiter) WaitForDelete(_ ResourceList, _ time.Duration) error {
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/client_test.go | pkg/kube/client_test.go | /*
Copyright The Helm 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 kube
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
jsonserializer "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/types"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
k8sfake "k8s.io/client-go/kubernetes/fake"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest/fake"
cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
)
var (
unstructuredSerializer = resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer
codec = scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
)
func objBody(obj runtime.Object) io.ReadCloser {
return io.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, obj))))
}
func newPod(name string) v1.Pod {
return newPodWithStatus(name, v1.PodStatus{}, "")
}
func newPodWithStatus(name string, status v1.PodStatus, namespace string) v1.Pod {
ns := v1.NamespaceDefault
if namespace != "" {
ns = namespace
}
return v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: ns,
SelfLink: "/api/v1/namespaces/default/pods/" + name,
},
Spec: v1.PodSpec{
Containers: []v1.Container{{
Name: "app:v4",
Image: "abc/app:v4",
Ports: []v1.ContainerPort{{Name: "http", ContainerPort: 80}},
}},
},
Status: status,
}
}
func newPodList(names ...string) v1.PodList {
var list v1.PodList
for _, name := range names {
list.Items = append(list.Items, newPod(name))
}
return list
}
func notFoundBody() *metav1.Status {
return &metav1.Status{
Code: http.StatusNotFound,
Status: metav1.StatusFailure,
Reason: metav1.StatusReasonNotFound,
Message: " \"\" not found",
Details: &metav1.StatusDetails{},
}
}
func newResponse(code int, obj runtime.Object) (*http.Response, error) {
header := http.Header{}
header.Set("Content-Type", runtime.ContentTypeJSON)
body := io.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(codec, obj))))
return &http.Response{StatusCode: code, Header: header, Body: body}, nil
}
func newResponseJSON(code int, json []byte) (*http.Response, error) {
header := http.Header{}
header.Set("Content-Type", runtime.ContentTypeJSON)
body := io.NopCloser(bytes.NewReader(json))
return &http.Response{StatusCode: code, Header: header, Body: body}, nil
}
func newTestClient(t *testing.T) *Client {
t.Helper()
testFactory := cmdtesting.NewTestFactory()
t.Cleanup(testFactory.Cleanup)
return &Client{
Factory: testFactory.WithNamespace(v1.NamespaceDefault),
}
}
type RequestResponseAction struct {
Request http.Request
Response http.Response
Error error
}
type RoundTripperTestFunc func(previous []RequestResponseAction, req *http.Request) (*http.Response, error)
func NewRequestResponseLogClient(t *testing.T, cb RoundTripperTestFunc) RequestResponseLogClient {
t.Helper()
return RequestResponseLogClient{
t: t,
cb: cb,
}
}
// RequestResponseLogClient is a test client that logs requests and responses
// Satisfying http.RoundTripper interface, it can be used to mock HTTP requests in tests.
// Forwarding requests to a callback function (cb) that can be used to simulate server responses.
type RequestResponseLogClient struct {
t *testing.T
cb RoundTripperTestFunc
actionsLock sync.Mutex
Actions []RequestResponseAction
}
func (r *RequestResponseLogClient) Do(req *http.Request) (*http.Response, error) {
t := r.t
t.Helper()
readBodyBytes := func(body io.ReadCloser) []byte {
if body == nil {
return []byte{}
}
defer body.Close()
bodyBytes, err := io.ReadAll(body)
require.NoError(t, err)
return bodyBytes
}
reqBytes := readBodyBytes(req.Body)
t.Logf("Request: %s %s %s", req.Method, req.URL.String(), reqBytes)
if req.Body != nil {
req.Body = io.NopCloser(bytes.NewReader(reqBytes))
}
resp, err := r.cb(r.Actions, req)
respBytes := readBodyBytes(resp.Body)
t.Logf("Response: %d %s", resp.StatusCode, string(respBytes))
if resp.Body != nil {
resp.Body = io.NopCloser(bytes.NewReader(respBytes))
}
r.actionsLock.Lock()
defer r.actionsLock.Unlock()
r.Actions = append(r.Actions, RequestResponseAction{
Request: *req,
Response: *resp,
Error: err,
})
return resp, err
}
func TestCreate(t *testing.T) {
// Note: c.Create with the fake client can currently only test creation of a single pod/object in the same list. When testing
// with more than one pod, c.Create will run into a data race as it calls perform->batchPerform which performs creation
// in batches. The race is something in the fake client itself in `func (c *RESTClient) do(...)`
// when it stores the req: c.Req = req and cannot (?) be fixed easily.
type testCase struct {
Name string
Pods v1.PodList
Callback func(t *testing.T, tc testCase, previous []RequestResponseAction, req *http.Request) (*http.Response, error)
ServerSideApply bool
ExpectedActions []string
ExpectedErrorContains string
}
testCases := map[string]testCase{
"Create success (client-side apply)": {
Pods: newPodList("starfish"),
ServerSideApply: false,
Callback: func(t *testing.T, tc testCase, previous []RequestResponseAction, _ *http.Request) (*http.Response, error) {
t.Helper()
if len(previous) < 2 { // simulate a conflict
return newResponseJSON(http.StatusConflict, resourceQuotaConflict)
}
return newResponse(http.StatusOK, &tc.Pods.Items[0])
},
ExpectedActions: []string{
"/namespaces/default/pods:POST",
"/namespaces/default/pods:POST",
"/namespaces/default/pods:POST",
},
},
"Create success (server-side apply)": {
Pods: newPodList("whale"),
ServerSideApply: true,
Callback: func(t *testing.T, tc testCase, _ []RequestResponseAction, _ *http.Request) (*http.Response, error) {
t.Helper()
return newResponse(http.StatusOK, &tc.Pods.Items[0])
},
ExpectedActions: []string{
"/namespaces/default/pods/whale:PATCH",
},
},
"Create fail: incompatible server (server-side apply)": {
Pods: newPodList("lobster"),
ServerSideApply: true,
Callback: func(t *testing.T, _ testCase, _ []RequestResponseAction, req *http.Request) (*http.Response, error) {
t.Helper()
return &http.Response{
StatusCode: http.StatusUnsupportedMediaType,
Request: req,
}, nil
},
ExpectedErrorContains: "server-side apply not available on the server:",
ExpectedActions: []string{
"/namespaces/default/pods/lobster:PATCH",
},
},
"Create fail: quota (server-side apply)": {
Pods: newPodList("dolphin"),
ServerSideApply: true,
Callback: func(t *testing.T, _ testCase, _ []RequestResponseAction, _ *http.Request) (*http.Response, error) {
t.Helper()
return newResponseJSON(http.StatusConflict, resourceQuotaConflict)
},
ExpectedErrorContains: "Operation cannot be fulfilled on resourcequotas \"quota\": the object has been modified; " +
"please apply your changes to the latest version and try again",
ExpectedActions: []string{
"/namespaces/default/pods/dolphin:PATCH",
},
},
}
c := newTestClient(t)
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
client := NewRequestResponseLogClient(t, func(previous []RequestResponseAction, req *http.Request) (*http.Response, error) {
return tc.Callback(t, tc, previous, req)
})
c.Factory.(*cmdtesting.TestFactory).UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(client.Do),
}
list, err := c.Build(objBody(&tc.Pods), false)
require.NoError(t, err)
if err != nil {
t.Fatal(err)
}
result, err := c.Create(
list,
ClientCreateOptionServerSideApply(tc.ServerSideApply, false))
if tc.ExpectedErrorContains != "" {
require.ErrorContains(t, err, tc.ExpectedErrorContains)
} else {
require.NoError(t, err)
// See note above about limitations in supporting more than a single object
assert.Len(t, result.Created, 1, "expected 1 object created, got %d", len(result.Created))
}
actions := []string{}
for _, action := range client.Actions {
path, method := action.Request.URL.Path, action.Request.Method
actions = append(actions, path+":"+method)
}
assert.Equal(t, tc.ExpectedActions, actions)
})
}
}
func TestUpdate(t *testing.T) {
type testCase struct {
OriginalPods v1.PodList
TargetPods v1.PodList
ThreeWayMergeForUnstructured bool
ServerSideApply bool
ExpectedActions []string
ExpectedError string
}
expectedActionsClientSideApply := []string{
"/namespaces/default/pods/starfish:GET",
"/namespaces/default/pods/starfish:GET",
"/namespaces/default/pods/starfish:PATCH",
"/namespaces/default/pods/otter:GET",
"/namespaces/default/pods/otter:GET",
"/namespaces/default/pods/otter:GET",
"/namespaces/default/pods/dolphin:GET",
"/namespaces/default/pods:POST", // create dolphin
"/namespaces/default/pods:POST", // retry due to 409
"/namespaces/default/pods:POST", // retry due to 409
"/namespaces/default/pods/squid:GET",
"/namespaces/default/pods/squid:DELETE",
"/namespaces/default/pods/notfound:GET",
"/namespaces/default/pods/notfound:DELETE",
}
expectedActionsServerSideApply := []string{
"/namespaces/default/pods/starfish:GET",
"/namespaces/default/pods/starfish:GET",
"/namespaces/default/pods/starfish:PATCH",
"/namespaces/default/pods/otter:GET",
"/namespaces/default/pods/otter:GET",
"/namespaces/default/pods/otter:PATCH",
"/namespaces/default/pods/dolphin:GET",
"/namespaces/default/pods/dolphin:PATCH", // create dolphin
"/namespaces/default/pods/squid:GET",
"/namespaces/default/pods/squid:DELETE",
"/namespaces/default/pods/notfound:GET",
"/namespaces/default/pods/notfound:DELETE",
}
testCases := map[string]testCase{
"client-side apply": {
OriginalPods: newPodList("starfish", "otter", "squid", "notfound"),
TargetPods: func() v1.PodList {
listTarget := newPodList("starfish", "otter", "dolphin")
listTarget.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}
return listTarget
}(),
ThreeWayMergeForUnstructured: false,
ServerSideApply: false,
ExpectedActions: expectedActionsClientSideApply,
ExpectedError: "",
},
"client-side apply (three-way merge for unstructured)": {
OriginalPods: newPodList("starfish", "otter", "squid", "notfound"),
TargetPods: func() v1.PodList {
listTarget := newPodList("starfish", "otter", "dolphin")
listTarget.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}
return listTarget
}(),
ThreeWayMergeForUnstructured: true,
ServerSideApply: false,
ExpectedActions: expectedActionsClientSideApply,
ExpectedError: "",
},
"serverSideApply": {
OriginalPods: newPodList("starfish", "otter", "squid", "notfound"),
TargetPods: func() v1.PodList {
listTarget := newPodList("starfish", "otter", "dolphin")
listTarget.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}
return listTarget
}(),
ThreeWayMergeForUnstructured: false,
ServerSideApply: true,
ExpectedActions: expectedActionsServerSideApply,
ExpectedError: "",
},
"serverSideApply with forbidden deletion": {
OriginalPods: newPodList("starfish", "otter", "squid", "notfound", "forbidden"),
TargetPods: func() v1.PodList {
listTarget := newPodList("starfish", "otter", "dolphin")
listTarget.Items[0].Spec.Containers[0].Ports = []v1.ContainerPort{{Name: "https", ContainerPort: 443}}
return listTarget
}(),
ThreeWayMergeForUnstructured: false,
ServerSideApply: true,
ExpectedActions: append(expectedActionsServerSideApply,
"/namespaces/default/pods/forbidden:GET",
"/namespaces/default/pods/forbidden:DELETE",
),
ExpectedError: "failed to delete resource forbidden:",
},
}
c := newTestClient(t)
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
listOriginal := tc.OriginalPods
listTarget := tc.TargetPods
iterationCounter := 0
cb := func(_ []RequestResponseAction, req *http.Request) (*http.Response, error) {
p, m := req.URL.Path, req.Method
switch {
case p == "/namespaces/default/pods/starfish" && m == http.MethodGet:
return newResponse(http.StatusOK, &listOriginal.Items[0])
case p == "/namespaces/default/pods/otter" && m == http.MethodGet:
return newResponse(http.StatusOK, &listOriginal.Items[1])
case p == "/namespaces/default/pods/otter" && m == http.MethodPatch:
if !tc.ServerSideApply {
defer req.Body.Close()
data, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Equal(t, `{}`, string(data))
}
return newResponse(http.StatusOK, &listTarget.Items[0])
case p == "/namespaces/default/pods/dolphin" && m == http.MethodGet:
return newResponse(http.StatusNotFound, notFoundBody())
case p == "/namespaces/default/pods/starfish" && m == http.MethodPatch:
if !tc.ServerSideApply {
// Ensure client-side apply specifies correct patch
defer req.Body.Close()
data, err := io.ReadAll(req.Body)
require.NoError(t, err)
expected := `{"spec":{"$setElementOrder/containers":[{"name":"app:v4"}],"containers":[{"$setElementOrder/ports":[{"containerPort":443}],"name":"app:v4","ports":[{"containerPort":443,"name":"https"},{"$patch":"delete","containerPort":80}]}]}}`
assert.Equal(t, expected, string(data))
}
return newResponse(http.StatusOK, &listTarget.Items[0])
case p == "/namespaces/default/pods" && m == http.MethodPost:
if iterationCounter < 2 {
iterationCounter++
return newResponseJSON(http.StatusConflict, resourceQuotaConflict)
}
return newResponse(http.StatusOK, &listTarget.Items[1])
case p == "/namespaces/default/pods/dolphin" && m == http.MethodPatch:
return newResponse(http.StatusOK, &listTarget.Items[1])
case p == "/namespaces/default/pods/squid" && m == http.MethodDelete:
return newResponse(http.StatusOK, &listTarget.Items[1])
case p == "/namespaces/default/pods/squid" && m == http.MethodGet:
return newResponse(http.StatusOK, &listTarget.Items[2])
case p == "/namespaces/default/pods/notfound" && m == http.MethodGet:
// Resource exists in original but will simulate not found on delete
return newResponse(http.StatusOK, &listOriginal.Items[3])
case p == "/namespaces/default/pods/notfound" && m == http.MethodDelete:
// Simulate a not found during deletion; should not cause update to fail
return newResponse(http.StatusNotFound, notFoundBody())
case p == "/namespaces/default/pods/forbidden" && m == http.MethodGet:
return newResponse(http.StatusOK, &listOriginal.Items[4])
case p == "/namespaces/default/pods/forbidden" && m == http.MethodDelete:
// Simulate RBAC forbidden that should cause update to fail
return newResponse(http.StatusForbidden, &metav1.Status{
Status: metav1.StatusFailure,
Message: "pods \"forbidden\" is forbidden: User \"test-user\" cannot delete resource \"pods\" in API group \"\" in the namespace \"default\"",
Reason: metav1.StatusReasonForbidden,
Code: http.StatusForbidden,
})
}
t.FailNow()
return nil, nil
}
client := NewRequestResponseLogClient(t, cb)
c.Factory.(*cmdtesting.TestFactory).UnstructuredClient = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(client.Do),
}
first, err := c.Build(objBody(&listOriginal), false)
require.NoError(t, err)
second, err := c.Build(objBody(&listTarget), false)
require.NoError(t, err)
result, err := c.Update(
first,
second,
ClientUpdateOptionThreeWayMergeForUnstructured(tc.ThreeWayMergeForUnstructured),
ClientUpdateOptionForceReplace(false),
ClientUpdateOptionServerSideApply(tc.ServerSideApply, false),
ClientUpdateOptionUpgradeClientSideFieldManager(true))
if tc.ExpectedError != "" {
require.Error(t, err)
require.Contains(t, err.Error(), tc.ExpectedError)
} else {
require.NoError(t, err)
}
assert.Len(t, result.Created, 1, "expected 1 resource created, got %d", len(result.Created))
assert.Len(t, result.Updated, 2, "expected 2 resource updated, got %d", len(result.Updated))
assert.Len(t, result.Deleted, 1, "expected 1 resource deleted, got %d", len(result.Deleted))
actions := []string{}
for _, action := range client.Actions {
path, method := action.Request.URL.Path, action.Request.Method
actions = append(actions, path+":"+method)
}
assert.Equal(t, tc.ExpectedActions, actions)
})
}
}
func TestBuild(t *testing.T) {
tests := []struct {
name string
namespace string
reader io.Reader
count int
err bool
}{
{
name: "Valid input",
namespace: "test",
reader: strings.NewReader(guestbookManifest),
count: 6,
}, {
name: "Valid input, deploying resources into different namespaces",
namespace: "test",
reader: strings.NewReader(namespacedGuestbookManifest),
count: 1,
},
}
c := newTestClient(t)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test for an invalid manifest
infos, err := c.Build(tt.reader, false)
if err != nil && !tt.err {
t.Errorf("Got error message when no error should have occurred: %v", err)
} else if err != nil && strings.Contains(err.Error(), "--validate=false") {
t.Error("error message was not scrubbed")
}
if len(infos) != tt.count {
t.Errorf("expected %d result objects, got %d", tt.count, len(infos))
}
})
}
}
func TestBuildTable(t *testing.T) {
tests := []struct {
name string
namespace string
reader io.Reader
count int
err bool
}{
{
name: "Valid input",
namespace: "test",
reader: strings.NewReader(guestbookManifest),
count: 6,
}, {
name: "Valid input, deploying resources into different namespaces",
namespace: "test",
reader: strings.NewReader(namespacedGuestbookManifest),
count: 1,
},
}
c := newTestClient(t)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Test for an invalid manifest
infos, err := c.BuildTable(tt.reader, false)
if err != nil && !tt.err {
t.Errorf("Got error message when no error should have occurred: %v", err)
} else if err != nil && strings.Contains(err.Error(), "--validate=false") {
t.Error("error message was not scrubbed")
}
if len(infos) != tt.count {
t.Errorf("expected %d result objects, got %d", tt.count, len(infos))
}
})
}
}
func TestPerform(t *testing.T) {
tests := []struct {
name string
reader io.Reader
count int
err bool
errMessage string
}{
{
name: "Valid input",
reader: strings.NewReader(guestbookManifest),
count: 6,
}, {
name: "Empty manifests",
reader: strings.NewReader(""),
err: true,
errMessage: "no objects visited",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
results := []*resource.Info{}
fn := func(info *resource.Info) error {
results = append(results, info)
return nil
}
c := newTestClient(t)
infos, err := c.Build(tt.reader, false)
if err != nil && err.Error() != tt.errMessage {
t.Errorf("Error while building manifests: %v", err)
}
err = perform(infos, fn)
if (err != nil) != tt.err {
t.Errorf("expected error: %v, got %v", tt.err, err)
}
if err != nil && err.Error() != tt.errMessage {
t.Errorf("expected error message: %v, got %v", tt.errMessage, err)
}
if len(results) != tt.count {
t.Errorf("expected %d result objects, got %d", tt.count, len(results))
}
})
}
}
func TestWait(t *testing.T) {
podList := newPodList("starfish", "otter", "squid")
var created *time.Time
c := newTestClient(t)
c.Factory.(*cmdtesting.TestFactory).Client = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
p, m := req.URL.Path, req.Method
t.Logf("got request %s %s", p, m)
switch {
case p == "/api/v1/namespaces/default/pods/starfish" && m == http.MethodGet:
pod := &podList.Items[0]
if created != nil && time.Since(*created) >= time.Second*5 {
pod.Status.Conditions = []v1.PodCondition{
{
Type: v1.PodReady,
Status: v1.ConditionTrue,
},
}
}
return newResponse(http.StatusOK, pod)
case p == "/api/v1/namespaces/default/pods/otter" && m == http.MethodGet:
pod := &podList.Items[1]
if created != nil && time.Since(*created) >= time.Second*5 {
pod.Status.Conditions = []v1.PodCondition{
{
Type: v1.PodReady,
Status: v1.ConditionTrue,
},
}
}
return newResponse(http.StatusOK, pod)
case p == "/api/v1/namespaces/default/pods/squid" && m == http.MethodGet:
pod := &podList.Items[2]
if created != nil && time.Since(*created) >= time.Second*5 {
pod.Status.Conditions = []v1.PodCondition{
{
Type: v1.PodReady,
Status: v1.ConditionTrue,
},
}
}
return newResponse(http.StatusOK, pod)
case p == "/namespaces/default/pods" && m == http.MethodPost:
resources, err := c.Build(req.Body, false)
if err != nil {
t.Fatal(err)
}
now := time.Now()
created = &now
return newResponse(http.StatusOK, resources[0].Object)
default:
t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
return nil, nil
}
}),
}
var err error
c.Waiter, err = c.GetWaiter(LegacyStrategy)
if err != nil {
t.Fatal(err)
}
resources, err := c.Build(objBody(&podList), false)
if err != nil {
t.Fatal(err)
}
result, err := c.Create(
resources,
ClientCreateOptionServerSideApply(false, false))
if err != nil {
t.Fatal(err)
}
if len(result.Created) != 3 {
t.Errorf("expected 3 resource created, got %d", len(result.Created))
}
if err := c.Wait(resources, time.Second*30); err != nil {
t.Errorf("expected wait without error, got %s", err)
}
if time.Since(*created) < time.Second*5 {
t.Errorf("expected to wait at least 5 seconds before ready status was detected, but got %s", time.Since(*created))
}
}
func TestWaitJob(t *testing.T) {
job := newJob("starfish", 0, intToInt32(1), 0, 0)
var created *time.Time
c := newTestClient(t)
c.Factory.(*cmdtesting.TestFactory).Client = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
p, m := req.URL.Path, req.Method
t.Logf("got request %s %s", p, m)
switch {
case p == "/apis/batch/v1/namespaces/default/jobs/starfish" && m == http.MethodGet:
if created != nil && time.Since(*created) >= time.Second*5 {
job.Status.Succeeded = 1
}
return newResponse(http.StatusOK, job)
case p == "/namespaces/default/jobs" && m == http.MethodPost:
resources, err := c.Build(req.Body, false)
if err != nil {
t.Fatal(err)
}
now := time.Now()
created = &now
return newResponse(http.StatusOK, resources[0].Object)
default:
t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
return nil, nil
}
}),
}
var err error
c.Waiter, err = c.GetWaiter(LegacyStrategy)
if err != nil {
t.Fatal(err)
}
resources, err := c.Build(objBody(job), false)
if err != nil {
t.Fatal(err)
}
result, err := c.Create(
resources,
ClientCreateOptionServerSideApply(false, false))
if err != nil {
t.Fatal(err)
}
if len(result.Created) != 1 {
t.Errorf("expected 1 resource created, got %d", len(result.Created))
}
if err := c.WaitWithJobs(resources, time.Second*30); err != nil {
t.Errorf("expected wait without error, got %s", err)
}
if time.Since(*created) < time.Second*5 {
t.Errorf("expected to wait at least 5 seconds before ready status was detected, but got %s", time.Since(*created))
}
}
func TestWaitDelete(t *testing.T) {
pod := newPod("starfish")
var deleted *time.Time
c := newTestClient(t)
c.Factory.(*cmdtesting.TestFactory).Client = &fake.RESTClient{
NegotiatedSerializer: unstructuredSerializer,
Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
p, m := req.URL.Path, req.Method
t.Logf("got request %s %s", p, m)
switch {
case p == "/namespaces/default/pods/starfish" && m == http.MethodGet:
if deleted != nil && time.Since(*deleted) >= time.Second*5 {
return newResponse(http.StatusNotFound, notFoundBody())
}
return newResponse(http.StatusOK, &pod)
case p == "/namespaces/default/pods/starfish" && m == http.MethodDelete:
now := time.Now()
deleted = &now
return newResponse(http.StatusOK, &pod)
case p == "/namespaces/default/pods" && m == http.MethodPost:
resources, err := c.Build(req.Body, false)
if err != nil {
t.Fatal(err)
}
return newResponse(http.StatusOK, resources[0].Object)
default:
t.Fatalf("unexpected request: %s %s", req.Method, req.URL.Path)
return nil, nil
}
}),
}
var err error
c.Waiter, err = c.GetWaiter(LegacyStrategy)
if err != nil {
t.Fatal(err)
}
resources, err := c.Build(objBody(&pod), false)
if err != nil {
t.Fatal(err)
}
result, err := c.Create(
resources,
ClientCreateOptionServerSideApply(false, false))
if err != nil {
t.Fatal(err)
}
if len(result.Created) != 1 {
t.Errorf("expected 1 resource created, got %d", len(result.Created))
}
if _, err := c.Delete(resources, metav1.DeletePropagationBackground); err != nil {
t.Fatal(err)
}
if err := c.WaitForDelete(resources, time.Second*30); err != nil {
t.Errorf("expected wait without error, got %s", err)
}
if time.Since(*deleted) < time.Second*5 {
t.Errorf("expected to wait at least 5 seconds before ready status was detected, but got %s", time.Since(*deleted))
}
}
func TestReal(t *testing.T) {
t.Skip("This is a live test, comment this line to run")
c := New(nil)
resources, err := c.Build(strings.NewReader(guestbookManifest), false)
if err != nil {
t.Fatal(err)
}
if _, err := c.Create(resources); err != nil {
t.Fatal(err)
}
testSvcEndpointManifest := testServiceManifest + "\n---\n" + testEndpointManifest
c = New(nil)
resources, err = c.Build(strings.NewReader(testSvcEndpointManifest), false)
if err != nil {
t.Fatal(err)
}
if _, err := c.Create(resources); err != nil {
t.Fatal(err)
}
resources, err = c.Build(strings.NewReader(testEndpointManifest), false)
if err != nil {
t.Fatal(err)
}
if _, errs := c.Delete(resources, metav1.DeletePropagationBackground); errs != nil {
t.Fatal(errs)
}
resources, err = c.Build(strings.NewReader(testSvcEndpointManifest), false)
if err != nil {
t.Fatal(err)
}
// ensures that delete does not fail if a resource is not found
if _, errs := c.Delete(resources, metav1.DeletePropagationBackground); errs != nil {
t.Fatal(errs)
}
}
func TestGetPodList(t *testing.T) {
namespace := "some-namespace"
names := []string{"dave", "jimmy"}
var responsePodList v1.PodList
for _, name := range names {
responsePodList.Items = append(responsePodList.Items, newPodWithStatus(name, v1.PodStatus{}, namespace))
}
kubeClient := k8sfake.NewClientset(&responsePodList)
c := Client{Namespace: namespace, kubeClient: kubeClient}
podList, err := c.GetPodList(namespace, metav1.ListOptions{})
clientAssertions := assert.New(t)
clientAssertions.NoError(err)
clientAssertions.Equal(&responsePodList, podList)
}
func TestOutputContainerLogsForPodList(t *testing.T) {
namespace := "some-namespace"
somePodList := newPodList("jimmy", "three", "structs")
kubeClient := k8sfake.NewClientset(&somePodList)
c := Client{Namespace: namespace, kubeClient: kubeClient}
outBuffer := &bytes.Buffer{}
outBufferFunc := func(_, _, _ string) io.Writer { return outBuffer }
err := c.OutputContainerLogsForPodList(&somePodList, namespace, outBufferFunc)
clientAssertions := assert.New(t)
clientAssertions.NoError(err)
clientAssertions.Equal("fake logsfake logsfake logs", outBuffer.String())
}
const testServiceManifest = `
kind: Service
apiVersion: v1
metadata:
name: my-service
spec:
selector:
app: myapp
ports:
- port: 80
protocol: TCP
targetPort: 9376
`
const testEndpointManifest = `
kind: Endpoints
apiVersion: v1
metadata:
name: my-service
subsets:
- addresses:
- ip: "1.2.3.4"
ports:
- port: 9376
`
const guestbookManifest = `
apiVersion: v1
kind: Service
metadata:
name: redis-master
labels:
app: redis
tier: backend
role: master
spec:
ports:
- port: 6379
targetPort: 6379
selector:
app: redis
tier: backend
role: master
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: redis-master
spec:
replicas: 1
template:
metadata:
labels:
app: redis
role: master
tier: backend
spec:
containers:
- name: master
image: registry.k8s.io/redis:e2e # or just image: redis
resources:
requests:
cpu: 100m
memory: 100Mi
ports:
- containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
name: redis-replica
labels:
app: redis
tier: backend
role: replica
spec:
ports:
# the port that this service should serve on
- port: 6379
selector:
app: redis
tier: backend
role: replica
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: redis-replica
spec:
replicas: 2
template:
metadata:
labels:
app: redis
role: replica
tier: backend
spec:
containers:
- name: replica
image: gcr.io/google_samples/gb-redisreplica:v1
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
name: frontend
labels:
app: guestbook
tier: frontend
spec:
ports:
- port: 80
selector:
app: guestbook
tier: frontend
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: frontend
spec:
replicas: 3
template:
metadata:
labels:
app: guestbook
tier: frontend
spec:
containers:
- name: php-redis
image: gcr.io/google-samples/gb-frontend:v4
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 80
`
const namespacedGuestbookManifest = `
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: frontend
namespace: guestbook
spec:
replicas: 3
template:
metadata:
labels:
app: guestbook
tier: frontend
spec:
containers:
- name: php-redis
image: gcr.io/google-samples/gb-frontend:v4
resources:
requests:
cpu: 100m
memory: 100Mi
env:
- name: GET_HOSTS_FROM
value: dns
ports:
- containerPort: 80
`
var resourceQuotaConflict = []byte(`
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | true |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/roundtripper.go | pkg/kube/roundtripper.go | /*
Copyright The Helm 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 kube
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strings"
)
type RetryingRoundTripper struct {
Wrapped http.RoundTripper
}
func (rt *RetryingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
return rt.roundTrip(req, 1, nil)
}
func (rt *RetryingRoundTripper) roundTrip(req *http.Request, retry int, prevResp *http.Response) (*http.Response, error) {
if retry < 0 {
return prevResp, nil
}
resp, rtErr := rt.Wrapped.RoundTrip(req)
if rtErr != nil {
return resp, rtErr
}
if resp.StatusCode < 500 {
return resp, rtErr
}
if resp.Header.Get("content-type") != "application/json" {
return resp, rtErr
}
b, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return resp, err
}
var ke kubernetesError
r := bytes.NewReader(b)
err = json.NewDecoder(r).Decode(&ke)
r.Seek(0, io.SeekStart)
resp.Body = io.NopCloser(r)
if err != nil {
return resp, err
}
if ke.Code < 500 {
return resp, nil
}
// Matches messages like "etcdserver: leader changed"
if strings.HasSuffix(ke.Message, "etcdserver: leader changed") {
return rt.roundTrip(req, retry-1, resp)
}
// Matches messages like "rpc error: code = Unknown desc = raft proposal dropped"
if strings.HasSuffix(ke.Message, "raft proposal dropped") {
return rt.roundTrip(req, retry-1, resp)
}
return resp, nil
}
type kubernetesError struct {
Message string `json:"message"`
Code int `json:"code"`
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/resource_test.go | pkg/kube/resource_test.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"testing"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource"
)
func TestResourceList(t *testing.T) {
mapping := &meta.RESTMapping{
Resource: schema.GroupVersionResource{Group: "group", Version: "version", Resource: "pod"},
}
info := func(name string) *resource.Info {
return &resource.Info{Name: name, Mapping: mapping}
}
var r1, r2 ResourceList
r1 = []*resource.Info{info("foo"), info("bar")}
r2 = []*resource.Info{info("bar")}
if r1.Get(info("bar")).Mapping.Resource.Resource != "pod" {
t.Error("expected get pod")
}
diff := r1.Difference(r2)
if len(diff) != 1 {
t.Error("expected 1 result")
}
if !diff.Contains(info("foo")) {
t.Error("expected diff to return foo")
}
inter := r1.Intersect(r2)
if len(inter) != 1 {
t.Error("expected 1 result")
}
if !inter.Contains(info("bar")) {
t.Error("expected intersect to return bar")
}
}
func TestIsMatchingInfo(t *testing.T) {
gvk := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "pod"}
resourceInfo := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}}
gvkDiffGroup := schema.GroupVersionKind{Group: "diff", Version: "version1", Kind: "pod"}
resourceInfoDiffGroup := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffGroup}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffGroup) {
t.Error("expected resources not equal")
}
gvkDiffVersion := schema.GroupVersionKind{Group: "group1", Version: "diff", Kind: "pod"}
resourceInfoDiffVersion := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffVersion}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffVersion) {
t.Error("expected resources not equal")
}
gvkDiffKind := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "deployment"}
resourceInfoDiffKind := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkDiffKind}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffKind) {
t.Error("expected resources not equal")
}
resourceInfoDiffName := resource.Info{Name: "diff", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffName) {
t.Error("expected resources not equal")
}
resourceInfoDiffNamespace := resource.Info{Name: "name1", Namespace: "diff", Mapping: &meta.RESTMapping{GroupVersionKind: gvk}}
if isMatchingInfo(&resourceInfo, &resourceInfoDiffNamespace) {
t.Error("expected resources not equal")
}
gvkEqual := schema.GroupVersionKind{Group: "group1", Version: "version1", Kind: "pod"}
resourceInfoEqual := resource.Info{Name: "name1", Namespace: "namespace1", Mapping: &meta.RESTMapping{GroupVersionKind: gvkEqual}}
if !isMatchingInfo(&resourceInfo, &resourceInfoEqual) {
t.Error("expected resources to be equal")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/factory.go | pkg/kube/factory.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/kubectl/pkg/validation"
)
// Factory provides abstractions that allow the Kubectl command to be extended across multiple types
// of resources and different API sets.
// This interface is a minimal copy of the kubectl Factory interface containing only the functions
// needed by Helm. Since Kubernetes Go APIs, including interfaces, can change in any minor release
// this interface is not covered by the Helm backwards compatibility guarantee. The reasons for the
// minimal copy is that it does not include the full interface. Changes or additions to functions
// Helm does not need are not impacted or exposed. This minimizes the impact of Kubernetes changes
// being exposed.
type Factory interface {
// ToRESTConfig returns restconfig
ToRESTConfig() (*rest.Config, error)
// ToRawKubeConfigLoader return kubeconfig loader as-is
ToRawKubeConfigLoader() clientcmd.ClientConfig
// DynamicClient returns a dynamic client ready for use
DynamicClient() (dynamic.Interface, error)
// KubernetesClientSet gives you back an external clientset
KubernetesClientSet() (*kubernetes.Clientset, error)
// NewBuilder returns an object that assists in loading objects from both disk and the server
// and which implements the common patterns for CLI interactions with generic resources.
NewBuilder() *resource.Builder
// Returns a schema that can validate objects stored on disk.
Validator(validationDirective string) (validation.Schema, error)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/resource.go | pkg/kube/resource.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import "k8s.io/cli-runtime/pkg/resource"
// ResourceList provides convenience methods for comparing collections of Infos.
type ResourceList []*resource.Info
// Append adds an Info to the Result.
func (r *ResourceList) Append(val *resource.Info) {
*r = append(*r, val)
}
// Visit implements resource.Visitor. The visitor stops if fn returns an error.
func (r ResourceList) Visit(fn resource.VisitorFunc) error {
for _, i := range r {
if err := fn(i, nil); err != nil {
return err
}
}
return nil
}
// Filter returns a new Result with Infos that satisfy the predicate fn.
func (r ResourceList) Filter(fn func(*resource.Info) bool) ResourceList {
var result ResourceList
for _, i := range r {
if fn(i) {
result.Append(i)
}
}
return result
}
// Get returns the Info from the result that matches the name and kind.
func (r ResourceList) Get(info *resource.Info) *resource.Info {
for _, i := range r {
if isMatchingInfo(i, info) {
return i
}
}
return nil
}
// Contains checks to see if an object exists.
func (r ResourceList) Contains(info *resource.Info) bool {
for _, i := range r {
if isMatchingInfo(i, info) {
return true
}
}
return false
}
// Difference will return a new Result with objects not contained in rs.
func (r ResourceList) Difference(rs ResourceList) ResourceList {
return r.Filter(func(info *resource.Info) bool {
return !rs.Contains(info)
})
}
// Intersect will return a new Result with objects contained in both Results.
func (r ResourceList) Intersect(rs ResourceList) ResourceList {
return r.Filter(rs.Contains)
}
// isMatchingInfo returns true if infos match on Name and GroupVersionKind.
func isMatchingInfo(a, b *resource.Info) bool {
return a.Name == b.Name && a.Namespace == b.Namespace && a.Mapping.GroupVersionKind == b.Mapping.GroupVersionKind
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/ready_test.go | pkg/kube/ready_test.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"context"
"testing"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/fake"
)
const defaultNamespace = metav1.NamespaceDefault
func Test_ReadyChecker_IsReady_Pod(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
pod *corev1.Pod
want bool
wantErr bool
}{
{
name: "IsReady Pod",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.Pod{}, Name: "foo", Namespace: defaultNamespace},
},
pod: newPodWithCondition("foo", corev1.ConditionTrue),
want: true,
wantErr: false,
},
{
name: "IsReady Pod returns error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.Pod{}, Name: "foo", Namespace: defaultNamespace},
},
pod: newPodWithCondition("bar", corev1.ConditionTrue),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(t.Context(), tt.pod, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create Pod error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_Job(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
job *batchv1.Job
want bool
wantErr bool
}{
{
name: "IsReady Job error while getting job",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &batchv1.Job{}, Name: "foo", Namespace: defaultNamespace},
},
job: newJob("bar", 1, intToInt32(1), 1, 0),
want: false,
wantErr: true,
},
{
name: "IsReady Job",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &batchv1.Job{}, Name: "foo", Namespace: defaultNamespace},
},
job: newJob("foo", 1, intToInt32(1), 1, 0),
want: true,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.BatchV1().Jobs(defaultNamespace).Create(t.Context(), tt.job, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create Job error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_Deployment(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
replicaSet *appsv1.ReplicaSet
deployment *appsv1.Deployment
want bool
wantErr bool
}{
{
name: "IsReady Deployments error while getting current Deployment",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.Deployment{}, Name: "foo", Namespace: defaultNamespace},
},
replicaSet: newReplicaSet("foo", 0, 0, true),
deployment: newDeployment("bar", 1, 1, 0, true),
want: false,
wantErr: true,
},
{
name: "IsReady Deployments", //TODO fix this one
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.Deployment{}, Name: "foo", Namespace: defaultNamespace},
},
replicaSet: newReplicaSet("foo", 0, 0, true),
deployment: newDeployment("foo", 1, 1, 0, true),
want: false,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.AppsV1().Deployments(defaultNamespace).Create(t.Context(), tt.deployment, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create Deployment error: %v", err)
return
}
if _, err := c.client.AppsV1().ReplicaSets(defaultNamespace).Create(t.Context(), tt.replicaSet, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create ReplicaSet error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_PersistentVolumeClaim(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
pvc *corev1.PersistentVolumeClaim
want bool
wantErr bool
}{
{
name: "IsReady PersistentVolumeClaim",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.PersistentVolumeClaim{}, Name: "foo", Namespace: defaultNamespace},
},
pvc: newPersistentVolumeClaim("foo", corev1.ClaimPending),
want: false,
wantErr: false,
},
{
name: "IsReady PersistentVolumeClaim with error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.PersistentVolumeClaim{}, Name: "foo", Namespace: defaultNamespace},
},
pvc: newPersistentVolumeClaim("bar", corev1.ClaimPending),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.CoreV1().PersistentVolumeClaims(defaultNamespace).Create(t.Context(), tt.pvc, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create PersistentVolumeClaim error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_Service(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
svc *corev1.Service
want bool
wantErr bool
}{
{
name: "IsReady Service",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.Service{}, Name: "foo", Namespace: defaultNamespace},
},
svc: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, ClusterIP: ""}),
want: false,
wantErr: false,
},
{
name: "IsReady Service with error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.Service{}, Name: "foo", Namespace: defaultNamespace},
},
svc: newService("bar", corev1.ServiceSpec{Type: corev1.ServiceTypeExternalName, ClusterIP: ""}),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.CoreV1().Services(defaultNamespace).Create(t.Context(), tt.svc, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create Service error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_DaemonSet(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
ds *appsv1.DaemonSet
want bool
wantErr bool
}{
{
name: "IsReady DaemonSet",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.DaemonSet{}, Name: "foo", Namespace: defaultNamespace},
},
ds: newDaemonSet("foo", 0, 0, 1, 0, true),
want: false,
wantErr: false,
},
{
name: "IsReady DaemonSet with error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.DaemonSet{}, Name: "foo", Namespace: defaultNamespace},
},
ds: newDaemonSet("bar", 0, 1, 1, 1, true),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.AppsV1().DaemonSets(defaultNamespace).Create(t.Context(), tt.ds, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create DaemonSet error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_StatefulSet(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
ss *appsv1.StatefulSet
want bool
wantErr bool
}{
{
name: "IsReady StatefulSet",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.StatefulSet{}, Name: "foo", Namespace: defaultNamespace},
},
ss: newStatefulSet("foo", 1, 0, 0, 1, true),
want: false,
wantErr: false,
},
{
name: "IsReady StatefulSet with error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.StatefulSet{}, Name: "foo", Namespace: defaultNamespace},
},
ss: newStatefulSet("bar", 1, 0, 1, 1, true),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.AppsV1().StatefulSets(defaultNamespace).Create(t.Context(), tt.ss, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create StatefulSet error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_ReplicationController(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
rc *corev1.ReplicationController
want bool
wantErr bool
}{
{
name: "IsReady ReplicationController",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace},
},
rc: newReplicationController("foo", false),
want: false,
wantErr: false,
},
{
name: "IsReady ReplicationController with error",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace},
},
rc: newReplicationController("bar", false),
want: false,
wantErr: true,
},
{
name: "IsReady ReplicationController and pods not ready for object",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &corev1.ReplicationController{}, Name: "foo", Namespace: defaultNamespace},
},
rc: newReplicationController("foo", true),
want: true,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
if _, err := c.client.CoreV1().ReplicationControllers(defaultNamespace).Create(t.Context(), tt.rc, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create ReplicationController error: %v", err)
return
}
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_IsReady_ReplicaSet(t *testing.T) {
type fields struct {
client kubernetes.Interface
checkJobs bool
pausedAsReady bool
}
type args struct {
ctx context.Context
resource *resource.Info
}
tests := []struct {
name string
fields fields
args args
rs *appsv1.ReplicaSet
want bool
wantErr bool
}{
{
name: "IsReady ReplicaSet",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.ReplicaSet{}, Name: "foo", Namespace: defaultNamespace},
},
rs: newReplicaSet("foo", 1, 1, true),
want: false,
wantErr: true,
},
{
name: "IsReady ReplicaSet not ready",
fields: fields{
client: fake.NewClientset(),
checkJobs: true,
pausedAsReady: false,
},
args: args{
ctx: t.Context(),
resource: &resource.Info{Object: &appsv1.ReplicaSet{}, Name: "foo", Namespace: defaultNamespace},
},
rs: newReplicaSet("bar", 1, 1, false),
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ReadyChecker{
client: tt.fields.client,
checkJobs: tt.fields.checkJobs,
pausedAsReady: tt.fields.pausedAsReady,
}
//
got, err := c.IsReady(tt.args.ctx, tt.args.resource)
if (err != nil) != tt.wantErr {
t.Errorf("IsReady() error = %v, wantErr %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("IsReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_deploymentReady(t *testing.T) {
type args struct {
rs *appsv1.ReplicaSet
dep *appsv1.Deployment
}
tests := []struct {
name string
args args
want bool
}{
{
name: "deployment is ready",
args: args{
rs: newReplicaSet("foo", 1, 1, true),
dep: newDeployment("foo", 1, 1, 0, true),
},
want: true,
},
{
name: "deployment is not ready",
args: args{
rs: newReplicaSet("foo", 0, 0, true),
dep: newDeployment("foo", 1, 1, 0, true),
},
want: false,
},
{
name: "deployment is ready when maxUnavailable is set",
args: args{
rs: newReplicaSet("foo", 2, 1, true),
dep: newDeployment("foo", 2, 1, 1, true),
},
want: true,
},
{
name: "deployment is not ready when replicaset generations are out of sync",
args: args{
rs: newReplicaSet("foo", 1, 1, false),
dep: newDeployment("foo", 1, 1, 0, true),
},
want: false,
},
{
name: "deployment is not ready when deployment generations are out of sync",
args: args{
rs: newReplicaSet("foo", 1, 1, true),
dep: newDeployment("foo", 1, 1, 0, false),
},
want: false,
},
{
name: "deployment is not ready when generations are out of sync",
args: args{
rs: newReplicaSet("foo", 1, 1, false),
dep: newDeployment("foo", 1, 1, 0, false),
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.deploymentReady(tt.args.rs, tt.args.dep); got != tt.want {
t.Errorf("deploymentReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_replicaSetReady(t *testing.T) {
type args struct {
rs *appsv1.ReplicaSet
}
tests := []struct {
name string
args args
want bool
}{
{
name: "replicaSet is ready",
args: args{
rs: newReplicaSet("foo", 1, 1, true),
},
want: true,
},
{
name: "replicaSet is not ready when generations are out of sync",
args: args{
rs: newReplicaSet("foo", 1, 1, false),
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.replicaSetReady(tt.args.rs); got != tt.want {
t.Errorf("replicaSetReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_replicationControllerReady(t *testing.T) {
type args struct {
rc *corev1.ReplicationController
}
tests := []struct {
name string
args args
want bool
}{
{
name: "replicationController is ready",
args: args{
rc: newReplicationController("foo", true),
},
want: true,
},
{
name: "replicationController is not ready when generations are out of sync",
args: args{
rc: newReplicationController("foo", false),
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.replicationControllerReady(tt.args.rc); got != tt.want {
t.Errorf("replicationControllerReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_daemonSetReady(t *testing.T) {
type args struct {
ds *appsv1.DaemonSet
}
tests := []struct {
name string
args args
want bool
}{
{
name: "daemonset is ready",
args: args{
ds: newDaemonSet("foo", 0, 1, 1, 1, true),
},
want: true,
},
{
name: "daemonset is not ready",
args: args{
ds: newDaemonSet("foo", 0, 0, 1, 1, true),
},
want: false,
},
{
name: "daemonset pods have not been scheduled successfully",
args: args{
ds: newDaemonSet("foo", 0, 0, 1, 0, true),
},
want: false,
},
{
name: "daemonset is ready when maxUnavailable is set",
args: args{
ds: newDaemonSet("foo", 1, 1, 2, 2, true),
},
want: true,
},
{
name: "daemonset is not ready when generations are out of sync",
args: args{
ds: newDaemonSet("foo", 0, 1, 1, 1, false),
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.daemonSetReady(tt.args.ds); got != tt.want {
t.Errorf("daemonSetReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_statefulSetReady(t *testing.T) {
type args struct {
sts *appsv1.StatefulSet
}
tests := []struct {
name string
args args
want bool
}{
{
name: "statefulset is ready",
args: args{
sts: newStatefulSet("foo", 1, 0, 1, 1, true),
},
want: true,
},
{
name: "statefulset is not ready",
args: args{
sts: newStatefulSet("foo", 1, 0, 0, 1, true),
},
want: false,
},
{
name: "statefulset is ready when partition is specified",
args: args{
sts: newStatefulSet("foo", 2, 1, 2, 1, true),
},
want: true,
},
{
name: "statefulset is not ready when partition is set",
args: args{
sts: newStatefulSet("foo", 2, 1, 1, 0, true),
},
want: false,
},
{
name: "statefulset is ready when partition is set and no change in template",
args: args{
sts: newStatefulSet("foo", 2, 1, 2, 2, true),
},
want: true,
},
{
name: "statefulset is ready when partition is greater than replicas",
args: args{
sts: newStatefulSet("foo", 1, 2, 1, 1, true),
},
want: true,
},
{
name: "statefulset is not ready when generations are out of sync",
args: args{
sts: newStatefulSet("foo", 1, 0, 1, 1, false),
},
want: false,
},
{
name: "statefulset is ready when current revision for current replicas does not match update revision for updated replicas when using partition !=0",
args: args{
sts: newStatefulSetWithUpdateRevision("foo", 3, 2, 3, 3, "foo-bbbbbbb", true),
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.statefulSetReady(tt.args.sts); got != tt.want {
t.Errorf("statefulSetReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_podsReadyForObject(t *testing.T) {
type args struct {
namespace string
obj runtime.Object
}
tests := []struct {
name string
args args
existPods []corev1.Pod
want bool
wantErr bool
}{
{
name: "pods ready for a replicaset",
args: args{
namespace: defaultNamespace,
obj: newReplicaSet("foo", 1, 1, true),
},
existPods: []corev1.Pod{
*newPodWithCondition("foo", corev1.ConditionTrue),
},
want: true,
wantErr: false,
},
{
name: "pods not ready for a replicaset",
args: args{
namespace: defaultNamespace,
obj: newReplicaSet("foo", 1, 1, true),
},
existPods: []corev1.Pod{
*newPodWithCondition("foo", corev1.ConditionFalse),
},
want: false,
wantErr: false,
},
{
name: "ReplicaSet not set",
args: args{
namespace: defaultNamespace,
obj: nil,
},
existPods: []corev1.Pod{
*newPodWithCondition("foo", corev1.ConditionFalse),
},
want: false,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
for _, pod := range tt.existPods {
if _, err := c.client.CoreV1().Pods(defaultNamespace).Create(t.Context(), &pod, metav1.CreateOptions{}); err != nil {
t.Errorf("Failed to create Pod error: %v", err)
return
}
}
got, err := c.podsReadyForObject(t.Context(), tt.args.namespace, tt.args.obj)
if (err != nil) != tt.wantErr {
t.Errorf("podsReadyForObject() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("podsReadyForObject() got = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_jobReady(t *testing.T) {
type args struct {
job *batchv1.Job
}
tests := []struct {
name string
args args
want bool
wantErr bool
}{
{
name: "job is completed",
args: args{job: newJob("foo", 1, intToInt32(1), 1, 0)},
want: true,
wantErr: false,
},
{
name: "job is incomplete",
args: args{job: newJob("foo", 1, intToInt32(1), 0, 0)},
want: false,
wantErr: false,
},
{
name: "job is failed but within BackoffLimit",
args: args{job: newJob("foo", 1, intToInt32(1), 0, 1)},
want: false,
wantErr: false,
},
{
name: "job is completed with retry",
args: args{job: newJob("foo", 1, intToInt32(1), 1, 1)},
want: true,
wantErr: false,
},
{
name: "job is failed and beyond BackoffLimit",
args: args{job: newJob("foo", 1, intToInt32(1), 0, 2)},
want: false,
wantErr: true,
},
{
name: "job is completed single run",
args: args{job: newJob("foo", 0, intToInt32(1), 1, 0)},
want: true,
wantErr: false,
},
{
name: "job is failed single run",
args: args{job: newJob("foo", 0, intToInt32(1), 0, 1)},
want: false,
wantErr: true,
},
{
name: "job with null completions",
args: args{job: newJob("foo", 0, nil, 1, 0)},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
got, err := c.jobReady(tt.args.job)
if (err != nil) != tt.wantErr {
t.Errorf("jobReady() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("jobReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_volumeReady(t *testing.T) {
type args struct {
v *corev1.PersistentVolumeClaim
}
tests := []struct {
name string
args args
want bool
}{
{
name: "pvc is bound",
args: args{
v: newPersistentVolumeClaim("foo", corev1.ClaimBound),
},
want: true,
},
{
name: "pvc is not ready",
args: args{
v: newPersistentVolumeClaim("foo", corev1.ClaimPending),
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
if got := c.volumeReady(tt.args.v); got != tt.want {
t.Errorf("volumeReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_serviceReady(t *testing.T) {
type args struct {
service *corev1.Service
}
tests := []struct {
name string
args args
want bool
}{
{
name: "service type is of external name",
args: args{service: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeExternalName, ClusterIP: ""})},
want: true,
},
{
name: "service cluster ip is empty",
args: args{service: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, ClusterIP: ""})},
want: false,
},
{
name: "service has a cluster ip that is greater than 0",
args: args{service: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, ClusterIP: "bar", ExternalIPs: []string{"bar"}})},
want: true,
},
{
name: "service has a cluster ip that is less than 0 and ingress is nil",
args: args{service: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeLoadBalancer, ClusterIP: "bar"})},
want: false,
},
{
name: "service has a cluster ip that is less than 0 and ingress is nil",
args: args{service: newService("foo", corev1.ServiceSpec{Type: corev1.ServiceTypeClusterIP, ClusterIP: "bar"})},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
got := c.serviceReady(tt.args.service)
if got != tt.want {
t.Errorf("serviceReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_crdBetaReady(t *testing.T) {
type args struct {
crdBeta apiextv1beta1.CustomResourceDefinition
}
tests := []struct {
name string
args args
want bool
}{
{
name: "crdBeta type is Establish and Conditional is true",
args: args{crdBeta: newcrdBetaReady("foo", apiextv1beta1.CustomResourceDefinitionStatus{
Conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
{
Type: apiextv1beta1.Established,
Status: apiextv1beta1.ConditionTrue,
},
},
})},
want: true,
},
{
name: "crdBeta type is Establish and Conditional is false",
args: args{crdBeta: newcrdBetaReady("foo", apiextv1beta1.CustomResourceDefinitionStatus{
Conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
{
Type: apiextv1beta1.Established,
Status: apiextv1beta1.ConditionFalse,
},
},
})},
want: false,
},
{
name: "crdBeta type is NamesAccepted and Conditional is true",
args: args{crdBeta: newcrdBetaReady("foo", apiextv1beta1.CustomResourceDefinitionStatus{
Conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
{
Type: apiextv1beta1.NamesAccepted,
Status: apiextv1beta1.ConditionTrue,
},
},
})},
want: false,
},
{
name: "crdBeta type is NamesAccepted and Conditional is false",
args: args{crdBeta: newcrdBetaReady("foo", apiextv1beta1.CustomResourceDefinitionStatus{
Conditions: []apiextv1beta1.CustomResourceDefinitionCondition{
{
Type: apiextv1beta1.NamesAccepted,
Status: apiextv1beta1.ConditionFalse,
},
},
})},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewReadyChecker(fake.NewClientset())
got := c.crdBetaReady(tt.args.crdBeta)
if got != tt.want {
t.Errorf("crdBetaReady() = %v, want %v", got, tt.want)
}
})
}
}
func Test_ReadyChecker_crdReady(t *testing.T) {
type args struct {
crdBeta apiextv1.CustomResourceDefinition
}
tests := []struct {
name string
args args
want bool
}{
{
name: "crdBeta type is Establish and Conditional is true",
args: args{crdBeta: newcrdReady("foo", apiextv1.CustomResourceDefinitionStatus{
Conditions: []apiextv1.CustomResourceDefinitionCondition{
{
Type: apiextv1.Established,
Status: apiextv1.ConditionTrue,
},
},
})},
want: true,
},
{
name: "crdBeta type is Establish and Conditional is false",
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | true |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/roundtripper_test.go | pkg/kube/roundtripper_test.go | /*
Copyright The Helm 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 kube
import (
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
type fakeRoundTripper struct {
resp *http.Response
err error
calls int
}
func (f *fakeRoundTripper) RoundTrip(_ *http.Request) (*http.Response, error) {
f.calls++
return f.resp, f.err
}
func newRespWithBody(statusCode int, contentType, body string) *http.Response {
return &http.Response{
StatusCode: statusCode,
Header: http.Header{"Content-Type": []string{contentType}},
Body: io.NopCloser(strings.NewReader(body)),
}
}
func TestRetryingRoundTripper_RoundTrip(t *testing.T) {
marshalErr := func(code int, msg string) string {
b, _ := json.Marshal(kubernetesError{
Code: code,
Message: msg,
})
return string(b)
}
tests := []struct {
name string
resp *http.Response
err error
expectedCalls int
expectedErr string
expectedCode int
}{
{
name: "no retry, status < 500 returns response",
resp: newRespWithBody(200, "application/json", `{"message":"ok","code":200}`),
err: nil,
expectedCalls: 1,
expectedCode: 200,
},
{
name: "error from wrapped RoundTripper propagates",
resp: nil,
err: errors.New("wrapped error"),
expectedCalls: 1,
expectedErr: "wrapped error",
},
{
name: "no retry, content-type not application/json",
resp: newRespWithBody(500, "text/plain", "server error"),
err: nil,
expectedCalls: 1,
expectedCode: 500,
},
{
name: "error reading body returns error",
resp: &http.Response{
StatusCode: http.StatusInternalServerError,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: &errReader{},
},
err: nil,
expectedCalls: 1,
expectedErr: "read error",
},
{
name: "error decoding JSON returns error",
resp: newRespWithBody(500, "application/json", `invalid-json`),
err: nil,
expectedCalls: 1,
expectedErr: "invalid character",
},
{
name: "retry on etcdserver leader changed message",
resp: newRespWithBody(500, "application/json", marshalErr(500, "some error etcdserver: leader changed")),
err: nil,
expectedCalls: 2,
expectedCode: 500,
},
{
name: "retry on raft proposal dropped message",
resp: newRespWithBody(500, "application/json", marshalErr(500, "rpc error: code = Unknown desc = raft proposal dropped")),
err: nil,
expectedCalls: 2,
expectedCode: 500,
},
{
name: "no retry on other error message",
resp: newRespWithBody(500, "application/json", marshalErr(500, "other server error")),
err: nil,
expectedCalls: 1,
expectedCode: 500,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeRT := &fakeRoundTripper{
resp: tt.resp,
err: tt.err,
}
rt := RetryingRoundTripper{
Wrapped: fakeRT,
}
req, _ := http.NewRequest(http.MethodGet, "http://example.com", nil)
resp, err := rt.RoundTrip(req)
if tt.expectedErr != "" {
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedErr)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.expectedCode, resp.StatusCode)
assert.Equal(t, tt.expectedCalls, fakeRT.calls)
})
}
}
type errReader struct{}
func (e *errReader) Read(_ []byte) (int, error) {
return 0, errors.New("read error")
}
func (e *errReader) Close() error {
return nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/converter.go | pkg/kube/converter.go | /*
Copyright The Helm 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 kube // import "helm.sh/helm/v4/pkg/kube"
import (
"sync"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes/scheme"
)
var k8sNativeScheme *runtime.Scheme
var k8sNativeSchemeOnce sync.Once
// AsVersioned converts the given info into a runtime.Object with the correct
// group and version set
func AsVersioned(info *resource.Info) runtime.Object {
return convertWithMapper(info.Object, info.Mapping)
}
// convertWithMapper converts the given object with the optional provided
// RESTMapping. If no mapping is provided, the default schema versioner is used
func convertWithMapper(obj runtime.Object, mapping *meta.RESTMapping) runtime.Object {
s := kubernetesNativeScheme()
var gv = runtime.GroupVersioner(schema.GroupVersions(s.PrioritizedVersionsAllGroups()))
if mapping != nil {
gv = mapping.GroupVersionKind.GroupVersion()
}
if obj, err := runtime.ObjectConvertor(s).ConvertToVersion(obj, gv); err == nil {
return obj
}
return obj
}
// kubernetesNativeScheme returns a clean *runtime.Scheme with _only_ Kubernetes
// native resources added to it. This is required to break free of custom resources
// that may have been added to scheme.Scheme due to Helm being used as a package in
// combination with e.g. a versioned kube client. If we would not do this, the client
// may attempt to perform e.g. a 3-way-merge strategy patch for custom resources.
func kubernetesNativeScheme() *runtime.Scheme {
k8sNativeSchemeOnce.Do(func() {
k8sNativeScheme = runtime.NewScheme()
scheme.AddToScheme(k8sNativeScheme)
// API extensions are not in the above scheme set,
// and must thus be added separately.
apiextensionsv1beta1.AddToScheme(k8sNativeScheme)
apiextensionsv1.AddToScheme(k8sNativeScheme)
})
return k8sNativeScheme
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/fake/printer.go | pkg/kube/fake/printer.go | /*
Copyright The Helm 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 fake
import (
"fmt"
"io"
"strings"
"time"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/resource"
"helm.sh/helm/v4/pkg/kube"
)
// PrintingKubeClient implements KubeClient, but simply prints the reader to
// the given output.
type PrintingKubeClient struct {
Out io.Writer
LogOutput io.Writer
}
// PrintingKubeWaiter implements kube.Waiter, but simply prints the reader to the given output
type PrintingKubeWaiter struct {
Out io.Writer
LogOutput io.Writer
}
var _ kube.Interface = &PrintingKubeClient{}
// IsReachable checks if the cluster is reachable
func (p *PrintingKubeClient) IsReachable() error {
return nil
}
// Create prints the values of what would be created with a real KubeClient.
func (p *PrintingKubeClient) Create(resources kube.ResourceList, _ ...kube.ClientCreateOption) (*kube.Result, error) {
_, err := io.Copy(p.Out, bufferize(resources))
if err != nil {
return nil, err
}
return &kube.Result{Created: resources}, nil
}
func (p *PrintingKubeClient) Get(resources kube.ResourceList, _ bool) (map[string][]runtime.Object, error) {
_, err := io.Copy(p.Out, bufferize(resources))
if err != nil {
return nil, err
}
return make(map[string][]runtime.Object), nil
}
func (p *PrintingKubeWaiter) Wait(resources kube.ResourceList, _ time.Duration) error {
_, err := io.Copy(p.Out, bufferize(resources))
return err
}
func (p *PrintingKubeWaiter) WaitWithJobs(resources kube.ResourceList, _ time.Duration) error {
_, err := io.Copy(p.Out, bufferize(resources))
return err
}
func (p *PrintingKubeWaiter) WaitForDelete(resources kube.ResourceList, _ time.Duration) error {
_, err := io.Copy(p.Out, bufferize(resources))
return err
}
// WatchUntilReady implements KubeClient WatchUntilReady.
func (p *PrintingKubeWaiter) WatchUntilReady(resources kube.ResourceList, _ time.Duration) error {
_, err := io.Copy(p.Out, bufferize(resources))
return err
}
// Delete implements KubeClient delete.
//
// It only prints out the content to be deleted.
func (p *PrintingKubeClient) Delete(resources kube.ResourceList, _ metav1.DeletionPropagation) (*kube.Result, []error) {
_, err := io.Copy(p.Out, bufferize(resources))
if err != nil {
return nil, []error{err}
}
return &kube.Result{Deleted: resources}, nil
}
// Update implements KubeClient Update.
func (p *PrintingKubeClient) Update(_, modified kube.ResourceList, _ ...kube.ClientUpdateOption) (*kube.Result, error) {
_, err := io.Copy(p.Out, bufferize(modified))
if err != nil {
return nil, err
}
// TODO: This doesn't completely mock out have some that get created,
// updated, and deleted. I don't think these are used in any unit tests, but
// we may want to refactor a way to handle future tests
return &kube.Result{Updated: modified}, nil
}
// Build implements KubeClient Build.
func (p *PrintingKubeClient) Build(_ io.Reader, _ bool) (kube.ResourceList, error) {
return []*resource.Info{}, nil
}
// BuildTable implements KubeClient BuildTable.
func (p *PrintingKubeClient) BuildTable(_ io.Reader, _ bool) (kube.ResourceList, error) {
return []*resource.Info{}, nil
}
// WaitAndGetCompletedPodPhase implements KubeClient WaitAndGetCompletedPodPhase.
func (p *PrintingKubeClient) WaitAndGetCompletedPodPhase(_ string, _ time.Duration) (v1.PodPhase, error) {
return v1.PodSucceeded, nil
}
// GetPodList implements KubeClient GetPodList.
func (p *PrintingKubeClient) GetPodList(_ string, _ metav1.ListOptions) (*v1.PodList, error) {
return &v1.PodList{}, nil
}
// OutputContainerLogsForPodList implements KubeClient OutputContainerLogsForPodList.
func (p *PrintingKubeClient) OutputContainerLogsForPodList(_ *v1.PodList, someNamespace string, _ func(namespace, pod, container string) io.Writer) error {
_, err := io.Copy(p.LogOutput, strings.NewReader(fmt.Sprintf("attempted to output logs for namespace: %s", someNamespace)))
return err
}
// DeleteWithPropagationPolicy implements KubeClient delete.
//
// It only prints out the content to be deleted.
func (p *PrintingKubeClient) DeleteWithPropagationPolicy(resources kube.ResourceList, _ metav1.DeletionPropagation) (*kube.Result, []error) {
_, err := io.Copy(p.Out, bufferize(resources))
if err != nil {
return nil, []error{err}
}
return &kube.Result{Deleted: resources}, nil
}
func (p *PrintingKubeClient) GetWaiter(_ kube.WaitStrategy) (kube.Waiter, error) {
return &PrintingKubeWaiter{Out: p.Out, LogOutput: p.LogOutput}, nil
}
func bufferize(resources kube.ResourceList) io.Reader {
var builder strings.Builder
for _, info := range resources {
builder.WriteString(info.String() + "\n")
}
return strings.NewReader(builder.String())
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/kube/fake/failing_kube_client.go | pkg/kube/fake/failing_kube_client.go | /*
Copyright The Helm 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 fake implements various fake KubeClients for use in testing
package fake
import (
"io"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/resource"
"helm.sh/helm/v4/pkg/kube"
)
// FailingKubeClient implements KubeClient for testing purposes. It also has
// additional errors you can set to fail different functions, otherwise it
// delegates all its calls to `PrintingKubeClient`
type FailingKubeClient struct {
PrintingKubeClient
CreateError error
GetError error
DeleteError error
UpdateError error
BuildError error
BuildTableError error
ConnectionError error
BuildDummy bool
DummyResources kube.ResourceList
BuildUnstructuredError error
WaitError error
WaitForDeleteError error
WatchUntilReadyError error
WaitDuration time.Duration
}
var _ kube.Interface = &FailingKubeClient{}
// FailingKubeWaiter implements kube.Waiter for testing purposes.
// It also has additional errors you can set to fail different functions, otherwise it delegates all its calls to `PrintingKubeWaiter`
type FailingKubeWaiter struct {
*PrintingKubeWaiter
waitError error
waitForDeleteError error
watchUntilReadyError error
waitDuration time.Duration
}
// Create returns the configured error if set or prints
func (f *FailingKubeClient) Create(resources kube.ResourceList, options ...kube.ClientCreateOption) (*kube.Result, error) {
if f.CreateError != nil {
return nil, f.CreateError
}
return f.PrintingKubeClient.Create(resources, options...)
}
// Get returns the configured error if set or prints
func (f *FailingKubeClient) Get(resources kube.ResourceList, related bool) (map[string][]runtime.Object, error) {
if f.GetError != nil {
return nil, f.GetError
}
return f.PrintingKubeClient.Get(resources, related)
}
// Waits the amount of time defined on f.WaitDuration, then returns the configured error if set or prints.
func (f *FailingKubeWaiter) Wait(resources kube.ResourceList, d time.Duration) error {
time.Sleep(f.waitDuration)
if f.waitError != nil {
return f.waitError
}
return f.PrintingKubeWaiter.Wait(resources, d)
}
// WaitWithJobs returns the configured error if set or prints
func (f *FailingKubeWaiter) WaitWithJobs(resources kube.ResourceList, d time.Duration) error {
if f.waitError != nil {
return f.waitError
}
return f.PrintingKubeWaiter.WaitWithJobs(resources, d)
}
// WaitForDelete returns the configured error if set or prints
func (f *FailingKubeWaiter) WaitForDelete(resources kube.ResourceList, d time.Duration) error {
if f.waitForDeleteError != nil {
return f.waitForDeleteError
}
return f.PrintingKubeWaiter.WaitForDelete(resources, d)
}
// Delete returns the configured error if set or prints
func (f *FailingKubeClient) Delete(resources kube.ResourceList, deletionPropagation metav1.DeletionPropagation) (*kube.Result, []error) {
if f.DeleteError != nil {
return nil, []error{f.DeleteError}
}
return f.PrintingKubeClient.Delete(resources, deletionPropagation)
}
// WatchUntilReady returns the configured error if set or prints
func (f *FailingKubeWaiter) WatchUntilReady(resources kube.ResourceList, d time.Duration) error {
if f.watchUntilReadyError != nil {
return f.watchUntilReadyError
}
return f.PrintingKubeWaiter.WatchUntilReady(resources, d)
}
// Update returns the configured error if set or prints
func (f *FailingKubeClient) Update(r, modified kube.ResourceList, options ...kube.ClientUpdateOption) (*kube.Result, error) {
if f.UpdateError != nil {
return &kube.Result{}, f.UpdateError
}
return f.PrintingKubeClient.Update(r, modified, options...)
}
// Build returns the configured error if set or prints
func (f *FailingKubeClient) Build(r io.Reader, _ bool) (kube.ResourceList, error) {
if f.BuildError != nil {
return []*resource.Info{}, f.BuildError
}
if f.DummyResources != nil {
return f.DummyResources, nil
}
if f.BuildDummy {
return createDummyResourceList(), nil
}
return f.PrintingKubeClient.Build(r, false)
}
// BuildTable returns the configured error if set or prints
func (f *FailingKubeClient) BuildTable(r io.Reader, _ bool) (kube.ResourceList, error) {
if f.BuildTableError != nil {
return []*resource.Info{}, f.BuildTableError
}
if f.BuildDummy {
return createDummyResourceList(), nil
}
return f.PrintingKubeClient.BuildTable(r, false)
}
func (f *FailingKubeClient) GetWaiter(ws kube.WaitStrategy) (kube.Waiter, error) {
waiter, _ := f.PrintingKubeClient.GetWaiter(ws)
printingKubeWaiter, _ := waiter.(*PrintingKubeWaiter)
return &FailingKubeWaiter{
PrintingKubeWaiter: printingKubeWaiter,
waitError: f.WaitError,
waitForDeleteError: f.WaitForDeleteError,
watchUntilReadyError: f.WatchUntilReadyError,
waitDuration: f.WaitDuration,
}, nil
}
func (f *FailingKubeClient) IsReachable() error {
if f.ConnectionError != nil {
return f.ConnectionError
}
return f.PrintingKubeClient.IsReachable()
}
func createDummyResourceList() kube.ResourceList {
var resInfo resource.Info
resInfo.Name = "dummyName"
resInfo.Namespace = "dummyNamespace"
var resourceList kube.ResourceList
resourceList.Append(&resInfo)
return resourceList
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/client_insecure_tls_test.go | pkg/registry/client_insecure_tls_test.go | /*
Copyright The Helm 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 registry
import (
"os"
"testing"
"github.com/stretchr/testify/suite"
)
type InsecureTLSRegistryClientTestSuite struct {
TestRegistry
}
func (suite *InsecureTLSRegistryClientTestSuite) SetupSuite() {
// init test client
setup(&suite.TestRegistry, true, true)
}
func (suite *InsecureTLSRegistryClientTestSuite) TearDownSuite() {
teardown(&suite.TestRegistry)
_ = os.RemoveAll(suite.WorkspaceDir)
}
func (suite *InsecureTLSRegistryClientTestSuite) Test_0_Login() {
err := suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth("badverybad", "ohsobad"),
LoginOptInsecure(true))
suite.NotNil(err, "error logging into registry with bad credentials")
err = suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth(testUsername, testPassword),
LoginOptInsecure(true))
suite.Nil(err, "no error logging into registry with good credentials")
}
func (suite *InsecureTLSRegistryClientTestSuite) Test_1_Push() {
testPush(&suite.TestRegistry)
}
func (suite *InsecureTLSRegistryClientTestSuite) Test_2_Pull() {
testPull(&suite.TestRegistry)
}
func (suite *InsecureTLSRegistryClientTestSuite) Test_3_Tags() {
testTags(&suite.TestRegistry)
}
func (suite *InsecureTLSRegistryClientTestSuite) Test_4_Logout() {
err := suite.RegistryClient.Logout("this-host-aint-real:5000")
if err != nil {
// credential backend for mac generates an error
suite.NotNil(err, "failed to delete the credential for this-host-aint-real:5000")
}
err = suite.RegistryClient.Logout(suite.DockerRegistryHost)
suite.Nil(err, "no error logging out of registry")
}
func TestInsecureTLSRegistryClientTestSuite(t *testing.T) {
suite.Run(t, new(InsecureTLSRegistryClientTestSuite))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/generic.go | pkg/registry/generic.go | /*
Copyright The Helm 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 registry
import (
"context"
"io"
"net/http"
"slices"
"sort"
"sync"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"oras.land/oras-go/v2"
"oras.land/oras-go/v2/content"
"oras.land/oras-go/v2/content/memory"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials"
)
// GenericClient provides low-level OCI operations without artifact-specific assumptions
type GenericClient struct {
debug bool
enableCache bool
credentialsFile string
username string
password string
out io.Writer
authorizer *auth.Client
registryAuthorizer RemoteClient
credentialsStore credentials.Store
httpClient *http.Client
plainHTTP bool
}
// GenericPullOptions configures a generic pull operation
type GenericPullOptions struct {
// MediaTypes to include in the pull (empty means all)
AllowedMediaTypes []string
// Skip descriptors with these media types
SkipMediaTypes []string
// Custom PreCopy function for filtering
PreCopy func(context.Context, ocispec.Descriptor) error
}
// GenericPullResult contains the result of a generic pull operation
type GenericPullResult struct {
Manifest ocispec.Descriptor
Descriptors []ocispec.Descriptor
MemoryStore *memory.Store
Ref string
}
// NewGenericClient creates a new generic OCI client from an existing Client
func NewGenericClient(client *Client) *GenericClient {
return &GenericClient{
debug: client.debug,
enableCache: client.enableCache,
credentialsFile: client.credentialsFile,
username: client.username,
password: client.password,
out: client.out,
authorizer: client.authorizer,
registryAuthorizer: client.registryAuthorizer,
credentialsStore: client.credentialsStore,
httpClient: client.httpClient,
plainHTTP: client.plainHTTP,
}
}
// PullGeneric performs a generic OCI pull without artifact-specific assumptions
func (c *GenericClient) PullGeneric(ref string, options GenericPullOptions) (*GenericPullResult, error) {
parsedRef, err := newReference(ref)
if err != nil {
return nil, err
}
memoryStore := memory.New()
var descriptors []ocispec.Descriptor
// Set up a repository with authentication and configuration
repository, err := remote.NewRepository(parsedRef.String())
if err != nil {
return nil, err
}
repository.PlainHTTP = c.plainHTTP
repository.Client = c.authorizer
ctx := context.Background()
// Prepare allowed media types for filtering
var allowedMediaTypes []string
if len(options.AllowedMediaTypes) > 0 {
allowedMediaTypes = make([]string, len(options.AllowedMediaTypes))
copy(allowedMediaTypes, options.AllowedMediaTypes)
sort.Strings(allowedMediaTypes)
}
var mu sync.Mutex
manifest, err := oras.Copy(ctx, repository, parsedRef.String(), memoryStore, "", oras.CopyOptions{
CopyGraphOptions: oras.CopyGraphOptions{
PreCopy: func(ctx context.Context, desc ocispec.Descriptor) error {
// Apply a custom PreCopy function if provided
if options.PreCopy != nil {
if err := options.PreCopy(ctx, desc); err != nil {
return err
}
}
mediaType := desc.MediaType
// Skip media types if specified
if slices.Contains(options.SkipMediaTypes, mediaType) {
return oras.SkipNode
}
// Filter by allowed media types if specified
if len(allowedMediaTypes) > 0 {
if i := sort.SearchStrings(allowedMediaTypes, mediaType); i >= len(allowedMediaTypes) || allowedMediaTypes[i] != mediaType {
return oras.SkipNode
}
}
mu.Lock()
descriptors = append(descriptors, desc)
mu.Unlock()
return nil
},
},
})
if err != nil {
return nil, err
}
return &GenericPullResult{
Manifest: manifest,
Descriptors: descriptors,
MemoryStore: memoryStore,
Ref: parsedRef.String(),
}, nil
}
// GetDescriptorData retrieves the data for a specific descriptor
func (c *GenericClient) GetDescriptorData(store *memory.Store, desc ocispec.Descriptor) ([]byte, error) {
return content.FetchAll(context.Background(), store, desc)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/chart.go | pkg/registry/chart.go | /*
Copyright The Helm 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 registry // import "helm.sh/helm/v4/pkg/registry"
import (
"bytes"
"strings"
"time"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
var immutableOciAnnotations = []string{
ocispec.AnnotationVersion,
ocispec.AnnotationTitle,
}
// extractChartMeta is used to extract a chart metadata from a byte array
func extractChartMeta(chartData []byte) (*chart.Metadata, error) {
ch, err := loader.LoadArchive(bytes.NewReader(chartData))
if err != nil {
return nil, err
}
return ch.Metadata, nil
}
// generateOCIAnnotations will generate OCI annotations to include within the OCI manifest
func generateOCIAnnotations(meta *chart.Metadata, creationTime string) map[string]string {
// Get annotations from Chart attributes
ociAnnotations := generateChartOCIAnnotations(meta, creationTime)
// Copy Chart annotations
annotations:
for chartAnnotationKey, chartAnnotationValue := range meta.Annotations {
// Avoid overriding key properties
for _, immutableOciKey := range immutableOciAnnotations {
if immutableOciKey == chartAnnotationKey {
continue annotations
}
}
// Add chart annotation
ociAnnotations[chartAnnotationKey] = chartAnnotationValue
}
return ociAnnotations
}
// generateChartOCIAnnotations will generate OCI annotations from the provided chart
func generateChartOCIAnnotations(meta *chart.Metadata, creationTime string) map[string]string {
chartOCIAnnotations := map[string]string{}
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationDescription, meta.Description)
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationTitle, meta.Name)
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationVersion, meta.Version)
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationURL, meta.Home)
if len(creationTime) == 0 {
creationTime = time.Now().UTC().Format(time.RFC3339)
}
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationCreated, creationTime)
if len(meta.Sources) > 0 {
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationSource, meta.Sources[0])
}
if len(meta.Maintainers) > 0 {
var maintainerSb strings.Builder
for maintainerIdx, maintainer := range meta.Maintainers {
if len(maintainer.Name) > 0 {
maintainerSb.WriteString(maintainer.Name)
}
if len(maintainer.Email) > 0 {
maintainerSb.WriteString(" (")
maintainerSb.WriteString(maintainer.Email)
maintainerSb.WriteString(")")
}
if maintainerIdx < len(meta.Maintainers)-1 {
maintainerSb.WriteString(", ")
}
}
chartOCIAnnotations = addToMap(chartOCIAnnotations, ocispec.AnnotationAuthors, maintainerSb.String())
}
return chartOCIAnnotations
}
// addToMap takes an existing map and adds an item if the value is not empty
func addToMap(inputMap map[string]string, newKey string, newValue string) map[string]string {
// Add item to map if its
if len(strings.TrimSpace(newValue)) > 0 {
inputMap[newKey] = newValue
}
return inputMap
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/constants.go | pkg/registry/constants.go | /*
Copyright The Helm 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 registry // import "helm.sh/helm/v4/pkg/registry"
const (
// OCIScheme is the URL scheme for OCI-based requests
OCIScheme = "oci"
// CredentialsFileBasename is the filename for auth credentials file
CredentialsFileBasename = "registry/config.json"
// ConfigMediaType is the reserved media type for the Helm chart manifest config
ConfigMediaType = "application/vnd.cncf.helm.config.v1+json"
// ChartLayerMediaType is the reserved media type for Helm chart package content
ChartLayerMediaType = "application/vnd.cncf.helm.chart.content.v1.tar+gzip"
// ProvLayerMediaType is the reserved media type for Helm chart provenance files
ProvLayerMediaType = "application/vnd.cncf.helm.chart.provenance.v1.prov"
// LegacyChartLayerMediaType is the legacy reserved media type for Helm chart package content.
LegacyChartLayerMediaType = "application/tar+gzip"
)
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/client.go | pkg/registry/client.go | /*
Copyright The Helm 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 registry // import "helm.sh/helm/v4/pkg/registry"
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"sort"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/opencontainers/image-spec/specs-go"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"oras.land/oras-go/v2"
"oras.land/oras-go/v2/content/memory"
"oras.land/oras-go/v2/registry"
"oras.land/oras-go/v2/registry/remote"
"oras.land/oras-go/v2/registry/remote/auth"
"oras.land/oras-go/v2/registry/remote/credentials"
"oras.land/oras-go/v2/registry/remote/retry"
"helm.sh/helm/v4/internal/version"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/helmpath"
)
// See https://github.com/helm/helm/issues/10166
const registryUnderscoreMessage = `
OCI artifact references (e.g. tags) do not support the plus sign (+). To support
storing semantic versions, Helm adopts the convention of changing plus (+) to
an underscore (_) in chart version tags when pushing to a registry and back to
a plus (+) when pulling from a registry.`
type (
// RemoteClient shadows the ORAS remote.Client interface
// (hiding the ORAS type from Helm client visibility)
// https://pkg.go.dev/oras.land/oras-go/pkg/registry/remote#Client
RemoteClient interface {
Do(req *http.Request) (*http.Response, error)
}
// Client works with OCI-compliant registries
Client struct {
debug bool
enableCache bool
// path to repository config file e.g. ~/.docker/config.json
credentialsFile string
username string
password string
out io.Writer
authorizer *auth.Client
registryAuthorizer RemoteClient
credentialsStore credentials.Store
httpClient *http.Client
plainHTTP bool
}
// ClientOption allows specifying various settings configurable by the user for overriding the defaults
// used when creating a new default client
// TODO(TerryHowe): ClientOption should return error in v5
ClientOption func(*Client)
)
// NewClient returns a new registry client with config
func NewClient(options ...ClientOption) (*Client, error) {
client := &Client{
out: io.Discard,
}
for _, option := range options {
option(client)
}
if client.credentialsFile == "" {
client.credentialsFile = helmpath.ConfigPath(CredentialsFileBasename)
}
if client.httpClient == nil {
client.httpClient = &http.Client{
Transport: NewTransport(client.debug),
}
}
storeOptions := credentials.StoreOptions{
AllowPlaintextPut: true,
DetectDefaultNativeStore: true,
}
store, err := credentials.NewStore(client.credentialsFile, storeOptions)
if err != nil {
return nil, err
}
dockerStore, err := credentials.NewStoreFromDocker(storeOptions)
if err != nil {
// should only fail if user home directory can't be determined
client.credentialsStore = store
} else {
// use Helm credentials with fallback to Docker
client.credentialsStore = credentials.NewStoreWithFallbacks(store, dockerStore)
}
if client.authorizer == nil {
authorizer := auth.Client{
Client: client.httpClient,
}
authorizer.SetUserAgent(version.GetUserAgent())
if client.username != "" && client.password != "" {
authorizer.Credential = func(_ context.Context, _ string) (auth.Credential, error) {
return auth.Credential{Username: client.username, Password: client.password}, nil
}
} else {
authorizer.Credential = credentials.Credential(client.credentialsStore)
}
if client.enableCache {
authorizer.Cache = auth.NewCache()
}
client.authorizer = &authorizer
}
return client, nil
}
// Generic returns a GenericClient for low-level OCI operations
func (c *Client) Generic() *GenericClient {
return NewGenericClient(c)
}
// ClientOptDebug returns a function that sets the debug setting on client options set
func ClientOptDebug(debug bool) ClientOption {
return func(client *Client) {
client.debug = debug
}
}
// ClientOptEnableCache returns a function that sets the enableCache setting on a client options set
func ClientOptEnableCache(enableCache bool) ClientOption {
return func(client *Client) {
client.enableCache = enableCache
}
}
// ClientOptBasicAuth returns a function that sets the username and password setting on client options set
func ClientOptBasicAuth(username, password string) ClientOption {
return func(client *Client) {
client.username = username
client.password = password
}
}
// ClientOptWriter returns a function that sets the writer setting on client options set
func ClientOptWriter(out io.Writer) ClientOption {
return func(client *Client) {
client.out = out
}
}
// ClientOptAuthorizer returns a function that sets the authorizer setting on a client options set. This
// can be used to override the default authorization mechanism.
//
// Depending on the use-case you may need to set both ClientOptAuthorizer and ClientOptRegistryAuthorizer.
func ClientOptAuthorizer(authorizer auth.Client) ClientOption {
return func(client *Client) {
client.authorizer = &authorizer
}
}
// ClientOptRegistryAuthorizer returns a function that sets the registry authorizer setting on a client options set. This
// can be used to override the default authorization mechanism.
//
// Depending on the use-case you may need to set both ClientOptAuthorizer and ClientOptRegistryAuthorizer.
func ClientOptRegistryAuthorizer(registryAuthorizer RemoteClient) ClientOption {
return func(client *Client) {
client.registryAuthorizer = registryAuthorizer
}
}
// ClientOptCredentialsFile returns a function that sets the credentialsFile setting on a client options set
func ClientOptCredentialsFile(credentialsFile string) ClientOption {
return func(client *Client) {
client.credentialsFile = credentialsFile
}
}
// ClientOptHTTPClient returns a function that sets the httpClient setting on a client options set
func ClientOptHTTPClient(httpClient *http.Client) ClientOption {
return func(client *Client) {
client.httpClient = httpClient
}
}
func ClientOptPlainHTTP() ClientOption {
return func(c *Client) {
c.plainHTTP = true
}
}
type (
// LoginOption allows specifying various settings on login
LoginOption func(*loginOperation)
loginOperation struct {
host string
client *Client
}
)
// warnIfHostHasPath checks if the host contains a repository path and logs a warning if it does.
// Returns true if the host contains a path component (i.e., contains a '/').
func warnIfHostHasPath(host string) bool {
if strings.Contains(host, "/") {
registryHost := strings.Split(host, "/")[0]
slog.Warn("registry login currently only supports registry hostname, not a repository path", "host", host, "suggested", registryHost)
return true
}
return false
}
// Login logs into a registry
func (c *Client) Login(host string, options ...LoginOption) error {
for _, option := range options {
option(&loginOperation{host, c})
}
warnIfHostHasPath(host)
reg, err := remote.NewRegistry(host)
if err != nil {
return err
}
reg.PlainHTTP = c.plainHTTP
cred := auth.Credential{Username: c.username, Password: c.password}
c.authorizer.ForceAttemptOAuth2 = true
reg.Client = c.authorizer
ctx := context.Background()
if err := reg.Ping(ctx); err != nil {
c.authorizer.ForceAttemptOAuth2 = false
if err := reg.Ping(ctx); err != nil {
return fmt.Errorf("authenticating to %q: %w", host, err)
}
}
// Always restore to false after probing, to avoid forcing POST to token endpoints like GHCR.
c.authorizer.ForceAttemptOAuth2 = false
key := credentials.ServerAddressFromRegistry(host)
key = credentials.ServerAddressFromHostname(key)
if err := c.credentialsStore.Put(ctx, key, cred); err != nil {
return err
}
_, _ = fmt.Fprintln(c.out, "Login Succeeded")
return nil
}
// LoginOptBasicAuth returns a function that sets the username/password settings on login
func LoginOptBasicAuth(username string, password string) LoginOption {
return func(o *loginOperation) {
o.client.username = username
o.client.password = password
o.client.authorizer.Credential = auth.StaticCredential(o.host, auth.Credential{Username: username, Password: password})
}
}
// LoginOptPlainText returns a function that allows plaintext (HTTP) login
func LoginOptPlainText(isPlainText bool) LoginOption {
return func(o *loginOperation) {
o.client.plainHTTP = isPlainText
}
}
func ensureTLSConfig(client *auth.Client, setConfig *tls.Config) (*tls.Config, error) {
var transport *http.Transport
switch t := client.Client.Transport.(type) {
case *http.Transport:
transport = t
case *retry.Transport:
switch t := t.Base.(type) {
case *http.Transport:
transport = t
case *LoggingTransport:
switch t := t.RoundTripper.(type) {
case *http.Transport:
transport = t
}
}
}
if transport == nil {
// we don't know how to access the http.Transport, most likely the
// auth.Client.Client was provided by API user
return nil, fmt.Errorf("unable to access TLS client configuration, the provided HTTP Transport is not supported, given: %T", client.Client.Transport)
}
switch {
case setConfig != nil:
transport.TLSClientConfig = setConfig
case transport.TLSClientConfig == nil:
transport.TLSClientConfig = &tls.Config{}
}
return transport.TLSClientConfig, nil
}
// LoginOptInsecure returns a function that sets the insecure setting on login
func LoginOptInsecure(insecure bool) LoginOption {
return func(o *loginOperation) {
tlsConfig, err := ensureTLSConfig(o.client.authorizer, nil)
if err != nil {
panic(err)
}
tlsConfig.InsecureSkipVerify = insecure
}
}
// LoginOptTLSClientConfig returns a function that sets the TLS settings on login.
func LoginOptTLSClientConfig(certFile, keyFile, caFile string) LoginOption {
return func(o *loginOperation) {
if (certFile == "" || keyFile == "") && caFile == "" {
return
}
tlsConfig, err := ensureTLSConfig(o.client.authorizer, nil)
if err != nil {
panic(err)
}
if certFile != "" && keyFile != "" {
authCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
panic(err)
}
tlsConfig.Certificates = []tls.Certificate{authCert}
}
if caFile != "" {
certPool := x509.NewCertPool()
ca, err := os.ReadFile(caFile)
if err != nil {
panic(err)
}
if !certPool.AppendCertsFromPEM(ca) {
panic(fmt.Errorf("unable to parse CA file: %q", caFile))
}
tlsConfig.RootCAs = certPool
}
}
}
// LoginOptTLSClientConfigFromConfig returns a function that sets the TLS settings on login
// receiving the configuration in memory rather than from files.
func LoginOptTLSClientConfigFromConfig(conf *tls.Config) LoginOption {
return func(o *loginOperation) {
_, err := ensureTLSConfig(o.client.authorizer, conf)
if err != nil {
panic(err)
}
}
}
type (
// LogoutOption allows specifying various settings on logout
LogoutOption func(*logoutOperation)
logoutOperation struct{}
)
// Logout logs out of a registry
func (c *Client) Logout(host string, opts ...LogoutOption) error {
operation := &logoutOperation{}
for _, opt := range opts {
opt(operation)
}
if err := credentials.Logout(context.Background(), c.credentialsStore, host); err != nil {
return err
}
_, _ = fmt.Fprintf(c.out, "Removing login credentials for %s\n", host)
return nil
}
type (
// PullOption allows specifying various settings on pull
PullOption func(*pullOperation)
// PullResult is the result returned upon successful pull.
PullResult struct {
Manifest *DescriptorPullSummary `json:"manifest"`
Config *DescriptorPullSummary `json:"config"`
Chart *DescriptorPullSummaryWithMeta `json:"chart"`
Prov *DescriptorPullSummary `json:"prov"`
Ref string `json:"ref"`
}
DescriptorPullSummary struct {
Data []byte `json:"-"`
Digest string `json:"digest"`
Size int64 `json:"size"`
}
DescriptorPullSummaryWithMeta struct {
DescriptorPullSummary
Meta *chart.Metadata `json:"meta"`
}
pullOperation struct {
withChart bool
withProv bool
ignoreMissingProv bool
}
)
// processChartPull handles chart-specific processing of a generic pull result
func (c *Client) processChartPull(genericResult *GenericPullResult, operation *pullOperation) (*PullResult, error) {
var err error
// Chart-specific validation
minNumDescriptors := 1 // 1 for the config
if operation.withChart {
minNumDescriptors++
}
if operation.withProv && !operation.ignoreMissingProv {
minNumDescriptors++
}
numDescriptors := len(genericResult.Descriptors)
if numDescriptors < minNumDescriptors {
return nil, fmt.Errorf("manifest does not contain minimum number of descriptors (%d), descriptors found: %d",
minNumDescriptors, numDescriptors)
}
// Find chart-specific descriptors
var configDescriptor *ocispec.Descriptor
var chartDescriptor *ocispec.Descriptor
var provDescriptor *ocispec.Descriptor
for _, descriptor := range genericResult.Descriptors {
d := descriptor
switch d.MediaType {
case ConfigMediaType:
configDescriptor = &d
case ChartLayerMediaType:
chartDescriptor = &d
case ProvLayerMediaType:
provDescriptor = &d
case LegacyChartLayerMediaType:
chartDescriptor = &d
_, _ = fmt.Fprintf(c.out, "Warning: chart media type %s is deprecated\n", LegacyChartLayerMediaType)
}
}
// Chart-specific validation
if configDescriptor == nil {
return nil, fmt.Errorf("could not load config with mediatype %s", ConfigMediaType)
}
if operation.withChart && chartDescriptor == nil {
return nil, fmt.Errorf("manifest does not contain a layer with mediatype %s",
ChartLayerMediaType)
}
var provMissing bool
if operation.withProv && provDescriptor == nil {
if operation.ignoreMissingProv {
provMissing = true
} else {
return nil, fmt.Errorf("manifest does not contain a layer with mediatype %s",
ProvLayerMediaType)
}
}
// Build chart-specific result
result := &PullResult{
Manifest: &DescriptorPullSummary{
Digest: genericResult.Manifest.Digest.String(),
Size: genericResult.Manifest.Size,
},
Config: &DescriptorPullSummary{
Digest: configDescriptor.Digest.String(),
Size: configDescriptor.Size,
},
Chart: &DescriptorPullSummaryWithMeta{},
Prov: &DescriptorPullSummary{},
Ref: genericResult.Ref,
}
// Fetch data using generic client
genericClient := c.Generic()
result.Manifest.Data, err = genericClient.GetDescriptorData(genericResult.MemoryStore, genericResult.Manifest)
if err != nil {
return nil, fmt.Errorf("unable to retrieve blob with digest %s: %w", genericResult.Manifest.Digest, err)
}
result.Config.Data, err = genericClient.GetDescriptorData(genericResult.MemoryStore, *configDescriptor)
if err != nil {
return nil, fmt.Errorf("unable to retrieve blob with digest %s: %w", configDescriptor.Digest, err)
}
if err := json.Unmarshal(result.Config.Data, &result.Chart.Meta); err != nil {
return nil, err
}
if operation.withChart {
result.Chart.Data, err = genericClient.GetDescriptorData(genericResult.MemoryStore, *chartDescriptor)
if err != nil {
return nil, fmt.Errorf("unable to retrieve blob with digest %s: %w", chartDescriptor.Digest, err)
}
result.Chart.Digest = chartDescriptor.Digest.String()
result.Chart.Size = chartDescriptor.Size
}
if operation.withProv && !provMissing {
result.Prov.Data, err = genericClient.GetDescriptorData(genericResult.MemoryStore, *provDescriptor)
if err != nil {
return nil, fmt.Errorf("unable to retrieve blob with digest %s: %w", provDescriptor.Digest, err)
}
result.Prov.Digest = provDescriptor.Digest.String()
result.Prov.Size = provDescriptor.Size
}
_, _ = fmt.Fprintf(c.out, "Pulled: %s\n", result.Ref)
_, _ = fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest)
if strings.Contains(result.Ref, "_") {
_, _ = fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref)
_, _ = fmt.Fprint(c.out, registryUnderscoreMessage+"\n")
}
return result, nil
}
// Pull downloads a chart from a registry
func (c *Client) Pull(ref string, options ...PullOption) (*PullResult, error) {
operation := &pullOperation{
withChart: true, // By default, always download the chart layer
}
for _, option := range options {
option(operation)
}
if !operation.withChart && !operation.withProv {
return nil, errors.New(
"must specify at least one layer to pull (chart/prov)")
}
// Build allowed media types for chart pull
allowedMediaTypes := []string{
ocispec.MediaTypeImageManifest,
ConfigMediaType,
}
if operation.withChart {
allowedMediaTypes = append(allowedMediaTypes, ChartLayerMediaType, LegacyChartLayerMediaType)
}
if operation.withProv {
allowedMediaTypes = append(allowedMediaTypes, ProvLayerMediaType)
}
// Use generic client for the pull operation
genericClient := c.Generic()
genericResult, err := genericClient.PullGeneric(ref, GenericPullOptions{
AllowedMediaTypes: allowedMediaTypes,
})
if err != nil {
return nil, err
}
// Process the result with chart-specific logic
return c.processChartPull(genericResult, operation)
}
// PullOptWithChart returns a function that sets the withChart setting on pull
func PullOptWithChart(withChart bool) PullOption {
return func(operation *pullOperation) {
operation.withChart = withChart
}
}
// PullOptWithProv returns a function that sets the withProv setting on pull
func PullOptWithProv(withProv bool) PullOption {
return func(operation *pullOperation) {
operation.withProv = withProv
}
}
// PullOptIgnoreMissingProv returns a function that sets the ignoreMissingProv setting on pull
func PullOptIgnoreMissingProv(ignoreMissingProv bool) PullOption {
return func(operation *pullOperation) {
operation.ignoreMissingProv = ignoreMissingProv
}
}
type (
// PushOption allows specifying various settings on push
PushOption func(*pushOperation)
// PushResult is the result returned upon successful push.
PushResult struct {
Manifest *descriptorPushSummary `json:"manifest"`
Config *descriptorPushSummary `json:"config"`
Chart *descriptorPushSummaryWithMeta `json:"chart"`
Prov *descriptorPushSummary `json:"prov"`
Ref string `json:"ref"`
}
descriptorPushSummary struct {
Digest string `json:"digest"`
Size int64 `json:"size"`
}
descriptorPushSummaryWithMeta struct {
descriptorPushSummary
Meta *chart.Metadata `json:"meta"`
}
pushOperation struct {
provData []byte
strictMode bool
creationTime string
}
)
// Push uploads a chart to a registry.
func (c *Client) Push(data []byte, ref string, options ...PushOption) (*PushResult, error) {
parsedRef, err := newReference(ref)
if err != nil {
return nil, err
}
operation := &pushOperation{
strictMode: true, // By default, enable strict mode
}
for _, option := range options {
option(operation)
}
meta, err := extractChartMeta(data)
if err != nil {
return nil, err
}
if operation.strictMode {
if !strings.HasSuffix(ref, fmt.Sprintf("/%s:%s", meta.Name, meta.Version)) {
return nil, errors.New(
"strict mode enabled, ref basename and tag must match the chart name and version")
}
}
ctx := context.Background()
memoryStore := memory.New()
chartDescriptor, err := oras.PushBytes(ctx, memoryStore, ChartLayerMediaType, data)
if err != nil {
return nil, err
}
configData, err := json.Marshal(meta)
if err != nil {
return nil, err
}
configDescriptor, err := oras.PushBytes(ctx, memoryStore, ConfigMediaType, configData)
if err != nil {
return nil, err
}
layers := []ocispec.Descriptor{chartDescriptor}
var provDescriptor ocispec.Descriptor
if operation.provData != nil {
provDescriptor, err = oras.PushBytes(ctx, memoryStore, ProvLayerMediaType, operation.provData)
if err != nil {
return nil, err
}
layers = append(layers, provDescriptor)
}
// sort layers for determinism, similar to how ORAS v1 does it
sort.Slice(layers, func(i, j int) bool {
return layers[i].Digest < layers[j].Digest
})
ociAnnotations := generateOCIAnnotations(meta, operation.creationTime)
manifestDescriptor, err := c.tagManifest(ctx, memoryStore, configDescriptor,
layers, ociAnnotations, parsedRef)
if err != nil {
return nil, err
}
repository, err := remote.NewRepository(parsedRef.String())
if err != nil {
return nil, err
}
repository.PlainHTTP = c.plainHTTP
repository.Client = c.authorizer
manifestDescriptor, err = oras.ExtendedCopy(ctx, memoryStore, parsedRef.String(), repository, parsedRef.String(), oras.DefaultExtendedCopyOptions)
if err != nil {
return nil, err
}
chartSummary := &descriptorPushSummaryWithMeta{
Meta: meta,
}
chartSummary.Digest = chartDescriptor.Digest.String()
chartSummary.Size = chartDescriptor.Size
result := &PushResult{
Manifest: &descriptorPushSummary{
Digest: manifestDescriptor.Digest.String(),
Size: manifestDescriptor.Size,
},
Config: &descriptorPushSummary{
Digest: configDescriptor.Digest.String(),
Size: configDescriptor.Size,
},
Chart: chartSummary,
Prov: &descriptorPushSummary{}, // prevent nil references
Ref: parsedRef.String(),
}
if operation.provData != nil {
result.Prov = &descriptorPushSummary{
Digest: provDescriptor.Digest.String(),
Size: provDescriptor.Size,
}
}
_, _ = fmt.Fprintf(c.out, "Pushed: %s\n", result.Ref)
_, _ = fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest)
if strings.Contains(parsedRef.orasReference.Reference, "_") {
_, _ = fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref)
_, _ = fmt.Fprint(c.out, registryUnderscoreMessage+"\n")
}
return result, err
}
// PushOptProvData returns a function that sets the prov bytes setting on push
func PushOptProvData(provData []byte) PushOption {
return func(operation *pushOperation) {
operation.provData = provData
}
}
// PushOptStrictMode returns a function that sets the strictMode setting on push
func PushOptStrictMode(strictMode bool) PushOption {
return func(operation *pushOperation) {
operation.strictMode = strictMode
}
}
// PushOptCreationTime returns a function that sets the creation time
func PushOptCreationTime(creationTime string) PushOption {
return func(operation *pushOperation) {
operation.creationTime = creationTime
}
}
// Tags provides a sorted list all semver compliant tags for a given repository
func (c *Client) Tags(ref string) ([]string, error) {
parsedReference, err := registry.ParseReference(ref)
if err != nil {
return nil, err
}
ctx := context.Background()
repository, err := remote.NewRepository(parsedReference.String())
if err != nil {
return nil, err
}
repository.PlainHTTP = c.plainHTTP
repository.Client = c.authorizer
var tagVersions []*semver.Version
err = repository.Tags(ctx, "", func(tags []string) error {
for _, tag := range tags {
// Change underscore (_) back to plus (+) for Helm
// See https://github.com/helm/helm/issues/10166
tagVersion, err := semver.StrictNewVersion(strings.ReplaceAll(tag, "_", "+"))
if err == nil {
tagVersions = append(tagVersions, tagVersion)
}
}
return nil
})
if err != nil {
return nil, err
}
// Sort the collection
sort.Sort(sort.Reverse(semver.Collection(tagVersions)))
tags := make([]string, len(tagVersions))
for iTv, tv := range tagVersions {
tags[iTv] = tv.String()
}
return tags, nil
}
// Resolve a reference to a descriptor.
func (c *Client) Resolve(ref string) (desc ocispec.Descriptor, err error) {
remoteRepository, err := remote.NewRepository(ref)
if err != nil {
return desc, err
}
remoteRepository.PlainHTTP = c.plainHTTP
remoteRepository.Client = c.authorizer
parsedReference, err := newReference(ref)
if err != nil {
return desc, err
}
ctx := context.Background()
parsedString := parsedReference.String()
return remoteRepository.Resolve(ctx, parsedString)
}
// ValidateReference for path and version
func (c *Client) ValidateReference(ref, version string, u *url.URL) (string, *url.URL, error) {
var tag string
registryReference, err := newReference(u.Host + u.Path)
if err != nil {
return "", nil, err
}
if version == "" {
// Use OCI URI tag as default
version = registryReference.Tag
} else {
if registryReference.Tag != "" && registryReference.Tag != version {
return "", nil, fmt.Errorf("chart reference and version mismatch: %s is not %s", version, registryReference.Tag)
}
}
if registryReference.Digest != "" {
if version == "" {
// Install by digest only
return "", u, nil
}
u.Path = fmt.Sprintf("%s@%s", registryReference.Repository, registryReference.Digest)
// Validate the tag if it was specified
path := registryReference.Registry + "/" + registryReference.Repository + ":" + version
desc, err := c.Resolve(path)
if err != nil {
// The resource does not have to be tagged when digest is specified
return "", u, nil
}
if desc.Digest.String() != registryReference.Digest {
return "", nil, fmt.Errorf("chart reference digest mismatch: %s is not %s", desc.Digest.String(), registryReference.Digest)
}
return registryReference.Digest, u, nil
}
// Evaluate whether an explicit version has been provided. Otherwise, determine version to use
_, errSemVer := semver.NewVersion(version)
if errSemVer == nil {
tag = version
} else {
// Retrieve list of repository tags
tags, err := c.Tags(strings.TrimPrefix(ref, fmt.Sprintf("%s://", OCIScheme)))
if err != nil {
return "", nil, err
}
if len(tags) == 0 {
return "", nil, fmt.Errorf("unable to locate any tags in provided repository: %s", ref)
}
// Determine if version provided
// If empty, try to get the highest available tag
// If exact version, try to find it
// If semver constraint string, try to find a match
tag, err = GetTagMatchingVersionOrConstraint(tags, version)
if err != nil {
return "", nil, err
}
}
u.Path = fmt.Sprintf("%s:%s", registryReference.Repository, tag)
// desc, err := c.Resolve(u.Path)
return "", u, err
}
// tagManifest prepares and tags a manifest in memory storage
func (c *Client) tagManifest(ctx context.Context, memoryStore *memory.Store,
configDescriptor ocispec.Descriptor, layers []ocispec.Descriptor,
ociAnnotations map[string]string, parsedRef reference) (ocispec.Descriptor, error) {
manifest := ocispec.Manifest{
Versioned: specs.Versioned{SchemaVersion: 2},
Config: configDescriptor,
Layers: layers,
Annotations: ociAnnotations,
}
manifestData, err := json.Marshal(manifest)
if err != nil {
return ocispec.Descriptor{}, err
}
return oras.TagBytes(ctx, memoryStore, ocispec.MediaTypeImageManifest,
manifestData, parsedRef.String())
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/transport_test.go | pkg/registry/transport_test.go | /*
Copyright The Helm 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 registry
import (
"bytes"
"errors"
"io"
"net/http"
"testing"
)
var errMockRead = errors.New("mock read error")
type errorReader struct{}
func (e *errorReader) Read(_ []byte) (n int, err error) {
return 0, errMockRead
}
func Test_isPrintableContentType(t *testing.T) {
tests := []struct {
name string
contentType string
want bool
}{
{
name: "Empty content type",
contentType: "",
want: false,
},
{
name: "General JSON type",
contentType: "application/json",
want: true,
},
{
name: "General JSON type with charset",
contentType: "application/json; charset=utf-8",
want: true,
},
{
name: "Random type with application/json prefix",
contentType: "application/jsonwhatever",
want: false,
},
{
name: "Manifest type in JSON",
contentType: "application/vnd.oci.image.manifest.v1+json",
want: true,
},
{
name: "Manifest type in JSON with charset",
contentType: "application/vnd.oci.image.manifest.v1+json; charset=utf-8",
want: true,
},
{
name: "Random content type in JSON",
contentType: "application/whatever+json",
want: true,
},
{
name: "Plain text type",
contentType: "text/plain",
want: true,
},
{
name: "Plain text type with charset",
contentType: "text/plain; charset=utf-8",
want: true,
},
{
name: "Random type with text/plain prefix",
contentType: "text/plainnnnn",
want: false,
},
{
name: "HTML type",
contentType: "text/html",
want: true,
},
{
name: "Plain text type with charset",
contentType: "text/html; charset=utf-8",
want: true,
},
{
name: "Random type with text/html prefix",
contentType: "text/htmlllll",
want: false,
},
{
name: "Binary type",
contentType: "application/octet-stream",
want: false,
},
{
name: "Unknown type",
contentType: "unknown/unknown",
want: false,
},
{
name: "Invalid type",
contentType: "text/",
want: false,
},
{
name: "Random string",
contentType: "random123!@#",
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isPrintableContentType(tt.contentType); got != tt.want {
t.Errorf("isPrintableContentType() = %v, want %v", got, tt.want)
}
})
}
}
func Test_logResponseBody(t *testing.T) {
tests := []struct {
name string
resp *http.Response
want string
wantData []byte
}{
{
name: "Nil body",
resp: &http.Response{
Body: nil,
Header: http.Header{"Content-Type": []string{"application/json"}},
},
want: " No response body to print",
},
{
name: "No body",
wantData: nil,
resp: &http.Response{
Body: http.NoBody,
ContentLength: 100, // in case of HEAD response, the content length is set but the body is empty
Header: http.Header{"Content-Type": []string{"application/json"}},
},
want: " No response body to print",
},
{
name: "Empty body",
wantData: []byte(""),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte(""))),
ContentLength: 0,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: " Response body is empty",
},
{
name: "Unknown content length",
wantData: []byte("whatever"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("whatever"))),
ContentLength: -1,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: "whatever",
},
{
name: "Missing content type header",
wantData: []byte("whatever"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("whatever"))),
ContentLength: 8,
},
want: " Response body without a content type is not printed",
},
{
name: "Empty content type header",
wantData: []byte("whatever"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("whatever"))),
ContentLength: 8,
Header: http.Header{"Content-Type": []string{""}},
},
want: " Response body without a content type is not printed",
},
{
name: "Non-printable content type",
wantData: []byte("binary data"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("binary data"))),
ContentLength: 11,
Header: http.Header{"Content-Type": []string{"application/octet-stream"}},
},
want: " Response body of content type \"application/octet-stream\" is not printed",
},
{
name: "Body at the limit",
wantData: bytes.Repeat([]byte("a"), int(payloadSizeLimit)),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader(bytes.Repeat([]byte("a"), int(payloadSizeLimit)))),
ContentLength: payloadSizeLimit,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: string(bytes.Repeat([]byte("a"), int(payloadSizeLimit))),
},
{
name: "Body larger than limit",
wantData: bytes.Repeat([]byte("a"), int(payloadSizeLimit+1)),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader(bytes.Repeat([]byte("a"), int(payloadSizeLimit+1)))), // 1 byte larger than limit
ContentLength: payloadSizeLimit + 1,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: string(bytes.Repeat([]byte("a"), int(payloadSizeLimit))) + "\n...(truncated)",
},
{
name: "Printable content type within limit",
wantData: []byte("data"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("data"))),
ContentLength: 4,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: "data",
},
{
name: "Actual body size is larger than content length",
wantData: []byte("data"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("data"))),
ContentLength: 3, // mismatched content length
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: "data",
},
{
name: "Actual body size is larger than content length and exceeds limit",
wantData: bytes.Repeat([]byte("a"), int(payloadSizeLimit+1)),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader(bytes.Repeat([]byte("a"), int(payloadSizeLimit+1)))), // 1 byte larger than limit
ContentLength: 1, // mismatched content length
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: string(bytes.Repeat([]byte("a"), int(payloadSizeLimit))) + "\n...(truncated)",
},
{
name: "Actual body size is smaller than content length",
wantData: []byte("data"),
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte("data"))),
ContentLength: 5, // mismatched content length
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: "data",
},
{
name: "Body contains token",
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte(`{"token":"12345"}`))),
ContentLength: 17,
Header: http.Header{"Content-Type": []string{"application/json"}},
},
wantData: []byte(`{"token":"12345"}`),
want: " Response body redacted due to potential credentials",
},
{
name: "Body contains access_token",
resp: &http.Response{
Body: io.NopCloser(bytes.NewReader([]byte(`{"access_token":"12345"}`))),
ContentLength: 17,
Header: http.Header{"Content-Type": []string{"application/json"}},
},
wantData: []byte(`{"access_token":"12345"}`),
want: " Response body redacted due to potential credentials",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := logResponseBody(tt.resp); got != tt.want {
t.Errorf("logResponseBody() = %v, want %v", got, tt.want)
}
// validate the response body
if tt.resp.Body != nil {
readBytes, err := io.ReadAll(tt.resp.Body)
if err != nil {
t.Errorf("failed to read body after logResponseBody(), err= %v", err)
}
if !bytes.Equal(readBytes, tt.wantData) {
t.Errorf("resp.Body after logResponseBody() = %v, want %v", readBytes, tt.wantData)
}
if closeErr := tt.resp.Body.Close(); closeErr != nil {
t.Errorf("failed to close body after logResponseBody(), err= %v", closeErr)
}
}
})
}
}
func Test_logResponseBody_error(t *testing.T) {
tests := []struct {
name string
resp *http.Response
want string
}{
{
name: "Error reading body",
resp: &http.Response{
Body: io.NopCloser(&errorReader{}),
ContentLength: 10,
Header: http.Header{"Content-Type": []string{"text/plain"}},
},
want: " Error reading response body: mock read error",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := logResponseBody(tt.resp); got != tt.want {
t.Errorf("logResponseBody() = %v, want %v", got, tt.want)
}
if closeErr := tt.resp.Body.Close(); closeErr != nil {
t.Errorf("failed to close body after logResponseBody(), err= %v", closeErr)
}
})
}
}
func Test_containsCredentials(t *testing.T) {
tests := []struct {
name string
body string
want bool
}{
{
name: "Contains token keyword",
body: `{"token": "12345"}`,
want: true,
},
{
name: "Contains quoted token keyword",
body: `whatever "token" blah`,
want: true,
},
{
name: "Contains unquoted token keyword",
body: `whatever token blah`,
want: false,
},
{
name: "Contains access_token keyword",
body: `{"access_token": "12345"}`,
want: true,
},
{
name: "Contains quoted access_token keyword",
body: `whatever "access_token" blah`,
want: true,
},
{
name: "Contains unquoted access_token keyword",
body: `whatever access_token blah`,
want: false,
},
{
name: "Does not contain credentials",
body: `{"key": "value"}`,
want: false,
},
{
name: "Empty body",
body: ``,
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := containsCredentials(tt.body); got != tt.want {
t.Errorf("containsCredentials() = %v, want %v", got, tt.want)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/tag_test.go | pkg/registry/tag_test.go | /*
Copyright The Helm 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 registry
import (
"strings"
"testing"
)
func TestGetTagMatchingVersionOrConstraint_ExactMatch(t *testing.T) {
tags := []string{"1.0.0", "1.2.3", "2.0.0"}
got, err := GetTagMatchingVersionOrConstraint(tags, "1.2.3")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.2.3" {
t.Fatalf("expected exact match '1.2.3', got %q", got)
}
}
func TestGetTagMatchingVersionOrConstraint_EmptyVersionWildcard(t *testing.T) {
// Includes a non-semver tag which should be skipped
tags := []string{"latest", "0.9.0", "1.0.0"}
got, err := GetTagMatchingVersionOrConstraint(tags, "")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
// Should pick the first valid semver tag in order, which is 0.9.0
if got != "0.9.0" {
t.Fatalf("expected '0.9.0', got %q", got)
}
}
func TestGetTagMatchingVersionOrConstraint_ConstraintRange(t *testing.T) {
tags := []string{"0.5.0", "1.0.0", "1.1.0", "2.0.0"}
// Caret range
got, err := GetTagMatchingVersionOrConstraint(tags, "^1.0.0")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.0.0" { // first match in order
t.Fatalf("expected '1.0.0', got %q", got)
}
// Compound range
got, err = GetTagMatchingVersionOrConstraint(tags, ">=1.0.0 <2.0.0")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.0.0" {
t.Fatalf("expected '1.0.0', got %q", got)
}
}
func TestGetTagMatchingVersionOrConstraint_InvalidConstraint(t *testing.T) {
tags := []string{"1.0.0"}
_, err := GetTagMatchingVersionOrConstraint(tags, ">a1")
if err == nil {
t.Fatalf("expected error for invalid constraint")
}
}
func TestGetTagMatchingVersionOrConstraint_NoMatches(t *testing.T) {
tags := []string{"0.1.0", "0.2.0"}
_, err := GetTagMatchingVersionOrConstraint(tags, ">=1.0.0")
if err == nil {
t.Fatalf("expected error when no tags match")
}
if !strings.Contains(err.Error(), ">=1.0.0") {
t.Fatalf("expected error to contain version string, got: %v", err)
}
}
func TestGetTagMatchingVersionOrConstraint_SkipsNonSemverTags(t *testing.T) {
tags := []string{"alpha", "1.0.0", "beta", "1.1.0"}
got, err := GetTagMatchingVersionOrConstraint(tags, ">=1.0.0 <2.0.0")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.0.0" {
t.Fatalf("expected '1.0.0', got %q", got)
}
}
func TestGetTagMatchingVersionOrConstraint_OrderMatters_FirstMatchReturned(t *testing.T) {
// Both 1.2.0 and 1.3.0 satisfy >=1.2.0 <2.0.0, but the function returns the first in input order
tags := []string{"1.3.0", "1.2.0"}
got, err := GetTagMatchingVersionOrConstraint(tags, ">=1.2.0 <2.0.0")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.3.0" {
t.Fatalf("expected '1.3.0' (first satisfying tag), got %q", got)
}
}
func TestGetTagMatchingVersionOrConstraint_ExactMatchHasPrecedence(t *testing.T) {
// Exact match should be returned even if another earlier tag would match the parsed constraint
tags := []string{"1.3.0", "1.2.3"}
got, err := GetTagMatchingVersionOrConstraint(tags, "1.2.3")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.2.3" {
t.Fatalf("expected exact match '1.2.3', got %q", got)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/plugin_test.go | pkg/registry/plugin_test.go | /*
Copyright The Helm 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 registry
import (
"testing"
)
func TestGetPluginName(t *testing.T) {
tests := []struct {
name string
source string
expected string
expectErr bool
}{
{
name: "valid OCI reference with tag",
source: "oci://ghcr.io/user/plugin-name:v1.0.0",
expected: "plugin-name",
},
{
name: "valid OCI reference with digest",
source: "oci://ghcr.io/user/plugin-name@sha256:1234567890abcdef",
expected: "plugin-name",
},
{
name: "valid OCI reference without tag",
source: "oci://ghcr.io/user/plugin-name",
expected: "plugin-name",
},
{
name: "valid OCI reference with multiple path segments",
source: "oci://registry.example.com/org/team/plugin-name:latest",
expected: "plugin-name",
},
{
name: "valid OCI reference with plus signs in tag",
source: "oci://registry.example.com/user/plugin-name:v1.0.0+build.1",
expected: "plugin-name",
},
{
name: "valid OCI reference - single path segment",
source: "oci://registry.example.com/plugin",
expected: "plugin",
},
{
name: "invalid OCI reference - no repository",
source: "oci://registry.example.com",
expectErr: true,
},
{
name: "invalid OCI reference - malformed",
source: "not-an-oci-reference",
expectErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pluginName, err := GetPluginName(tt.source)
if tt.expectErr {
if err == nil {
t.Errorf("expected error but got none")
}
return
}
if err != nil {
t.Errorf("unexpected error: %v", err)
return
}
if pluginName != tt.expected {
t.Errorf("expected plugin name %q, got %q", tt.expected, pluginName)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/client_test.go | pkg/registry/client_test.go | /*
Copyright The Helm 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 registry
import (
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/stretchr/testify/require"
"oras.land/oras-go/v2/content/memory"
)
// Inspired by oras test
// https://github.com/oras-project/oras-go/blob/05a2b09cbf2eab1df691411884dc4df741ec56ab/content_test.go#L1802
func TestTagManifestTransformsReferences(t *testing.T) {
memStore := memory.New()
client := &Client{out: io.Discard}
ctx := t.Context()
refWithPlus := "test-registry.io/charts/test:1.0.0+metadata"
expectedRef := "test-registry.io/charts/test:1.0.0_metadata" // + becomes _
configDesc := ocispec.Descriptor{MediaType: ConfigMediaType, Digest: "sha256:config", Size: 100}
layers := []ocispec.Descriptor{{MediaType: ChartLayerMediaType, Digest: "sha256:layer", Size: 200}}
parsedRef, err := newReference(refWithPlus)
require.NoError(t, err)
desc, err := client.tagManifest(ctx, memStore, configDesc, layers, nil, parsedRef)
require.NoError(t, err)
transformedDesc, err := memStore.Resolve(ctx, expectedRef)
require.NoError(t, err, "Should find the reference with _ instead of +")
require.Equal(t, desc.Digest, transformedDesc.Digest)
_, err = memStore.Resolve(ctx, refWithPlus)
require.Error(t, err, "Should NOT find the reference with the original +")
}
// Verifies that Login always restores ForceAttemptOAuth2 to false on success.
func TestLogin_ResetsForceAttemptOAuth2_OnSuccess(t *testing.T) {
t.Parallel()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v2/" {
// Accept either HEAD or GET
w.WriteHeader(http.StatusOK)
return
}
http.NotFound(w, r)
}))
defer srv.Close()
host := strings.TrimPrefix(srv.URL, "http://")
credFile := filepath.Join(t.TempDir(), "config.json")
c, err := NewClient(
ClientOptWriter(io.Discard),
ClientOptCredentialsFile(credFile),
)
if err != nil {
t.Fatalf("NewClient error: %v", err)
}
if c.authorizer == nil || c.authorizer.ForceAttemptOAuth2 {
t.Fatalf("expected ForceAttemptOAuth2 default to be false")
}
// Call Login with plain HTTP against our test server
if err := c.Login(host, LoginOptPlainText(true), LoginOptBasicAuth("u", "p")); err != nil {
t.Fatalf("Login error: %v", err)
}
if c.authorizer.ForceAttemptOAuth2 {
t.Errorf("ForceAttemptOAuth2 should be false after successful Login")
}
}
// Verifies that Login restores ForceAttemptOAuth2 to false even when ping fails.
func TestLogin_ResetsForceAttemptOAuth2_OnFailure(t *testing.T) {
t.Parallel()
// Start and immediately close, so connections will fail
srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {}))
host := strings.TrimPrefix(srv.URL, "http://")
srv.Close()
credFile := filepath.Join(t.TempDir(), "config.json")
c, err := NewClient(
ClientOptWriter(io.Discard),
ClientOptCredentialsFile(credFile),
)
if err != nil {
t.Fatalf("NewClient error: %v", err)
}
// Invoke Login, expect an error but ForceAttemptOAuth2 must end false
_ = c.Login(host, LoginOptPlainText(true), LoginOptBasicAuth("u", "p"))
if c.authorizer.ForceAttemptOAuth2 {
t.Errorf("ForceAttemptOAuth2 should be false after failed Login")
}
}
// TestWarnIfHostHasPath verifies that warnIfHostHasPath correctly detects path components.
func TestWarnIfHostHasPath(t *testing.T) {
t.Parallel()
tests := []struct {
name string
host string
wantWarn bool
}{
{
name: "domain only",
host: "ghcr.io",
wantWarn: false,
},
{
name: "domain with port",
host: "localhost:8000",
wantWarn: false,
},
{
name: "domain with repository path",
host: "ghcr.io/terryhowe",
wantWarn: true,
},
{
name: "domain with nested path",
host: "ghcr.io/terryhowe/myrepo",
wantWarn: true,
},
{
name: "localhost with port and path",
host: "localhost:8000/myrepo",
wantWarn: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := warnIfHostHasPath(tt.host)
if got != tt.wantWarn {
t.Errorf("warnIfHostHasPath(%q) = %v, want %v", tt.host, got, tt.wantWarn)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/main_test.go | pkg/registry/main_test.go | /*
Copyright The Helm 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 registry
import (
"net"
"os"
"testing"
"github.com/foxcpp/go-mockdns"
)
func TestMain(m *testing.M) {
// A mock DNS server needed for TLS connection testing.
var srv *mockdns.Server
var err error
srv, err = mockdns.NewServer(map[string]mockdns.Zone{
"helm-test-registry.": {
A: []string{"127.0.0.1"},
},
}, false)
if err != nil {
panic(err)
}
saveDialFunction := net.DefaultResolver.Dial
srv.PatchNet(net.DefaultResolver)
// Run all tests in the package
code := m.Run()
net.DefaultResolver.Dial = saveDialFunction
_ = srv.Close()
os.Exit(code)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/client_http_test.go | pkg/registry/client_http_test.go | /*
Copyright The Helm 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 registry
import (
"errors"
"fmt"
"os"
"testing"
"github.com/stretchr/testify/suite"
"oras.land/oras-go/v2/content"
)
type HTTPRegistryClientTestSuite struct {
TestRegistry
}
func (suite *HTTPRegistryClientTestSuite) SetupSuite() {
// init test client
setup(&suite.TestRegistry, false, false)
}
func (suite *HTTPRegistryClientTestSuite) TearDownSuite() {
teardown(&suite.TestRegistry)
_ = os.RemoveAll(suite.WorkspaceDir)
}
func (suite *HTTPRegistryClientTestSuite) Test_0_Login() {
err := suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth("badverybad", "ohsobad"),
LoginOptPlainText(true))
suite.NotNil(err, "error logging into registry with bad credentials")
err = suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth(testUsername, testPassword),
LoginOptPlainText(true))
suite.Nil(err, "no error logging into registry with good credentials")
}
func (suite *HTTPRegistryClientTestSuite) Test_1_Push() {
testPush(&suite.TestRegistry)
}
func (suite *HTTPRegistryClientTestSuite) Test_2_Pull() {
testPull(&suite.TestRegistry)
}
func (suite *HTTPRegistryClientTestSuite) Test_3_Tags() {
testTags(&suite.TestRegistry)
}
func (suite *HTTPRegistryClientTestSuite) Test_4_ManInTheMiddle() {
ref := fmt.Sprintf("%s/testrepo/supposedlysafechart:9.9.9", suite.CompromisedRegistryHost)
// returns content that does not match the expected digest
_, err := suite.RegistryClient.Pull(ref)
suite.NotNil(err)
suite.True(errors.Is(err, content.ErrMismatchedDigest))
}
func TestHTTPRegistryClientTestSuite(t *testing.T) {
suite.Run(t, new(HTTPRegistryClientTestSuite))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/tag.go | pkg/registry/tag.go | /*
Copyright The Helm 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 registry // import "helm.sh/helm/v4/pkg/registry"
import (
"fmt"
"github.com/Masterminds/semver/v3"
)
func GetTagMatchingVersionOrConstraint(tags []string, versionString string) (string, error) {
var constraint *semver.Constraints
if versionString == "" {
// If the string is empty, set a wildcard constraint
constraint, _ = semver.NewConstraint("*")
} else {
// when customer inputs a specific version, check whether there's an exact match first
for _, v := range tags {
if versionString == v {
return v, nil
}
}
// Otherwise set constraint to the string given
var err error
constraint, err = semver.NewConstraint(versionString)
if err != nil {
return "", err
}
}
// Otherwise try to find the first available version matching the string,
// in case it is a constraint
for _, v := range tags {
test, err := semver.NewVersion(v)
if err != nil {
continue
}
if constraint.Check(test) {
return v, nil
}
}
return "", fmt.Errorf("could not locate a version matching provided version string %s", versionString)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/reference_test.go | pkg/registry/reference_test.go | /*
Copyright The Helm 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 registry
import "testing"
func verify(t *testing.T, actual reference, registry, repository, tag, digest string) {
t.Helper()
if registry != actual.orasReference.Registry {
t.Errorf("Oras reference registry expected %v actual %v", registry, actual.Registry)
}
if repository != actual.orasReference.Repository {
t.Errorf("Oras reference repository expected %v actual %v", repository, actual.Repository)
}
if tag != actual.orasReference.Reference {
t.Errorf("Oras reference reference expected %v actual %v", tag, actual.Tag)
}
if registry != actual.Registry {
t.Errorf("Registry expected %v actual %v", registry, actual.Registry)
}
if repository != actual.Repository {
t.Errorf("Repository expected %v actual %v", repository, actual.Repository)
}
if tag != actual.Tag {
t.Errorf("Tag expected %v actual %v", tag, actual.Tag)
}
if digest != actual.Digest {
t.Errorf("Digest expected %v actual %v", digest, actual.Digest)
}
expectedString := registry
if repository != "" {
expectedString = expectedString + "/" + repository
}
if tag != "" {
expectedString = expectedString + ":" + tag
} else {
expectedString = expectedString + "@" + digest
}
if actual.String() != expectedString {
t.Errorf("String expected %s actual %s", expectedString, actual.String())
}
}
func TestNewReference(t *testing.T) {
actual, err := newReference("registry.example.com/repository:1.0@sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "registry.example.com", "repository", "1.0", "sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
actual, err = newReference("oci://registry.example.com/repository:1.0@sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "registry.example.com", "repository", "1.0", "sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
actual, err = newReference("a/b:1@c")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "a", "b", "1", "c")
actual, err = newReference("a/b:@")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "a", "b", "", "")
actual, err = newReference("registry.example.com/repository:1.0+001")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "registry.example.com", "repository", "1.0_001", "")
actual, err = newReference("thing:1.0")
if err == nil {
t.Errorf("Expect error error %v", err)
}
verify(t, actual, "", "", "", "")
actual, err = newReference("registry.example.com/the/repository@sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
if err != nil {
t.Errorf("Unexpected error %v", err)
}
verify(t, actual, "registry.example.com", "the/repository", "", "sha256:c6841b3a895f1444a6738b5d04564a57e860ce42f8519c3be807fb6d9bee7888")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/client_tls_test.go | pkg/registry/client_tls_test.go | /*
Copyright The Helm 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 registry
import (
"crypto/tls"
"crypto/x509"
"os"
"testing"
"github.com/stretchr/testify/suite"
)
type TLSRegistryClientTestSuite struct {
TestRegistry
}
func (suite *TLSRegistryClientTestSuite) SetupSuite() {
// init test client
setup(&suite.TestRegistry, true, false)
}
func (suite *TLSRegistryClientTestSuite) TearDownSuite() {
teardown(&suite.TestRegistry)
_ = os.RemoveAll(suite.WorkspaceDir)
}
func (suite *TLSRegistryClientTestSuite) Test_0_Login() {
err := suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth("badverybad", "ohsobad"),
LoginOptTLSClientConfig(tlsCert, tlsKey, tlsCA))
suite.NotNil(err, "error logging into registry with bad credentials")
err = suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth(testUsername, testPassword),
LoginOptTLSClientConfig(tlsCert, tlsKey, tlsCA))
suite.Nil(err, "no error logging into registry with good credentials")
}
func (suite *TLSRegistryClientTestSuite) Test_1_Login() {
err := suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth("badverybad", "ohsobad"),
LoginOptTLSClientConfigFromConfig(&tls.Config{}))
suite.NotNil(err, "error logging into registry with bad credentials")
// Create a *tls.Config from tlsCert, tlsKey, and tlsCA.
cert, err := tls.LoadX509KeyPair(tlsCert, tlsKey)
suite.Nil(err, "error loading x509 key pair")
rootCAs := x509.NewCertPool()
caCert, err := os.ReadFile(tlsCA)
suite.Nil(err, "error reading CA certificate")
rootCAs.AppendCertsFromPEM(caCert)
conf := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: rootCAs,
}
err = suite.RegistryClient.Login(suite.DockerRegistryHost,
LoginOptBasicAuth(testUsername, testPassword),
LoginOptTLSClientConfigFromConfig(conf))
suite.Nil(err, "no error logging into registry with good credentials")
}
func (suite *TLSRegistryClientTestSuite) Test_1_Push() {
testPush(&suite.TestRegistry)
}
func (suite *TLSRegistryClientTestSuite) Test_2_Pull() {
testPull(&suite.TestRegistry)
}
func (suite *TLSRegistryClientTestSuite) Test_3_Tags() {
testTags(&suite.TestRegistry)
}
func (suite *TLSRegistryClientTestSuite) Test_4_Logout() {
err := suite.RegistryClient.Logout("this-host-aint-real:5000")
if err != nil {
// credential backend for mac generates an error
suite.NotNil(err, "failed to delete the credential for this-host-aint-real:5000")
}
err = suite.RegistryClient.Logout(suite.DockerRegistryHost)
suite.Nil(err, "no error logging out of registry")
}
func TestTLSRegistryClientTestSuite(t *testing.T) {
suite.Run(t, new(TLSRegistryClientTestSuite))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/chart_test.go | pkg/registry/chart_test.go | /*
Copyright The Helm 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 registry // import "helm.sh/helm/v4/pkg/registry"
import (
"reflect"
"testing"
"time"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
func TestGenerateOCIChartAnnotations(t *testing.T) {
nowString := time.Now().Format(time.RFC3339)
tests := []struct {
name string
chart *chart.Metadata
expect map[string]string
}{
{
"Baseline chart",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
},
},
{
"Simple chart values",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Home: "https://helm.sh",
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.url": "https://helm.sh",
},
},
{
"Maintainer without email",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Home: "https://helm.sh",
Maintainers: []*chart.Maintainer{
{
Name: "John Snow",
},
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.url": "https://helm.sh",
"org.opencontainers.image.authors": "John Snow",
},
},
{
"Maintainer with email",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Home: "https://helm.sh",
Maintainers: []*chart.Maintainer{
{Name: "John Snow", Email: "john@winterfell.com"},
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.url": "https://helm.sh",
"org.opencontainers.image.authors": "John Snow (john@winterfell.com)",
},
},
{
"Multiple Maintainers",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Home: "https://helm.sh",
Maintainers: []*chart.Maintainer{
{Name: "John Snow", Email: "john@winterfell.com"},
{Name: "Jane Snow"},
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.url": "https://helm.sh",
"org.opencontainers.image.authors": "John Snow (john@winterfell.com), Jane Snow",
},
},
{
"Chart with Sources",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Sources: []string{
"https://github.com/helm/helm",
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.source": "https://github.com/helm/helm",
},
},
}
for _, tt := range tests {
result := generateChartOCIAnnotations(tt.chart, nowString)
if !reflect.DeepEqual(tt.expect, result) {
t.Errorf("%s: expected map %v, got %v", tt.name, tt.expect, result)
}
}
}
func TestGenerateOCIAnnotations(t *testing.T) {
nowString := time.Now().Format(time.RFC3339)
tests := []struct {
name string
chart *chart.Metadata
expect map[string]string
}{
{
"Baseline chart",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.created": nowString,
},
},
{
"Simple chart values with custom Annotations",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Annotations: map[string]string{
"extrakey": "extravlue",
"anotherkey": "anothervalue",
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.created": nowString,
"extrakey": "extravlue",
"anotherkey": "anothervalue",
},
},
{
"Verify Chart Name and Version cannot be overridden from annotations",
&chart.Metadata{
Name: "oci",
Version: "0.0.1",
Description: "OCI Helm Chart",
Annotations: map[string]string{
"org.opencontainers.image.title": "badchartname",
"org.opencontainers.image.version": "1.0.0",
"extrakey": "extravlue",
},
},
map[string]string{
"org.opencontainers.image.title": "oci",
"org.opencontainers.image.version": "0.0.1",
"org.opencontainers.image.description": "OCI Helm Chart",
"org.opencontainers.image.created": nowString,
"extrakey": "extravlue",
},
},
}
for _, tt := range tests {
result := generateOCIAnnotations(tt.chart, nowString)
if !reflect.DeepEqual(tt.expect, result) {
t.Errorf("%s: expected map %v, got %v", tt.name, tt.expect, result)
}
}
}
func TestGenerateOCICreatedAnnotations(t *testing.T) {
nowTime := time.Now()
nowTimeString := nowTime.Format(time.RFC3339)
testChart := &chart.Metadata{
Name: "oci",
Version: "0.0.1",
}
result := generateOCIAnnotations(testChart, nowTimeString)
// Check that created annotation exists
if _, ok := result[ocispec.AnnotationCreated]; !ok {
t.Errorf("%s annotation not created", ocispec.AnnotationCreated)
}
// Verify value of created artifact in RFC3339 format
if _, err := time.Parse(time.RFC3339, result[ocispec.AnnotationCreated]); err != nil {
t.Errorf("%s annotation with value '%s' not in RFC3339 format", ocispec.AnnotationCreated, result[ocispec.AnnotationCreated])
}
// Verify default creation time set
result = generateOCIAnnotations(testChart, "")
// Check that created annotation exists
if _, ok := result[ocispec.AnnotationCreated]; !ok {
t.Errorf("%s annotation not created", ocispec.AnnotationCreated)
}
if createdTimeAnnotation, err := time.Parse(time.RFC3339, result[ocispec.AnnotationCreated]); err != nil {
t.Errorf("%s annotation with value '%s' not in RFC3339 format", ocispec.AnnotationCreated, result[ocispec.AnnotationCreated])
// Verify creation annotation after time test began
if !nowTime.Before(createdTimeAnnotation) {
t.Errorf("%s annotation with value '%s' not configured properly. Annotation value is not after %s", ocispec.AnnotationCreated, result[ocispec.AnnotationCreated], nowTimeString)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/transport.go | pkg/registry/transport.go | /*
Copyright The Helm 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 registry
import (
"bytes"
"fmt"
"io"
"log/slog"
"mime"
"net/http"
"strings"
"sync/atomic"
"oras.land/oras-go/v2/registry/remote/retry"
)
var (
// requestCount records the number of logged request-response pairs and will
// be used as the unique id for the next pair.
requestCount atomic.Uint64
// toScrub is a set of headers that should be scrubbed from the log.
toScrub = []string{
"Authorization",
"Set-Cookie",
}
)
// payloadSizeLimit limits the maximum size of the response body to be printed.
const payloadSizeLimit int64 = 16 * 1024 // 16 KiB
// LoggingTransport is an http.RoundTripper that keeps track of the in-flight
// request and add hooks to report HTTP tracing events.
type LoggingTransport struct {
http.RoundTripper
}
// NewTransport creates and returns a new instance of LoggingTransport
func NewTransport(debug bool) *retry.Transport {
type cloner[T any] interface {
Clone() T
}
// try to copy (clone) the http.DefaultTransport so any mutations we
// perform on it (e.g. TLS config) are not reflected globally
// follow https://github.com/golang/go/issues/39299 for a more elegant
// solution in the future
transport := http.DefaultTransport
if t, ok := transport.(cloner[*http.Transport]); ok {
transport = t.Clone()
} else if t, ok := transport.(cloner[http.RoundTripper]); ok {
// this branch will not be used with go 1.20, it was added
// optimistically to try to clone if the http.DefaultTransport
// implementation changes, still the Clone method in that case
// might not return http.RoundTripper...
transport = t.Clone()
}
if debug {
transport = &LoggingTransport{RoundTripper: transport}
}
return retry.NewTransport(transport)
}
// RoundTrip calls base round trip while keeping track of the current request.
func (t *LoggingTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
id := requestCount.Add(1) - 1
slog.Debug(req.Method, "id", id, "url", req.URL, "header", logHeader(req.Header))
resp, err = t.RoundTripper.RoundTrip(req)
if err != nil {
slog.Debug("Response"[:len(req.Method)], "id", id, "error", err)
} else if resp != nil {
slog.Debug("Response"[:len(req.Method)], "id", id, "status", resp.Status, "header", logHeader(resp.Header), "body", logResponseBody(resp))
} else {
slog.Debug("Response"[:len(req.Method)], "id", id, "response", "nil")
}
return resp, err
}
// logHeader prints out the provided header keys and values, with auth header scrubbed.
func logHeader(header http.Header) string {
if len(header) > 0 {
var headers []string
for k, v := range header {
for _, h := range toScrub {
if strings.EqualFold(k, h) {
v = []string{"*****"}
}
}
headers = append(headers, fmt.Sprintf(" %q: %q", k, strings.Join(v, ", ")))
}
return strings.Join(headers, "\n")
}
return " Empty header"
}
// logResponseBody prints out the response body if it is printable and within size limit.
func logResponseBody(resp *http.Response) string {
if resp.Body == nil || resp.Body == http.NoBody {
return " No response body to print"
}
// non-applicable body is not printed and remains untouched for subsequent processing
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
return " Response body without a content type is not printed"
}
if !isPrintableContentType(contentType) {
return fmt.Sprintf(" Response body of content type %q is not printed", contentType)
}
buf := bytes.NewBuffer(nil)
body := resp.Body
// restore the body by concatenating the read body with the remaining body
resp.Body = struct {
io.Reader
io.Closer
}{
Reader: io.MultiReader(buf, body),
Closer: body,
}
// read the body up to limit+1 to check if the body exceeds the limit
if _, err := io.CopyN(buf, body, payloadSizeLimit+1); err != nil && err != io.EOF {
return fmt.Sprintf(" Error reading response body: %v", err)
}
readBody := buf.String()
if len(readBody) == 0 {
return " Response body is empty"
}
if containsCredentials(readBody) {
return " Response body redacted due to potential credentials"
}
if len(readBody) > int(payloadSizeLimit) {
return readBody[:payloadSizeLimit] + "\n...(truncated)"
}
return readBody
}
// isPrintableContentType returns true if the contentType is printable.
func isPrintableContentType(contentType string) bool {
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return false
}
switch mediaType {
case "application/json", // JSON types
"text/plain", "text/html": // text types
return true
}
return strings.HasSuffix(mediaType, "+json")
}
// containsCredentials returns true if the body contains potential credentials.
func containsCredentials(body string) bool {
return strings.Contains(body, `"token"`) || strings.Contains(body, `"access_token"`)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/plugin.go | pkg/registry/plugin.go | /*
Copyright The Helm 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 registry
import (
"encoding/json"
"fmt"
"strings"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
// Plugin-specific constants
const (
// PluginArtifactType is the artifact type for Helm plugins
PluginArtifactType = "application/vnd.helm.plugin.v1+json"
)
// PluginPullOptions configures a plugin pull operation
type PluginPullOptions struct {
// PluginName specifies the expected plugin name for layer validation
PluginName string
}
// PluginPullResult contains the result of a plugin pull operation
type PluginPullResult struct {
Manifest ocispec.Descriptor
PluginData []byte
Prov struct {
Data []byte
}
Ref string
PluginName string
}
// PullPlugin downloads a plugin from an OCI registry using artifact type
func (c *Client) PullPlugin(ref string, pluginName string, options ...PluginPullOption) (*PluginPullResult, error) {
operation := &pluginPullOperation{
pluginName: pluginName,
}
for _, option := range options {
option(operation)
}
// Use generic client for the pull operation with artifact type filtering
genericClient := c.Generic()
genericResult, err := genericClient.PullGeneric(ref, GenericPullOptions{
// Allow manifests and all layer types - we'll validate artifact type after download
AllowedMediaTypes: []string{
ocispec.MediaTypeImageManifest,
"application/vnd.oci.image.layer.v1.tar",
"application/vnd.oci.image.layer.v1.tar+gzip",
},
})
if err != nil {
return nil, err
}
// Process the result with plugin-specific logic
return c.processPluginPull(genericResult, operation.pluginName)
}
// processPluginPull handles plugin-specific processing of a generic pull result using artifact type
func (c *Client) processPluginPull(genericResult *GenericPullResult, pluginName string) (*PluginPullResult, error) {
// First validate that this is actually a plugin artifact
manifestData, err := c.Generic().GetDescriptorData(genericResult.MemoryStore, genericResult.Manifest)
if err != nil {
return nil, fmt.Errorf("unable to retrieve manifest: %w", err)
}
// Parse the manifest to check artifact type
var manifest ocispec.Manifest
if err := json.Unmarshal(manifestData, &manifest); err != nil {
return nil, fmt.Errorf("unable to parse manifest: %w", err)
}
// Validate artifact type (for OCI v1.1+ manifests)
if manifest.ArtifactType != "" && manifest.ArtifactType != PluginArtifactType {
return nil, fmt.Errorf("expected artifact type %s, got %s", PluginArtifactType, manifest.ArtifactType)
}
// For backwards compatibility, also check config media type if no artifact type
if manifest.ArtifactType == "" && manifest.Config.MediaType != PluginArtifactType {
return nil, fmt.Errorf("expected config media type %s for legacy compatibility, got %s", PluginArtifactType, manifest.Config.MediaType)
}
// Find the plugin tarball and optional provenance using NAME-VERSION.tgz format
var pluginDescriptor *ocispec.Descriptor
var provenanceDescriptor *ocispec.Descriptor
var foundProvenanceName string
// Look for layers with the expected titles/annotations
for _, layer := range manifest.Layers {
d := layer
// Check for title annotation
if title, exists := d.Annotations[ocispec.AnnotationTitle]; exists {
// Check if this looks like a plugin tarball: {pluginName}-{version}.tgz
if pluginDescriptor == nil && strings.HasPrefix(title, pluginName+"-") && strings.HasSuffix(title, ".tgz") {
pluginDescriptor = &d
}
// Check if this looks like a plugin provenance: {pluginName}-{version}.tgz.prov
if provenanceDescriptor == nil && strings.HasPrefix(title, pluginName+"-") && strings.HasSuffix(title, ".tgz.prov") {
provenanceDescriptor = &d
foundProvenanceName = title
}
}
}
// Plugin tarball is required
if pluginDescriptor == nil {
return nil, fmt.Errorf("required layer matching pattern %s-VERSION.tgz not found in manifest", pluginName)
}
// Build plugin-specific result
result := &PluginPullResult{
Manifest: genericResult.Manifest,
Ref: genericResult.Ref,
PluginName: pluginName,
}
// Fetch plugin data using generic client
genericClient := c.Generic()
result.PluginData, err = genericClient.GetDescriptorData(genericResult.MemoryStore, *pluginDescriptor)
if err != nil {
return nil, fmt.Errorf("unable to retrieve plugin data with digest %s: %w", pluginDescriptor.Digest, err)
}
// Fetch provenance data if available
if provenanceDescriptor != nil {
result.Prov.Data, err = genericClient.GetDescriptorData(genericResult.MemoryStore, *provenanceDescriptor)
if err != nil {
return nil, fmt.Errorf("unable to retrieve provenance data with digest %s: %w", provenanceDescriptor.Digest, err)
}
}
_, _ = fmt.Fprintf(c.out, "Pulled plugin: %s\n", result.Ref)
_, _ = fmt.Fprintf(c.out, "Digest: %s\n", result.Manifest.Digest)
if result.Prov.Data != nil {
_, _ = fmt.Fprintf(c.out, "Provenance: %s\n", foundProvenanceName)
}
if strings.Contains(result.Ref, "_") {
_, _ = fmt.Fprintf(c.out, "%s contains an underscore.\n", result.Ref)
_, _ = fmt.Fprint(c.out, registryUnderscoreMessage+"\n")
}
return result, nil
}
// Plugin pull operation types and options
type (
pluginPullOperation struct {
pluginName string
withProv bool
}
// PluginPullOption allows customizing plugin pull operations
PluginPullOption func(*pluginPullOperation)
)
// PluginPullOptWithPluginName sets the plugin name for validation
func PluginPullOptWithPluginName(name string) PluginPullOption {
return func(operation *pluginPullOperation) {
operation.pluginName = name
}
}
// GetPluginName extracts the plugin name from an OCI reference using proper reference parsing
func GetPluginName(source string) (string, error) {
ref, err := newReference(source)
if err != nil {
return "", fmt.Errorf("invalid OCI reference: %w", err)
}
// Extract plugin name from the repository path
// e.g., "ghcr.io/user/plugin-name:v1.0.0" -> Repository: "user/plugin-name"
repository := ref.Repository
if repository == "" {
return "", fmt.Errorf("invalid OCI reference: missing repository")
}
// Get the last part of the repository path as the plugin name
parts := strings.Split(repository, "/")
pluginName := parts[len(parts)-1]
if pluginName == "" {
return "", fmt.Errorf("invalid OCI reference: cannot determine plugin name from repository %s", repository)
}
return pluginName, nil
}
// PullPluginOptWithProv configures the pull to fetch provenance data
func PullPluginOptWithProv(withProv bool) PluginPullOption {
return func(operation *pluginPullOperation) {
operation.withProv = withProv
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/registry_test.go | pkg/registry/registry_test.go | /*
Copyright The Helm 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 registry
import (
"bytes"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/distribution/distribution/v3/configuration"
"github.com/distribution/distribution/v3/registry"
_ "github.com/distribution/distribution/v3/registry/auth/htpasswd"
_ "github.com/distribution/distribution/v3/registry/storage/driver/inmemory"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"golang.org/x/crypto/bcrypt"
"helm.sh/helm/v4/internal/tlsutil"
)
const (
tlsServerKey = "./testdata/tls/server.key"
tlsServerCert = "./testdata/tls/server.crt"
tlsCA = "./testdata/tls/ca.crt"
tlsKey = "./testdata/tls/client.key"
tlsCert = "./testdata/tls/client.crt"
)
var (
testWorkspaceDir = "helm-registry-test"
testHtpasswdFileBasename = "authtest.htpasswd"
testUsername = "myuser"
testPassword = "mypass"
)
type TestRegistry struct {
suite.Suite
Out io.Writer
DockerRegistryHost string
CompromisedRegistryHost string
WorkspaceDir string
RegistryClient *Client
dockerRegistry *registry.Registry
}
func setup(suite *TestRegistry, tlsEnabled, insecure bool) {
suite.WorkspaceDir = testWorkspaceDir
err := os.RemoveAll(suite.WorkspaceDir)
require.NoError(suite.T(), err, "no error removing test workspace dir")
err = os.Mkdir(suite.WorkspaceDir, 0700)
require.NoError(suite.T(), err, "no error creating test workspace dir")
var out bytes.Buffer
suite.Out = &out
credentialsFile := filepath.Join(suite.WorkspaceDir, CredentialsFileBasename)
// init test client
opts := []ClientOption{
ClientOptDebug(true),
ClientOptEnableCache(true),
ClientOptWriter(suite.Out),
ClientOptCredentialsFile(credentialsFile),
ClientOptBasicAuth(testUsername, testPassword),
}
if tlsEnabled {
var tlsConf *tls.Config
if insecure {
tlsConf, err = tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(true),
)
} else {
tlsConf, err = tlsutil.NewTLSConfig(
tlsutil.WithCertKeyPairFiles(tlsCert, tlsKey),
tlsutil.WithCAFile(tlsCA),
)
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConf,
},
}
suite.Nil(err, "no error loading tls config")
opts = append(opts, ClientOptHTTPClient(httpClient))
} else {
opts = append(opts, ClientOptPlainHTTP())
}
suite.RegistryClient, err = NewClient(opts...)
suite.Nil(err, "no error creating registry client")
// create htpasswd file (w BCrypt, which is required)
pwBytes, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.DefaultCost)
suite.Nil(err, "no error generating bcrypt password for test htpasswd file")
htpasswdPath := filepath.Join(suite.WorkspaceDir, testHtpasswdFileBasename)
err = os.WriteFile(htpasswdPath, fmt.Appendf(nil, "%s:%s\n", testUsername, string(pwBytes)), 0644)
suite.Nil(err, "no error creating test htpasswd file")
// Registry config
config := &configuration.Configuration{}
ln, err := net.Listen("tcp", "127.0.0.1:0")
suite.Nil(err, "no error finding free port for test registry")
defer func() { _ = ln.Close() }()
// Change the registry host to another host which is not localhost.
// This is required because Docker enforces HTTP if the registry
// host is localhost/127.0.0.1.
port := ln.Addr().(*net.TCPAddr).Port
suite.DockerRegistryHost = fmt.Sprintf("helm-test-registry:%d", port)
config.HTTP.Addr = ln.Addr().String()
config.HTTP.DrainTimeout = time.Duration(10) * time.Second
config.Storage = map[string]configuration.Parameters{"inmemory": map[string]interface{}{}}
config.Auth = configuration.Auth{
"htpasswd": configuration.Parameters{
"realm": "localhost",
"path": htpasswdPath,
},
}
// config tls
if tlsEnabled {
// TLS config
// this set tlsConf.ClientAuth = tls.RequireAndVerifyClientCert in the
// server tls config
config.HTTP.TLS.Certificate = tlsServerCert
config.HTTP.TLS.Key = tlsServerKey
// Skip client authentication if the registry is insecure.
if !insecure {
config.HTTP.TLS.ClientCAs = []string{tlsCA}
}
}
suite.dockerRegistry, err = registry.NewRegistry(context.Background(), config)
suite.Nil(err, "no error creating test registry")
suite.CompromisedRegistryHost = initCompromisedRegistryTestServer()
go func() {
_ = suite.dockerRegistry.ListenAndServe()
}()
}
func teardown(suite *TestRegistry) {
if suite.dockerRegistry != nil {
_ = suite.dockerRegistry.Shutdown(context.Background())
}
}
func initCompromisedRegistryTestServer() string {
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "manifests") {
w.Header().Set("Content-Type", "application/vnd.oci.image.manifest.v1+json")
w.WriteHeader(http.StatusOK)
_, _ = fmt.Fprintf(w, `{ "schemaVersion": 2, "config": {
"mediaType": "%s",
"digest": "sha256:a705ee2789ab50a5ba20930f246dbd5cc01ff9712825bb98f57ee8414377f133",
"size": 181
},
"layers": [
{
"mediaType": "%s",
"digest": "sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb",
"size": 1
}
]
}`, ConfigMediaType, ChartLayerMediaType)
} else if r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:a705ee2789ab50a5ba20930f246dbd5cc01ff9712825bb98f57ee8414377f133" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("{\"name\":\"mychart\",\"version\":\"0.1.0\",\"description\":\"A Helm chart for Kubernetes\\n" +
"an 'application' or a 'library' chart.\",\"apiVersion\":\"v2\",\"appVersion\":\"1.16.0\",\"type\":" +
"\"application\"}"))
} else if r.URL.Path == "/v2/testrepo/supposedlysafechart/blobs/sha256:ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb" {
w.Header().Set("Content-Type", ChartLayerMediaType)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("b"))
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}))
u, _ := url.Parse(s.URL)
return fmt.Sprintf("localhost:%s", u.Port())
}
func testPush(suite *TestRegistry) {
testingChartCreationTime := "1977-09-02T22:04:05Z"
// Bad bytes
ref := fmt.Sprintf("%s/testrepo/testchart:1.2.3", suite.DockerRegistryHost)
_, err := suite.RegistryClient.Push([]byte("hello"), ref, PushOptCreationTime(testingChartCreationTime))
suite.NotNil(err, "error pushing non-chart bytes")
// Load a test chart
chartData, err := os.ReadFile("../repo/v1/repotest/testdata/examplechart-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err := extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
// non-strict ref (chart name)
ref = fmt.Sprintf("%s/testrepo/boop:%s", suite.DockerRegistryHost, meta.Version)
_, err = suite.RegistryClient.Push(chartData, ref, PushOptCreationTime(testingChartCreationTime))
suite.NotNil(err, "error pushing non-strict ref (bad basename)")
// non-strict ref (chart name), with strict mode disabled
_, err = suite.RegistryClient.Push(chartData, ref, PushOptStrictMode(false), PushOptCreationTime(testingChartCreationTime))
suite.Nil(err, "no error pushing non-strict ref (bad basename), with strict mode disabled")
// non-strict ref (chart version)
ref = fmt.Sprintf("%s/testrepo/%s:latest", suite.DockerRegistryHost, meta.Name)
_, err = suite.RegistryClient.Push(chartData, ref, PushOptCreationTime(testingChartCreationTime))
suite.NotNil(err, "error pushing non-strict ref (bad tag)")
// non-strict ref (chart version), with strict mode disabled
_, err = suite.RegistryClient.Push(chartData, ref, PushOptStrictMode(false), PushOptCreationTime(testingChartCreationTime))
suite.Nil(err, "no error pushing non-strict ref (bad tag), with strict mode disabled")
// basic push, good ref
chartData, err = os.ReadFile("../downloader/testdata/local-subchart-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err = extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
ref = fmt.Sprintf("%s/testrepo/%s:%s", suite.DockerRegistryHost, meta.Name, meta.Version)
_, err = suite.RegistryClient.Push(chartData, ref, PushOptCreationTime(testingChartCreationTime))
suite.Nil(err, "no error pushing good ref")
_, err = suite.RegistryClient.Pull(ref)
suite.Nil(err, "no error pulling a simple chart")
// Load another test chart
chartData, err = os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err = extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
// Load prov file
provData, err := os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz.prov")
suite.Nil(err, "no error loading test prov")
// push with prov
ref = fmt.Sprintf("%s/testrepo/%s:%s", suite.DockerRegistryHost, meta.Name, meta.Version)
result, err := suite.RegistryClient.Push(chartData, ref, PushOptProvData(provData), PushOptCreationTime(testingChartCreationTime))
suite.Nil(err, "no error pushing good ref with prov")
_, err = suite.RegistryClient.Pull(ref, PullOptWithProv(true))
suite.Nil(err, "no error pulling a simple chart")
// Validate the output
// Note: these digests/sizes etc may change if the test chart/prov files are modified,
// or if the format of the OCI manifest changes
suite.Equal(ref, result.Ref)
suite.Equal(meta.Name, result.Chart.Meta.Name)
suite.Equal(meta.Version, result.Chart.Meta.Version)
suite.Equal(int64(742), result.Manifest.Size)
suite.Equal(int64(99), result.Config.Size)
suite.Equal(int64(973), result.Chart.Size)
suite.Equal(int64(695), result.Prov.Size)
suite.Equal(
"sha256:fbbade96da6050f68f94f122881e3b80051a18f13ab5f4081868dd494538f5c2",
result.Manifest.Digest)
suite.Equal(
"sha256:8d17cb6bf6ccd8c29aace9a658495cbd5e2e87fc267876e86117c7db681c9580",
result.Config.Digest)
suite.Equal(
"sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55",
result.Chart.Digest)
suite.Equal(
"sha256:b0a02b7412f78ae93324d48df8fcc316d8482e5ad7827b5b238657a29a22f256",
result.Prov.Digest)
}
func testPull(suite *TestRegistry) {
// bad/missing ref
ref := fmt.Sprintf("%s/testrepo/no-existy:1.2.3", suite.DockerRegistryHost)
_, err := suite.RegistryClient.Pull(ref)
suite.NotNil(err, "error on bad/missing ref")
// Load test chart (to build ref pushed in previous test)
chartData, err := os.ReadFile("../downloader/testdata/local-subchart-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err := extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
ref = fmt.Sprintf("%s/testrepo/%s:%s", suite.DockerRegistryHost, meta.Name, meta.Version)
// Simple pull, chart only
_, err = suite.RegistryClient.Pull(ref)
suite.Nil(err, "no error pulling a simple chart")
// Simple pull with prov (no prov uploaded)
_, err = suite.RegistryClient.Pull(ref, PullOptWithProv(true))
suite.NotNil(err, "error pulling a chart with prov when no prov exists")
// Simple pull with prov, ignoring missing prov
_, err = suite.RegistryClient.Pull(ref,
PullOptWithProv(true),
PullOptIgnoreMissingProv(true))
suite.Nil(err,
"no error pulling a chart with prov when no prov exists, ignoring missing")
// Load test chart (to build ref pushed in previous test)
chartData, err = os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err = extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
ref = fmt.Sprintf("%s/testrepo/%s:%s", suite.DockerRegistryHost, meta.Name, meta.Version)
// Load prov file
provData, err := os.ReadFile("../downloader/testdata/signtest-0.1.0.tgz.prov")
suite.Nil(err, "no error loading test prov")
// no chart and no prov causes error
_, err = suite.RegistryClient.Pull(ref,
PullOptWithChart(false),
PullOptWithProv(false))
suite.NotNil(err, "error on both no chart and no prov")
// full pull with chart and prov
result, err := suite.RegistryClient.Pull(ref, PullOptWithProv(true))
suite.Require().Nil(err, "no error pulling a chart with prov")
// Validate the output
// Note: these digests/sizes etc may change if the test chart/prov files are modified,
// or if the format of the OCI manifest changes
suite.Equal(ref, result.Ref)
suite.Equal(meta.Name, result.Chart.Meta.Name)
suite.Equal(meta.Version, result.Chart.Meta.Version)
suite.Equal(int64(742), result.Manifest.Size)
suite.Equal(int64(99), result.Config.Size)
suite.Equal(int64(973), result.Chart.Size)
suite.Equal(int64(695), result.Prov.Size)
suite.Equal(
"sha256:fbbade96da6050f68f94f122881e3b80051a18f13ab5f4081868dd494538f5c2",
result.Manifest.Digest)
suite.Equal(
"sha256:8d17cb6bf6ccd8c29aace9a658495cbd5e2e87fc267876e86117c7db681c9580",
result.Config.Digest)
suite.Equal(
"sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55",
result.Chart.Digest)
suite.Equal(
"sha256:b0a02b7412f78ae93324d48df8fcc316d8482e5ad7827b5b238657a29a22f256",
result.Prov.Digest)
suite.Equal("{\"schemaVersion\":2,\"config\":{\"mediaType\":\"application/vnd.cncf.helm.config.v1+json\",\"digest\":\"sha256:8d17cb6bf6ccd8c29aace9a658495cbd5e2e87fc267876e86117c7db681c9580\",\"size\":99},\"layers\":[{\"mediaType\":\"application/vnd.cncf.helm.chart.provenance.v1.prov\",\"digest\":\"sha256:b0a02b7412f78ae93324d48df8fcc316d8482e5ad7827b5b238657a29a22f256\",\"size\":695},{\"mediaType\":\"application/vnd.cncf.helm.chart.content.v1.tar+gzip\",\"digest\":\"sha256:e5ef611620fb97704d8751c16bab17fedb68883bfb0edc76f78a70e9173f9b55\",\"size\":973}],\"annotations\":{\"org.opencontainers.image.created\":\"1977-09-02T22:04:05Z\",\"org.opencontainers.image.description\":\"A Helm chart for Kubernetes\",\"org.opencontainers.image.title\":\"signtest\",\"org.opencontainers.image.version\":\"0.1.0\"}}",
string(result.Manifest.Data))
suite.Equal("{\"name\":\"signtest\",\"version\":\"0.1.0\",\"description\":\"A Helm chart for Kubernetes\",\"apiVersion\":\"v1\"}",
string(result.Config.Data))
suite.Equal(chartData, result.Chart.Data)
suite.Equal(provData, result.Prov.Data)
}
func testTags(suite *TestRegistry) {
// Load test chart (to build ref pushed in previous test)
chartData, err := os.ReadFile("../downloader/testdata/local-subchart-0.1.0.tgz")
suite.Nil(err, "no error loading test chart")
meta, err := extractChartMeta(chartData)
suite.Nil(err, "no error extracting chart meta")
ref := fmt.Sprintf("%s/testrepo/%s", suite.DockerRegistryHost, meta.Name)
// Query for tags and validate length
tags, err := suite.RegistryClient.Tags(ref)
suite.Nil(err, "no error retrieving tags")
suite.Equal(1, len(tags))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/registry/reference.go | pkg/registry/reference.go | /*
Copyright The Helm 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 registry
import (
"fmt"
"strings"
"oras.land/oras-go/v2/registry"
)
type reference struct {
orasReference registry.Reference
Registry string
Repository string
Tag string
Digest string
}
// newReference will parse and validate the reference, and clean tags when
// applicable tags are only cleaned when plus (+) signs are present and are
// converted to underscores (_) before pushing
// See https://github.com/helm/helm/issues/10166
func newReference(raw string) (result reference, err error) {
// Remove the oci:// prefix if it is there
raw = strings.TrimPrefix(raw, OCIScheme+"://")
// The sole possible reference modification is replacing plus (+) signs
// present in tags with underscores (_). To do this properly, we first
// need to identify a tag, and then pass it on to the reference parser
// NOTE: Passing immediately to the reference parser will fail since (+)
// signs are an invalid tag character, and simply replacing all plus (+)
// occurrences could invalidate other portions of the URI
lastIndex := strings.LastIndex(raw, "@")
if lastIndex >= 0 {
result.Digest = raw[(lastIndex + 1):]
raw = raw[:lastIndex]
}
parts := strings.Split(raw, ":")
if len(parts) > 1 && !strings.Contains(parts[len(parts)-1], "/") {
tag := parts[len(parts)-1]
if tag != "" {
// Replace any plus (+) signs with known underscore (_) conversion
newTag := strings.ReplaceAll(tag, "+", "_")
raw = strings.ReplaceAll(raw, tag, newTag)
}
}
result.orasReference, err = registry.ParseReference(raw)
if err != nil {
return result, err
}
result.Registry = result.orasReference.Registry
result.Repository = result.orasReference.Repository
result.Tag = result.orasReference.Reference
return result, nil
}
func (r *reference) String() string {
if r.Tag == "" {
return r.orasReference.String() + "@" + r.Digest
}
return r.orasReference.String()
}
// IsOCI determines whether a URL is to be treated as an OCI URL
func IsOCI(url string) bool {
return strings.HasPrefix(url, fmt.Sprintf("%s://", OCIScheme))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/postrenderer/postrenderer_test.go | pkg/postrenderer/postrenderer_test.go | /*
Copyright The Helm 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 postrenderer
import (
"bytes"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/cli"
)
func TestNewPostRenderPluginRunWithNoOutput(t *testing.T) {
if runtime.GOOS == "windows" {
// the actual Run test uses a basic sed example, so skip this test on windows
t.Skip("skipping on windows")
}
is := assert.New(t)
s := cli.New()
s.PluginsDirectory = "testdata/plugins"
name := "postrenderer-v1"
renderer, err := NewPostRendererPlugin(s, name, "")
require.NoError(t, err)
_, err = renderer.Run(bytes.NewBufferString(""))
is.Error(err)
}
func TestNewPostRenderPluginWithOneArgsRun(t *testing.T) {
if runtime.GOOS == "windows" {
// the actual Run test uses a basic sed example, so skip this test on windows
t.Skip("skipping on windows")
}
is := assert.New(t)
s := cli.New()
s.PluginsDirectory = "testdata/plugins"
name := "postrenderer-v1"
renderer, err := NewPostRendererPlugin(s, name, "ARG1")
require.NoError(t, err)
output, err := renderer.Run(bytes.NewBufferString("FOOTEST"))
is.NoError(err)
is.Contains(output.String(), "ARG1")
}
func TestNewPostRenderPluginWithTwoArgsRun(t *testing.T) {
if runtime.GOOS == "windows" {
// the actual Run test uses a basic sed example, so skip this test on windows
t.Skip("skipping on windows")
}
is := assert.New(t)
s := cli.New()
s.PluginsDirectory = "testdata/plugins"
name := "postrenderer-v1"
renderer, err := NewPostRendererPlugin(s, name, "ARG1", "ARG2")
require.NoError(t, err)
output, err := renderer.Run(bytes.NewBufferString("FOOTEST"))
is.NoError(err)
is.Contains(output.String(), "ARG1 ARG2")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/postrenderer/postrenderer.go | pkg/postrenderer/postrenderer.go | /*
Copyright The Helm 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 postrenderer
import (
"bytes"
"context"
"fmt"
"path/filepath"
"helm.sh/helm/v4/internal/plugin/schema"
"helm.sh/helm/v4/internal/plugin"
"helm.sh/helm/v4/pkg/cli"
)
// PostRenderer is an interface different plugin runtimes
// it may be also be used without the factory for custom post-renderers
type PostRenderer interface {
// Run expects a single buffer filled with Helm rendered manifests. It
// expects the modified results to be returned on a separate buffer or an
// error if there was an issue or failure while running the post render step
Run(renderedManifests *bytes.Buffer) (modifiedManifests *bytes.Buffer, err error)
}
// NewPostRendererPlugin creates a PostRenderer that uses the plugin's Runtime
func NewPostRendererPlugin(settings *cli.EnvSettings, pluginName string, args ...string) (PostRenderer, error) {
descriptor := plugin.Descriptor{
Name: pluginName,
Type: "postrenderer/v1",
}
p, err := plugin.FindPlugin(filepath.SplitList(settings.PluginsDirectory), descriptor)
if err != nil {
return nil, err
}
return &postRendererPlugin{
plugin: p,
args: args,
settings: settings,
}, nil
}
// postRendererPlugin implements PostRenderer by delegating to the plugin's Runtime
type postRendererPlugin struct {
plugin plugin.Plugin
args []string
settings *cli.EnvSettings
}
// Run implements PostRenderer by using the plugin's Runtime
func (r *postRendererPlugin) Run(renderedManifests *bytes.Buffer) (*bytes.Buffer, error) {
input := &plugin.Input{
Message: schema.InputMessagePostRendererV1{
ExtraArgs: r.args,
Manifests: renderedManifests,
},
}
output, err := r.plugin.Invoke(context.Background(), input)
if err != nil {
return nil, fmt.Errorf("failed to invoke post-renderer plugin %q: %w", r.plugin.Metadata().Name, err)
}
outputMessage := output.Message.(schema.OutputMessagePostRendererV1)
// If the binary returned almost nothing, it's likely that it didn't
// successfully render anything
if len(bytes.TrimSpace(outputMessage.Manifests.Bytes())) == 0 {
return nil, fmt.Errorf("post-renderer %q produced empty output", r.plugin.Metadata().Name)
}
return outputMessage.Manifests, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/helmpath/lazypath_darwin_test.go | pkg/helmpath/lazypath_darwin_test.go | // Copyright The Helm 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.
//go:build darwin
package helmpath
import (
"os"
"path/filepath"
"testing"
"k8s.io/client-go/util/homedir"
"helm.sh/helm/v4/pkg/helmpath/xdg"
)
const (
appName = "helm"
testFile = "test.txt"
lazy = lazypath(appName)
)
func TestDataPath(t *testing.T) {
os.Unsetenv(xdg.DataHomeEnvVar)
expected := filepath.Join(homedir.HomeDir(), "Library", appName, testFile)
if lazy.dataPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.dataPath(testFile))
}
t.Setenv(xdg.DataHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.dataPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.dataPath(testFile))
}
}
func TestConfigPath(t *testing.T) {
os.Unsetenv(xdg.ConfigHomeEnvVar)
expected := filepath.Join(homedir.HomeDir(), "Library", "Preferences", appName, testFile)
if lazy.configPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.configPath(testFile))
}
t.Setenv(xdg.ConfigHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.configPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.configPath(testFile))
}
}
func TestCachePath(t *testing.T) {
os.Unsetenv(xdg.CacheHomeEnvVar)
expected := filepath.Join(homedir.HomeDir(), "Library", "Caches", appName, testFile)
if lazy.cachePath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.cachePath(testFile))
}
t.Setenv(xdg.CacheHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.cachePath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.cachePath(testFile))
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/helmpath/lazypath.go | pkg/helmpath/lazypath.go | // Copyright The Helm 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 helmpath
import (
"os"
"path/filepath"
"helm.sh/helm/v4/pkg/helmpath/xdg"
)
const (
// CacheHomeEnvVar is the environment variable used by Helm
// for the cache directory. When no value is set a default is used.
CacheHomeEnvVar = "HELM_CACHE_HOME"
// ConfigHomeEnvVar is the environment variable used by Helm
// for the config directory. When no value is set a default is used.
ConfigHomeEnvVar = "HELM_CONFIG_HOME"
// DataHomeEnvVar is the environment variable used by Helm
// for the data directory. When no value is set a default is used.
DataHomeEnvVar = "HELM_DATA_HOME"
)
// lazypath is a lazy-loaded path buffer for the XDG base directory specification.
type lazypath string
func (l lazypath) path(helmEnvVar, xdgEnvVar string, defaultFn func() string, elem ...string) string {
// There is an order to checking for a path.
// 1. See if a Helm specific environment variable has been set.
// 2. Check if an XDG environment variable is set
// 3. Fall back to a default
base := os.Getenv(helmEnvVar)
if base != "" {
return filepath.Join(base, filepath.Join(elem...))
}
base = os.Getenv(xdgEnvVar)
if base == "" {
base = defaultFn()
}
return filepath.Join(base, string(l), filepath.Join(elem...))
}
// cachePath defines the base directory relative to which user specific non-essential data files
// should be stored.
func (l lazypath) cachePath(elem ...string) string {
return l.path(CacheHomeEnvVar, xdg.CacheHomeEnvVar, cacheHome, filepath.Join(elem...))
}
// configPath defines the base directory relative to which user specific configuration files should
// be stored.
func (l lazypath) configPath(elem ...string) string {
return l.path(ConfigHomeEnvVar, xdg.ConfigHomeEnvVar, configHome, filepath.Join(elem...))
}
// dataPath defines the base directory relative to which user specific data files should be stored.
func (l lazypath) dataPath(elem ...string) string {
return l.path(DataHomeEnvVar, xdg.DataHomeEnvVar, dataHome, filepath.Join(elem...))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/helmpath/lazypath_unix.go | pkg/helmpath/lazypath_unix.go | // Copyright The Helm 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.
//go:build !windows && !darwin
package helmpath
import (
"path/filepath"
"k8s.io/client-go/util/homedir"
)
// dataHome defines the base directory relative to which user specific data files should be stored.
//
// If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share is used.
func dataHome() string {
return filepath.Join(homedir.HomeDir(), ".local", "share")
}
// configHome defines the base directory relative to which user specific configuration files should
// be stored.
//
// If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config is used.
func configHome() string {
return filepath.Join(homedir.HomeDir(), ".config")
}
// cacheHome defines the base directory relative to which user specific non-essential data files
// should be stored.
//
// If $XDG_CACHE_HOME is either not set or empty, a default equal to $HOME/.cache is used.
func cacheHome() string {
return filepath.Join(homedir.HomeDir(), ".cache")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/helmpath/lazypath_unix_test.go | pkg/helmpath/lazypath_unix_test.go | // Copyright The Helm 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.
//go:build !windows && !darwin
package helmpath
import (
"path/filepath"
"testing"
"k8s.io/client-go/util/homedir"
"helm.sh/helm/v4/pkg/helmpath/xdg"
)
const (
appName = "helm"
testFile = "test.txt"
lazy = lazypath(appName)
)
func TestDataPath(t *testing.T) {
expected := filepath.Join(homedir.HomeDir(), ".local", "share", appName, testFile)
if lazy.dataPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.dataPath(testFile))
}
t.Setenv(xdg.DataHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.dataPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.dataPath(testFile))
}
}
func TestConfigPath(t *testing.T) {
expected := filepath.Join(homedir.HomeDir(), ".config", appName, testFile)
if lazy.configPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.configPath(testFile))
}
t.Setenv(xdg.ConfigHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.configPath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.configPath(testFile))
}
}
func TestCachePath(t *testing.T) {
expected := filepath.Join(homedir.HomeDir(), ".cache", appName, testFile)
if lazy.cachePath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.cachePath(testFile))
}
t.Setenv(xdg.CacheHomeEnvVar, "/tmp")
expected = filepath.Join("/tmp", appName, testFile)
if lazy.cachePath(testFile) != expected {
t.Errorf("expected '%s', got '%s'", expected, lazy.cachePath(testFile))
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.