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/action/rollback_test.go | pkg/action/rollback_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 action
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/assert"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
)
func TestNewRollback(t *testing.T) {
config := actionConfigFixture(t)
client := NewRollback(config)
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
}
func TestRollbackRun_UnreachableKubeClient(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
client := NewRollback(config)
assert.Error(t, client.Run(""))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/action.go | pkg/action/action.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 action
import (
"bytes"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
"text/template"
"time"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/client-go/discovery"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"sigs.k8s.io/kustomize/kyaml/kio"
kyaml "sigs.k8s.io/kustomize/kyaml/yaml"
"helm.sh/helm/v4/internal/logging"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/engine"
"helm.sh/helm/v4/pkg/kube"
"helm.sh/helm/v4/pkg/postrenderer"
"helm.sh/helm/v4/pkg/registry"
ri "helm.sh/helm/v4/pkg/release"
release "helm.sh/helm/v4/pkg/release/v1"
releaseutil "helm.sh/helm/v4/pkg/release/v1/util"
"helm.sh/helm/v4/pkg/storage"
"helm.sh/helm/v4/pkg/storage/driver"
)
// Timestamper is a function capable of producing a timestamp.Timestamper.
//
// By default, this is a time.Time function from the Helm time package. This can
// be overridden for testing though, so that timestamps are predictable.
var Timestamper = time.Now
var (
// errMissingChart indicates that a chart was not provided.
errMissingChart = errors.New("no chart provided")
// errMissingRelease indicates that a release (name) was not provided.
errMissingRelease = errors.New("no release provided")
// errInvalidRevision indicates that an invalid release revision number was provided.
errInvalidRevision = errors.New("invalid release revision")
// errPending indicates that another instance of Helm is already applying an operation on a release.
errPending = errors.New("another operation (install/upgrade/rollback) is in progress")
)
type DryRunStrategy string
const (
// DryRunNone indicates the client will make all mutating calls
DryRunNone DryRunStrategy = "none"
// DryRunClient, or client-side dry-run, indicates the client will avoid
// making calls to the server
DryRunClient DryRunStrategy = "client"
// DryRunServer, or server-side dry-run, indicates the client will send
// calls to the APIServer with the dry-run parameter to prevent persisting changes
DryRunServer DryRunStrategy = "server"
)
// Configuration injects the dependencies that all actions share.
type Configuration struct {
// RESTClientGetter is an interface that loads Kubernetes clients.
RESTClientGetter RESTClientGetter
// Releases stores records of releases.
Releases *storage.Storage
// KubeClient is a Kubernetes API client.
KubeClient kube.Interface
// RegistryClient is a client for working with registries
RegistryClient *registry.Client
// Capabilities describes the capabilities of the Kubernetes cluster.
Capabilities *common.Capabilities
// CustomTemplateFuncs is defined by users to provide custom template funcs
CustomTemplateFuncs template.FuncMap
// HookOutputFunc called with container name and returns and expects writer that will receive the log output.
HookOutputFunc func(namespace, pod, container string) io.Writer
// Mutex is an exclusive lock for concurrent access to the action
mutex sync.Mutex
// Embed a LogHolder to provide logger functionality
logging.LogHolder
}
type ConfigurationOption func(c *Configuration)
// Override the default logging handler
// If unspecified, the default logger will be used
func ConfigurationSetLogger(h slog.Handler) ConfigurationOption {
return func(c *Configuration) {
c.SetLogger(h)
}
}
func NewConfiguration(options ...ConfigurationOption) *Configuration {
c := &Configuration{}
c.SetLogger(slog.Default().Handler())
for _, o := range options {
o(c)
}
return c
}
const (
// filenameAnnotation is the annotation key used to store the original filename
// information in manifest annotations for post-rendering reconstruction.
filenameAnnotation = "postrenderer.helm.sh/postrender-filename"
)
// annotateAndMerge combines multiple YAML files into a single stream of documents,
// adding filename annotations to each document for later reconstruction.
func annotateAndMerge(files map[string]string) (string, error) {
var combinedManifests []*kyaml.RNode
// Get sorted filenames to ensure result is deterministic
fnames := slices.Sorted(maps.Keys(files))
for _, fname := range fnames {
content := files[fname]
// Skip partials and empty files.
if strings.HasPrefix(path.Base(fname), "_") || strings.TrimSpace(content) == "" {
continue
}
manifests, err := kio.ParseAll(content)
if err != nil {
return "", fmt.Errorf("parsing %s: %w", fname, err)
}
for _, manifest := range manifests {
if err := manifest.PipeE(kyaml.SetAnnotation(filenameAnnotation, fname)); err != nil {
return "", fmt.Errorf("annotating %s: %w", fname, err)
}
combinedManifests = append(combinedManifests, manifest)
}
}
merged, err := kio.StringAll(combinedManifests)
if err != nil {
return "", fmt.Errorf("writing merged docs: %w", err)
}
return merged, nil
}
// splitAndDeannotate reconstructs individual files from a merged YAML stream,
// removing filename annotations and grouping documents by their original filenames.
func splitAndDeannotate(postrendered string) (map[string]string, error) {
manifests, err := kio.ParseAll(postrendered)
if err != nil {
return nil, fmt.Errorf("error parsing YAML: %w", err)
}
manifestsByFilename := make(map[string][]*kyaml.RNode)
for i, manifest := range manifests {
meta, err := manifest.GetMeta()
if err != nil {
return nil, fmt.Errorf("getting metadata: %w", err)
}
fname := meta.Annotations[filenameAnnotation]
if fname == "" {
fname = fmt.Sprintf("generated-by-postrender-%d.yaml", i)
}
if err := manifest.PipeE(kyaml.ClearAnnotation(filenameAnnotation)); err != nil {
return nil, fmt.Errorf("clearing filename annotation: %w", err)
}
manifestsByFilename[fname] = append(manifestsByFilename[fname], manifest)
}
reconstructed := make(map[string]string, len(manifestsByFilename))
for fname, docs := range manifestsByFilename {
fileContents, err := kio.StringAll(docs)
if err != nil {
return nil, fmt.Errorf("re-writing %s: %w", fname, err)
}
reconstructed[fname] = fileContents
}
return reconstructed, nil
}
// renderResources renders the templates in a chart
//
// TODO: This function is badly in need of a refactor.
// TODO: As part of the refactor the duplicate code in cmd/helm/template.go should be removed
//
// This code has to do with writing files to disk.
func (cfg *Configuration) renderResources(ch *chart.Chart, values common.Values, releaseName, outputDir string, subNotes, useReleaseName, includeCrds bool, pr postrenderer.PostRenderer, interactWithRemote, enableDNS, hideSecret bool) ([]*release.Hook, *bytes.Buffer, string, error) {
var hs []*release.Hook
b := bytes.NewBuffer(nil)
caps, err := cfg.getCapabilities()
if err != nil {
return hs, b, "", err
}
if ch.Metadata.KubeVersion != "" {
if !chartutil.IsCompatibleRange(ch.Metadata.KubeVersion, caps.KubeVersion.String()) {
return hs, b, "", fmt.Errorf("chart requires kubeVersion: %s which is incompatible with Kubernetes %s", ch.Metadata.KubeVersion, caps.KubeVersion.Version)
}
}
var files map[string]string
var err2 error
// A `helm template` should not talk to the remote cluster. However, commands with the flag
// `--dry-run` with the value of `false`, `none`, or `server` should try to interact with the cluster.
// It may break in interesting and exotic ways because other data (e.g. discovery) is mocked.
if interactWithRemote && cfg.RESTClientGetter != nil {
restConfig, err := cfg.RESTClientGetter.ToRESTConfig()
if err != nil {
return hs, b, "", err
}
e := engine.New(restConfig)
e.EnableDNS = enableDNS
e.CustomTemplateFuncs = cfg.CustomTemplateFuncs
files, err2 = e.Render(ch, values)
} else {
var e engine.Engine
e.EnableDNS = enableDNS
e.CustomTemplateFuncs = cfg.CustomTemplateFuncs
files, err2 = e.Render(ch, values)
}
if err2 != nil {
return hs, b, "", err2
}
// NOTES.txt gets rendered like all the other files, but because it's not a hook nor a resource,
// pull it out of here into a separate file so that we can actually use the output of the rendered
// text file. We have to spin through this map because the file contains path information, so we
// look for terminating NOTES.txt. We also remove it from the files so that we don't have to skip
// it in the sortHooks.
var notesBuffer bytes.Buffer
for k, v := range files {
if strings.HasSuffix(k, notesFileSuffix) {
if subNotes || (k == path.Join(ch.Name(), "templates", notesFileSuffix)) {
// If buffer contains data, add newline before adding more
if notesBuffer.Len() > 0 {
notesBuffer.WriteString("\n")
}
notesBuffer.WriteString(v)
}
delete(files, k)
}
}
notes := notesBuffer.String()
if pr != nil {
// We need to send files to the post-renderer before sorting and splitting
// hooks from manifests. The post-renderer interface expects a stream of
// manifests (similar to what tools like Kustomize and kubectl expect), whereas
// the sorter uses filenames.
// Here, we merge the documents into a stream, post-render them, and then split
// them back into a map of filename -> content.
// Merge files as stream of documents for sending to post renderer
merged, err := annotateAndMerge(files)
if err != nil {
return hs, b, notes, fmt.Errorf("error merging manifests: %w", err)
}
// Run the post renderer
postRendered, err := pr.Run(bytes.NewBufferString(merged))
if err != nil {
return hs, b, notes, fmt.Errorf("error while running post render on files: %w", err)
}
// Use the file list and contents received from the post renderer
files, err = splitAndDeannotate(postRendered.String())
if err != nil {
return hs, b, notes, fmt.Errorf("error while parsing post rendered output: %w", err)
}
}
// Sort hooks, manifests, and partials. Only hooks and manifests are returned,
// as partials are not used after renderer.Render. Empty manifests are also
// removed here.
hs, manifests, err := releaseutil.SortManifests(files, nil, releaseutil.InstallOrder)
if err != nil {
// By catching parse errors here, we can prevent bogus releases from going
// to Kubernetes.
//
// We return the files as a big blob of data to help the user debug parser
// errors.
for name, content := range files {
if strings.TrimSpace(content) == "" {
continue
}
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", name, content)
}
return hs, b, "", err
}
// Aggregate all valid manifests into one big doc.
fileWritten := make(map[string]bool)
if includeCrds {
for _, crd := range ch.CRDObjects() {
if outputDir == "" {
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", crd.Filename, string(crd.File.Data[:]))
} else {
err = writeToFile(outputDir, crd.Filename, string(crd.File.Data[:]), fileWritten[crd.Filename])
if err != nil {
return hs, b, "", err
}
fileWritten[crd.Filename] = true
}
}
}
for _, m := range manifests {
if outputDir == "" {
if hideSecret && m.Head.Kind == "Secret" && m.Head.Version == "v1" {
fmt.Fprintf(b, "---\n# Source: %s\n# HIDDEN: The Secret output has been suppressed\n", m.Name)
} else {
fmt.Fprintf(b, "---\n# Source: %s\n%s\n", m.Name, m.Content)
}
} else {
newDir := outputDir
if useReleaseName {
newDir = filepath.Join(outputDir, releaseName)
}
// NOTE: We do not have to worry about the post-renderer because
// output dir is only used by `helm template`. In the next major
// release, we should move this logic to template only as it is not
// used by install or upgrade
err = writeToFile(newDir, m.Name, m.Content, fileWritten[m.Name])
if err != nil {
return hs, b, "", err
}
fileWritten[m.Name] = true
}
}
return hs, b, notes, nil
}
// RESTClientGetter gets the rest client
type RESTClientGetter interface {
ToRESTConfig() (*rest.Config, error)
ToDiscoveryClient() (discovery.CachedDiscoveryInterface, error)
ToRESTMapper() (meta.RESTMapper, error)
}
// capabilities builds a Capabilities from discovery information.
func (cfg *Configuration) getCapabilities() (*common.Capabilities, error) {
if cfg.Capabilities != nil {
return cfg.Capabilities, nil
}
dc, err := cfg.RESTClientGetter.ToDiscoveryClient()
if err != nil {
return nil, fmt.Errorf("could not get Kubernetes discovery client: %w", err)
}
// force a discovery cache invalidation to always fetch the latest server version/capabilities.
dc.Invalidate()
kubeVersion, err := dc.ServerVersion()
if err != nil {
return nil, fmt.Errorf("could not get server version from Kubernetes: %w", err)
}
// Issue #6361:
// Client-Go emits an error when an API service is registered but unimplemented.
// We trap that error here and print a warning. But since the discovery client continues
// building the API object, it is correctly populated with all valid APIs.
// See https://github.com/kubernetes/kubernetes/issues/72051#issuecomment-521157642
apiVersions, err := GetVersionSet(dc)
if err != nil {
if discovery.IsGroupDiscoveryFailedError(err) {
cfg.Logger().Warn("the kubernetes server has an orphaned API service", slog.Any("error", err))
cfg.Logger().Warn("to fix this, kubectl delete apiservice <service-name>")
} else {
return nil, fmt.Errorf("could not get apiVersions from Kubernetes: %w", err)
}
}
cfg.Capabilities = &common.Capabilities{
APIVersions: apiVersions,
KubeVersion: common.KubeVersion{
Version: kubeVersion.GitVersion,
Major: kubeVersion.Major,
Minor: kubeVersion.Minor,
},
HelmVersion: common.DefaultCapabilities.HelmVersion,
}
return cfg.Capabilities, nil
}
// KubernetesClientSet creates a new kubernetes ClientSet based on the configuration
func (cfg *Configuration) KubernetesClientSet() (kubernetes.Interface, error) {
conf, err := cfg.RESTClientGetter.ToRESTConfig()
if err != nil {
return nil, fmt.Errorf("unable to generate config for kubernetes client: %w", err)
}
return kubernetes.NewForConfig(conf)
}
// Now generates a timestamp
//
// If the configuration has a Timestamper on it, that will be used.
// Otherwise, this will use time.Now().
func (cfg *Configuration) Now() time.Time {
return Timestamper()
}
func (cfg *Configuration) releaseContent(name string, version int) (ri.Releaser, error) {
if err := chartutil.ValidateReleaseName(name); err != nil {
return nil, fmt.Errorf("releaseContent: Release name is invalid: %s", name)
}
if version <= 0 {
return cfg.Releases.Last(name)
}
return cfg.Releases.Get(name, version)
}
// GetVersionSet retrieves a set of available k8s API versions
func GetVersionSet(client discovery.ServerResourcesInterface) (common.VersionSet, error) {
groups, resources, err := client.ServerGroupsAndResources()
if err != nil && !discovery.IsGroupDiscoveryFailedError(err) {
return common.DefaultVersionSet, fmt.Errorf("could not get apiVersions from Kubernetes: %w", err)
}
// FIXME: The Kubernetes test fixture for cli appears to always return nil
// for calls to Discovery().ServerGroupsAndResources(). So in this case, we
// return the default API list. This is also a safe value to return in any
// other odd-ball case.
if len(groups) == 0 && len(resources) == 0 {
return common.DefaultVersionSet, nil
}
versionMap := make(map[string]interface{})
var versions []string
// Extract the groups
for _, g := range groups {
for _, gv := range g.Versions {
versionMap[gv.GroupVersion] = struct{}{}
}
}
// Extract the resources
var id string
var ok bool
for _, r := range resources {
for _, rl := range r.APIResources {
// A Kind at a GroupVersion can show up more than once. We only want
// it displayed once in the final output.
id = path.Join(r.GroupVersion, rl.Kind)
if _, ok = versionMap[id]; !ok {
versionMap[id] = struct{}{}
}
}
}
// Convert to a form that NewVersionSet can use
for k := range versionMap {
versions = append(versions, k)
}
return common.VersionSet(versions), nil
}
// recordRelease with an update operation in case reuse has been set.
func (cfg *Configuration) recordRelease(r *release.Release) {
if err := cfg.Releases.Update(r); err != nil {
cfg.Logger().Warn(
"failed to update release",
slog.String("name", r.Name),
slog.Int("revision", r.Version),
slog.Any("error", err),
)
}
}
// Init initializes the action configuration
func (cfg *Configuration) Init(getter genericclioptions.RESTClientGetter, namespace, helmDriver string) error {
kc := kube.New(getter)
kc.SetLogger(cfg.Logger().Handler())
lazyClient := &lazyClient{
namespace: namespace,
clientFn: kc.Factory.KubernetesClientSet,
}
var store *storage.Storage
switch helmDriver {
case "secret", "secrets", "":
d := driver.NewSecrets(newSecretClient(lazyClient))
d.SetLogger(cfg.Logger().Handler())
store = storage.Init(d)
case "configmap", "configmaps":
d := driver.NewConfigMaps(newConfigMapClient(lazyClient))
d.SetLogger(cfg.Logger().Handler())
store = storage.Init(d)
case "memory":
var d *driver.Memory
if cfg.Releases != nil {
if mem, ok := cfg.Releases.Driver.(*driver.Memory); ok {
// This function can be called more than once (e.g., helm list --all-namespaces).
// If a memory driver was already initialized, reuse it but set the possibly new namespace.
// We reuse it in case some releases where already created in the existing memory driver.
d = mem
}
}
if d == nil {
d = driver.NewMemory()
}
d.SetLogger(cfg.Logger().Handler())
d.SetNamespace(namespace)
store = storage.Init(d)
case "sql":
d, err := driver.NewSQL(
os.Getenv("HELM_DRIVER_SQL_CONNECTION_STRING"),
namespace,
)
if err != nil {
return fmt.Errorf("unable to instantiate SQL driver: %w", err)
}
d.SetLogger(cfg.Logger().Handler())
store = storage.Init(d)
default:
return fmt.Errorf("unknown driver %q", helmDriver)
}
cfg.RESTClientGetter = getter
cfg.KubeClient = kc
cfg.Releases = store
cfg.HookOutputFunc = func(_, _, _ string) io.Writer { return io.Discard }
return nil
}
// SetHookOutputFunc sets the HookOutputFunc on the Configuration.
func (cfg *Configuration) SetHookOutputFunc(hookOutputFunc func(_, _, _ string) io.Writer) {
cfg.HookOutputFunc = hookOutputFunc
}
func determineReleaseSSApplyMethod(serverSideApply bool) release.ApplyMethod {
if serverSideApply {
return release.ApplyMethodServerSideApply
}
return release.ApplyMethodClientSideApply
}
// isDryRun returns true if the strategy is set to run as a DryRun
func isDryRun(strategy DryRunStrategy) bool {
return strategy == DryRunClient || strategy == DryRunServer
}
// interactWithServer determine whether or not to interact with a remote Kubernetes server
func interactWithServer(strategy DryRunStrategy) bool {
return strategy == DryRunNone || strategy == DryRunServer
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get_values.go | pkg/action/get_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 action
import (
"fmt"
"helm.sh/helm/v4/pkg/chart/common/util"
release "helm.sh/helm/v4/pkg/release"
rspb "helm.sh/helm/v4/pkg/release/v1"
)
// GetValues is the action for checking a given release's values.
//
// It provides the implementation of 'helm get values'.
type GetValues struct {
cfg *Configuration
Version int
AllValues bool
}
// NewGetValues creates a new GetValues object with the given configuration.
func NewGetValues(cfg *Configuration) *GetValues {
return &GetValues{
cfg: cfg,
}
}
// Run executes 'helm get values' against the given release.
func (g *GetValues) Run(name string) (map[string]interface{}, error) {
if err := g.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
reli, err := g.cfg.releaseContent(name, g.Version)
if err != nil {
return nil, err
}
rel, err := releaserToV1Release(reli)
if err != nil {
return nil, err
}
// If the user wants all values, compute the values and return.
if g.AllValues {
cfg, err := util.CoalesceValues(rel.Chart, rel.Config)
if err != nil {
return nil, err
}
return cfg, nil
}
return rel.Config, nil
}
// releaserToV1Release is a helper function to convert a v1 release passed by interface
// into the type object.
func releaserToV1Release(rel release.Releaser) (*rspb.Release, error) {
switch r := rel.(type) {
case rspb.Release:
return &r, nil
case *rspb.Release:
return r, nil
case nil:
return nil, nil
default:
return nil, fmt.Errorf("unsupported release type: %T", rel)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/status_test.go | pkg/action/status_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 action
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
rcommon "helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestNewStatus(t *testing.T) {
config := actionConfigFixture(t)
client := NewStatus(config)
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
assert.Equal(t, 0, client.Version)
}
func TestStatusRun(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.BuildDummy = true
config.KubeClient = &failingKubeClient
client := NewStatus(config)
client.ShowResourcesTable = true
releaseName := "test-release"
require.NoError(t, configureReleaseContent(config, releaseName))
releaser, err := client.Run(releaseName)
require.NoError(t, err)
result, err := releaserToV1Release(releaser)
require.NoError(t, err)
assert.Equal(t, releaseName, result.Name)
assert.Equal(t, 1, result.Version)
}
func TestStatusRun_KubeClientNotReachable(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
client := NewStatus(config)
result, err := client.Run("")
assert.Nil(t, result)
assert.Error(t, err)
}
func TestStatusRun_KubeClientBuildTableError(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.BuildTableError = errors.New("build table error")
config.KubeClient = &failingKubeClient
releaseName := "test-release"
require.NoError(t, configureReleaseContent(config, releaseName))
client := NewStatus(config)
client.ShowResourcesTable = true
result, err := client.Run(releaseName)
assert.Nil(t, result)
assert.ErrorContains(t, err, "build table error")
}
func TestStatusRun_KubeClientBuildError(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.BuildError = errors.New("build error")
config.KubeClient = &failingKubeClient
releaseName := "test-release"
require.NoError(t, configureReleaseContent(config, releaseName))
client := NewStatus(config)
client.ShowResourcesTable = false
result, err := client.Run(releaseName)
assert.Nil(t, result)
assert.ErrorContains(t, err, "build error")
}
func TestStatusRun_KubeClientGetError(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.BuildError = errors.New("get error")
config.KubeClient = &failingKubeClient
releaseName := "test-release"
require.NoError(t, configureReleaseContent(config, releaseName))
client := NewStatus(config)
result, err := client.Run(releaseName)
assert.Nil(t, result)
assert.ErrorContains(t, err, "get error")
}
func configureReleaseContent(cfg *Configuration, releaseName string) error {
rel := &release.Release{
Name: releaseName,
Info: &release.Info{
Status: rcommon.StatusDeployed,
},
Manifest: testManifest,
Version: 1,
Namespace: "default",
}
return cfg.Releases.Create(rel)
}
const testManifest = `
apiVersion: v1
kind: Pod
metadata:
namespace: default
name: test-application
`
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/pull_test.go | pkg/action/pull_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 action
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/registry"
)
func TestNewPull(t *testing.T) {
config := actionConfigFixture(t)
client := NewPull(WithConfig(config))
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
}
func TestPullSetRegistryClient(t *testing.T) {
config := actionConfigFixture(t)
client := NewPull(WithConfig(config))
registryClient := ®istry.Client{}
client.SetRegistryClient(registryClient)
assert.Equal(t, registryClient, client.cfg.RegistryClient)
}
func TestPullRun_ChartNotFound(t *testing.T) {
srv, err := startLocalServerForTests(t, nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
config := actionConfigFixture(t)
client := NewPull(WithConfig(config))
client.Settings = cli.New()
client.RepoURL = srv.URL
chartRef := "nginx"
_, err = client.Run(chartRef)
require.ErrorContains(t, err, "404 Not Found")
}
func startLocalServerForTests(t *testing.T, handler http.Handler) (*httptest.Server, error) {
t.Helper()
if handler == nil {
fileBytes, err := os.ReadFile("../repo/v1/testdata/local-index.yaml")
if err != nil {
return nil, err
}
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err = w.Write(fileBytes)
require.NoError(t, err)
})
}
return httptest.NewServer(handler), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/verify_test.go | pkg/action/verify_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 action
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewVerify(t *testing.T) {
client := NewVerify()
assert.NotNil(t, client)
}
func TestVerifyRun(t *testing.T) {
client := NewVerify()
client.Keyring = "../downloader/testdata/helm-test-key.pub"
output, err := client.Run("../downloader/testdata/signtest-0.1.0.tgz")
assert.Contains(t, output, "Signed by:")
assert.Contains(t, output, "Using Key With Fingerprint:")
assert.Contains(t, output, "Chart Hash Verified:")
require.NoError(t, err)
}
func TestVerifyRun_DownloadError(t *testing.T) {
client := NewVerify()
output, err := client.Run("invalid-chart-path")
require.Error(t, err)
assert.Empty(t, output)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/uninstall.go | pkg/action/uninstall.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 action
import (
"errors"
"fmt"
"log/slog"
"strings"
"time"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/kube"
releasei "helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
releaseutil "helm.sh/helm/v4/pkg/release/v1/util"
"helm.sh/helm/v4/pkg/storage/driver"
)
// Uninstall is the action for uninstalling releases.
//
// It provides the implementation of 'helm uninstall'.
type Uninstall struct {
cfg *Configuration
DisableHooks bool
DryRun bool
IgnoreNotFound bool
KeepHistory bool
WaitStrategy kube.WaitStrategy
DeletionPropagation string
Timeout time.Duration
Description string
}
// NewUninstall creates a new Uninstall object with the given configuration.
func NewUninstall(cfg *Configuration) *Uninstall {
return &Uninstall{
cfg: cfg,
}
}
// Run uninstalls the given release.
func (u *Uninstall) Run(name string) (*releasei.UninstallReleaseResponse, error) {
if err := u.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
waiter, err := u.cfg.KubeClient.GetWaiter(u.WaitStrategy)
if err != nil {
return nil, err
}
if u.DryRun {
ri, err := u.cfg.releaseContent(name, 0)
if err != nil {
if u.IgnoreNotFound && errors.Is(err, driver.ErrReleaseNotFound) {
return nil, nil
}
return &releasei.UninstallReleaseResponse{}, err
}
r, err := releaserToV1Release(ri)
if err != nil {
return nil, err
}
return &releasei.UninstallReleaseResponse{Release: r}, nil
}
if err := chartutil.ValidateReleaseName(name); err != nil {
return nil, fmt.Errorf("uninstall: Release name is invalid: %s", name)
}
relsi, err := u.cfg.Releases.History(name)
if err != nil {
if u.IgnoreNotFound {
return nil, nil
}
return nil, fmt.Errorf("uninstall: Release not loaded: %s: %w", name, err)
}
if len(relsi) < 1 {
return nil, errMissingRelease
}
rels, err := releaseListToV1List(relsi)
if err != nil {
return nil, err
}
releaseutil.SortByRevision(rels)
rel := rels[len(rels)-1]
// TODO: Are there any cases where we want to force a delete even if it's
// already marked deleted?
if rel.Info.Status == common.StatusUninstalled {
if !u.KeepHistory {
if err := u.purgeReleases(rels...); err != nil {
return nil, fmt.Errorf("uninstall: Failed to purge the release: %w", err)
}
return &releasei.UninstallReleaseResponse{Release: rel}, nil
}
return nil, fmt.Errorf("the release named %q is already deleted", name)
}
u.cfg.Logger().Debug("uninstall: deleting release", "name", name)
rel.Info.Status = common.StatusUninstalling
rel.Info.Deleted = time.Now()
rel.Info.Description = "Deletion in progress (or silently failed)"
res := &releasei.UninstallReleaseResponse{Release: rel}
if !u.DisableHooks {
serverSideApply := true
if err := u.cfg.execHook(rel, release.HookPreDelete, u.WaitStrategy, u.Timeout, serverSideApply); err != nil {
return res, err
}
} else {
u.cfg.Logger().Debug("delete hooks disabled", "release", name)
}
// From here on out, the release is currently considered to be in StatusUninstalling
// state.
if err := u.cfg.Releases.Update(rel); err != nil {
u.cfg.Logger().Debug("uninstall: Failed to store updated release", slog.Any("error", err))
}
deletedResources, kept, errs := u.deleteRelease(rel)
if errs != nil {
u.cfg.Logger().Debug("uninstall: Failed to delete release", slog.Any("error", errs))
return nil, fmt.Errorf("failed to delete release: %s", name)
}
if kept != "" {
kept = "These resources were kept due to the resource policy:\n" + kept
}
res.Info = kept
if err := waiter.WaitForDelete(deletedResources, u.Timeout); err != nil {
errs = append(errs, err)
}
if !u.DisableHooks {
serverSideApply := true
if err := u.cfg.execHook(rel, release.HookPostDelete, u.WaitStrategy, u.Timeout, serverSideApply); err != nil {
errs = append(errs, err)
}
}
rel.Info.Status = common.StatusUninstalled
if len(u.Description) > 0 {
rel.Info.Description = u.Description
} else {
rel.Info.Description = "Uninstallation complete"
}
if !u.KeepHistory {
u.cfg.Logger().Debug("purge requested", "release", name)
err := u.purgeReleases(rels...)
if err != nil {
errs = append(errs, fmt.Errorf("uninstall: Failed to purge the release: %w", err))
}
// Return the errors that occurred while deleting the release, if any
if len(errs) > 0 {
return res, fmt.Errorf("uninstallation completed with %d error(s): %w", len(errs), joinErrors(errs, "; "))
}
return res, nil
}
if err := u.cfg.Releases.Update(rel); err != nil {
u.cfg.Logger().Debug("uninstall: Failed to store updated release", slog.Any("error", err))
}
// Supersede all previous deployments, see issue #12556 (which is a
// variation on #2941).
deployed, err := u.cfg.Releases.DeployedAll(name)
if err != nil && !errors.Is(err, driver.ErrNoDeployedReleases) {
return nil, err
}
for _, reli := range deployed {
rel, err := releaserToV1Release(reli)
if err != nil {
return nil, err
}
u.cfg.Logger().Debug("superseding previous deployment", "version", rel.Version)
rel.Info.Status = common.StatusSuperseded
if err := u.cfg.Releases.Update(rel); err != nil {
u.cfg.Logger().Debug("uninstall: Failed to store updated release", slog.Any("error", err))
}
}
if len(errs) > 0 {
return res, fmt.Errorf("uninstallation completed with %d error(s): %w", len(errs), joinErrors(errs, "; "))
}
return res, nil
}
func (u *Uninstall) purgeReleases(rels ...*release.Release) error {
for _, rel := range rels {
if _, err := u.cfg.Releases.Delete(rel.Name, rel.Version); err != nil {
return err
}
}
return nil
}
type joinedErrors struct {
errs []error
sep string
}
func joinErrors(errs []error, sep string) error {
return &joinedErrors{
errs: errs,
sep: sep,
}
}
func (e *joinedErrors) Error() string {
errs := make([]string, 0, len(e.errs))
for _, err := range e.errs {
errs = append(errs, err.Error())
}
return strings.Join(errs, e.sep)
}
func (e *joinedErrors) Unwrap() []error {
return e.errs
}
// deleteRelease deletes the release and returns list of delete resources and manifests that were kept in the deletion process
func (u *Uninstall) deleteRelease(rel *release.Release) (kube.ResourceList, string, []error) {
var errs []error
manifests := releaseutil.SplitManifests(rel.Manifest)
_, files, err := releaseutil.SortManifests(manifests, nil, releaseutil.UninstallOrder)
if err != nil {
// We could instead just delete everything in no particular order.
// FIXME: One way to delete at this point would be to try a label-based
// deletion. The problem with this is that we could get a false positive
// and delete something that was not legitimately part of this release.
return nil, rel.Manifest, []error{fmt.Errorf("corrupted release record. You must manually delete the resources: %w", err)}
}
filesToKeep, filesToDelete := filterManifestsToKeep(files)
var kept strings.Builder
for _, f := range filesToKeep {
fmt.Fprintf(&kept, "[%s] %s\n", f.Head.Kind, f.Head.Metadata.Name)
}
var builder strings.Builder
for _, file := range filesToDelete {
builder.WriteString("\n---\n" + file.Content)
}
resources, err := u.cfg.KubeClient.Build(strings.NewReader(builder.String()), false)
if err != nil {
return nil, "", []error{fmt.Errorf("unable to build kubernetes objects for delete: %w", err)}
}
if len(resources) > 0 {
_, errs = u.cfg.KubeClient.Delete(resources, parseCascadingFlag(u.DeletionPropagation))
}
return resources, kept.String(), errs
}
func parseCascadingFlag(cascadingFlag string) v1.DeletionPropagation {
switch cascadingFlag {
case "orphan":
return v1.DeletePropagationOrphan
case "foreground":
return v1.DeletePropagationForeground
case "background":
return v1.DeletePropagationBackground
default:
slog.Debug("uninstall: given cascade value, defaulting to delete propagation background", "value", cascadingFlag)
return v1.DeletePropagationBackground
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/upgrade_test.go | pkg/action/upgrade_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 action
import (
"context"
"errors"
"fmt"
"io"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/kube"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/storage/driver"
)
func upgradeAction(t *testing.T) *Upgrade {
t.Helper()
config := actionConfigFixture(t)
upAction := NewUpgrade(config)
upAction.Namespace = "spaced"
return upAction
}
func TestUpgradeRelease_Success(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "previous-release"
rel.Info.Status = common.StatusDeployed
req.NoError(upAction.cfg.Releases.Create(rel))
upAction.WaitStrategy = kube.StatusWatcherStrategy
vals := map[string]interface{}{}
ctx, done := context.WithCancel(t.Context())
resi, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals)
req.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(res.Info.Status, common.StatusDeployed)
done()
// Detecting previous bug where context termination after successful release
// caused release to fail.
time.Sleep(time.Millisecond * 100)
lastReleasei, err := upAction.cfg.Releases.Last(rel.Name)
req.NoError(err)
lastRelease, err := releaserToV1Release(lastReleasei)
req.NoError(err)
is.Equal(lastRelease.Info.Status, common.StatusDeployed)
}
func TestUpgradeRelease_Wait(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
upAction.cfg.KubeClient = failer
upAction.WaitStrategy = kube.StatusWatcherStrategy
vals := map[string]interface{}{}
resi, err := upAction.Run(rel.Name, buildChart(), vals)
req.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "I timed out")
is.Equal(res.Info.Status, common.StatusFailed)
}
func TestUpgradeRelease_WaitForJobs(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
upAction.cfg.KubeClient = failer
upAction.WaitStrategy = kube.StatusWatcherStrategy
upAction.WaitForJobs = true
vals := map[string]interface{}{}
resi, err := upAction.Run(rel.Name, buildChart(), vals)
req.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "I timed out")
is.Equal(res.Info.Status, common.StatusFailed)
}
func TestUpgradeRelease_CleanupOnFail(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
failer.DeleteError = fmt.Errorf("I tried to delete nil")
upAction.cfg.KubeClient = failer
upAction.WaitStrategy = kube.StatusWatcherStrategy
upAction.CleanupOnFail = true
vals := map[string]interface{}{}
resi, err := upAction.Run(rel.Name, buildChart(), vals)
req.Error(err)
is.NotContains(err.Error(), "unable to cleanup resources")
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "I timed out")
is.Equal(res.Info.Status, common.StatusFailed)
}
func TestUpgradeRelease_RollbackOnFailure(t *testing.T) {
is := assert.New(t)
req := require.New(t)
t.Run("rollback-on-failure rollback succeeds", func(t *testing.T) {
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "nuketown"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
// We can't make Update error because then the rollback won't work
failer.WatchUntilReadyError = fmt.Errorf("arming key removed")
upAction.cfg.KubeClient = failer
upAction.RollbackOnFailure = true
vals := map[string]interface{}{}
resi, err := upAction.Run(rel.Name, buildChart(), vals)
req.Error(err)
is.Contains(err.Error(), "arming key removed")
is.Contains(err.Error(), "rollback-on-failure")
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it is actually upgraded
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 3)
is.NoError(err)
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
// Should have rolled back to the previous
is.Equal(updatedRes.Info.Status, common.StatusDeployed)
})
t.Run("rollback-on-failure uninstall fails", func(t *testing.T) {
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "fallout"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.UpdateError = fmt.Errorf("update fail")
upAction.cfg.KubeClient = failer
upAction.RollbackOnFailure = true
vals := map[string]interface{}{}
_, err := upAction.Run(rel.Name, buildChart(), vals)
req.Error(err)
is.Contains(err.Error(), "update fail")
is.Contains(err.Error(), "an error occurred while rolling back the release")
})
}
func TestUpgradeRelease_ReuseValues(t *testing.T) {
is := assert.New(t)
t.Run("reuse values should work with values", func(t *testing.T) {
upAction := upgradeAction(t)
existingValues := map[string]interface{}{
"name": "value",
"maxHeapSize": "128m",
"replicas": 2,
}
newValues := map[string]interface{}{
"name": "newValue",
"maxHeapSize": "512m",
"cpu": "12m",
}
expectedValues := map[string]interface{}{
"name": "newValue",
"maxHeapSize": "512m",
"cpu": "12m",
"replicas": 2,
}
rel := releaseStub()
rel.Name = "nuketown"
rel.Info.Status = common.StatusDeployed
rel.Config = existingValues
err := upAction.cfg.Releases.Create(rel)
is.NoError(err)
upAction.ReuseValues = true
// setting newValues and upgrading
resi, err := upAction.Run(rel.Name, buildChart(), newValues)
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it is actually upgraded
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 2)
is.NoError(err)
if updatedResi == nil {
is.Fail("Updated Release is nil")
return
}
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
is.Equal(common.StatusDeployed, updatedRes.Info.Status)
is.Equal(expectedValues, updatedRes.Config)
})
t.Run("reuse values should not install disabled charts", func(t *testing.T) {
upAction := upgradeAction(t)
chartDefaultValues := map[string]interface{}{
"subchart": map[string]interface{}{
"enabled": true,
},
}
dependency := chart.Dependency{
Name: "subchart",
Version: "0.1.0",
Repository: "http://some-repo.com",
Condition: "subchart.enabled",
}
sampleChart := buildChart(
withName("sample"),
withValues(chartDefaultValues),
withMetadataDependency(dependency),
)
now := time.Now()
existingValues := map[string]interface{}{
"subchart": map[string]interface{}{
"enabled": false,
},
}
rel := &release.Release{
Name: "nuketown",
Info: &release.Info{
FirstDeployed: now,
LastDeployed: now,
Status: common.StatusDeployed,
Description: "Named Release Stub",
},
Chart: sampleChart,
Config: existingValues,
Version: 1,
}
err := upAction.cfg.Releases.Create(rel)
is.NoError(err)
upAction.ReuseValues = true
sampleChartWithSubChart := buildChart(
withName(sampleChart.Name()),
withValues(sampleChart.Values),
withDependency(withName("subchart")),
withMetadataDependency(dependency),
)
// reusing values and upgrading
resi, err := upAction.Run(rel.Name, sampleChartWithSubChart, map[string]interface{}{})
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now get the upgraded release
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 2)
is.NoError(err)
if updatedResi == nil {
is.Fail("Updated Release is nil")
return
}
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
is.Equal(common.StatusDeployed, updatedRes.Info.Status)
is.Equal(0, len(updatedRes.Chart.Dependencies()), "expected 0 dependencies")
expectedValues := map[string]interface{}{
"subchart": map[string]interface{}{
"enabled": false,
},
}
is.Equal(expectedValues, updatedRes.Config)
})
}
func TestUpgradeRelease_ResetThenReuseValues(t *testing.T) {
is := assert.New(t)
t.Run("reset then reuse values should work with values", func(t *testing.T) {
upAction := upgradeAction(t)
existingValues := map[string]interface{}{
"name": "value",
"maxHeapSize": "128m",
"replicas": 2,
}
newValues := map[string]interface{}{
"name": "newValue",
"maxHeapSize": "512m",
"cpu": "12m",
}
newChartValues := map[string]interface{}{
"memory": "256m",
}
expectedValues := map[string]interface{}{
"name": "newValue",
"maxHeapSize": "512m",
"cpu": "12m",
"replicas": 2,
}
rel := releaseStub()
rel.Name = "nuketown"
rel.Info.Status = common.StatusDeployed
rel.Config = existingValues
err := upAction.cfg.Releases.Create(rel)
is.NoError(err)
upAction.ResetThenReuseValues = true
// setting newValues and upgrading
resi, err := upAction.Run(rel.Name, buildChart(withValues(newChartValues)), newValues)
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it is actually upgraded
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 2)
is.NoError(err)
if updatedResi == nil {
is.Fail("Updated Release is nil")
return
}
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
is.Equal(common.StatusDeployed, updatedRes.Info.Status)
is.Equal(expectedValues, updatedRes.Config)
is.Equal(newChartValues, updatedRes.Chart.Values)
})
}
func TestUpgradeRelease_Pending(t *testing.T) {
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
rel2 := releaseStub()
rel2.Name = "come-fail-away"
rel2.Info.Status = common.StatusPendingUpgrade
rel2.Version = 2
require.NoError(t, upAction.cfg.Releases.Create(rel2))
vals := map[string]interface{}{}
_, err := upAction.Run(rel.Name, buildChart(), vals)
req.Contains(err.Error(), "progress", err)
}
func TestUpgradeRelease_Interrupted_Wait(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "interrupted-release"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitDuration = 10 * time.Second
upAction.cfg.KubeClient = failer
upAction.WaitStrategy = kube.StatusWatcherStrategy
vals := map[string]interface{}{}
ctx, cancel := context.WithCancel(t.Context())
time.AfterFunc(time.Second, cancel)
resi, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals)
req.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "Upgrade \"interrupted-release\" failed: context canceled")
is.Equal(res.Info.Status, common.StatusFailed)
}
func TestUpgradeRelease_Interrupted_RollbackOnFailure(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "interrupted-release"
rel.Info.Status = common.StatusDeployed
require.NoError(t, upAction.cfg.Releases.Create(rel))
failer := upAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitDuration = 5 * time.Second
upAction.cfg.KubeClient = failer
upAction.RollbackOnFailure = true
vals := map[string]interface{}{}
ctx, cancel := context.WithCancel(t.Context())
time.AfterFunc(time.Second, cancel)
resi, err := upAction.RunWithContext(ctx, rel.Name, buildChart(), vals)
req.Error(err)
is.Contains(err.Error(), "release interrupted-release failed, and has been rolled back due to rollback-on-failure being set: context canceled")
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it is actually upgraded
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 3)
is.NoError(err)
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
// Should have rolled back to the previous
is.Equal(updatedRes.Info.Status, common.StatusDeployed)
}
func TestMergeCustomLabels(t *testing.T) {
tests := [][3]map[string]string{
{nil, nil, map[string]string{}},
{map[string]string{}, map[string]string{}, map[string]string{}},
{map[string]string{"k1": "v1", "k2": "v2"}, nil, map[string]string{"k1": "v1", "k2": "v2"}},
{nil, map[string]string{"k1": "v1", "k2": "v2"}, map[string]string{"k1": "v1", "k2": "v2"}},
{map[string]string{"k1": "v1", "k2": "v2"}, map[string]string{"k1": "null", "k2": "v3"}, map[string]string{"k2": "v3"}},
}
for _, test := range tests {
if output := mergeCustomLabels(test[0], test[1]); !reflect.DeepEqual(test[2], output) {
t.Errorf("Expected {%v}, got {%v}", test[2], output)
}
}
}
func TestUpgradeRelease_Labels(t *testing.T) {
is := assert.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "labels"
// It's needed to check that suppressed release would keep original labels
rel.Labels = map[string]string{
"key1": "val1",
"key2": "val2.1",
}
rel.Info.Status = common.StatusDeployed
err := upAction.cfg.Releases.Create(rel)
is.NoError(err)
upAction.Labels = map[string]string{
"key1": "null",
"key2": "val2.2",
"key3": "val3",
}
// setting newValues and upgrading
resi, err := upAction.Run(rel.Name, buildChart(), nil)
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it is actually upgraded and labels were merged
updatedResi, err := upAction.cfg.Releases.Get(res.Name, 2)
is.NoError(err)
if updatedResi == nil {
is.Fail("Updated Release is nil")
return
}
updatedRes, err := releaserToV1Release(updatedResi)
is.NoError(err)
is.Equal(common.StatusDeployed, updatedRes.Info.Status)
is.Equal(mergeCustomLabels(rel.Labels, upAction.Labels), updatedRes.Labels)
// Now make sure it is suppressed release still contains original labels
initialResi, err := upAction.cfg.Releases.Get(res.Name, 1)
is.NoError(err)
if initialResi == nil {
is.Fail("Updated Release is nil")
return
}
initialRes, err := releaserToV1Release(initialResi)
is.NoError(err)
is.Equal(initialRes.Info.Status, common.StatusSuperseded)
is.Equal(initialRes.Labels, rel.Labels)
}
func TestUpgradeRelease_SystemLabels(t *testing.T) {
is := assert.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "labels"
// It's needed to check that suppressed release would keep original labels
rel.Labels = map[string]string{
"key1": "val1",
"key2": "val2.1",
}
rel.Info.Status = common.StatusDeployed
err := upAction.cfg.Releases.Create(rel)
is.NoError(err)
upAction.Labels = map[string]string{
"key1": "null",
"key2": "val2.2",
"owner": "val3",
}
// setting newValues and upgrading
_, err = upAction.Run(rel.Name, buildChart(), nil)
if err == nil {
t.Fatal("expected an error")
}
is.Equal(fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()), err)
}
func TestUpgradeRelease_DryRun(t *testing.T) {
is := assert.New(t)
req := require.New(t)
upAction := upgradeAction(t)
rel := releaseStub()
rel.Name = "previous-release"
rel.Info.Status = common.StatusDeployed
req.NoError(upAction.cfg.Releases.Create(rel))
upAction.DryRunStrategy = DryRunClient
vals := map[string]interface{}{}
ctx, done := context.WithCancel(t.Context())
resi, err := upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals)
done()
req.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(common.StatusPendingUpgrade, res.Info.Status)
is.Contains(res.Manifest, "kind: Secret")
lastReleasei, err := upAction.cfg.Releases.Last(rel.Name)
req.NoError(err)
lastRelease, err := releaserToV1Release(lastReleasei)
req.NoError(err)
is.Equal(lastRelease.Info.Status, common.StatusDeployed)
is.Equal(1, lastRelease.Version)
// Test the case for hiding the secret to ensure it is not displayed
upAction.HideSecret = true
vals = map[string]interface{}{}
ctx, done = context.WithCancel(t.Context())
resi, err = upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals)
done()
req.NoError(err)
res, err = releaserToV1Release(resi)
is.NoError(err)
is.Equal(common.StatusPendingUpgrade, res.Info.Status)
is.NotContains(res.Manifest, "kind: Secret")
lastReleasei, err = upAction.cfg.Releases.Last(rel.Name)
req.NoError(err)
lastRelease, err = releaserToV1Release(lastReleasei)
req.NoError(err)
is.Equal(lastRelease.Info.Status, common.StatusDeployed)
is.Equal(1, lastRelease.Version)
// Ensure in a dry run mode when using HideSecret
upAction.DryRunStrategy = DryRunNone
vals = map[string]interface{}{}
ctx, done = context.WithCancel(t.Context())
_, err = upAction.RunWithContext(ctx, rel.Name, buildChart(withSampleSecret()), vals)
done()
req.Error(err)
}
func TestGetUpgradeServerSideValue(t *testing.T) {
tests := []struct {
name string
actionServerSideOption string
releaseApplyMethod string
expectedServerSideApply bool
}{
{
name: "action ssa auto / release csa",
actionServerSideOption: "auto",
releaseApplyMethod: "csa",
expectedServerSideApply: false,
},
{
name: "action ssa auto / release ssa",
actionServerSideOption: "auto",
releaseApplyMethod: "ssa",
expectedServerSideApply: true,
},
{
name: "action ssa auto / release empty",
actionServerSideOption: "auto",
releaseApplyMethod: "",
expectedServerSideApply: false,
},
{
name: "action ssa true / release csa",
actionServerSideOption: "true",
releaseApplyMethod: "csa",
expectedServerSideApply: true,
},
{
name: "action ssa true / release ssa",
actionServerSideOption: "true",
releaseApplyMethod: "ssa",
expectedServerSideApply: true,
},
{
name: "action ssa true / release 'unknown'",
actionServerSideOption: "true",
releaseApplyMethod: "foo",
expectedServerSideApply: true,
},
{
name: "action ssa true / release empty",
actionServerSideOption: "true",
releaseApplyMethod: "",
expectedServerSideApply: true,
},
{
name: "action ssa false / release csa",
actionServerSideOption: "false",
releaseApplyMethod: "ssa",
expectedServerSideApply: false,
},
{
name: "action ssa false / release ssa",
actionServerSideOption: "false",
releaseApplyMethod: "ssa",
expectedServerSideApply: false,
},
{
name: "action ssa false / release 'unknown'",
actionServerSideOption: "false",
releaseApplyMethod: "foo",
expectedServerSideApply: false,
},
{
name: "action ssa false / release empty",
actionServerSideOption: "false",
releaseApplyMethod: "ssa",
expectedServerSideApply: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
serverSideApply, err := getUpgradeServerSideValue(tt.actionServerSideOption, tt.releaseApplyMethod)
assert.Nil(t, err)
assert.Equal(t, tt.expectedServerSideApply, serverSideApply)
})
}
testsError := []struct {
name string
actionServerSideOption string
releaseApplyMethod string
expectedErrorMsg string
}{
{
name: "action invalid option",
actionServerSideOption: "invalid",
releaseApplyMethod: "ssa",
expectedErrorMsg: "invalid/unknown release server-side apply method: invalid",
},
}
for _, tt := range testsError {
t.Run(tt.name, func(t *testing.T) {
_, err := getUpgradeServerSideValue(tt.actionServerSideOption, tt.releaseApplyMethod)
assert.ErrorContains(t, err, tt.expectedErrorMsg)
})
}
}
func TestUpgradeRun_UnreachableKubeClient(t *testing.T) {
t.Helper()
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
client := NewUpgrade(config)
vals := map[string]interface{}{}
result, err := client.Run("", buildChart(), vals)
assert.Nil(t, result)
assert.ErrorContains(t, err, "connection refused")
}
func TestUpgradeSetRegistryClient(t *testing.T) {
config := actionConfigFixture(t)
client := NewUpgrade(config)
registryClient := ®istry.Client{}
client.SetRegistryClient(registryClient)
assert.Equal(t, registryClient, client.registryClient)
}
func TestObjectKey(t *testing.T) {
obj := &appsv1.Deployment{}
obj.SetGroupVersionKind(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"})
info := resource.Info{Name: "name", Namespace: "namespace", Object: obj}
assert.Equal(t, "apps/v1/Deployment/namespace/name", objectKey(&info))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/install_test.go | pkg/action/install_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 action
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
appsv1 "k8s.io/api/apps/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
kuberuntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest/fake"
ci "helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/internal/test"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/kube"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/registry"
rcommon "helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/storage/driver"
)
type nameTemplateTestCase struct {
tpl string
expected string
expectedErrorStr string
}
func createDummyResourceList(owned bool) kube.ResourceList {
obj := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "dummyName",
Namespace: "spaced",
},
}
if owned {
obj.Labels = map[string]string{
"app.kubernetes.io/managed-by": "Helm",
}
obj.Annotations = map[string]string{
"meta.helm.sh/release-name": "test-install-release",
"meta.helm.sh/release-namespace": "spaced",
}
}
resInfo := resource.Info{
Name: "dummyName",
Namespace: "spaced",
Mapping: &meta.RESTMapping{
Resource: schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployment"},
GroupVersionKind: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"},
Scope: meta.RESTScopeNamespace,
},
Object: obj,
}
body := io.NopCloser(bytes.NewReader([]byte(kuberuntime.EncodeOrDie(appsv1Codec, obj))))
resInfo.Client = &fake.RESTClient{
GroupVersion: schema.GroupVersion{Group: "apps", Version: "v1"},
NegotiatedSerializer: scheme.Codecs.WithoutConversion(),
Client: fake.CreateHTTPClient(func(_ *http.Request) (*http.Response, error) {
header := http.Header{}
header.Set("Content-Type", kuberuntime.ContentTypeJSON)
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
Body: body,
}, nil
}),
}
var resourceList kube.ResourceList
resourceList.Append(&resInfo)
return resourceList
}
func installActionWithConfig(config *Configuration) *Install {
instAction := NewInstall(config)
instAction.Namespace = "spaced"
instAction.ReleaseName = "test-install-release"
return instAction
}
func installAction(t *testing.T) *Install {
t.Helper()
config := actionConfigFixture(t)
instAction := NewInstall(config)
instAction.Namespace = "spaced"
instAction.ReleaseName = "test-install-release"
return instAction
}
func TestInstallRelease(t *testing.T) {
is := assert.New(t)
req := require.New(t)
instAction := installAction(t)
vals := map[string]interface{}{}
ctx, done := context.WithCancel(t.Context())
resi, err := instAction.RunWithContext(ctx, buildChart(), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(res.Name, "test-install-release", "Expected release name.")
is.Equal(res.Namespace, "spaced")
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Len(rel.Hooks, 1)
is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")
is.NotEqual(len(res.Manifest), 0)
is.NotEqual(len(rel.Manifest), 0)
is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
is.Equal(rel.Info.Description, "Install complete")
// Detecting previous bug where context termination after successful release
// caused release to fail.
done()
time.Sleep(time.Millisecond * 100)
lastRelease, err := instAction.cfg.Releases.Last(rel.Name)
req.NoError(err)
lrel, err := releaserToV1Release(lastRelease)
is.NoError(err)
is.Equal(lrel.Info.Status, rcommon.StatusDeployed)
}
func TestInstallReleaseWithTakeOwnership_ResourceNotOwned(t *testing.T) {
// This test will test checking ownership of a resource
// returned by the fake client. If the resource is not
// owned by the chart, ownership is taken.
// To verify ownership has been taken, the fake client
// needs to store state which is a bigger rewrite.
// TODO: Ensure fake kube client stores state. Maybe using
// "k8s.io/client-go/kubernetes/fake" could be sufficient? i.e
// "Client{Namespace: namespace, kubeClient: k8sfake.NewClientset()}"
is := assert.New(t)
// Resource list from cluster is NOT owned by helm chart
config := actionConfigFixtureWithDummyResources(t, createDummyResourceList(false))
instAction := installActionWithConfig(config)
instAction.TakeOwnership = true
resi, err := instAction.Run(buildChart(), nil)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Equal(rel.Info.Description, "Install complete")
}
func TestInstallReleaseWithTakeOwnership_ResourceOwned(t *testing.T) {
is := assert.New(t)
// Resource list from cluster is owned by helm chart
config := actionConfigFixtureWithDummyResources(t, createDummyResourceList(true))
instAction := installActionWithConfig(config)
instAction.TakeOwnership = false
resi, err := instAction.Run(buildChart(), nil)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Equal(rel.Info.Description, "Install complete")
}
func TestInstallReleaseWithTakeOwnership_ResourceOwnedNoFlag(t *testing.T) {
is := assert.New(t)
// Resource list from cluster is NOT owned by helm chart
config := actionConfigFixtureWithDummyResources(t, createDummyResourceList(false))
instAction := installActionWithConfig(config)
_, err := instAction.Run(buildChart(), nil)
is.Error(err)
is.Contains(err.Error(), "unable to continue with install")
}
func TestInstallReleaseWithValues(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
userVals := map[string]interface{}{
"nestedKey": map[string]interface{}{
"simpleKey": "simpleValue",
},
}
expectedUserValues := map[string]interface{}{
"nestedKey": map[string]interface{}{
"simpleKey": "simpleValue",
},
}
resi, err := instAction.Run(buildChart(withSampleValues()), userVals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(res.Name, "test-install-release", "Expected release name.")
is.Equal(res.Namespace, "spaced")
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Len(rel.Hooks, 1)
is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")
is.NotEqual(len(res.Manifest), 0)
is.NotEqual(len(rel.Manifest), 0)
is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
is.Equal("Install complete", rel.Info.Description)
is.Equal(expectedUserValues, rel.Config)
}
func TestInstallRelease_NoName(t *testing.T) {
instAction := installAction(t)
instAction.ReleaseName = ""
vals := map[string]interface{}{}
_, err := instAction.Run(buildChart(), vals)
if err == nil {
t.Fatal("expected failure when no name is specified")
}
assert.Contains(t, err.Error(), "no name provided")
}
func TestInstallRelease_WithNotes(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "with-notes"
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withNotes("note here")), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(res.Name, "with-notes")
is.Equal(res.Namespace, "spaced")
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Len(rel.Hooks, 1)
is.Equal(rel.Hooks[0].Manifest, manifestWithHook)
is.Equal(rel.Hooks[0].Events[0], release.HookPostInstall)
is.Equal(rel.Hooks[0].Events[1], release.HookPreDelete, "Expected event 0 is pre-delete")
is.NotEqual(len(res.Manifest), 0)
is.NotEqual(len(rel.Manifest), 0)
is.Contains(rel.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
is.Equal(rel.Info.Description, "Install complete")
is.Equal(rel.Info.Notes, "note here")
}
func TestInstallRelease_WithNotesRendered(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "with-notes"
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withNotes("got-{{.Release.Name}}")), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
expectedNotes := fmt.Sprintf("got-%s", res.Name)
is.Equal(expectedNotes, rel.Info.Notes)
is.Equal(rel.Info.Description, "Install complete")
}
func TestInstallRelease_WithChartAndDependencyParentNotes(t *testing.T) {
// Regression: Make sure that the child's notes don't override the parent's
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "with-notes"
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withNotes("parent"), withDependency(withNotes("child"))), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Equal("with-notes", rel.Name)
is.Equal("parent", rel.Info.Notes)
is.Equal(rel.Info.Description, "Install complete")
}
func TestInstallRelease_WithChartAndDependencyAllNotes(t *testing.T) {
// Regression: Make sure that the child's notes don't override the parent's
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "with-notes"
instAction.SubNotes = true
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withNotes("parent"), withDependency(withNotes("child"))), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
r, err := instAction.cfg.Releases.Get(res.Name, res.Version)
is.NoError(err)
rel, err := releaserToV1Release(r)
is.NoError(err)
is.Equal("with-notes", rel.Name)
// test run can return as either 'parent\nchild' or 'child\nparent'
if !strings.Contains(rel.Info.Notes, "parent") && !strings.Contains(rel.Info.Notes, "child") {
t.Fatalf("Expected 'parent\nchild' or 'child\nparent', got '%s'", rel.Info.Notes)
}
is.Equal(rel.Info.Description, "Install complete")
}
func TestInstallRelease_DryRunClient(t *testing.T) {
for _, dryRunStrategy := range []DryRunStrategy{DryRunClient, DryRunServer} {
is := assert.New(t)
instAction := installAction(t)
instAction.DryRunStrategy = dryRunStrategy
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withSampleTemplates()), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Manifest, "---\n# Source: hello/templates/hello\nhello: world")
is.Contains(res.Manifest, "---\n# Source: hello/templates/goodbye\ngoodbye: world")
is.Contains(res.Manifest, "hello: Earth")
is.NotContains(res.Manifest, "hello: {{ template \"_planet\" . }}")
is.NotContains(res.Manifest, "empty")
_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
is.Error(err)
is.Len(res.Hooks, 1)
is.True(res.Hooks[0].LastRun.CompletedAt.IsZero(), "expect hook to not be marked as run")
is.Equal(res.Info.Description, "Dry run complete")
}
}
func TestInstallRelease_DryRunHiddenSecret(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
// First perform a normal dry-run with the secret and confirm its presence.
instAction.DryRunStrategy = DryRunClient
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(withSampleSecret(), withSampleTemplates()), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Manifest, "---\n# Source: hello/templates/secret.yaml\napiVersion: v1\nkind: Secret")
_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
is.Error(err)
is.Equal(res.Info.Description, "Dry run complete")
// Perform a dry-run where the secret should not be present
instAction.HideSecret = true
vals = map[string]interface{}{}
res2i, err := instAction.Run(buildChart(withSampleSecret(), withSampleTemplates()), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res2, err := releaserToV1Release(res2i)
is.NoError(err)
is.NotContains(res2.Manifest, "---\n# Source: hello/templates/secret.yaml\napiVersion: v1\nkind: Secret")
_, err = instAction.cfg.Releases.Get(res2.Name, res2.Version)
is.Error(err)
is.Equal(res2.Info.Description, "Dry run complete")
// Ensure there is an error when HideSecret True but not in a dry-run mode
instAction.DryRunStrategy = DryRunNone
vals = map[string]interface{}{}
_, err = instAction.Run(buildChart(withSampleSecret(), withSampleTemplates()), vals)
if err == nil {
t.Fatalf("Did not get expected an error when dry-run false and hide secret is true")
}
}
// Regression test for #7955
func TestInstallRelease_DryRun_Lookup(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.DryRunStrategy = DryRunNone
vals := map[string]interface{}{}
mockChart := buildChart(withSampleTemplates())
mockChart.Templates = append(mockChart.Templates, &common.File{
Name: "templates/lookup",
ModTime: time.Now(),
Data: []byte(`goodbye: {{ lookup "v1" "Namespace" "" "___" }}`),
})
resi, err := instAction.Run(mockChart, vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Manifest, "goodbye: map[]")
}
func TestInstallReleaseIncorrectTemplate_DryRun(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.DryRunStrategy = DryRunNone
vals := map[string]interface{}{}
_, err := instAction.Run(buildChart(withSampleIncludingIncorrectTemplates()), vals)
expectedErr := `hello/templates/incorrect:1:10
executing "hello/templates/incorrect" at <.Values.bad.doh>:
nil pointer evaluating interface {}.doh`
if err == nil {
t.Fatalf("Install should fail containing error: %s", expectedErr)
}
is.Contains(err.Error(), expectedErr)
}
func TestInstallRelease_NoHooks(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.DisableHooks = true
instAction.ReleaseName = "no-hooks"
require.NoError(t, instAction.cfg.Releases.Create(releaseStub()))
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.True(res.Hooks[0].LastRun.CompletedAt.IsZero(), "hooks should not run with no-hooks")
}
func TestInstallRelease_FailedHooks(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "failed-hooks"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WatchUntilReadyError = fmt.Errorf("Failed watch")
instAction.cfg.KubeClient = failer
outBuffer := &bytes.Buffer{}
failer.PrintingKubeClient = kubefake.PrintingKubeClient{Out: io.Discard, LogOutput: outBuffer}
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(), vals)
is.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "failed post-install")
is.Equal("", outBuffer.String())
is.Equal(rcommon.StatusFailed, res.Info.Status)
}
func TestInstallRelease_ReplaceRelease(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.Replace = true
rel := releaseStub()
rel.Info.Status = rcommon.StatusUninstalled
require.NoError(t, instAction.cfg.Releases.Create(rel))
instAction.ReleaseName = rel.Name
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(), vals)
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
// This should have been auto-incremented
is.Equal(2, res.Version)
is.Equal(res.Name, rel.Name)
r, err := instAction.cfg.Releases.Get(rel.Name, res.Version)
is.NoError(err)
getres, err := releaserToV1Release(r)
is.NoError(err)
is.Equal(getres.Info.Status, rcommon.StatusDeployed)
}
func TestInstallRelease_KubeVersion(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
vals := map[string]interface{}{}
_, err := instAction.Run(buildChart(withKube(">=0.0.0")), vals)
is.NoError(err)
// This should fail for a few hundred years
instAction.ReleaseName = "should-fail"
vals = map[string]interface{}{}
_, err = instAction.Run(buildChart(withKube(">=99.0.0")), vals)
is.Error(err)
is.Contains(err.Error(), "chart requires kubeVersion: >=99.0.0 which is incompatible with Kubernetes v1.20.")
}
func TestInstallRelease_Wait(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "come-fail-away"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
instAction.cfg.KubeClient = failer
instAction.WaitStrategy = kube.StatusWatcherStrategy
vals := map[string]interface{}{}
goroutines := instAction.getGoroutineCount()
resi, err := instAction.Run(buildChart(), vals)
is.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "I timed out")
is.Equal(res.Info.Status, rcommon.StatusFailed)
is.Equal(goroutines, instAction.getGoroutineCount())
}
func TestInstallRelease_Wait_Interrupted(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "interrupted-release"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitDuration = 10 * time.Second
instAction.cfg.KubeClient = failer
instAction.WaitStrategy = kube.StatusWatcherStrategy
vals := map[string]interface{}{}
ctx, cancel := context.WithCancel(t.Context())
time.AfterFunc(time.Second, cancel)
goroutines := instAction.getGoroutineCount()
_, err := instAction.RunWithContext(ctx, buildChart(), vals)
is.Error(err)
is.Contains(err.Error(), "context canceled")
is.Equal(goroutines+1, instAction.getGoroutineCount()) // installation goroutine still is in background
time.Sleep(10 * time.Second) // wait for goroutine to finish
is.Equal(goroutines, instAction.getGoroutineCount())
}
func TestInstallRelease_WaitForJobs(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "come-fail-away"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
instAction.cfg.KubeClient = failer
instAction.WaitStrategy = kube.StatusWatcherStrategy
instAction.WaitForJobs = true
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(), vals)
is.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "I timed out")
is.Equal(res.Info.Status, rcommon.StatusFailed)
}
func TestInstallRelease_RollbackOnFailure(t *testing.T) {
is := assert.New(t)
t.Run("rollback-on-failure uninstall succeeds", func(t *testing.T) {
instAction := installAction(t)
instAction.ReleaseName = "come-fail-away"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
instAction.cfg.KubeClient = failer
instAction.RollbackOnFailure = true
// disabling hooks to avoid an early fail when
// WaitForDelete is called on the pre-delete hook execution
instAction.DisableHooks = true
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChart(), vals)
is.Error(err)
is.Contains(err.Error(), "I timed out")
is.Contains(err.Error(), "rollback-on-failure")
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it isn't in storage anymore
_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
is.Error(err)
is.Equal(err, driver.ErrReleaseNotFound)
})
t.Run("rollback-on-failure uninstall fails", func(t *testing.T) {
instAction := installAction(t)
instAction.ReleaseName = "come-fail-away-with-me"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitError = fmt.Errorf("I timed out")
failer.DeleteError = fmt.Errorf("uninstall fail")
instAction.cfg.KubeClient = failer
instAction.RollbackOnFailure = true
vals := map[string]interface{}{}
_, err := instAction.Run(buildChart(), vals)
is.Error(err)
is.Contains(err.Error(), "I timed out")
is.Contains(err.Error(), "uninstall fail")
is.Contains(err.Error(), "an error occurred while uninstalling the release")
})
}
func TestInstallRelease_RollbackOnFailure_Interrupted(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "interrupted-release"
failer := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitDuration = 10 * time.Second
instAction.cfg.KubeClient = failer
instAction.RollbackOnFailure = true
vals := map[string]interface{}{}
ctx, cancel := context.WithCancel(t.Context())
time.AfterFunc(time.Second, cancel)
goroutines := instAction.getGoroutineCount()
resi, err := instAction.RunWithContext(ctx, buildChart(), vals)
is.Error(err)
is.Contains(err.Error(), "context canceled")
is.Contains(err.Error(), "rollback-on-failure")
is.Contains(err.Error(), "uninstalled")
res, err := releaserToV1Release(resi)
is.NoError(err)
// Now make sure it isn't in storage anymore
_, err = instAction.cfg.Releases.Get(res.Name, res.Version)
is.Error(err)
is.Equal(err, driver.ErrReleaseNotFound)
is.Equal(goroutines+1, instAction.getGoroutineCount()) // installation goroutine still is in background
time.Sleep(10 * time.Second) // wait for goroutine to finish
is.Equal(goroutines, instAction.getGoroutineCount())
}
func TestNameTemplate(t *testing.T) {
testCases := []nameTemplateTestCase{
// Just a straight up nop please
{
tpl: "foobar",
expected: "foobar",
expectedErrorStr: "",
},
// Random numbers at the end for fun & profit
{
tpl: "foobar-{{randNumeric 6}}",
expected: "foobar-[0-9]{6}$",
expectedErrorStr: "",
},
// Random numbers in the middle for fun & profit
{
tpl: "foobar-{{randNumeric 4}}-baz",
expected: "foobar-[0-9]{4}-baz$",
expectedErrorStr: "",
},
// No such function
{
tpl: "foobar-{{randInteger}}",
expected: "",
expectedErrorStr: "function \"randInteger\" not defined",
},
// Invalid template
{
tpl: "foobar-{{",
expected: "",
expectedErrorStr: "template: name-template:1: unclosed action",
},
}
for _, tc := range testCases {
n, err := TemplateName(tc.tpl)
if err != nil {
if tc.expectedErrorStr == "" {
t.Errorf("Was not expecting error, but got: %v", err)
continue
}
re, compErr := regexp.Compile(tc.expectedErrorStr)
if compErr != nil {
t.Errorf("Expected error string failed to compile: %v", compErr)
continue
}
if !re.MatchString(err.Error()) {
t.Errorf("Error didn't match for %s expected %s but got %v", tc.tpl, tc.expectedErrorStr, err)
continue
}
}
if err == nil && tc.expectedErrorStr != "" {
t.Errorf("Was expecting error %s but didn't get an error back", tc.expectedErrorStr)
}
if tc.expected != "" {
re, err := regexp.Compile(tc.expected)
if err != nil {
t.Errorf("Expected string failed to compile: %v", err)
continue
}
if !re.MatchString(n) {
t.Errorf("Returned name didn't match for %s expected %s but got %s", tc.tpl, tc.expected, n)
}
}
}
}
func TestInstallReleaseOutputDir(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
vals := map[string]interface{}{}
dir := t.TempDir()
instAction.OutputDir = dir
_, err := instAction.Run(buildChart(withSampleTemplates(), withMultipleManifestTemplate()), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
_, err = os.Stat(filepath.Join(dir, "hello/templates/goodbye"))
is.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/hello"))
is.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/with-partials"))
is.NoError(err)
_, err = os.Stat(filepath.Join(dir, "hello/templates/rbac"))
is.NoError(err)
test.AssertGoldenFile(t, filepath.Join(dir, "hello/templates/rbac"), "rbac.txt")
_, err = os.Stat(filepath.Join(dir, "hello/templates/empty"))
is.True(errors.Is(err, fs.ErrNotExist))
}
func TestInstallOutputDirWithReleaseName(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
vals := map[string]interface{}{}
dir := t.TempDir()
instAction.OutputDir = dir
instAction.UseReleaseName = true
instAction.ReleaseName = "madra"
newDir := filepath.Join(dir, instAction.ReleaseName)
_, err := instAction.Run(buildChart(withSampleTemplates(), withMultipleManifestTemplate()), vals)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
_, err = os.Stat(filepath.Join(newDir, "hello/templates/goodbye"))
is.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/hello"))
is.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/with-partials"))
is.NoError(err)
_, err = os.Stat(filepath.Join(newDir, "hello/templates/rbac"))
is.NoError(err)
test.AssertGoldenFile(t, filepath.Join(newDir, "hello/templates/rbac"), "rbac.txt")
_, err = os.Stat(filepath.Join(newDir, "hello/templates/empty"))
is.True(errors.Is(err, fs.ErrNotExist))
}
func TestNameAndChart(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
chartName := "./foo"
name, chrt, err := instAction.NameAndChart([]string{chartName})
if err != nil {
t.Fatal(err)
}
is.Equal(instAction.ReleaseName, name)
is.Equal(chartName, chrt)
instAction.GenerateName = true
_, _, err = instAction.NameAndChart([]string{"foo", chartName})
if err == nil {
t.Fatal("expected an error")
}
is.Equal("cannot set --generate-name and also specify a name", err.Error())
instAction.GenerateName = false
instAction.NameTemplate = "{{ . }}"
_, _, err = instAction.NameAndChart([]string{"foo", chartName})
if err == nil {
t.Fatal("expected an error")
}
is.Equal("cannot set --name-template and also specify a name", err.Error())
instAction.NameTemplate = ""
instAction.ReleaseName = ""
_, _, err = instAction.NameAndChart([]string{chartName})
if err == nil {
t.Fatal("expected an error")
}
is.Equal("must either provide a name or specify --generate-name", err.Error())
instAction.NameTemplate = ""
instAction.ReleaseName = ""
_, _, err = instAction.NameAndChart([]string{"foo", chartName, "bar"})
if err == nil {
t.Fatal("expected an error")
}
is.Equal("expected at most two arguments, unexpected arguments: bar", err.Error())
}
func TestNameAndChartGenerateName(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = ""
instAction.GenerateName = true
tests := []struct {
Name string
Chart string
ExpectedName string
}{
{
"local filepath",
"./chart",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
{
"dot filepath",
".",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
{
"empty filepath",
"",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
{
"packaged chart",
"chart.tgz",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
{
"packaged chart with .tar.gz extension",
"chart.tar.gz",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
{
"packaged chart with local extension",
"./chart.tgz",
fmt.Sprintf("chart-%d", time.Now().Unix()),
},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
name, chrt, err := instAction.NameAndChart([]string{tc.Chart})
if err != nil {
t.Fatal(err)
}
is.Equal(tc.ExpectedName, name)
is.Equal(tc.Chart, chrt)
})
}
}
func TestInstallWithLabels(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.Labels = map[string]string{
"key1": "val1",
"key2": "val2",
}
resi, err := instAction.Run(buildChart(), nil)
if err != nil {
t.Fatalf("Failed install: %s", err)
}
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(instAction.Labels, res.Labels)
}
func TestInstallWithSystemLabels(t *testing.T) {
is := assert.New(t)
instAction := installAction(t)
instAction.Labels = map[string]string{
"owner": "val1",
"key2": "val2",
}
_, err := instAction.Run(buildChart(), nil)
if err == nil {
t.Fatal("expected an error")
}
is.Equal(fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels()), err)
}
func TestUrlEqual(t *testing.T) {
is := assert.New(t)
tests := []struct {
name string
url1 string
url2 string
expected bool
}{
{
name: "identical URLs",
url1: "https://example.com:443",
url2: "https://example.com:443",
expected: true,
},
{
name: "same host, scheme, default HTTPS port vs explicit",
url1: "https://example.com",
url2: "https://example.com:443",
expected: true,
},
{
name: "same host, scheme, default HTTP port vs explicit",
url1: "http://example.com",
url2: "http://example.com:80",
expected: true,
},
{
name: "different schemes",
url1: "http://example.com",
url2: "https://example.com",
expected: false,
},
{
name: "different hosts",
url1: "https://example.com",
url2: "https://www.example.com",
expected: false,
},
{
name: "different ports",
url1: "https://example.com:8080",
url2: "https://example.com:9090",
expected: false,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
u1, err := url.Parse(tc.url1)
if err != nil {
t.Fatalf("Failed to parse URL1 %s: %v", tc.url1, err)
}
u2, err := url.Parse(tc.url2)
if err != nil {
t.Fatalf("Failed to parse URL2 %s: %v", tc.url2, err)
}
is.Equal(tc.expected, urlEqual(u1, u2))
})
}
}
func TestInstallRun_UnreachableKubeClient(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
instAction := NewInstall(config)
ctx, done := context.WithCancel(t.Context())
chrt := buildChart()
res, err := instAction.RunWithContext(ctx, chrt, nil)
done()
assert.Nil(t, res)
assert.ErrorContains(t, err, "connection refused")
}
func TestInstallSetRegistryClient(t *testing.T) {
config := actionConfigFixture(t)
instAction := NewInstall(config)
registryClient := ®istry.Client{}
instAction.SetRegistryClient(registryClient)
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | true |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/history.go | pkg/action/history.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 action
import (
"fmt"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/release"
)
// History is the action for checking the release's ledger.
//
// It provides the implementation of 'helm history'.
// It returns all the revisions for a specific release.
// To list up to one revision of every release in one specific, or in all,
// namespaces, see the List action.
type History struct {
cfg *Configuration
Max int
Version int
}
// NewHistory creates a new History object with the given configuration.
func NewHistory(cfg *Configuration) *History {
return &History{
cfg: cfg,
}
}
// Run executes 'helm history' against the given release.
func (h *History) Run(name string) ([]release.Releaser, error) {
if err := h.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
if err := chartutil.ValidateReleaseName(name); err != nil {
return nil, fmt.Errorf("release name is invalid: %s", name)
}
h.cfg.Logger().Debug("getting history for release", "release", name)
return h.cfg.Releases.History(name)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/release_testing.go | pkg/action/release_testing.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 action
import (
"context"
"fmt"
"io"
"slices"
"sort"
"time"
v1 "k8s.io/api/core/v1"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/kube"
ri "helm.sh/helm/v4/pkg/release"
release "helm.sh/helm/v4/pkg/release/v1"
)
const (
ExcludeNameFilter = "!name"
IncludeNameFilter = "name"
)
// ReleaseTesting is the action for testing a release.
//
// It provides the implementation of 'helm test'.
type ReleaseTesting struct {
cfg *Configuration
Timeout time.Duration
// Used for fetching logs from test pods
Namespace string
Filters map[string][]string
}
// NewReleaseTesting creates a new ReleaseTesting object with the given configuration.
func NewReleaseTesting(cfg *Configuration) *ReleaseTesting {
return &ReleaseTesting{
cfg: cfg,
Filters: map[string][]string{},
}
}
// Run executes 'helm test' against the given release.
func (r *ReleaseTesting) Run(name string) (ri.Releaser, error) {
if err := r.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
if err := chartutil.ValidateReleaseName(name); err != nil {
return nil, fmt.Errorf("releaseTest: Release name is invalid: %s", name)
}
// finds the non-deleted release with the given name
reli, err := r.cfg.Releases.Last(name)
if err != nil {
return reli, err
}
rel, err := releaserToV1Release(reli)
if err != nil {
return rel, err
}
skippedHooks := []*release.Hook{}
executingHooks := []*release.Hook{}
if len(r.Filters[ExcludeNameFilter]) != 0 {
for _, h := range rel.Hooks {
if slices.Contains(r.Filters[ExcludeNameFilter], h.Name) {
skippedHooks = append(skippedHooks, h)
} else {
executingHooks = append(executingHooks, h)
}
}
rel.Hooks = executingHooks
}
if len(r.Filters[IncludeNameFilter]) != 0 {
executingHooks = nil
for _, h := range rel.Hooks {
if slices.Contains(r.Filters[IncludeNameFilter], h.Name) {
executingHooks = append(executingHooks, h)
} else {
skippedHooks = append(skippedHooks, h)
}
}
rel.Hooks = executingHooks
}
serverSideApply := rel.ApplyMethod == string(release.ApplyMethodServerSideApply)
if err := r.cfg.execHook(rel, release.HookTest, kube.StatusWatcherStrategy, r.Timeout, serverSideApply); err != nil {
rel.Hooks = append(skippedHooks, rel.Hooks...)
r.cfg.Releases.Update(rel)
return rel, err
}
rel.Hooks = append(skippedHooks, rel.Hooks...)
return rel, r.cfg.Releases.Update(rel)
}
// GetPodLogs will write the logs for all test pods in the given release into
// the given writer. These can be immediately output to the user or captured for
// other uses
func (r *ReleaseTesting) GetPodLogs(out io.Writer, rel *release.Release) error {
client, err := r.cfg.KubernetesClientSet()
if err != nil {
return fmt.Errorf("unable to get kubernetes client to fetch pod logs: %w", err)
}
hooksByWight := append([]*release.Hook{}, rel.Hooks...)
sort.Stable(hookByWeight(hooksByWight))
for _, h := range hooksByWight {
for _, e := range h.Events {
if e == release.HookTest {
if slices.Contains(r.Filters[ExcludeNameFilter], h.Name) {
continue
}
if len(r.Filters[IncludeNameFilter]) > 0 && !slices.Contains(r.Filters[IncludeNameFilter], h.Name) {
continue
}
req := client.CoreV1().Pods(r.Namespace).GetLogs(h.Name, &v1.PodLogOptions{})
logReader, err := req.Stream(context.Background())
if err != nil {
return fmt.Errorf("unable to get pod logs for %s: %w", h.Name, err)
}
fmt.Fprintf(out, "POD LOGS: %s\n", h.Name)
_, err = io.Copy(out, logReader)
fmt.Fprintln(out)
if err != nil {
return fmt.Errorf("unable to write pod logs for %s: %w", h.Name, 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/action/package_test.go | pkg/action/package_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 action
import (
"os"
"path"
"testing"
"github.com/Masterminds/semver/v3"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/test/ensure"
)
func TestPassphraseFileFetcher(t *testing.T) {
secret := "secret"
directory := ensure.TempFile(t, "passphrase-file", []byte(secret))
testPkg := NewPackage()
fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil)
if err != nil {
t.Fatal("Unable to create passphraseFileFetcher", err)
}
passphrase, err := fetcher("key")
if err != nil {
t.Fatal("Unable to fetch passphrase")
}
if string(passphrase) != secret {
t.Errorf("Expected %s got %s", secret, string(passphrase))
}
}
func TestPassphraseFileFetcher_WithLineBreak(t *testing.T) {
secret := "secret"
directory := ensure.TempFile(t, "passphrase-file", []byte(secret+"\n\n."))
testPkg := NewPackage()
fetcher, err := testPkg.passphraseFileFetcher(path.Join(directory, "passphrase-file"), nil)
if err != nil {
t.Fatal("Unable to create passphraseFileFetcher", err)
}
passphrase, err := fetcher("key")
if err != nil {
t.Fatal("Unable to fetch passphrase")
}
if string(passphrase) != secret {
t.Errorf("Expected %s got %s", secret, string(passphrase))
}
}
func TestPassphraseFileFetcher_WithInvalidStdin(t *testing.T) {
directory := t.TempDir()
testPkg := NewPackage()
stdin, err := os.CreateTemp(directory, "non-existing")
if err != nil {
t.Fatal("Unable to create test file", err)
}
if _, err := testPkg.passphraseFileFetcher("-", stdin); err == nil {
t.Error("Expected passphraseFileFetcher returning an error")
}
}
func TestPassphraseFileFetcher_WithStdinAndMultipleFetches(t *testing.T) {
testPkg := NewPackage()
stdin, w, err := os.Pipe()
if err != nil {
t.Fatal("Unable to create pipe", err)
}
passphrase := "secret-from-stdin"
go func() {
_, err = w.Write([]byte(passphrase + "\n"))
require.NoError(t, err)
}()
for range 4 {
fetcher, err := testPkg.passphraseFileFetcher("-", stdin)
if err != nil {
t.Errorf("Expected passphraseFileFetcher to not return an error, but got %v", err)
}
pass, err := fetcher("key")
if err != nil {
t.Errorf("Expected passphraseFileFetcher invocation to succeed, failed with %v", err)
}
if string(pass) != string(passphrase) {
t.Errorf("Expected multiple passphrase fetch to return %q, got %q", passphrase, pass)
}
}
}
func TestValidateVersion(t *testing.T) {
type args struct {
ver string
}
tests := []struct {
name string
args args
wantErr error
}{
{
"normal semver version",
args{
ver: "1.1.3-23658",
},
nil,
},
{
"Pre version number starting with 0",
args{
ver: "1.1.3-023658",
},
semver.ErrSegmentStartsZero,
},
{
"Invalid version number",
args{
ver: "1.1.3.sd.023658",
},
semver.ErrInvalidSemVer,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := validateVersion(tt.args.ver); err != nil {
if err != tt.wantErr {
t.Errorf("Expected {%v}, got {%v}", tt.wantErr, err)
}
}
})
}
}
func TestRun_ErrorPath(t *testing.T) {
client := NewPackage()
_, err := client.Run("err-path", nil)
require.Error(t, err)
}
func TestRun(t *testing.T) {
chartPath := "testdata/charts/chart-with-schema"
client := NewPackage()
filename, err := client.Run(chartPath, nil)
require.NoError(t, err)
require.Equal(t, "empty-0.1.0.tgz", filename)
require.NoError(t, os.Remove(filename))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/show_test.go | pkg/action/show_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 action
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/registry"
)
func TestShow(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowAll, config)
modTime := time.Now()
client.chart = &chart.Chart{
Metadata: &chart.Metadata{Name: "alpine"},
Files: []*common.File{
{Name: "README.md", ModTime: modTime, Data: []byte("README\n")},
{Name: "crds/ignoreme.txt", ModTime: modTime, Data: []byte("error")},
{Name: "crds/foo.yaml", ModTime: modTime, Data: []byte("---\nfoo\n")},
{Name: "crds/bar.json", ModTime: modTime, Data: []byte("---\nbar\n")},
{Name: "crds/baz.yaml", ModTime: modTime, Data: []byte("baz\n")},
},
Raw: []*common.File{
{Name: "values.yaml", ModTime: modTime, Data: []byte("VALUES\n")},
},
Values: map[string]interface{}{},
}
output, err := client.Run("")
if err != nil {
t.Fatal(err)
}
expect := `name: alpine
---
VALUES
---
README
---
foo
---
bar
---
baz
`
if output != expect {
t.Errorf("Expected\n%q\nGot\n%q\n", expect, output)
}
}
func TestShowNoValues(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowAll, config)
client.chart = new(chart.Chart)
// Regression tests for missing values. See issue #1024.
client.OutputFormat = ShowValues
output, err := client.Run("")
if err != nil {
t.Fatal(err)
}
if len(output) != 0 {
t.Errorf("expected empty values buffer, got %s", output)
}
}
func TestShowValuesByJsonPathFormat(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowValues, config)
client.JSONPathTemplate = "{$.nestedKey.simpleKey}"
client.chart = buildChart(withSampleValues())
output, err := client.Run("")
if err != nil {
t.Fatal(err)
}
expect := "simpleValue"
if output != expect {
t.Errorf("Expected\n%q\nGot\n%q\n", expect, output)
}
}
func TestShowCRDs(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowCRDs, config)
modTime := time.Now()
client.chart = &chart.Chart{
Metadata: &chart.Metadata{Name: "alpine"},
Files: []*common.File{
{Name: "crds/ignoreme.txt", ModTime: modTime, Data: []byte("error")},
{Name: "crds/foo.yaml", ModTime: modTime, Data: []byte("---\nfoo\n")},
{Name: "crds/bar.json", ModTime: modTime, Data: []byte("---\nbar\n")},
{Name: "crds/baz.yaml", ModTime: modTime, Data: []byte("baz\n")},
},
}
output, err := client.Run("")
if err != nil {
t.Fatal(err)
}
expect := `---
foo
---
bar
---
baz
`
if output != expect {
t.Errorf("Expected\n%q\nGot\n%q\n", expect, output)
}
}
func TestShowNoReadme(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowAll, config)
modTime := time.Now()
client.chart = &chart.Chart{
Metadata: &chart.Metadata{Name: "alpine"},
Files: []*common.File{
{Name: "crds/ignoreme.txt", ModTime: modTime, Data: []byte("error")},
{Name: "crds/foo.yaml", ModTime: modTime, Data: []byte("---\nfoo\n")},
{Name: "crds/bar.json", ModTime: modTime, Data: []byte("---\nbar\n")},
},
}
output, err := client.Run("")
if err != nil {
t.Fatal(err)
}
expect := `name: alpine
---
foo
---
bar
`
if output != expect {
t.Errorf("Expected\n%q\nGot\n%q\n", expect, output)
}
}
func TestShowSetRegistryClient(t *testing.T) {
config := actionConfigFixture(t)
client := NewShow(ShowAll, config)
registryClient := ®istry.Client{}
client.SetRegistryClient(registryClient)
assert.Equal(t, registryClient, client.registryClient)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/list_test.go | pkg/action/list_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 action
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/assert"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
ri "helm.sh/helm/v4/pkg/release"
"helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/storage"
)
func TestListStates(t *testing.T) {
for input, expect := range map[string]ListStates{
"deployed": ListDeployed,
"uninstalled": ListUninstalled,
"uninstalling": ListUninstalling,
"superseded": ListSuperseded,
"failed": ListFailed,
"pending-install": ListPendingInstall,
"pending-rollback": ListPendingRollback,
"pending-upgrade": ListPendingUpgrade,
"unknown": ListUnknown,
"totally made up key": ListUnknown,
} {
if expect != expect.FromName(input) {
t.Errorf("Expected %d for %s", expect, input)
}
// This is a cheap way to verify that ListAll actually allows everything but Unknown
if got := expect.FromName(input); got != ListUnknown && got&ListAll == 0 {
t.Errorf("Expected %s to match the ListAll filter", input)
}
}
filter := ListDeployed | ListPendingRollback
if status := filter.FromName("deployed"); filter&status == 0 {
t.Errorf("Expected %d to match mask %d", status, filter)
}
if status := filter.FromName("failed"); filter&status != 0 {
t.Errorf("Expected %d to fail to match mask %d", status, filter)
}
}
func TestList_Empty(t *testing.T) {
lister := NewList(actionConfigFixture(t))
list, err := lister.Run()
assert.NoError(t, err)
assert.Len(t, list, 0)
}
func newListFixture(t *testing.T) *List {
t.Helper()
return NewList(actionConfigFixture(t))
}
func TestList_OneNamespace(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
makeMeSomeReleases(t, lister.cfg.Releases)
list, err := lister.Run()
is.NoError(err)
is.Len(list, 3)
}
func TestList_AllNamespaces(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
makeMeSomeReleases(t, lister.cfg.Releases)
lister.AllNamespaces = true
lister.SetStateMask()
list, err := lister.Run()
is.NoError(err)
is.Len(list, 3)
}
func TestList_Sort(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Sort = ByNameDesc // Other sorts are tested elsewhere
makeMeSomeReleases(t, lister.cfg.Releases)
l, err := lister.Run()
is.NoError(err)
list, err := releaseListToV1List(l)
is.NoError(err)
is.Len(list, 3)
is.Equal("two", list[0].Name)
is.Equal("three", list[1].Name)
is.Equal("one", list[2].Name)
}
func TestList_Limit(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Limit = 2
makeMeSomeReleases(t, lister.cfg.Releases)
l, err := lister.Run()
is.NoError(err)
list, err := releaseListToV1List(l)
is.NoError(err)
is.Len(list, 2)
// Lex order means one, three, two
is.Equal("one", list[0].Name)
is.Equal("three", list[1].Name)
}
func TestList_BigLimit(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Limit = 20
makeMeSomeReleases(t, lister.cfg.Releases)
l, err := lister.Run()
is.NoError(err)
list, err := releaseListToV1List(l)
is.NoError(err)
is.Len(list, 3)
// Lex order means one, three, two
is.Equal("one", list[0].Name)
is.Equal("three", list[1].Name)
is.Equal("two", list[2].Name)
}
func TestList_LimitOffset(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Limit = 2
lister.Offset = 1
makeMeSomeReleases(t, lister.cfg.Releases)
l, err := lister.Run()
is.NoError(err)
list, err := releaseListToV1List(l)
is.NoError(err)
is.Len(list, 2)
// Lex order means one, three, two
is.Equal("three", list[0].Name)
is.Equal("two", list[1].Name)
}
func TestList_LimitOffsetOutOfBounds(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Limit = 2
lister.Offset = 3 // Last item is index 2
makeMeSomeReleases(t, lister.cfg.Releases)
list, err := lister.Run()
is.NoError(err)
is.Len(list, 0)
lister.Limit = 10
lister.Offset = 1
list, err = lister.Run()
is.NoError(err)
is.Len(list, 2)
}
func TestList_StateMask(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
makeMeSomeReleases(t, lister.cfg.Releases)
oner, err := lister.cfg.Releases.Get("one", 1)
is.NoError(err)
var one release.Release
switch v := oner.(type) {
case release.Release:
one = v
case *release.Release:
one = *v
default:
t.Fatal("unsupported release type")
}
one.SetStatus(common.StatusUninstalled, "uninstalled")
err = lister.cfg.Releases.Update(one)
is.NoError(err)
res, err := lister.Run()
is.NoError(err)
is.Len(res, 3)
ac0, err := ri.NewAccessor(res[0])
is.NoError(err)
ac1, err := ri.NewAccessor(res[1])
is.NoError(err)
ac2, err := ri.NewAccessor(res[2])
is.NoError(err)
is.Equal("one", ac0.Name())
is.Equal("three", ac1.Name())
is.Equal("two", ac2.Name())
lister.StateMask = ListUninstalled
res, err = lister.Run()
is.NoError(err)
is.Len(res, 1)
ac0, err = ri.NewAccessor(res[0])
is.NoError(err)
is.Equal("one", ac0.Name())
lister.StateMask |= ListDeployed
res, err = lister.Run()
is.NoError(err)
is.Len(res, 3)
}
func TestList_StateMaskWithStaleRevisions(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.StateMask = ListFailed
makeMeSomeReleasesWithStaleFailure(t, lister.cfg.Releases)
res, err := lister.Run()
is.NoError(err)
is.Len(res, 1)
// "dirty" release should _not_ be present as most recent
// release is deployed despite failed release in past
ac0, err := ri.NewAccessor(res[0])
is.NoError(err)
is.Equal("failed", ac0.Name())
}
func makeMeSomeReleasesWithStaleFailure(t *testing.T, store *storage.Storage) {
t.Helper()
one := namedReleaseStub("clean", common.StatusDeployed)
one.Namespace = "default"
one.Version = 1
two := namedReleaseStub("dirty", common.StatusDeployed)
two.Namespace = "default"
two.Version = 1
three := namedReleaseStub("dirty", common.StatusFailed)
three.Namespace = "default"
three.Version = 2
four := namedReleaseStub("dirty", common.StatusDeployed)
four.Namespace = "default"
four.Version = 3
five := namedReleaseStub("failed", common.StatusFailed)
five.Namespace = "default"
five.Version = 1
for _, rel := range []*release.Release{one, two, three, four, five} {
if err := store.Create(rel); err != nil {
t.Fatal(err)
}
}
all, err := store.ListReleases()
assert.NoError(t, err)
assert.Len(t, all, 5, "sanity test: five items added")
}
func TestList_Filter(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Filter = "th."
makeMeSomeReleases(t, lister.cfg.Releases)
res, err := lister.Run()
is.NoError(err)
is.Len(res, 1)
ac0, err := ri.NewAccessor(res[0])
is.NoError(err)
is.Equal("three", ac0.Name())
}
func TestList_FilterFailsCompile(t *testing.T) {
is := assert.New(t)
lister := newListFixture(t)
lister.Filter = "t[h.{{{"
makeMeSomeReleases(t, lister.cfg.Releases)
_, err := lister.Run()
is.Error(err)
}
func makeMeSomeReleases(t *testing.T, store *storage.Storage) {
t.Helper()
one := releaseStub()
one.Name = "one"
one.Namespace = "default"
one.Version = 1
two := releaseStub()
two.Name = "two"
two.Namespace = "default"
two.Version = 2
three := releaseStub()
three.Name = "three"
three.Namespace = "default"
three.Version = 3
for _, rel := range []*release.Release{one, two, three} {
if err := store.Create(rel); err != nil {
t.Fatal(err)
}
}
all, err := store.ListReleases()
assert.NoError(t, err)
assert.Len(t, all, 3, "sanity test: three items added")
}
func TestFilterLatestReleases(t *testing.T) {
t.Run("should filter old versions of the same release", func(t *testing.T) {
r1 := releaseStub()
r1.Name = "r"
r1.Version = 1
r2 := releaseStub()
r2.Name = "r"
r2.Version = 2
another := releaseStub()
another.Name = "another"
another.Version = 1
filteredList := filterLatestReleases([]*release.Release{r1, r2, another})
expectedFilteredList := []*release.Release{r2, another}
assert.ElementsMatch(t, expectedFilteredList, filteredList)
})
t.Run("should not filter out any version across namespaces", func(t *testing.T) {
r1 := releaseStub()
r1.Name = "r"
r1.Namespace = "default"
r1.Version = 1
r2 := releaseStub()
r2.Name = "r"
r2.Namespace = "testing"
r2.Version = 2
filteredList := filterLatestReleases([]*release.Release{r1, r2})
expectedFilteredList := []*release.Release{r1, r2}
assert.ElementsMatch(t, expectedFilteredList, filteredList)
})
}
func TestSelectorList(t *testing.T) {
r1 := releaseStub()
r1.Name = "r1"
r1.Version = 1
r1.Labels = map[string]string{"key": "value1"}
r2 := releaseStub()
r2.Name = "r2"
r2.Version = 1
r2.Labels = map[string]string{"key": "value2"}
r3 := releaseStub()
r3.Name = "r3"
r3.Version = 1
r3.Labels = map[string]string{}
lister := newListFixture(t)
for _, rel := range []*release.Release{r1, r2, r3} {
if err := lister.cfg.Releases.Create(rel); err != nil {
t.Fatal(err)
}
}
t.Run("should fail selector parsing", func(t *testing.T) {
is := assert.New(t)
lister.Selector = "a?=b"
_, err := lister.Run()
is.Error(err)
})
t.Run("should select one release with matching label", func(t *testing.T) {
lister.Selector = "key==value1"
res, _ := lister.Run()
expectedFilteredList := []*release.Release{r1}
assert.ElementsMatch(t, expectedFilteredList, res)
})
t.Run("should select two releases with non matching label", func(t *testing.T) {
lister.Selector = "key!=value1"
res, _ := lister.Run()
expectedFilteredList := []*release.Release{r2, r3}
assert.ElementsMatch(t, expectedFilteredList, res)
})
}
func TestListRun_UnreachableKubeClient(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
lister := NewList(config)
result, err := lister.Run()
assert.Nil(t, result)
assert.ErrorContains(t, err, "connection refused")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/list.go | pkg/action/list.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 action
import (
"path"
"regexp"
"k8s.io/apimachinery/pkg/labels"
ri "helm.sh/helm/v4/pkg/release"
release "helm.sh/helm/v4/pkg/release/v1"
releaseutil "helm.sh/helm/v4/pkg/release/v1/util"
)
// ListStates represents zero or more status codes that a list item may have set
//
// Because this is used as a bitmask filter, more than one bit can be flipped
// in the ListStates.
type ListStates uint
const (
// ListDeployed filters on status "deployed"
ListDeployed ListStates = 1 << iota
// ListUninstalled filters on status "uninstalled"
ListUninstalled
// ListUninstalling filters on status "uninstalling" (uninstall in progress)
ListUninstalling
// ListPendingInstall filters on status "pending" (deployment in progress)
ListPendingInstall
// ListPendingUpgrade filters on status "pending_upgrade" (upgrade in progress)
ListPendingUpgrade
// ListPendingRollback filters on status "pending_rollback" (rollback in progress)
ListPendingRollback
// ListSuperseded filters on status "superseded" (historical release version that is no longer deployed)
ListSuperseded
// ListFailed filters on status "failed" (release version not deployed because of error)
ListFailed
// ListUnknown filters on an unknown status
ListUnknown
)
// FromName takes a state name and returns a ListStates representation.
//
// Currently, there are only names for individual flipped bits, so the returned
// ListStates will only match one of the constants. However, it is possible that
// this behavior could change in the future.
func (s ListStates) FromName(str string) ListStates {
switch str {
case "deployed":
return ListDeployed
case "uninstalled":
return ListUninstalled
case "superseded":
return ListSuperseded
case "failed":
return ListFailed
case "uninstalling":
return ListUninstalling
case "pending-install":
return ListPendingInstall
case "pending-upgrade":
return ListPendingUpgrade
case "pending-rollback":
return ListPendingRollback
}
return ListUnknown
}
// ListAll is a convenience for enabling all list filters
const ListAll = ListDeployed | ListUninstalled | ListUninstalling | ListPendingInstall | ListPendingRollback | ListPendingUpgrade | ListSuperseded | ListFailed
// Sorter is a top-level sort
type Sorter uint
const (
// ByNameDesc sorts by descending lexicographic order
ByNameDesc Sorter = iota + 1
// ByDateAsc sorts by ascending dates (oldest updated release first)
ByDateAsc
// ByDateDesc sorts by descending dates (latest updated release first)
ByDateDesc
)
// List is the action for listing releases.
//
// It provides, for example, the implementation of 'helm list'.
// It returns no more than one revision of every release in one specific, or in
// all, namespaces.
// To list all the revisions of a specific release, see the History action.
type List struct {
cfg *Configuration
// All ignores the limit/offset
All bool
// AllNamespaces searches across namespaces
AllNamespaces bool
// Sort indicates the sort to use
//
// see pkg/releaseutil for several useful sorters
Sort Sorter
// Overrides the default lexicographic sorting
ByDate bool
SortReverse bool
// StateMask accepts a bitmask of states for items to show.
// The default is ListDeployed
StateMask ListStates
// Limit is the number of items to return per Run()
Limit int
// Offset is the starting index for the Run() call
Offset int
// Filter is a filter that is applied to the results
Filter string
Short bool
NoHeaders bool
TimeFormat string
Uninstalled bool
Superseded bool
Uninstalling bool
Deployed bool
Failed bool
Pending bool
Selector string
}
// NewList constructs a new *List
func NewList(cfg *Configuration) *List {
return &List{
StateMask: ListAll,
cfg: cfg,
}
}
// Run executes the list command, returning a set of matches.
func (l *List) Run() ([]ri.Releaser, error) {
if err := l.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
var filter *regexp.Regexp
if l.Filter != "" {
var err error
filter, err = regexp.Compile(l.Filter)
if err != nil {
return nil, err
}
}
results, err := l.cfg.Releases.List(func(rel ri.Releaser) bool {
r, err := releaserToV1Release(rel)
if err != nil {
return false
}
// Skip anything that doesn't match the filter.
if filter != nil && !filter.MatchString(r.Name) {
return false
}
return true
})
if err != nil {
return nil, err
}
if results == nil {
return results, nil
}
rresults, err := releaseListToV1List(results)
if err != nil {
return nil, err
}
// by definition, superseded releases are never shown if
// only the latest releases are returned. so if requested statemask
// is _only_ ListSuperseded, skip the latest release filter
if l.StateMask != ListSuperseded {
rresults = filterLatestReleases(rresults)
}
// State mask application must occur after filtering to
// latest releases, otherwise outdated entries can be returned
rresults = l.filterStateMask(rresults)
// Skip anything that doesn't match the selector
selectorObj, err := labels.Parse(l.Selector)
if err != nil {
return nil, err
}
rresults = l.filterSelector(rresults, selectorObj)
// Unfortunately, we have to sort before truncating, which can incur substantial overhead
l.sort(rresults)
// Guard on offset
if l.Offset >= len(rresults) {
return releaseV1ListToReleaserList([]*release.Release{})
}
// Calculate the limit and offset, and then truncate results if necessary.
limit := len(results)
if l.Limit > 0 && l.Limit < limit {
limit = l.Limit
}
last := l.Offset + limit
if l := len(rresults); l < last {
last = l
}
rresults = rresults[l.Offset:last]
return releaseV1ListToReleaserList(rresults)
}
// sort is an in-place sort where order is based on the value of a.Sort
func (l *List) sort(rels []*release.Release) {
if l.SortReverse {
l.Sort = ByNameDesc
}
if l.ByDate {
l.Sort = ByDateDesc
if l.SortReverse {
l.Sort = ByDateAsc
}
}
switch l.Sort {
case ByDateDesc:
releaseutil.SortByDate(rels)
case ByDateAsc:
releaseutil.Reverse(rels, releaseutil.SortByDate)
case ByNameDesc:
releaseutil.Reverse(rels, releaseutil.SortByName)
default:
releaseutil.SortByName(rels)
}
}
// filterLatestReleases returns a list scrubbed of old releases.
func filterLatestReleases(releases []*release.Release) []*release.Release {
latestReleases := make(map[string]*release.Release)
for _, rls := range releases {
name, namespace := rls.Name, rls.Namespace
key := path.Join(namespace, name)
if latestRelease, exists := latestReleases[key]; exists && latestRelease.Version > rls.Version {
continue
}
latestReleases[key] = rls
}
var list = make([]*release.Release, 0, len(latestReleases))
for _, rls := range latestReleases {
list = append(list, rls)
}
return list
}
func (l *List) filterStateMask(releases []*release.Release) []*release.Release {
desiredStateReleases := make([]*release.Release, 0)
for _, rls := range releases {
currentStatus := l.StateMask.FromName(rls.Info.Status.String())
mask := l.StateMask & currentStatus
if mask == 0 {
continue
}
desiredStateReleases = append(desiredStateReleases, rls)
}
return desiredStateReleases
}
func (l *List) filterSelector(releases []*release.Release, selector labels.Selector) []*release.Release {
desiredStateReleases := make([]*release.Release, 0)
for _, rls := range releases {
if selector.Matches(labels.Set(rls.Labels)) {
desiredStateReleases = append(desiredStateReleases, rls)
}
}
return desiredStateReleases
}
// SetStateMask calculates the state mask based on parameters.
func (l *List) SetStateMask() {
if l.All {
l.StateMask = ListAll
return
}
state := ListStates(0)
if l.Deployed {
state |= ListDeployed
}
if l.Uninstalled {
state |= ListUninstalled
}
if l.Uninstalling {
state |= ListUninstalling
}
if l.Pending {
state |= ListPendingInstall | ListPendingRollback | ListPendingUpgrade
}
if l.Failed {
state |= ListFailed
}
if l.Superseded {
state |= ListSuperseded
}
// Apply a default
if state == 0 {
state = ListAll
}
l.StateMask = state
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/registry_login_test.go | pkg/action/registry_login_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 action
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRegistryLogin(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
}
func TestWithCertFile(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
certFile := "testdata/cert.pem"
opt := WithCertFile(certFile)
assert.Nil(t, opt(client))
assert.Equal(t, certFile, client.certFile)
}
func TestWithInsecure(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
opt := WithInsecure(true)
assert.Nil(t, opt(client))
assert.Equal(t, true, client.insecure)
}
func TestWithKeyFile(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
keyFile := "testdata/key.pem"
opt := WithKeyFile(keyFile)
assert.Nil(t, opt(client))
assert.Equal(t, keyFile, client.keyFile)
}
func TestWithCAFile(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
caFile := "testdata/ca.pem"
opt := WithCAFile(caFile)
assert.Nil(t, opt(client))
assert.Equal(t, caFile, client.caFile)
}
func TestWithPlainHTTPLogin(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogin(config)
opt := WithPlainHTTPLogin(true)
assert.Nil(t, opt(client))
assert.Equal(t, true, client.plainHTTP)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get_values_test.go | pkg/action/get_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 action
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
chart "helm.sh/helm/v4/pkg/chart/v2"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
)
func TestNewGetValues(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
assert.NotNil(t, client)
assert.Equal(t, cfg, client.cfg)
assert.Equal(t, 0, client.Version)
assert.Equal(t, false, client.AllValues)
}
func TestGetValues_Run_UserConfigOnly(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
releaseName := "test-release"
userConfig := map[string]interface{}{
"database": map[string]interface{}{
"host": "localhost",
"port": 5432,
},
"app": map[string]interface{}{
"name": "my-app",
"replicas": 3,
},
}
rel := &release.Release{
Name: releaseName,
Info: &release.Info{
Status: common.StatusDeployed,
},
Chart: &chart.Chart{
Metadata: &chart.Metadata{
Name: "test-chart",
Version: "1.0.0",
},
Values: map[string]interface{}{
"defaultKey": "defaultValue",
"app": map[string]interface{}{
"name": "default-app",
"timeout": 30,
},
},
},
Config: userConfig,
Version: 1,
Namespace: "default",
}
require.NoError(t, cfg.Releases.Create(rel))
result, err := client.Run(releaseName)
require.NoError(t, err)
assert.Equal(t, userConfig, result)
}
func TestGetValues_Run_AllValues(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
client.AllValues = true
releaseName := "test-release"
userConfig := map[string]interface{}{
"database": map[string]interface{}{
"host": "localhost",
"port": 5432,
},
"app": map[string]interface{}{
"name": "my-app",
},
}
chartDefaultValues := map[string]interface{}{
"defaultKey": "defaultValue",
"app": map[string]interface{}{
"name": "default-app",
"timeout": 30,
},
}
rel := &release.Release{
Name: releaseName,
Info: &release.Info{
Status: common.StatusDeployed,
},
Chart: &chart.Chart{
Metadata: &chart.Metadata{
Name: "test-chart",
Version: "1.0.0",
},
Values: chartDefaultValues,
},
Config: userConfig,
Version: 1,
Namespace: "default",
}
require.NoError(t, cfg.Releases.Create(rel))
result, err := client.Run(releaseName)
require.NoError(t, err)
assert.Equal(t, "my-app", result["app"].(map[string]interface{})["name"])
assert.Equal(t, 30, result["app"].(map[string]interface{})["timeout"])
assert.Equal(t, "defaultValue", result["defaultKey"])
assert.Equal(t, "localhost", result["database"].(map[string]interface{})["host"])
assert.Equal(t, 5432, result["database"].(map[string]interface{})["port"])
}
func TestGetValues_Run_EmptyValues(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
releaseName := "test-release"
rel := &release.Release{
Name: releaseName,
Info: &release.Info{
Status: common.StatusDeployed,
},
Chart: &chart.Chart{
Metadata: &chart.Metadata{
Name: "test-chart",
Version: "1.0.0",
},
},
Config: map[string]interface{}{},
Version: 1,
Namespace: "default",
}
require.NoError(t, cfg.Releases.Create(rel))
result, err := client.Run(releaseName)
require.NoError(t, err)
assert.Equal(t, map[string]interface{}{}, result)
}
func TestGetValues_Run_UnreachableKubeClient(t *testing.T) {
cfg := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
cfg.KubeClient = &failingKubeClient
client := NewGetValues(cfg)
_, err := client.Run("test-release")
assert.Error(t, err)
assert.Contains(t, err.Error(), "connection refused")
}
func TestGetValues_Run_ReleaseNotFound(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
_, err := client.Run("non-existent-release")
assert.Error(t, err)
assert.Contains(t, err.Error(), "not found")
}
func TestGetValues_Run_NilConfig(t *testing.T) {
cfg := actionConfigFixture(t)
client := NewGetValues(cfg)
releaseName := "test-release"
rel := &release.Release{
Name: releaseName,
Info: &release.Info{
Status: common.StatusDeployed,
},
Chart: &chart.Chart{
Metadata: &chart.Metadata{
Name: "test-chart",
Version: "1.0.0",
},
},
Config: nil,
Version: 1,
Namespace: "default",
}
require.NoError(t, cfg.Releases.Create(rel))
result, err := client.Run(releaseName)
require.NoError(t, err)
assert.Nil(t, result)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/lint.go | pkg/action/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 action
import (
"fmt"
"os"
"path/filepath"
"strings"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/v2/lint"
"helm.sh/helm/v4/pkg/chart/v2/lint/support"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
// Lint is the action for checking that the semantics of a chart are well-formed.
//
// It provides the implementation of 'helm lint'.
type Lint struct {
Strict bool
Namespace string
WithSubcharts bool
Quiet bool
SkipSchemaValidation bool
KubeVersion *common.KubeVersion
}
// LintResult is the result of Lint
type LintResult struct {
TotalChartsLinted int
Messages []support.Message
Errors []error
}
// NewLint creates a new Lint object with the given configuration.
func NewLint() *Lint {
return &Lint{}
}
// Run executes 'helm Lint' against the given chart.
func (l *Lint) Run(paths []string, vals map[string]interface{}) *LintResult {
lowestTolerance := support.ErrorSev
if l.Strict {
lowestTolerance = support.WarningSev
}
result := &LintResult{}
for _, path := range paths {
linter, err := lintChart(path, vals, l.Namespace, l.KubeVersion, l.SkipSchemaValidation)
if err != nil {
result.Errors = append(result.Errors, err)
continue
}
result.Messages = append(result.Messages, linter.Messages...)
result.TotalChartsLinted++
for _, msg := range linter.Messages {
if msg.Severity >= lowestTolerance {
result.Errors = append(result.Errors, msg.Err)
}
}
}
return result
}
// HasWarningsOrErrors checks is LintResult has any warnings or errors
func HasWarningsOrErrors(result *LintResult) bool {
for _, msg := range result.Messages {
if msg.Severity > support.InfoSev {
return true
}
}
return len(result.Errors) > 0
}
func lintChart(path string, vals map[string]interface{}, namespace string, kubeVersion *common.KubeVersion, skipSchemaValidation bool) (support.Linter, error) {
var chartPath string
linter := support.Linter{}
if strings.HasSuffix(path, ".tgz") || strings.HasSuffix(path, ".tar.gz") {
tempDir, err := os.MkdirTemp("", "helm-lint")
if err != nil {
return linter, fmt.Errorf("unable to create temp dir to extract tarball: %w", err)
}
defer os.RemoveAll(tempDir)
file, err := os.Open(path)
if err != nil {
return linter, fmt.Errorf("unable to open tarball: %w", err)
}
defer file.Close()
if err = chartutil.Expand(tempDir, file); err != nil {
return linter, fmt.Errorf("unable to extract tarball: %w", err)
}
files, err := os.ReadDir(tempDir)
if err != nil {
return linter, fmt.Errorf("unable to read temporary output directory %s: %w", tempDir, err)
}
if !files[0].IsDir() {
return linter, fmt.Errorf("unexpected file %s in temporary output directory %s", files[0].Name(), tempDir)
}
chartPath = filepath.Join(tempDir, files[0].Name())
} else {
chartPath = path
}
// Guard: Error out if this is not a chart.
if _, err := os.Stat(filepath.Join(chartPath, "Chart.yaml")); err != nil {
return linter, fmt.Errorf("unable to check Chart.yaml file in chart: %w", err)
}
return lint.RunAll(
chartPath,
vals,
namespace,
lint.WithKubeVersion(kubeVersion),
lint.WithSkipSchemaValidation(skipSchemaValidation),
), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/hooks_test.go | pkg/action/hooks_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 action
import (
"bytes"
"fmt"
"io"
"reflect"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/cli-runtime/pkg/resource"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/kube"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
rcommon "helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
"helm.sh/helm/v4/pkg/storage"
"helm.sh/helm/v4/pkg/storage/driver"
)
func podManifestWithOutputLogs(hookDefinitions []release.HookOutputLogPolicy) string {
hookDefinitionString := convertHooksToCommaSeparated(hookDefinitions)
return fmt.Sprintf(`kind: Pod
metadata:
name: finding-sharky,
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-output-log-policy": %s
spec:
containers:
- name: sharky-test
image: fake-image
cmd: fake-command`, hookDefinitionString)
}
func podManifestWithOutputLogWithNamespace(hookDefinitions []release.HookOutputLogPolicy) string {
hookDefinitionString := convertHooksToCommaSeparated(hookDefinitions)
return fmt.Sprintf(`kind: Pod
metadata:
name: finding-george
namespace: sneaky-namespace
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-output-log-policy": %s
spec:
containers:
- name: george-test
image: fake-image
cmd: fake-command`, hookDefinitionString)
}
func jobManifestWithOutputLog(hookDefinitions []release.HookOutputLogPolicy) string {
hookDefinitionString := convertHooksToCommaSeparated(hookDefinitions)
return fmt.Sprintf(`kind: Job
apiVersion: batch/v1
metadata:
name: losing-religion
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-output-log-policy": %s
spec:
completions: 1
parallelism: 1
activeDeadlineSeconds: 30
template:
spec:
containers:
- name: religion-container
image: religion-image
cmd: religion-command`, hookDefinitionString)
}
func jobManifestWithOutputLogWithNamespace(hookDefinitions []release.HookOutputLogPolicy) string {
hookDefinitionString := convertHooksToCommaSeparated(hookDefinitions)
return fmt.Sprintf(`kind: Job
apiVersion: batch/v1
metadata:
name: losing-religion
namespace: rem-namespace
annotations:
"helm.sh/hook": pre-install
"helm.sh/hook-output-log-policy": %s
spec:
completions: 1
parallelism: 1
activeDeadlineSeconds: 30
template:
spec:
containers:
- name: religion-container
image: religion-image
cmd: religion-command`, hookDefinitionString)
}
func convertHooksToCommaSeparated(hookDefinitions []release.HookOutputLogPolicy) string {
var commaSeparated strings.Builder
for i, policy := range hookDefinitions {
if i+1 == len(hookDefinitions) {
commaSeparated.WriteString(policy.String())
} else {
commaSeparated.WriteString(policy.String() + ",")
}
}
return commaSeparated.String()
}
func TestInstallRelease_HookOutputLogsOnFailure(t *testing.T) {
// Should output on failure with expected namespace if hook-failed is set
runInstallForHooksWithFailure(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithFailure(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "sneaky-namespace", true)
runInstallForHooksWithFailure(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithFailure(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "rem-namespace", true)
// Should not output on failure with expected namespace if hook-succeed is set
runInstallForHooksWithFailure(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "", false)
runInstallForHooksWithFailure(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "", false)
runInstallForHooksWithFailure(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "", false)
runInstallForHooksWithFailure(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "", false)
}
func TestInstallRelease_HookOutputLogsOnSuccess(t *testing.T) {
// Should output on success with expected namespace if hook-succeeded is set
runInstallForHooksWithSuccess(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "spaced", true)
runInstallForHooksWithSuccess(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "sneaky-namespace", true)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "spaced", true)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded}), "rem-namespace", true)
// Should not output on success if hook-failed is set
runInstallForHooksWithSuccess(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "", false)
runInstallForHooksWithSuccess(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "", false)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "", false)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnFailed}), "", false)
}
func TestInstallRelease_HooksOutputLogsOnSuccessAndFailure(t *testing.T) {
// Should output on success with expected namespace if hook-succeeded and hook-failed is set
runInstallForHooksWithSuccess(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithSuccess(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "sneaky-namespace", true)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithSuccess(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "rem-namespace", true)
// Should output on failure if hook-succeeded and hook-failed is set
runInstallForHooksWithFailure(t, podManifestWithOutputLogs([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithFailure(t, podManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "sneaky-namespace", true)
runInstallForHooksWithFailure(t, jobManifestWithOutputLog([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "spaced", true)
runInstallForHooksWithFailure(t, jobManifestWithOutputLogWithNamespace([]release.HookOutputLogPolicy{release.HookOutputOnSucceeded, release.HookOutputOnFailed}), "rem-namespace", true)
}
func runInstallForHooksWithSuccess(t *testing.T, manifest, expectedNamespace string, shouldOutput bool) {
t.Helper()
var expectedOutput string
if shouldOutput {
expectedOutput = fmt.Sprintf("attempted to output logs for namespace: %s", expectedNamespace)
}
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "failed-hooks"
outBuffer := &bytes.Buffer{}
instAction.cfg.KubeClient = &kubefake.PrintingKubeClient{Out: io.Discard, LogOutput: outBuffer}
modTime := time.Now()
templates := []*common.File{
{Name: "templates/hello", ModTime: modTime, Data: []byte("hello: world")},
{Name: "templates/hooks", ModTime: modTime, Data: []byte(manifest)},
}
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChartWithTemplates(templates), vals)
is.NoError(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Equal(expectedOutput, outBuffer.String())
is.Equal(rcommon.StatusDeployed, res.Info.Status)
}
func runInstallForHooksWithFailure(t *testing.T, manifest, expectedNamespace string, shouldOutput bool) {
t.Helper()
var expectedOutput string
if shouldOutput {
expectedOutput = fmt.Sprintf("attempted to output logs for namespace: %s", expectedNamespace)
}
is := assert.New(t)
instAction := installAction(t)
instAction.ReleaseName = "failed-hooks"
failingClient := instAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failingClient.WatchUntilReadyError = fmt.Errorf("failed watch")
instAction.cfg.KubeClient = failingClient
outBuffer := &bytes.Buffer{}
failingClient.PrintingKubeClient = kubefake.PrintingKubeClient{Out: io.Discard, LogOutput: outBuffer}
modTime := time.Now()
templates := []*common.File{
{Name: "templates/hello", ModTime: modTime, Data: []byte("hello: world")},
{Name: "templates/hooks", ModTime: modTime, Data: []byte(manifest)},
}
vals := map[string]interface{}{}
resi, err := instAction.Run(buildChartWithTemplates(templates), vals)
is.Error(err)
res, err := releaserToV1Release(resi)
is.NoError(err)
is.Contains(res.Info.Description, "failed pre-install")
is.Equal(expectedOutput, outBuffer.String())
is.Equal(rcommon.StatusFailed, res.Info.Status)
}
type HookFailedError struct{}
func (e *HookFailedError) Error() string {
return "Hook failed!"
}
type HookFailingKubeClient struct {
kubefake.PrintingKubeClient
failOn resource.Info
deleteRecord []resource.Info
}
type HookFailingKubeWaiter struct {
*kubefake.PrintingKubeWaiter
failOn resource.Info
}
func (*HookFailingKubeClient) Build(reader io.Reader, _ bool) (kube.ResourceList, error) {
configMap := &v1.ConfigMap{}
err := yaml.NewYAMLOrJSONDecoder(reader, 1000).Decode(configMap)
if err != nil {
return kube.ResourceList{}, err
}
return kube.ResourceList{{
Name: configMap.Name,
Namespace: configMap.Namespace,
}}, nil
}
func (h *HookFailingKubeWaiter) WatchUntilReady(resources kube.ResourceList, _ time.Duration) error {
for _, res := range resources {
if res.Name == h.failOn.Name && res.Namespace == h.failOn.Namespace {
return &HookFailedError{}
}
}
return nil
}
func (h *HookFailingKubeClient) Delete(resources kube.ResourceList, deletionPropagation metav1.DeletionPropagation) (*kube.Result, []error) {
for _, res := range resources {
h.deleteRecord = append(h.deleteRecord, resource.Info{
Name: res.Name,
Namespace: res.Namespace,
})
}
return h.PrintingKubeClient.Delete(resources, deletionPropagation)
}
func (h *HookFailingKubeClient) GetWaiter(strategy kube.WaitStrategy) (kube.Waiter, error) {
waiter, _ := h.PrintingKubeClient.GetWaiter(strategy)
return &HookFailingKubeWaiter{
PrintingKubeWaiter: waiter.(*kubefake.PrintingKubeWaiter),
failOn: h.failOn,
}, nil
}
func TestHooksCleanUp(t *testing.T) {
hookEvent := release.HookPreInstall
testCases := []struct {
name string
inputRelease release.Release
failOn resource.Info
expectedDeleteRecord []resource.Info
expectError bool
}{
{
"Deletion hook runs for previously successful hook on failure of a heavier weight hook",
release.Release{
Name: "test-release",
Namespace: "test",
Hooks: []*release.Hook{
{
Name: "hook-1",
Kind: "ConfigMap",
Path: "templates/service_account.yaml",
Manifest: `apiVersion: v1
kind: ConfigMap
metadata:
name: build-config-1
namespace: test
data:
foo: bar
`,
Weight: -5,
Events: []release.HookEvent{
hookEvent,
},
DeletePolicies: []release.HookDeletePolicy{
release.HookBeforeHookCreation,
release.HookSucceeded,
release.HookFailed,
},
LastRun: release.HookExecution{
Phase: release.HookPhaseSucceeded,
},
},
{
Name: "hook-2",
Kind: "ConfigMap",
Path: "templates/job.yaml",
Manifest: `apiVersion: v1
kind: ConfigMap
metadata:
name: build-config-2
namespace: test
data:
foo: bar
`,
Weight: 0,
Events: []release.HookEvent{
hookEvent,
},
DeletePolicies: []release.HookDeletePolicy{
release.HookBeforeHookCreation,
release.HookSucceeded,
release.HookFailed,
},
LastRun: release.HookExecution{
Phase: release.HookPhaseFailed,
},
},
},
}, resource.Info{
Name: "build-config-2",
Namespace: "test",
}, []resource.Info{
{
// This should be in the record for `before-hook-creation`
Name: "build-config-1",
Namespace: "test",
},
{
// This should be in the record for `before-hook-creation`
Name: "build-config-2",
Namespace: "test",
},
{
// This should be in the record for cleaning up (the failure first)
Name: "build-config-2",
Namespace: "test",
},
{
// This should be in the record for cleaning up (then the previously successful)
Name: "build-config-1",
Namespace: "test",
},
}, true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
kubeClient := &HookFailingKubeClient{
kubefake.PrintingKubeClient{Out: io.Discard}, tc.failOn, []resource.Info{},
}
configuration := &Configuration{
Releases: storage.Init(driver.NewMemory()),
KubeClient: kubeClient,
Capabilities: common.DefaultCapabilities,
}
serverSideApply := true
err := configuration.execHook(&tc.inputRelease, hookEvent, kube.StatusWatcherStrategy, 600, serverSideApply)
if !reflect.DeepEqual(kubeClient.deleteRecord, tc.expectedDeleteRecord) {
t.Fatalf("Got unexpected delete record, expected: %#v, but got: %#v", kubeClient.deleteRecord, tc.expectedDeleteRecord)
}
if err != nil && !tc.expectError {
t.Fatalf("Got an unexpected error.")
}
if err == nil && tc.expectError {
t.Fatalf("Expected and error but did not get it.")
}
})
}
}
func TestConfiguration_hookSetDeletePolicy(t *testing.T) {
tests := map[string]struct {
policies []release.HookDeletePolicy
expected []release.HookDeletePolicy
}{
"no polices specified result in the default policy": {
policies: nil,
expected: []release.HookDeletePolicy{
release.HookBeforeHookCreation,
},
},
"unknown policy is untouched": {
policies: []release.HookDeletePolicy{
release.HookDeletePolicy("never"),
},
expected: []release.HookDeletePolicy{
release.HookDeletePolicy("never"),
},
},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
cfg := &Configuration{}
h := &release.Hook{
DeletePolicies: tt.policies,
}
cfg.hookSetDeletePolicy(h)
assert.Equal(t, tt.expected, h.DeletePolicies)
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/hooks.go | pkg/action/hooks.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 action
import (
"bytes"
"fmt"
"log"
"slices"
"sort"
"time"
"helm.sh/helm/v4/pkg/kube"
"go.yaml.in/yaml/v3"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
release "helm.sh/helm/v4/pkg/release/v1"
)
// execHook executes all of the hooks for the given hook event.
func (cfg *Configuration) execHook(rl *release.Release, hook release.HookEvent, waitStrategy kube.WaitStrategy, timeout time.Duration, serverSideApply bool) error {
executingHooks := []*release.Hook{}
for _, h := range rl.Hooks {
for _, e := range h.Events {
if e == hook {
executingHooks = append(executingHooks, h)
}
}
}
// hooke are pre-ordered by kind, so keep order stable
sort.Stable(hookByWeight(executingHooks))
for i, h := range executingHooks {
// Set default delete policy to before-hook-creation
cfg.hookSetDeletePolicy(h)
if err := cfg.deleteHookByPolicy(h, release.HookBeforeHookCreation, waitStrategy, timeout); err != nil {
return err
}
resources, err := cfg.KubeClient.Build(bytes.NewBufferString(h.Manifest), true)
if err != nil {
return fmt.Errorf("unable to build kubernetes object for %s hook %s: %w", hook, h.Path, err)
}
// Record the time at which the hook was applied to the cluster
h.LastRun = release.HookExecution{
StartedAt: time.Now(),
Phase: release.HookPhaseRunning,
}
cfg.recordRelease(rl)
// As long as the implementation of WatchUntilReady does not panic, HookPhaseFailed or HookPhaseSucceeded
// should always be set by this function. If we fail to do that for any reason, then HookPhaseUnknown is
// the most appropriate value to surface.
h.LastRun.Phase = release.HookPhaseUnknown
// Create hook resources
if _, err := cfg.KubeClient.Create(
resources,
kube.ClientCreateOptionServerSideApply(serverSideApply, false)); err != nil {
h.LastRun.CompletedAt = time.Now()
h.LastRun.Phase = release.HookPhaseFailed
return fmt.Errorf("warning: Hook %s %s failed: %w", hook, h.Path, err)
}
waiter, err := cfg.KubeClient.GetWaiter(waitStrategy)
if err != nil {
return fmt.Errorf("unable to get waiter: %w", err)
}
// Watch hook resources until they have completed
err = waiter.WatchUntilReady(resources, timeout)
// Note the time of success/failure
h.LastRun.CompletedAt = time.Now()
// Mark hook as succeeded or failed
if err != nil {
h.LastRun.Phase = release.HookPhaseFailed
// If a hook is failed, check the annotation of the hook to determine if we should copy the logs client side
if errOutputting := cfg.outputLogsByPolicy(h, rl.Namespace, release.HookOutputOnFailed); errOutputting != nil {
// We log the error here as we want to propagate the hook failure upwards to the release object.
log.Printf("error outputting logs for hook failure: %v", errOutputting)
}
// If a hook is failed, check the annotation of the hook to determine whether the hook should be deleted
// under failed condition. If so, then clear the corresponding resource object in the hook
if errDeleting := cfg.deleteHookByPolicy(h, release.HookFailed, waitStrategy, timeout); errDeleting != nil {
// We log the error here as we want to propagate the hook failure upwards to the release object.
log.Printf("error deleting the hook resource on hook failure: %v", errDeleting)
}
// If a hook is failed, check the annotation of the previous successful hooks to determine whether the hooks
// should be deleted under succeeded condition.
if err := cfg.deleteHooksByPolicy(executingHooks[0:i], release.HookSucceeded, waitStrategy, timeout); err != nil {
return err
}
return err
}
h.LastRun.Phase = release.HookPhaseSucceeded
}
// If all hooks are successful, check the annotation of each hook to determine whether the hook should be deleted
// or output should be logged under succeeded condition. If so, then clear the corresponding resource object in each hook
for i := len(executingHooks) - 1; i >= 0; i-- {
h := executingHooks[i]
if err := cfg.outputLogsByPolicy(h, rl.Namespace, release.HookOutputOnSucceeded); err != nil {
// We log here as we still want to attempt hook resource deletion even if output logging fails.
log.Printf("error outputting logs for hook failure: %v", err)
}
if err := cfg.deleteHookByPolicy(h, release.HookSucceeded, waitStrategy, timeout); err != nil {
return err
}
}
return nil
}
// hookByWeight is a sorter for hooks
type hookByWeight []*release.Hook
func (x hookByWeight) Len() int { return len(x) }
func (x hookByWeight) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x hookByWeight) Less(i, j int) bool {
if x[i].Weight == x[j].Weight {
return x[i].Name < x[j].Name
}
return x[i].Weight < x[j].Weight
}
// deleteHookByPolicy deletes a hook if the hook policy instructs it to
func (cfg *Configuration) deleteHookByPolicy(h *release.Hook, policy release.HookDeletePolicy, waitStrategy kube.WaitStrategy, timeout time.Duration) error {
// Never delete CustomResourceDefinitions; this could cause lots of
// cascading garbage collection.
if h.Kind == "CustomResourceDefinition" {
return nil
}
if cfg.hookHasDeletePolicy(h, policy) {
resources, err := cfg.KubeClient.Build(bytes.NewBufferString(h.Manifest), false)
if err != nil {
return fmt.Errorf("unable to build kubernetes object for deleting hook %s: %w", h.Path, err)
}
_, errs := cfg.KubeClient.Delete(resources, metav1.DeletePropagationBackground)
if len(errs) > 0 {
return joinErrors(errs, "; ")
}
waiter, err := cfg.KubeClient.GetWaiter(waitStrategy)
if err != nil {
return err
}
if err := waiter.WaitForDelete(resources, timeout); err != nil {
return err
}
}
return nil
}
// deleteHooksByPolicy deletes all hooks if the hook policy instructs it to
func (cfg *Configuration) deleteHooksByPolicy(hooks []*release.Hook, policy release.HookDeletePolicy, waitStrategy kube.WaitStrategy, timeout time.Duration) error {
for _, h := range hooks {
if err := cfg.deleteHookByPolicy(h, policy, waitStrategy, timeout); err != nil {
return err
}
}
return nil
}
// hookHasDeletePolicy determines whether the defined hook deletion policy matches the hook deletion polices
// supported by helm. If so, mark the hook as one should be deleted.
func (cfg *Configuration) hookHasDeletePolicy(h *release.Hook, policy release.HookDeletePolicy) bool {
cfg.mutex.Lock()
defer cfg.mutex.Unlock()
return slices.Contains(h.DeletePolicies, policy)
}
// hookSetDeletePolicy determines whether the defined hook deletion policy matches the hook deletion polices
// supported by helm. If so, mark the hook as one should be deleted.
func (cfg *Configuration) hookSetDeletePolicy(h *release.Hook) {
cfg.mutex.Lock()
defer cfg.mutex.Unlock()
if len(h.DeletePolicies) == 0 {
// TODO(jlegrone): Only apply before-hook-creation delete policy to run to completion
// resources. For all other resource types update in place if a
// resource with the same name already exists and is owned by the
// current release.
h.DeletePolicies = []release.HookDeletePolicy{release.HookBeforeHookCreation}
}
}
// outputLogsByPolicy outputs a pods logs if the hook policy instructs it to
func (cfg *Configuration) outputLogsByPolicy(h *release.Hook, releaseNamespace string, policy release.HookOutputLogPolicy) error {
if !hookHasOutputLogPolicy(h, policy) {
return nil
}
namespace, err := cfg.deriveNamespace(h, releaseNamespace)
if err != nil {
return err
}
switch h.Kind {
case "Job":
return cfg.outputContainerLogsForListOptions(namespace, metav1.ListOptions{LabelSelector: fmt.Sprintf("job-name=%s", h.Name)})
case "Pod":
return cfg.outputContainerLogsForListOptions(namespace, metav1.ListOptions{FieldSelector: fmt.Sprintf("metadata.name=%s", h.Name)})
default:
return nil
}
}
func (cfg *Configuration) outputContainerLogsForListOptions(namespace string, listOptions metav1.ListOptions) error {
podList, err := cfg.KubeClient.GetPodList(namespace, listOptions)
if err != nil {
return err
}
return cfg.KubeClient.OutputContainerLogsForPodList(podList, namespace, cfg.HookOutputFunc)
}
func (cfg *Configuration) deriveNamespace(h *release.Hook, namespace string) (string, error) {
tmp := struct {
Metadata struct {
Namespace string
}
}{}
err := yaml.Unmarshal([]byte(h.Manifest), &tmp)
if err != nil {
return "", fmt.Errorf("unable to parse metadata.namespace from kubernetes manifest for output logs hook %s: %w", h.Path, err)
}
if tmp.Metadata.Namespace == "" {
return namespace, nil
}
return tmp.Metadata.Namespace, nil
}
// hookHasOutputLogPolicy determines whether the defined hook output log policy matches the hook output log policies
// supported by helm.
func hookHasOutputLogPolicy(h *release.Hook, policy release.HookOutputLogPolicy) bool {
return slices.Contains(h.OutputLogPolicies, policy)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get_test.go | pkg/action/get_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 action
import (
"errors"
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/release/common"
)
func TestNewGet(t *testing.T) {
config := actionConfigFixture(t)
client := NewGet(config)
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
assert.Equal(t, 0, client.Version)
}
func TestGetRun(t *testing.T) {
config := actionConfigFixture(t)
client := NewGet(config)
simpleRelease := namedReleaseStub("test-release", common.StatusPendingUpgrade)
require.NoError(t, config.Releases.Create(simpleRelease))
releaser, err := client.Run(simpleRelease.Name)
require.NoError(t, err)
result, err := releaserToV1Release(releaser)
require.NoError(t, err)
assert.Equal(t, simpleRelease.Name, result.Name)
assert.Equal(t, simpleRelease.Version, result.Version)
}
func TestGetRun_UnreachableKubeClient(t *testing.T) {
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
client := NewGet(config)
simpleRelease := namedReleaseStub("test-release", common.StatusPendingUpgrade)
require.NoError(t, config.Releases.Create(simpleRelease))
result, err := client.Run(simpleRelease.Name)
assert.Nil(t, result)
assert.Error(t, err)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/pull.go | pkg/action/pull.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 action
import (
"fmt"
"os"
"path/filepath"
"strings"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/downloader"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/repo/v1"
)
// Pull is the action for checking a given release's information.
//
// It provides the implementation of 'helm pull'.
type Pull struct {
ChartPathOptions
Settings *cli.EnvSettings // TODO: refactor this out of pkg/action
Devel bool
Untar bool
VerifyLater bool
UntarDir string
DestDir string
cfg *Configuration
}
type PullOpt func(*Pull)
func WithConfig(cfg *Configuration) PullOpt {
return func(p *Pull) {
p.cfg = cfg
}
}
// NewPull creates a new Pull with configuration options.
func NewPull(opts ...PullOpt) *Pull {
p := &Pull{}
for _, fn := range opts {
fn(p)
}
return p
}
// SetRegistryClient sets the registry client on the pull configuration object.
func (p *Pull) SetRegistryClient(client *registry.Client) {
p.cfg.RegistryClient = client
}
// Run executes 'helm pull' against the given release.
func (p *Pull) Run(chartRef string) (string, error) {
var out strings.Builder
c := downloader.ChartDownloader{
Out: &out,
Keyring: p.Keyring,
Verify: downloader.VerifyNever,
Getters: getter.All(p.Settings),
Options: []getter.Option{
getter.WithBasicAuth(p.Username, p.Password),
getter.WithPassCredentialsAll(p.PassCredentialsAll),
getter.WithTLSClientConfig(p.CertFile, p.KeyFile, p.CaFile),
getter.WithInsecureSkipVerifyTLS(p.InsecureSkipTLSVerify),
getter.WithPlainHTTP(p.PlainHTTP),
},
RegistryClient: p.cfg.RegistryClient,
RepositoryConfig: p.Settings.RepositoryConfig,
RepositoryCache: p.Settings.RepositoryCache,
ContentCache: p.Settings.ContentCache,
}
if registry.IsOCI(chartRef) {
c.Options = append(c.Options,
getter.WithRegistryClient(p.cfg.RegistryClient))
c.RegistryClient = p.cfg.RegistryClient
}
if p.Verify {
c.Verify = downloader.VerifyAlways
} else if p.VerifyLater {
c.Verify = downloader.VerifyLater
}
// If untar is set, we fetch to a tempdir, then untar and copy after
// verification.
dest := p.DestDir
if p.Untar {
var err error
dest, err = os.MkdirTemp("", "helm-")
if err != nil {
return out.String(), fmt.Errorf("failed to untar: %w", err)
}
defer os.RemoveAll(dest)
}
downloadSourceRef := chartRef
if p.RepoURL != "" {
chartURL, err := repo.FindChartInRepoURL(
p.RepoURL,
chartRef,
getter.All(p.Settings),
repo.WithChartVersion(p.Version),
repo.WithClientTLS(p.CertFile, p.KeyFile, p.CaFile),
repo.WithUsernamePassword(p.Username, p.Password),
repo.WithInsecureSkipTLSVerify(p.InsecureSkipTLSVerify),
repo.WithPassCredentialsAll(p.PassCredentialsAll),
)
if err != nil {
return out.String(), err
}
downloadSourceRef = chartURL
}
saved, v, err := c.DownloadTo(downloadSourceRef, p.Version, dest)
if err != nil {
return out.String(), err
}
if p.Verify {
for name := range v.SignedBy.Identities {
fmt.Fprintf(&out, "Signed by: %v\n", name)
}
fmt.Fprintf(&out, "Using Key With Fingerprint: %X\n", v.SignedBy.PrimaryKey.Fingerprint)
fmt.Fprintf(&out, "Chart Hash Verified: %s\n", v.FileHash)
}
// After verification, untar the chart into the requested directory.
if p.Untar {
ud := p.UntarDir
if !filepath.IsAbs(ud) {
ud = filepath.Join(p.DestDir, ud)
}
// Let udCheck to check conflict file/dir without replacing ud when untarDir is the current directory(.).
udCheck := ud
if udCheck == "." {
_, udCheck = filepath.Split(chartRef)
} else {
_, chartName := filepath.Split(chartRef)
udCheck = filepath.Join(udCheck, chartName)
}
if _, err := os.Stat(udCheck); err != nil {
if err := os.MkdirAll(udCheck, 0755); err != nil {
return out.String(), fmt.Errorf("failed to untar (mkdir): %w", err)
}
} else {
return out.String(), fmt.Errorf("failed to untar: a file or directory with the name %s already exists", udCheck)
}
return out.String(), chartutil.ExpandFile(ud, saved)
}
return out.String(), nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/get.go | pkg/action/get.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 action
import (
release "helm.sh/helm/v4/pkg/release"
)
// Get is the action for checking a given release's information.
//
// It provides the implementation of 'helm get' and its respective subcommands (except `helm get values`).
type Get struct {
cfg *Configuration
// Initializing Version to 0 will get the latest revision of the release.
Version int
}
// NewGet creates a new Get object with the given configuration.
func NewGet(cfg *Configuration) *Get {
return &Get{
cfg: cfg,
}
}
// Run executes 'helm get' against the given release.
func (g *Get) Run(name string) (release.Releaser, error) {
if err := g.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
return g.cfg.releaseContent(name, g.Version)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/doc.go | pkg/action/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 action contains the logic for each action that Helm can perform.
//
// This is a library for calling top-level Helm actions like 'install',
// 'upgrade', or 'list'. Actions approximately match the command line
// invocations that the Helm client uses.
package action
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/uninstall_test.go | pkg/action/uninstall_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 action
import (
"errors"
"fmt"
"io"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/pkg/kube"
kubefake "helm.sh/helm/v4/pkg/kube/fake"
"helm.sh/helm/v4/pkg/release/common"
)
func uninstallAction(t *testing.T) *Uninstall {
t.Helper()
config := actionConfigFixture(t)
unAction := NewUninstall(config)
return unAction
}
func TestUninstallRelease_dryRun_ignoreNotFound(t *testing.T) {
unAction := uninstallAction(t)
unAction.DryRun = true
unAction.IgnoreNotFound = true
is := assert.New(t)
res, err := unAction.Run("release-non-exist")
is.Nil(res)
is.NoError(err)
}
func TestUninstallRelease_ignoreNotFound(t *testing.T) {
unAction := uninstallAction(t)
unAction.DryRun = false
unAction.IgnoreNotFound = true
is := assert.New(t)
res, err := unAction.Run("release-non-exist")
is.Nil(res)
is.NoError(err)
}
func TestUninstallRelease_deleteRelease(t *testing.T) {
is := assert.New(t)
unAction := uninstallAction(t)
unAction.DisableHooks = true
unAction.DryRun = false
unAction.KeepHistory = true
rel := releaseStub()
rel.Name = "keep-secret"
rel.Manifest = `{
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"name": "secret",
"annotations": {
"helm.sh/resource-policy": "keep"
}
},
"type": "Opaque",
"data": {
"password": "password"
}
}`
require.NoError(t, unAction.cfg.Releases.Create(rel))
res, err := unAction.Run(rel.Name)
is.NoError(err)
expected := `These resources were kept due to the resource policy:
[Secret] secret
`
is.Contains(res.Info, expected)
}
func TestUninstallRelease_Wait(t *testing.T) {
is := assert.New(t)
unAction := uninstallAction(t)
unAction.DisableHooks = true
unAction.DryRun = false
unAction.WaitStrategy = kube.StatusWatcherStrategy
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Manifest = `{
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"name": "secret"
},
"type": "Opaque",
"data": {
"password": "password"
}
}`
require.NoError(t, unAction.cfg.Releases.Create(rel))
failer := unAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.WaitForDeleteError = fmt.Errorf("U timed out")
unAction.cfg.KubeClient = failer
resi, err := unAction.Run(rel.Name)
is.Error(err)
is.Contains(err.Error(), "U timed out")
res, err := releaserToV1Release(resi.Release)
is.NoError(err)
is.Equal(res.Info.Status, common.StatusUninstalled)
}
func TestUninstallRelease_Cascade(t *testing.T) {
is := assert.New(t)
unAction := uninstallAction(t)
unAction.DisableHooks = true
unAction.DryRun = false
unAction.WaitStrategy = kube.HookOnlyStrategy
unAction.DeletionPropagation = "foreground"
rel := releaseStub()
rel.Name = "come-fail-away"
rel.Manifest = `{
"apiVersion": "v1",
"kind": "Secret",
"metadata": {
"name": "secret"
},
"type": "Opaque",
"data": {
"password": "password"
}
}`
require.NoError(t, unAction.cfg.Releases.Create(rel))
failer := unAction.cfg.KubeClient.(*kubefake.FailingKubeClient)
failer.DeleteError = fmt.Errorf("Uninstall with cascade failed")
failer.BuildDummy = true
unAction.cfg.KubeClient = failer
_, err := unAction.Run(rel.Name)
require.Error(t, err)
is.Contains(err.Error(), "failed to delete release: come-fail-away")
}
func TestUninstallRun_UnreachableKubeClient(t *testing.T) {
t.Helper()
config := actionConfigFixture(t)
failingKubeClient := kubefake.FailingKubeClient{PrintingKubeClient: kubefake.PrintingKubeClient{Out: io.Discard}, DummyResources: nil}
failingKubeClient.ConnectionError = errors.New("connection refused")
config.KubeClient = &failingKubeClient
client := NewUninstall(config)
result, err := client.Run("")
assert.Nil(t, result)
assert.ErrorContains(t, err, "connection refused")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/registry_logout.go | pkg/action/registry_logout.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 action
import (
"io"
)
// RegistryLogout performs a registry login operation.
type RegistryLogout struct {
cfg *Configuration
}
// NewRegistryLogout creates a new RegistryLogout object with the given configuration.
func NewRegistryLogout(cfg *Configuration) *RegistryLogout {
return &RegistryLogout{
cfg: cfg,
}
}
// Run executes the registry logout operation
func (a *RegistryLogout) Run(_ io.Writer, hostname string) error {
return a.cfg.RegistryClient.Logout(hostname)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/package.go | pkg/action/package.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 action
import (
"bufio"
"errors"
"fmt"
"os"
"path/filepath"
"syscall"
"github.com/Masterminds/semver/v3"
"golang.org/x/term"
"sigs.k8s.io/yaml"
ci "helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/loader"
chart "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/provenance"
)
// Package is the action for packaging a chart.
//
// It provides the implementation of 'helm package'.
type Package struct {
Sign bool
Key string
Keyring string
PassphraseFile string
cachedPassphrase []byte
Version string
AppVersion string
Destination string
DependencyUpdate bool
RepositoryConfig string
RepositoryCache string
PlainHTTP bool
Username string
Password string
CertFile string
KeyFile string
CaFile string
InsecureSkipTLSVerify bool
}
const (
passPhraseFileStdin = "-"
)
// NewPackage creates a new Package object with the given configuration.
func NewPackage() *Package {
return &Package{}
}
// Run executes 'helm package' against the given chart and returns the path to the packaged chart.
func (p *Package) Run(path string, _ map[string]interface{}) (string, error) {
chrt, err := loader.LoadDir(path)
if err != nil {
return "", err
}
var ch *chart.Chart
switch c := chrt.(type) {
case *chart.Chart:
ch = c
case chart.Chart:
ch = &c
default:
return "", errors.New("invalid chart apiVersion")
}
ac, err := ci.NewAccessor(ch)
if err != nil {
return "", err
}
// If version is set, modify the version.
if p.Version != "" {
ch.Metadata.Version = p.Version
}
if err := validateVersion(ch.Metadata.Version); err != nil {
return "", err
}
if p.AppVersion != "" {
ch.Metadata.AppVersion = p.AppVersion
}
if reqs := ac.MetaDependencies(); len(reqs) > 0 {
if err := CheckDependencies(ch, reqs); err != nil {
return "", err
}
}
var dest string
if p.Destination == "." {
// Save to the current working directory.
dest, err = os.Getwd()
if err != nil {
return "", err
}
} else {
// Otherwise save to set destination
dest = p.Destination
}
name, err := chartutil.Save(ch, dest)
if err != nil {
return "", fmt.Errorf("failed to save: %w", err)
}
if p.Sign {
err = p.Clearsign(name)
}
return name, err
}
// validateVersion Verify that version is a Version, and error out if it is not.
func validateVersion(ver string) error {
if _, err := semver.NewVersion(ver); err != nil {
return err
}
return nil
}
// Clearsign signs a chart
func (p *Package) Clearsign(filename string) error {
// Load keyring
signer, err := provenance.NewFromKeyring(p.Keyring, p.Key)
if err != nil {
return err
}
passphraseFetcher := promptUser
if p.PassphraseFile != "" {
passphraseFetcher, err = p.passphraseFileFetcher(p.PassphraseFile, os.Stdin)
if err != nil {
return err
}
}
if err := signer.DecryptKey(passphraseFetcher); err != nil {
return err
}
// Load the chart archive to extract metadata
chrt, err := loader.LoadFile(filename)
if err != nil {
return fmt.Errorf("failed to load chart for signing: %w", err)
}
var ch *chart.Chart
switch c := chrt.(type) {
case *chart.Chart:
ch = c
case chart.Chart:
ch = &c
default:
return errors.New("invalid chart apiVersion")
}
// Marshal chart metadata to YAML bytes
metadataBytes, err := yaml.Marshal(ch.Metadata)
if err != nil {
return fmt.Errorf("failed to marshal chart metadata: %w", err)
}
// Read the chart archive file
archiveData, err := os.ReadFile(filename)
if err != nil {
return fmt.Errorf("failed to read chart archive: %w", err)
}
// Use the generic provenance signing function
sig, err := signer.ClearSign(archiveData, filepath.Base(filename), metadataBytes)
if err != nil {
return err
}
return os.WriteFile(filename+".prov", []byte(sig), 0644)
}
// promptUser implements provenance.PassphraseFetcher
func promptUser(name string) ([]byte, error) {
fmt.Printf("Password for key %q > ", name)
// syscall.Stdin is not an int in all environments and needs to be coerced
// into one there (e.g., Windows)
pw, err := term.ReadPassword(int(syscall.Stdin))
fmt.Println()
return pw, err
}
func (p *Package) passphraseFileFetcher(passphraseFile string, stdin *os.File) (provenance.PassphraseFetcher, error) {
// When reading from stdin we cache the passphrase here. If we are
// packaging multiple charts, we reuse the cached passphrase. This
// allows giving the passphrase once on stdin without failing with
// complaints about stdin already being closed.
//
// An alternative to this would be to omit file.Close() for stdin
// below and require the user to provide the same passphrase once
// per chart on stdin, but that does not seem very user-friendly.
if p.cachedPassphrase == nil {
file, err := openPassphraseFile(passphraseFile, stdin)
if err != nil {
return nil, err
}
defer file.Close()
reader := bufio.NewReader(file)
passphrase, _, err := reader.ReadLine()
if err != nil {
return nil, err
}
p.cachedPassphrase = passphrase
return func(_ string) ([]byte, error) {
return passphrase, nil
}, nil
}
return func(_ string) ([]byte, error) {
return p.cachedPassphrase, nil
}, nil
}
func openPassphraseFile(passphraseFile string, stdin *os.File) (*os.File, error) {
if passphraseFile == passPhraseFileStdin {
stat, err := stdin.Stat()
if err != nil {
return nil, err
}
if (stat.Mode() & os.ModeNamedPipe) == 0 {
return nil, errors.New("specified reading passphrase from stdin, without input on stdin")
}
return stdin, nil
}
return os.Open(passphraseFile)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/dependency_test.go | pkg/action/dependency_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 action
import (
"bytes"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/internal/test"
chart "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
)
func TestList(t *testing.T) {
for _, tcase := range []struct {
chart string
golden string
}{
{
chart: "testdata/charts/chart-with-compressed-dependencies",
golden: "output/list-compressed-deps.txt",
},
{
chart: "testdata/charts/chart-with-compressed-dependencies-2.1.8.tgz",
golden: "output/list-compressed-deps-tgz.txt",
},
{
chart: "testdata/charts/chart-with-uncompressed-dependencies",
golden: "output/list-uncompressed-deps.txt",
},
{
chart: "testdata/charts/chart-with-uncompressed-dependencies-2.1.8.tgz",
golden: "output/list-uncompressed-deps-tgz.txt",
},
{
chart: "testdata/charts/chart-missing-deps",
golden: "output/list-missing-deps.txt",
},
} {
buf := bytes.Buffer{}
if err := NewDependency().List(tcase.chart, &buf); err != nil {
t.Fatal(err)
}
test.AssertGoldenString(t, buf.String(), tcase.golden)
}
}
// TestDependencyStatus_Dashes is a regression test to make sure that dashes in
// chart names do not cause resolution problems.
func TestDependencyStatus_Dashes(t *testing.T) {
// Make a temp dir
dir := t.TempDir()
chartpath := filepath.Join(dir, "charts")
if err := os.MkdirAll(chartpath, 0700); err != nil {
t.Fatal(err)
}
// Add some fake charts
first := buildChart(withName("first-chart"))
_, err := chartutil.Save(first, chartpath)
if err != nil {
t.Fatal(err)
}
second := buildChart(withName("first-chart-second-chart"))
_, err = chartutil.Save(second, chartpath)
if err != nil {
t.Fatal(err)
}
dep := &chart.Dependency{
Name: "first-chart",
Version: "0.1.0",
}
// Now try to get the deps
stat := NewDependency().dependencyStatus(dir, dep, first)
if stat != "ok" {
t.Errorf("Unexpected status: %q", stat)
}
}
func TestStatArchiveForStatus(t *testing.T) {
// Make a temp dir
dir := t.TempDir()
chartpath := filepath.Join(dir, "charts")
if err := os.MkdirAll(chartpath, 0700); err != nil {
t.Fatal(err)
}
// unsaved chart
lilith := buildChart(withName("lilith"))
// dep referring to chart
dep := &chart.Dependency{
Name: "lilith",
Version: "1.2.3",
}
is := assert.New(t)
lilithpath := filepath.Join(chartpath, "lilith-1.2.3.tgz")
is.Empty(statArchiveForStatus(lilithpath, dep))
// save the chart (version 0.1.0, because that is the default)
where, err := chartutil.Save(lilith, chartpath)
is.NoError(err)
// Should get "wrong version" because we asked for 1.2.3 and got 0.1.0
is.Equal("wrong version", statArchiveForStatus(where, dep))
// Break version on dep
dep = &chart.Dependency{
Name: "lilith",
Version: "1.2.3.4.5",
}
is.Equal("invalid version", statArchiveForStatus(where, dep))
// Break the name
dep = &chart.Dependency{
Name: "lilith2",
Version: "1.2.3",
}
is.Equal("misnamed", statArchiveForStatus(where, dep))
// Now create the right version
dep = &chart.Dependency{
Name: "lilith",
Version: "0.1.0",
}
is.Equal("ok", statArchiveForStatus(where, dep))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/registry_logout_test.go | pkg/action/registry_logout_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 action
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNewRegistryLogout(t *testing.T) {
config := actionConfigFixture(t)
client := NewRegistryLogout(config)
assert.NotNil(t, client)
assert.Equal(t, config, client.cfg)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/upgrade.go | pkg/action/upgrade.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 action
import (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/cli-runtime/pkg/resource"
"helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/common"
"helm.sh/helm/v4/pkg/chart/common/util"
chartv2 "helm.sh/helm/v4/pkg/chart/v2"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/kube"
"helm.sh/helm/v4/pkg/postrenderer"
"helm.sh/helm/v4/pkg/registry"
ri "helm.sh/helm/v4/pkg/release"
rcommon "helm.sh/helm/v4/pkg/release/common"
release "helm.sh/helm/v4/pkg/release/v1"
releaseutil "helm.sh/helm/v4/pkg/release/v1/util"
"helm.sh/helm/v4/pkg/storage/driver"
)
// Upgrade is the action for upgrading releases.
//
// It provides the implementation of 'helm upgrade'.
type Upgrade struct {
cfg *Configuration
ChartPathOptions
// Install is a purely informative flag that indicates whether this upgrade was done in "install" mode.
//
// Applications may use this to determine whether this Upgrade operation was done as part of a
// pure upgrade (Upgrade.Install == false) or as part of an install-or-upgrade operation
// (Upgrade.Install == true).
//
// Setting this to `true` will NOT cause `Upgrade` to perform an install if the release does not exist.
// That process must be handled by creating an Install action directly. See cmd/upgrade.go for an
// example of how this flag is used.
Install bool
// Devel indicates that the operation is done in devel mode.
Devel bool
// Namespace is the namespace in which this operation should be performed.
Namespace string
// SkipCRDs skips installing CRDs when install flag is enabled during upgrade
SkipCRDs bool
// Timeout is the timeout for this operation
Timeout time.Duration
// WaitStrategy determines what type of waiting should be done
WaitStrategy kube.WaitStrategy
// WaitForJobs determines whether the wait operation for the Jobs should be performed after the upgrade is requested.
WaitForJobs bool
// DisableHooks disables hook processing if set to true.
DisableHooks bool
// DryRunStrategy can be set to prepare, but not execute the operation and whether or not to interact with the remote cluster
DryRunStrategy DryRunStrategy
// HideSecret can be set to true when DryRun is enabled in order to hide
// Kubernetes Secrets in the output. It cannot be used outside of DryRun.
HideSecret bool
// ForceReplace will, if set to `true`, ignore certain warnings and perform the upgrade anyway.
//
// This should be used with caution.
ForceReplace bool
// ForceConflicts causes server-side apply to force conflicts ("Overwrite value, become sole manager")
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/#conflicts
ForceConflicts bool
// ServerSideApply enables changes to be applied via Kubernetes server-side apply
// Can be the string: "true", "false" or "auto"
// When "auto", sever-side usage will be based upon the releases previous usage
// see: https://kubernetes.io/docs/reference/using-api/server-side-apply/
ServerSideApply string
// ResetValues will reset the values to the chart's built-ins rather than merging with existing.
ResetValues bool
// ReuseValues will reuse the user's last supplied values.
ReuseValues bool
// ResetThenReuseValues will reset the values to the chart's built-ins then merge with user's last supplied values.
ResetThenReuseValues bool
// MaxHistory limits the maximum number of revisions saved per release
MaxHistory int
// RollbackOnFailure enables rolling back the upgraded release on failure
RollbackOnFailure bool
// CleanupOnFail will, if true, cause the upgrade to delete newly-created resources on a failed update.
CleanupOnFail bool
// SubNotes determines whether sub-notes are rendered in the chart.
SubNotes bool
// HideNotes determines whether notes are output during upgrade
HideNotes bool
// SkipSchemaValidation determines if JSON schema validation is disabled.
SkipSchemaValidation bool
// Description is the description of this operation
Description string
Labels map[string]string
// PostRenderer is an optional post-renderer
//
// If this is non-nil, then after templates are rendered, they will be sent to the
// post renderer before sending to the Kubernetes API server.
PostRenderer postrenderer.PostRenderer
// DisableOpenAPIValidation controls whether OpenAPI validation is enforced.
DisableOpenAPIValidation bool
// Get missing dependencies
DependencyUpdate bool
// Lock to control raceconditions when the process receives a SIGTERM
Lock sync.Mutex
// Enable DNS lookups when rendering templates
EnableDNS bool
// TakeOwnership will skip the check for helm annotations and adopt all existing resources.
TakeOwnership bool
}
type resultMessage struct {
r *release.Release
e error
}
// NewUpgrade creates a new Upgrade object with the given configuration.
func NewUpgrade(cfg *Configuration) *Upgrade {
up := &Upgrade{
cfg: cfg,
ServerSideApply: "auto",
DryRunStrategy: DryRunNone,
}
up.registryClient = cfg.RegistryClient
return up
}
// SetRegistryClient sets the registry client to use when fetching charts.
func (u *Upgrade) SetRegistryClient(client *registry.Client) {
u.registryClient = client
}
// Run executes the upgrade on the given release.
func (u *Upgrade) Run(name string, chart chart.Charter, vals map[string]interface{}) (ri.Releaser, error) {
ctx := context.Background()
return u.RunWithContext(ctx, name, chart, vals)
}
// RunWithContext executes the upgrade on the given release with context.
func (u *Upgrade) RunWithContext(ctx context.Context, name string, ch chart.Charter, vals map[string]interface{}) (ri.Releaser, error) {
if err := u.cfg.KubeClient.IsReachable(); err != nil {
return nil, err
}
var chrt *chartv2.Chart
switch c := ch.(type) {
case *chartv2.Chart:
chrt = c
case chartv2.Chart:
chrt = &c
default:
return nil, errors.New("invalid chart apiVersion")
}
// Make sure wait is set if RollbackOnFailure. This makes it so
// the user doesn't have to specify both
if u.WaitStrategy == kube.HookOnlyStrategy && u.RollbackOnFailure {
u.WaitStrategy = kube.StatusWatcherStrategy
}
if err := chartutil.ValidateReleaseName(name); err != nil {
return nil, fmt.Errorf("release name is invalid: %s", name)
}
u.cfg.Logger().Debug("preparing upgrade", "name", name)
currentRelease, upgradedRelease, serverSideApply, err := u.prepareUpgrade(name, chrt, vals)
if err != nil {
return nil, err
}
u.cfg.Releases.MaxHistory = u.MaxHistory
u.cfg.Logger().Debug("performing update", "name", name)
res, err := u.performUpgrade(ctx, currentRelease, upgradedRelease, serverSideApply)
if err != nil {
return res, err
}
// Do not update for dry runs
if !isDryRun(u.DryRunStrategy) {
u.cfg.Logger().Debug("updating status for upgraded release", "name", name)
if err := u.cfg.Releases.Update(upgradedRelease); err != nil {
return res, err
}
}
return res, nil
}
// prepareUpgrade builds an upgraded release for an upgrade operation.
func (u *Upgrade) prepareUpgrade(name string, chart *chartv2.Chart, vals map[string]interface{}) (*release.Release, *release.Release, bool, error) {
if chart == nil {
return nil, nil, false, errMissingChart
}
// HideSecret must be used with dry run. Otherwise, return an error.
if !isDryRun(u.DryRunStrategy) && u.HideSecret {
return nil, nil, false, errors.New("hiding Kubernetes secrets requires a dry-run mode")
}
// finds the last non-deleted release with the given name
lastReleasei, err := u.cfg.Releases.Last(name)
if err != nil {
// to keep existing behavior of returning the "%q has no deployed releases" error when an existing release does not exist
if errors.Is(err, driver.ErrReleaseNotFound) {
return nil, nil, false, driver.NewErrNoDeployedReleases(name)
}
return nil, nil, false, err
}
lastRelease, err := releaserToV1Release(lastReleasei)
if err != nil {
return nil, nil, false, err
}
// Concurrent `helm upgrade`s will either fail here with `errPending` or when creating the release with "already exists". This should act as a pessimistic lock.
if lastRelease.Info.Status.IsPending() {
return nil, nil, false, errPending
}
var currentRelease *release.Release
if lastRelease.Info.Status == rcommon.StatusDeployed {
// no need to retrieve the last deployed release from storage as the last release is deployed
currentRelease = lastRelease
} else {
// finds the deployed release with the given name
currentReleasei, err := u.cfg.Releases.Deployed(name)
var cerr error
currentRelease, cerr = releaserToV1Release(currentReleasei)
if cerr != nil {
return nil, nil, false, err
}
if err != nil {
if errors.Is(err, driver.ErrNoDeployedReleases) &&
(lastRelease.Info.Status == rcommon.StatusFailed || lastRelease.Info.Status == rcommon.StatusSuperseded) {
currentRelease = lastRelease
} else {
return nil, nil, false, err
}
}
}
// determine if values will be reused
vals, err = u.reuseValues(chart, currentRelease, vals)
if err != nil {
return nil, nil, false, err
}
if err := chartutil.ProcessDependencies(chart, vals); err != nil {
return nil, nil, false, err
}
// Increment revision count. This is passed to templates, and also stored on
// the release object.
revision := lastRelease.Version + 1
options := common.ReleaseOptions{
Name: name,
Namespace: currentRelease.Namespace,
Revision: revision,
IsUpgrade: true,
}
caps, err := u.cfg.getCapabilities()
if err != nil {
return nil, nil, false, err
}
valuesToRender, err := util.ToRenderValuesWithSchemaValidation(chart, vals, options, caps, u.SkipSchemaValidation)
if err != nil {
return nil, nil, false, err
}
hooks, manifestDoc, notesTxt, err := u.cfg.renderResources(chart, valuesToRender, "", "", u.SubNotes, false, false, u.PostRenderer, interactWithServer(u.DryRunStrategy), u.EnableDNS, u.HideSecret)
if err != nil {
return nil, nil, false, err
}
if driver.ContainsSystemLabels(u.Labels) {
return nil, nil, false, fmt.Errorf("user supplied labels contains system reserved label name. System labels: %+v", driver.GetSystemLabels())
}
serverSideApply, err := getUpgradeServerSideValue(u.ServerSideApply, lastRelease.ApplyMethod)
if err != nil {
return nil, nil, false, err
}
u.cfg.Logger().Debug("determined release apply method", slog.Bool("server_side_apply", serverSideApply), slog.String("previous_release_apply_method", lastRelease.ApplyMethod))
// Store an upgraded release.
upgradedRelease := &release.Release{
Name: name,
Namespace: currentRelease.Namespace,
Chart: chart,
Config: vals,
Info: &release.Info{
FirstDeployed: currentRelease.Info.FirstDeployed,
LastDeployed: Timestamper(),
Status: rcommon.StatusPendingUpgrade,
Description: "Preparing upgrade", // This should be overwritten later.
},
Version: revision,
Manifest: manifestDoc.String(),
Hooks: hooks,
Labels: mergeCustomLabels(lastRelease.Labels, u.Labels),
ApplyMethod: string(determineReleaseSSApplyMethod(serverSideApply)),
}
if len(notesTxt) > 0 {
upgradedRelease.Info.Notes = notesTxt
}
err = validateManifest(u.cfg.KubeClient, manifestDoc.Bytes(), !u.DisableOpenAPIValidation)
return currentRelease, upgradedRelease, serverSideApply, err
}
func (u *Upgrade) performUpgrade(ctx context.Context, originalRelease, upgradedRelease *release.Release, serverSideApply bool) (*release.Release, error) {
current, err := u.cfg.KubeClient.Build(bytes.NewBufferString(originalRelease.Manifest), false)
if err != nil {
// Checking for removed Kubernetes API error so can provide a more informative error message to the user
// Ref: https://github.com/helm/helm/issues/7219
if strings.Contains(err.Error(), "unable to recognize \"\": no matches for kind") {
return upgradedRelease, fmt.Errorf("current release manifest contains removed kubernetes api(s) for this "+
"kubernetes version and it is therefore unable to build the kubernetes "+
"objects for performing the diff. error from kubernetes: %w", err)
}
return upgradedRelease, fmt.Errorf("unable to build kubernetes objects from current release manifest: %w", err)
}
target, err := u.cfg.KubeClient.Build(bytes.NewBufferString(upgradedRelease.Manifest), !u.DisableOpenAPIValidation)
if err != nil {
return upgradedRelease, fmt.Errorf("unable to build kubernetes objects from new release manifest: %w", err)
}
// It is safe to use force only on target because these are resources currently rendered by the chart.
err = target.Visit(setMetadataVisitor(upgradedRelease.Name, upgradedRelease.Namespace, true))
if err != nil {
return upgradedRelease, err
}
// Do a basic diff using gvk + name to figure out what new resources are being created so we can validate they don't already exist
existingResources := make(map[string]bool)
for _, r := range current {
existingResources[objectKey(r)] = true
}
var toBeCreated kube.ResourceList
for _, r := range target {
if !existingResources[objectKey(r)] {
toBeCreated = append(toBeCreated, r)
}
}
var toBeUpdated kube.ResourceList
if u.TakeOwnership {
toBeUpdated, err = requireAdoption(toBeCreated)
} else {
toBeUpdated, err = existingResourceConflict(toBeCreated, upgradedRelease.Name, upgradedRelease.Namespace)
}
if err != nil {
return nil, fmt.Errorf("unable to continue with update: %w", err)
}
toBeUpdated.Visit(func(r *resource.Info, err error) error {
if err != nil {
return err
}
current.Append(r)
return nil
})
if isDryRun(u.DryRunStrategy) {
u.cfg.Logger().Debug("dry run for release", "name", upgradedRelease.Name)
if len(u.Description) > 0 {
upgradedRelease.Info.Description = u.Description
} else {
upgradedRelease.Info.Description = "Dry run complete"
}
return upgradedRelease, nil
}
u.cfg.Logger().Debug("creating upgraded release", "name", upgradedRelease.Name)
if err := u.cfg.Releases.Create(upgradedRelease); err != nil {
return nil, err
}
rChan := make(chan resultMessage)
ctxChan := make(chan resultMessage)
doneChan := make(chan interface{})
defer close(doneChan)
go u.releasingUpgrade(rChan, upgradedRelease, current, target, originalRelease, serverSideApply)
go u.handleContext(ctx, doneChan, ctxChan, upgradedRelease)
select {
case result := <-rChan:
return result.r, result.e
case result := <-ctxChan:
return result.r, result.e
}
}
// Function used to lock the Mutex, this is important for the case when RollbackOnFailure is set.
// In that case the upgrade will finish before the rollback is finished so it is necessary to wait for the rollback to finish.
// The rollback will be trigger by the function failRelease
func (u *Upgrade) reportToPerformUpgrade(c chan<- resultMessage, rel *release.Release, created kube.ResourceList, err error) {
u.Lock.Lock()
if err != nil {
rel, err = u.failRelease(rel, created, err)
}
c <- resultMessage{r: rel, e: err}
u.Lock.Unlock()
}
// Setup listener for SIGINT and SIGTERM
func (u *Upgrade) handleContext(ctx context.Context, done chan interface{}, c chan<- resultMessage, upgradedRelease *release.Release) {
select {
case <-ctx.Done():
err := ctx.Err()
// when RollbackOnFailure is set, the ongoing release finish first and doesn't give time for the rollback happens.
u.reportToPerformUpgrade(c, upgradedRelease, kube.ResourceList{}, err)
case <-done:
return
}
}
func isReleaseApplyMethodClientSideApply(applyMethod string) bool {
return applyMethod == "" || applyMethod == string(release.ApplyMethodClientSideApply)
}
func (u *Upgrade) releasingUpgrade(c chan<- resultMessage, upgradedRelease *release.Release, current kube.ResourceList, target kube.ResourceList, originalRelease *release.Release, serverSideApply bool) {
// pre-upgrade hooks
if !u.DisableHooks {
if err := u.cfg.execHook(upgradedRelease, release.HookPreUpgrade, u.WaitStrategy, u.Timeout, serverSideApply); err != nil {
u.reportToPerformUpgrade(c, upgradedRelease, kube.ResourceList{}, fmt.Errorf("pre-upgrade hooks failed: %s", err))
return
}
} else {
u.cfg.Logger().Debug("upgrade hooks disabled", "name", upgradedRelease.Name)
}
upgradeClientSideFieldManager := isReleaseApplyMethodClientSideApply(originalRelease.ApplyMethod) && serverSideApply // Update client-side field manager if transitioning from client-side to server-side apply
results, err := u.cfg.KubeClient.Update(
current,
target,
kube.ClientUpdateOptionForceReplace(u.ForceReplace),
kube.ClientUpdateOptionServerSideApply(serverSideApply, u.ForceConflicts),
kube.ClientUpdateOptionUpgradeClientSideFieldManager(upgradeClientSideFieldManager))
if err != nil {
u.cfg.recordRelease(originalRelease)
u.reportToPerformUpgrade(c, upgradedRelease, results.Created, err)
return
}
waiter, err := u.cfg.KubeClient.GetWaiter(u.WaitStrategy)
if err != nil {
u.cfg.recordRelease(originalRelease)
u.reportToPerformUpgrade(c, upgradedRelease, results.Created, err)
return
}
if u.WaitForJobs {
if err := waiter.WaitWithJobs(target, u.Timeout); err != nil {
u.cfg.recordRelease(originalRelease)
u.reportToPerformUpgrade(c, upgradedRelease, results.Created, err)
return
}
} else {
if err := waiter.Wait(target, u.Timeout); err != nil {
u.cfg.recordRelease(originalRelease)
u.reportToPerformUpgrade(c, upgradedRelease, results.Created, err)
return
}
}
// post-upgrade hooks
if !u.DisableHooks {
if err := u.cfg.execHook(upgradedRelease, release.HookPostUpgrade, u.WaitStrategy, u.Timeout, serverSideApply); err != nil {
u.reportToPerformUpgrade(c, upgradedRelease, results.Created, fmt.Errorf("post-upgrade hooks failed: %s", err))
return
}
}
originalRelease.Info.Status = rcommon.StatusSuperseded
u.cfg.recordRelease(originalRelease)
upgradedRelease.Info.Status = rcommon.StatusDeployed
if len(u.Description) > 0 {
upgradedRelease.Info.Description = u.Description
} else {
upgradedRelease.Info.Description = "Upgrade complete"
}
u.reportToPerformUpgrade(c, upgradedRelease, nil, nil)
}
func (u *Upgrade) failRelease(rel *release.Release, created kube.ResourceList, err error) (*release.Release, error) {
msg := fmt.Sprintf("Upgrade %q failed: %s", rel.Name, err)
u.cfg.Logger().Warn(
"upgrade failed",
slog.String("name", rel.Name),
slog.Any("error", err),
)
rel.Info.Status = rcommon.StatusFailed
rel.Info.Description = msg
u.cfg.recordRelease(rel)
if u.CleanupOnFail && len(created) > 0 {
u.cfg.Logger().Debug("cleanup on fail set", "cleaning_resources", len(created))
_, errs := u.cfg.KubeClient.Delete(created, metav1.DeletePropagationBackground)
if errs != nil {
return rel, fmt.Errorf(
"an error occurred while cleaning up resources. original upgrade error: %w: %w",
err,
fmt.Errorf(
"unable to cleanup resources: %w",
joinErrors(errs, ", "),
),
)
}
u.cfg.Logger().Debug("resource cleanup complete")
}
if u.RollbackOnFailure {
u.cfg.Logger().Debug("Upgrade failed and rollback-on-failure is set, rolling back to previous successful release")
// As a protection, get the last successful release before rollback.
// If there are no successful releases, bail out
hist := NewHistory(u.cfg)
fullHistory, herr := hist.Run(rel.Name)
if herr != nil {
return rel, fmt.Errorf("an error occurred while finding last successful release. original upgrade error: %w: %w", err, herr)
}
fullHistoryV1, herr := releaseListToV1List(fullHistory)
if herr != nil {
return nil, herr
}
// There isn't a way to tell if a previous release was successful, but
// generally failed releases do not get superseded unless the next
// release is successful, so this should be relatively safe
filteredHistory := releaseutil.FilterFunc(func(r *release.Release) bool {
return r.Info.Status == rcommon.StatusSuperseded || r.Info.Status == rcommon.StatusDeployed
}).Filter(fullHistoryV1)
if len(filteredHistory) == 0 {
return rel, fmt.Errorf("unable to find a previously successful release when attempting to rollback. original upgrade error: %w", err)
}
releaseutil.Reverse(filteredHistory, releaseutil.SortByRevision)
rollin := NewRollback(u.cfg)
rollin.Version = filteredHistory[0].Version
rollin.WaitStrategy = u.WaitStrategy
rollin.WaitForJobs = u.WaitForJobs
rollin.DisableHooks = u.DisableHooks
rollin.ForceReplace = u.ForceReplace
rollin.ForceConflicts = u.ForceConflicts
rollin.ServerSideApply = u.ServerSideApply
rollin.Timeout = u.Timeout
if rollErr := rollin.Run(rel.Name); rollErr != nil {
return rel, fmt.Errorf("an error occurred while rolling back the release. original upgrade error: %w: %w", err, rollErr)
}
return rel, fmt.Errorf("release %s failed, and has been rolled back due to rollback-on-failure being set: %w", rel.Name, err)
}
return rel, err
}
// reuseValues copies values from the current release to a new release if the
// new release does not have any values.
//
// If the request already has values, or if there are no values in the current
// release, this does nothing.
//
// This is skipped if the u.ResetValues flag is set, in which case the
// request values are not altered.
func (u *Upgrade) reuseValues(chart *chartv2.Chart, current *release.Release, newVals map[string]interface{}) (map[string]interface{}, error) {
if u.ResetValues {
// If ResetValues is set, we completely ignore current.Config.
u.cfg.Logger().Debug("resetting values to the chart's original version")
return newVals, nil
}
// If the ReuseValues flag is set, we always copy the old values over the new config's values.
if u.ReuseValues {
u.cfg.Logger().Debug("reusing the old release's values")
// We have to regenerate the old coalesced values:
oldVals, err := util.CoalesceValues(current.Chart, current.Config)
if err != nil {
return nil, fmt.Errorf("failed to rebuild old values: %w", err)
}
newVals = util.CoalesceTables(newVals, current.Config)
chart.Values = oldVals
return newVals, nil
}
// If the ResetThenReuseValues flag is set, we use the new chart's values, but we copy the old config's values over the new config's values.
if u.ResetThenReuseValues {
u.cfg.Logger().Debug("merging values from old release to new values")
newVals = util.CoalesceTables(newVals, current.Config)
return newVals, nil
}
if len(newVals) == 0 && len(current.Config) > 0 {
u.cfg.Logger().Debug("copying values from old release", "name", current.Name, "version", current.Version)
newVals = current.Config
}
return newVals, nil
}
func validateManifest(c kube.Interface, manifest []byte, openAPIValidation bool) error {
_, err := c.Build(bytes.NewReader(manifest), openAPIValidation)
return err
}
func objectKey(r *resource.Info) string {
gvk := r.Object.GetObjectKind().GroupVersionKind()
return fmt.Sprintf("%s/%s/%s/%s", gvk.GroupVersion().String(), gvk.Kind, r.Namespace, r.Name)
}
func mergeCustomLabels(current, desired map[string]string) map[string]string {
labels := mergeStrStrMaps(current, desired)
for k, v := range labels {
if v == "null" {
delete(labels, k)
}
}
return labels
}
func getUpgradeServerSideValue(serverSideOption string, releaseApplyMethod string) (bool, error) {
switch serverSideOption {
case "auto":
return releaseApplyMethod == "ssa", nil
case "false":
return false, nil
case "true":
return true, nil
default:
return false, fmt.Errorf("invalid/unknown release server-side apply method: %s", serverSideOption)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/validate_test.go | pkg/action/validate_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 action
import (
"bytes"
"io"
"net/http"
"testing"
"helm.sh/helm/v4/pkg/kube"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/meta"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/rest/fake"
)
func newDeploymentResource(name, namespace string) *resource.Info {
return &resource.Info{
Name: name,
Mapping: &meta.RESTMapping{
Resource: schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployment"},
GroupVersionKind: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"},
},
Object: &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: name,
Namespace: namespace,
},
},
}
}
func newMissingDeployment(name, namespace string) *resource.Info {
info := &resource.Info{
Name: name,
Namespace: namespace,
Mapping: &meta.RESTMapping{
Resource: schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployment"},
GroupVersionKind: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"},
Scope: meta.RESTScopeNamespace,
},
Object: &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: name,
Namespace: namespace,
},
},
Client: fakeClientWith(http.StatusNotFound, appsV1GV, ""),
}
return info
}
func newDeploymentWithOwner(name, namespace string, labels map[string]string, annotations map[string]string) *resource.Info {
obj := &appsv1.Deployment{
ObjectMeta: v1.ObjectMeta{
Name: name,
Namespace: namespace,
Labels: labels,
Annotations: annotations,
},
}
return &resource.Info{
Name: name,
Namespace: namespace,
Mapping: &meta.RESTMapping{
Resource: schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployment"},
GroupVersionKind: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"},
Scope: meta.RESTScopeNamespace,
},
Object: obj,
Client: fakeClientWith(http.StatusOK, appsV1GV, runtime.EncodeOrDie(appsv1Codec, obj)),
}
}
var (
appsV1GV = schema.GroupVersion{Group: "apps", Version: "v1"}
appsv1Codec = scheme.Codecs.CodecForVersions(scheme.Codecs.LegacyCodec(appsV1GV), scheme.Codecs.UniversalDecoder(appsV1GV), appsV1GV, appsV1GV)
)
func stringBody(body string) io.ReadCloser {
return io.NopCloser(bytes.NewReader([]byte(body)))
}
func fakeClientWith(code int, gv schema.GroupVersion, body string) *fake.RESTClient {
return &fake.RESTClient{
GroupVersion: gv,
NegotiatedSerializer: scheme.Codecs.WithoutConversion(),
Client: fake.CreateHTTPClient(func(_ *http.Request) (*http.Response, error) {
header := http.Header{}
header.Set("Content-Type", runtime.ContentTypeJSON)
return &http.Response{
StatusCode: code,
Header: header,
Body: stringBody(body),
}, nil
}),
}
}
func TestRequireAdoption(t *testing.T) {
var (
missing = newMissingDeployment("missing", "ns-a")
existing = newDeploymentWithOwner("existing", "ns-a", nil, nil)
resources = kube.ResourceList{missing, existing}
)
// Verify that a resource that lacks labels/annotations can be adopted
found, err := requireAdoption(resources)
assert.NoError(t, err)
assert.Len(t, found, 1)
assert.Equal(t, found[0], existing)
assert.NotSame(t, found[0], existing)
}
func TestExistingResourceConflict(t *testing.T) {
var (
releaseName = "rel-name"
releaseNamespace = "rel-namespace"
labels = map[string]string{
appManagedByLabel: appManagedByHelm,
}
annotations = map[string]string{
helmReleaseNameAnnotation: releaseName,
helmReleaseNamespaceAnnotation: releaseNamespace,
}
missing = newMissingDeployment("missing", "ns-a")
existing = newDeploymentWithOwner("existing", "ns-a", labels, annotations)
conflict = newDeploymentWithOwner("conflict", "ns-a", nil, nil)
resources = kube.ResourceList{missing, existing}
)
// Verify only existing resources are returned
found, err := existingResourceConflict(resources, releaseName, releaseNamespace)
assert.NoError(t, err)
assert.Len(t, found, 1)
assert.Equal(t, found[0], existing)
assert.NotSame(t, found[0], existing)
// Verify that an existing resource that lacks labels/annotations results in an error
resources = append(resources, conflict)
_, err = existingResourceConflict(resources, releaseName, releaseNamespace)
assert.Error(t, err)
}
func TestCheckOwnership(t *testing.T) {
deployFoo := newDeploymentResource("foo", "ns-a")
// Verify that a resource that lacks labels/annotations is not owned
err := checkOwnership(deployFoo.Object, "rel-a", "ns-a")
assert.EqualError(t, err, `invalid ownership metadata; label validation error: missing key "app.kubernetes.io/managed-by": must be set to "Helm"; annotation validation error: missing key "meta.helm.sh/release-name": must be set to "rel-a"; annotation validation error: missing key "meta.helm.sh/release-namespace": must be set to "ns-a"`)
// Set managed by label and verify annotation error message
_ = accessor.SetLabels(deployFoo.Object, map[string]string{
appManagedByLabel: appManagedByHelm,
})
err = checkOwnership(deployFoo.Object, "rel-a", "ns-a")
assert.EqualError(t, err, `invalid ownership metadata; annotation validation error: missing key "meta.helm.sh/release-name": must be set to "rel-a"; annotation validation error: missing key "meta.helm.sh/release-namespace": must be set to "ns-a"`)
// Set only the release name annotation and verify missing release namespace error message
_ = accessor.SetAnnotations(deployFoo.Object, map[string]string{
helmReleaseNameAnnotation: "rel-a",
})
err = checkOwnership(deployFoo.Object, "rel-a", "ns-a")
assert.EqualError(t, err, `invalid ownership metadata; annotation validation error: missing key "meta.helm.sh/release-namespace": must be set to "ns-a"`)
// Set both release name and namespace annotations and verify no ownership errors
_ = accessor.SetAnnotations(deployFoo.Object, map[string]string{
helmReleaseNameAnnotation: "rel-a",
helmReleaseNamespaceAnnotation: "ns-a",
})
err = checkOwnership(deployFoo.Object, "rel-a", "ns-a")
assert.NoError(t, err)
// Verify ownership error for wrong release name
err = checkOwnership(deployFoo.Object, "rel-b", "ns-a")
assert.EqualError(t, err, `invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-name" must equal "rel-b": current value is "rel-a"`)
// Verify ownership error for wrong release namespace
err = checkOwnership(deployFoo.Object, "rel-a", "ns-b")
assert.EqualError(t, err, `invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "ns-b": current value is "ns-a"`)
// Verify ownership error for wrong manager label
_ = accessor.SetLabels(deployFoo.Object, map[string]string{
appManagedByLabel: "helm",
})
err = checkOwnership(deployFoo.Object, "rel-a", "ns-a")
assert.EqualError(t, err, `invalid ownership metadata; label validation error: key "app.kubernetes.io/managed-by" must equal "Helm": current value is "helm"`)
}
func TestSetMetadataVisitor(t *testing.T) {
var (
err error
deployFoo = newDeploymentResource("foo", "ns-a")
deployBar = newDeploymentResource("bar", "ns-a-system")
resources = kube.ResourceList{deployFoo, deployBar}
)
// Set release tracking metadata and verify no error
err = resources.Visit(setMetadataVisitor("rel-a", "ns-a", true))
assert.NoError(t, err)
// Verify that release "b" cannot take ownership of "a"
err = resources.Visit(setMetadataVisitor("rel-b", "ns-a", false))
assert.Error(t, err)
// Force release "b" to take ownership
err = resources.Visit(setMetadataVisitor("rel-b", "ns-a", true))
assert.NoError(t, err)
// Check that there is now no ownership error when setting metadata without force
err = resources.Visit(setMetadataVisitor("rel-b", "ns-a", false))
assert.NoError(t, err)
// Add a new resource that is missing ownership metadata and verify error
resources.Append(newDeploymentResource("baz", "default"))
err = resources.Visit(setMetadataVisitor("rel-b", "ns-a", false))
assert.Error(t, err)
assert.Contains(t, err.Error(), `Deployment "baz" in namespace "" cannot be owned`)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/lazyclient.go | pkg/action/lazyclient.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 action
import (
"context"
"sync"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
applycorev1 "k8s.io/client-go/applyconfigurations/core/v1"
"k8s.io/client-go/kubernetes"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
)
// lazyClient is a workaround to deal with Kubernetes having an unstable client API.
// In Kubernetes v1.18 the defaults where removed which broke creating a
// client without an explicit configuration. ಠ_ಠ
type lazyClient struct {
// client caches an initialized kubernetes client
initClient sync.Once
client kubernetes.Interface
clientErr error
// clientFn loads a kubernetes client
clientFn func() (*kubernetes.Clientset, error)
// namespace passed to each client request
namespace string
}
func (s *lazyClient) init() error {
s.initClient.Do(func() {
s.client, s.clientErr = s.clientFn()
})
return s.clientErr
}
// secretClient implements a corev1.SecretsInterface
type secretClient struct{ *lazyClient }
var _ corev1.SecretInterface = (*secretClient)(nil)
func newSecretClient(lc *lazyClient) *secretClient {
return &secretClient{lazyClient: lc}
}
func (s *secretClient) Create(ctx context.Context, secret *v1.Secret, opts metav1.CreateOptions) (result *v1.Secret, err error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Create(ctx, secret, opts)
}
func (s *secretClient) Update(ctx context.Context, secret *v1.Secret, opts metav1.UpdateOptions) (*v1.Secret, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Update(ctx, secret, opts)
}
func (s *secretClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
if err := s.init(); err != nil {
return err
}
return s.client.CoreV1().Secrets(s.namespace).Delete(ctx, name, opts)
}
func (s *secretClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
if err := s.init(); err != nil {
return err
}
return s.client.CoreV1().Secrets(s.namespace).DeleteCollection(ctx, opts, listOpts)
}
func (s *secretClient) Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.Secret, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Get(ctx, name, opts)
}
func (s *secretClient) List(ctx context.Context, opts metav1.ListOptions) (*v1.SecretList, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).List(ctx, opts)
}
func (s *secretClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Watch(ctx, opts)
}
func (s *secretClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*v1.Secret, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Patch(ctx, name, pt, data, opts, subresources...)
}
func (s *secretClient) Apply(ctx context.Context, secretConfiguration *applycorev1.SecretApplyConfiguration, opts metav1.ApplyOptions) (*v1.Secret, error) {
if err := s.init(); err != nil {
return nil, err
}
return s.client.CoreV1().Secrets(s.namespace).Apply(ctx, secretConfiguration, opts)
}
// configMapClient implements a corev1.ConfigMapInterface
type configMapClient struct{ *lazyClient }
var _ corev1.ConfigMapInterface = (*configMapClient)(nil)
func newConfigMapClient(lc *lazyClient) *configMapClient {
return &configMapClient{lazyClient: lc}
}
func (c *configMapClient) Create(ctx context.Context, configMap *v1.ConfigMap, opts metav1.CreateOptions) (*v1.ConfigMap, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Create(ctx, configMap, opts)
}
func (c *configMapClient) Update(ctx context.Context, configMap *v1.ConfigMap, opts metav1.UpdateOptions) (*v1.ConfigMap, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Update(ctx, configMap, opts)
}
func (c *configMapClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
if err := c.init(); err != nil {
return err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Delete(ctx, name, opts)
}
func (c *configMapClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
if err := c.init(); err != nil {
return err
}
return c.client.CoreV1().ConfigMaps(c.namespace).DeleteCollection(ctx, opts, listOpts)
}
func (c *configMapClient) Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ConfigMap, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Get(ctx, name, opts)
}
func (c *configMapClient) List(ctx context.Context, opts metav1.ListOptions) (*v1.ConfigMapList, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).List(ctx, opts)
}
func (c *configMapClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Watch(ctx, opts)
}
func (c *configMapClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*v1.ConfigMap, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Patch(ctx, name, pt, data, opts, subresources...)
}
func (c *configMapClient) Apply(ctx context.Context, configMap *applycorev1.ConfigMapApplyConfiguration, opts metav1.ApplyOptions) (*v1.ConfigMap, error) {
if err := c.init(); err != nil {
return nil, err
}
return c.client.CoreV1().ConfigMaps(c.namespace).Apply(ctx, configMap, opts)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/action/push.go | pkg/action/push.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 action
import (
"io"
"strings"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/pusher"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/uploader"
)
// Push is the action for uploading a chart.
//
// It provides the implementation of 'helm push'.
type Push struct {
Settings *cli.EnvSettings
cfg *Configuration
certFile string
keyFile string
caFile string
insecureSkipTLSVerify bool
plainHTTP bool
out io.Writer
}
// PushOpt is a type of function that sets options for a push action.
type PushOpt func(*Push)
// WithPushConfig sets the cfg field on the push configuration object.
func WithPushConfig(cfg *Configuration) PushOpt {
return func(p *Push) {
p.cfg = cfg
}
}
// WithTLSClientConfig sets the certFile, keyFile, and caFile fields on the push configuration object.
func WithTLSClientConfig(certFile, keyFile, caFile string) PushOpt {
return func(p *Push) {
p.certFile = certFile
p.keyFile = keyFile
p.caFile = caFile
}
}
// WithInsecureSkipTLSVerify determines if a TLS Certificate will be checked
func WithInsecureSkipTLSVerify(insecureSkipTLSVerify bool) PushOpt {
return func(p *Push) {
p.insecureSkipTLSVerify = insecureSkipTLSVerify
}
}
// WithPlainHTTP configures the use of plain HTTP connections.
func WithPlainHTTP(plainHTTP bool) PushOpt {
return func(p *Push) {
p.plainHTTP = plainHTTP
}
}
// WithPushOptWriter sets the registryOut field on the push configuration object.
func WithPushOptWriter(out io.Writer) PushOpt {
return func(p *Push) {
p.out = out
}
}
// NewPushWithOpts creates a new push, with configuration options.
func NewPushWithOpts(opts ...PushOpt) *Push {
p := &Push{}
for _, fn := range opts {
fn(p)
}
return p
}
// Run executes 'helm push' against the given chart archive.
func (p *Push) Run(chartRef string, remote string) (string, error) {
var out strings.Builder
c := uploader.ChartUploader{
Out: &out,
Pushers: pusher.All(p.Settings),
Options: []pusher.Option{
pusher.WithTLSClientConfig(p.certFile, p.keyFile, p.caFile),
pusher.WithInsecureSkipTLSVerify(p.insecureSkipTLSVerify),
pusher.WithPlainHTTP(p.plainHTTP),
},
}
if registry.IsOCI(remote) {
// Don't use the default registry client if tls options are set.
c.Options = append(c.Options, pusher.WithRegistryClient(p.cfg.RegistryClient))
}
return out.String(), c.UploadTo(chartRef, remote)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/pusher/pusher.go | pkg/pusher/pusher.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 pusher
import (
"fmt"
"slices"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/registry"
)
// options are generic parameters to be provided to the pusher during instantiation.
//
// Pushers may or may not ignore these parameters as they are passed in.
type options struct {
registryClient *registry.Client
certFile string
keyFile string
caFile string
insecureSkipTLSVerify bool
plainHTTP bool
}
// Option allows specifying various settings configurable by the user for overriding the defaults
// used when performing Push operations with the Pusher.
type Option func(*options)
// WithRegistryClient sets the registryClient option.
func WithRegistryClient(client *registry.Client) Option {
return func(opts *options) {
opts.registryClient = client
}
}
// WithTLSClientConfig sets the client auth with the provided credentials.
func WithTLSClientConfig(certFile, keyFile, caFile string) Option {
return func(opts *options) {
opts.certFile = certFile
opts.keyFile = keyFile
opts.caFile = caFile
}
}
// WithInsecureSkipTLSVerify determines if a TLS Certificate will be checked
func WithInsecureSkipTLSVerify(insecureSkipTLSVerify bool) Option {
return func(opts *options) {
opts.insecureSkipTLSVerify = insecureSkipTLSVerify
}
}
func WithPlainHTTP(plainHTTP bool) Option {
return func(opts *options) {
opts.plainHTTP = plainHTTP
}
}
// Pusher is an interface to support upload to the specified URL.
type Pusher interface {
// Push file content by url string
Push(chartRef, url string, options ...Option) error
}
// Constructor is the function for every pusher which creates a specific instance
// according to the configuration
type Constructor func(options ...Option) (Pusher, error)
// Provider represents any pusher and the schemes that it supports.
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) (Pusher, error) {
for _, pp := range p {
if pp.Provides(scheme) {
return pp.New()
}
}
return nil, fmt.Errorf("scheme %q not supported", scheme)
}
var ociProvider = Provider{
Schemes: []string{registry.OCIScheme},
New: NewOCIPusher,
}
// All finds all of the registered pushers as a list of Provider instances.
// Currently, just the built-in pushers are collected.
func All(_ *cli.EnvSettings) Providers {
result := Providers{ociProvider}
return result
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/pusher/ocipusher_test.go | pkg/pusher/ocipusher_test.go | //go:build !windows
/*
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 pusher
import (
"io"
"os"
"path/filepath"
"strings"
"testing"
"helm.sh/helm/v4/pkg/registry"
)
func TestNewOCIPusher(t *testing.T) {
p, err := NewOCIPusher()
if err != nil {
t.Fatal(err)
}
if _, ok := p.(*OCIPusher); !ok {
t.Fatal("Expected NewOCIPusher to produce an *OCIPusher")
}
cd := "../../testdata"
join := filepath.Join
ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem")
insecureSkipTLSVerify := false
plainHTTP := false
// Test with options
p, err = NewOCIPusher(
WithTLSClientConfig(pub, priv, ca),
WithInsecureSkipTLSVerify(insecureSkipTLSVerify),
WithPlainHTTP(plainHTTP),
)
if err != nil {
t.Fatal(err)
}
op, ok := p.(*OCIPusher)
if !ok {
t.Fatal("Expected NewOCIPusher to produce an *OCIPusher")
}
if op.opts.certFile != pub {
t.Errorf("Expected NewOCIPusher to contain %q as the public key file, got %q", pub, op.opts.certFile)
}
if op.opts.keyFile != priv {
t.Errorf("Expected NewOCIPusher to contain %q as the private key file, got %q", priv, op.opts.keyFile)
}
if op.opts.caFile != ca {
t.Errorf("Expected NewOCIPusher to contain %q as the CA file, got %q", ca, op.opts.caFile)
}
if op.opts.plainHTTP != plainHTTP {
t.Errorf("Expected NewOCIPusher to have plainHTTP as %t, got %t", plainHTTP, op.opts.plainHTTP)
}
if op.opts.insecureSkipTLSVerify != insecureSkipTLSVerify {
t.Errorf("Expected NewOCIPusher to have insecureSkipVerifyTLS as %t, got %t", insecureSkipTLSVerify, op.opts.insecureSkipTLSVerify)
}
// Test if setting registryClient is being passed to the ops
registryClient, err := registry.NewClient()
if err != nil {
t.Fatal(err)
}
p, err = NewOCIPusher(
WithRegistryClient(registryClient),
)
if err != nil {
t.Fatal(err)
}
op, ok = p.(*OCIPusher)
if !ok {
t.Fatal("expected NewOCIPusher to produce an *OCIPusher")
}
if op.opts.registryClient != registryClient {
t.Errorf("Expected NewOCIPusher to contain %p as RegistryClient, got %p", registryClient, op.opts.registryClient)
}
}
func TestOCIPusher_Push_ErrorHandling(t *testing.T) {
tests := []struct {
name string
chartRef string
expectedError string
setupFunc func() string
}{
{
name: "non-existent file",
chartRef: "/non/existent/file.tgz",
expectedError: "no such file",
},
{
name: "directory instead of file",
expectedError: "cannot push directory, must provide chart archive (.tgz)",
setupFunc: func() string {
tempDir := t.TempDir()
return tempDir
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pusher, err := NewOCIPusher()
if err != nil {
t.Fatal(err)
}
chartRef := tt.chartRef
if tt.setupFunc != nil {
chartRef = tt.setupFunc()
}
err = pusher.Push(chartRef, "oci://localhost:5000/test")
if err == nil {
t.Fatal("Expected error but got none")
}
if !strings.Contains(err.Error(), tt.expectedError) {
t.Errorf("Expected error containing %q, got %q", tt.expectedError, err.Error())
}
})
}
}
func TestOCIPusher_newRegistryClient(t *testing.T) {
cd := "../../testdata"
join := filepath.Join
ca, pub, priv := join(cd, "rootca.crt"), join(cd, "crt.pem"), join(cd, "key.pem")
tests := []struct {
name string
opts []Option
expectError bool
errorContains string
}{
{
name: "plain HTTP",
opts: []Option{WithPlainHTTP(true)},
},
{
name: "with TLS client config",
opts: []Option{
WithTLSClientConfig(pub, priv, ca),
},
},
{
name: "with insecure skip TLS verify",
opts: []Option{
WithInsecureSkipTLSVerify(true),
},
},
{
name: "with cert and key only",
opts: []Option{
WithTLSClientConfig(pub, priv, ""),
},
},
{
name: "with CA file only",
opts: []Option{
WithTLSClientConfig("", "", ca),
},
},
{
name: "default client without options",
opts: []Option{},
},
{
name: "invalid cert file",
opts: []Option{
WithTLSClientConfig("/non/existent/cert.pem", priv, ca),
},
expectError: true,
errorContains: "can't create TLS config",
},
{
name: "invalid key file",
opts: []Option{
WithTLSClientConfig(pub, "/non/existent/key.pem", ca),
},
expectError: true,
errorContains: "can't create TLS config",
},
{
name: "invalid CA file",
opts: []Option{
WithTLSClientConfig("", "", "/non/existent/ca.crt"),
},
expectError: true,
errorContains: "can't create TLS config",
},
{
name: "combined TLS options",
opts: []Option{
WithTLSClientConfig(pub, priv, ca),
WithInsecureSkipTLSVerify(true),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
pusher, err := NewOCIPusher(tt.opts...)
if err != nil {
t.Fatal(err)
}
op, ok := pusher.(*OCIPusher)
if !ok {
t.Fatal("Expected *OCIPusher")
}
client, err := op.newRegistryClient()
if tt.expectError {
if err == nil {
t.Fatal("Expected error but got none")
}
if tt.errorContains != "" && !strings.Contains(err.Error(), tt.errorContains) {
t.Errorf("Expected error containing %q, got %q", tt.errorContains, err.Error())
}
} else {
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if client == nil {
t.Fatal("Expected non-nil registry client")
}
}
})
}
}
func TestOCIPusher_Push_ChartOperations(t *testing.T) {
// Path to test charts
chartPath := "../../pkg/cmd/testdata/testcharts/compressedchart-0.1.0.tgz"
chartWithProvPath := "../../pkg/cmd/testdata/testcharts/signtest-0.1.0.tgz"
tests := []struct {
name string
chartRef string
href string
options []Option
setupFunc func(t *testing.T) (string, func())
expectError bool
errorContains string
}{
{
name: "invalid chart file",
chartRef: "../../pkg/action/testdata/charts/corrupted-compressed-chart.tgz",
href: "oci://localhost:5000/test",
expectError: true,
errorContains: "does not appear to be a gzipped archive",
},
{
name: "chart read error",
setupFunc: func(t *testing.T) (string, func()) {
t.Helper()
// Create a valid chart file that we'll make unreadable
tempDir := t.TempDir()
tempChart := filepath.Join(tempDir, "temp-chart.tgz")
// Copy a valid chart
src, err := os.Open(chartPath)
if err != nil {
t.Fatal(err)
}
defer src.Close()
dst, err := os.Create(tempChart)
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(dst, src); err != nil {
t.Fatal(err)
}
dst.Close()
// Make the file unreadable
if err := os.Chmod(tempChart, 0000); err != nil {
t.Fatal(err)
}
return tempChart, func() {
os.Chmod(tempChart, 0644) // Restore permissions for cleanup
}
},
href: "oci://localhost:5000/test",
expectError: true,
errorContains: "permission denied",
},
{
name: "push with provenance file - loading phase",
chartRef: chartWithProvPath,
href: "oci://registry.example.com/charts",
setupFunc: func(t *testing.T) (string, func()) {
t.Helper()
// Copy chart and create a .prov file for it
tempDir := t.TempDir()
tempChart := filepath.Join(tempDir, "signtest-0.1.0.tgz")
tempProv := filepath.Join(tempDir, "signtest-0.1.0.tgz.prov")
// Copy chart file
src, err := os.Open(chartWithProvPath)
if err != nil {
t.Fatal(err)
}
defer src.Close()
dst, err := os.Create(tempChart)
if err != nil {
t.Fatal(err)
}
if _, err := io.Copy(dst, src); err != nil {
t.Fatal(err)
}
dst.Close()
// Create provenance file
if err := os.WriteFile(tempProv, []byte("test provenance data"), 0644); err != nil {
t.Fatal(err)
}
return tempChart, func() {}
},
expectError: true, // Will fail at the registry push step
errorContains: "", // Error depends on registry client behavior
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
chartRef := tt.chartRef
var cleanup func()
if tt.setupFunc != nil {
chartRef, cleanup = tt.setupFunc(t)
if cleanup != nil {
defer cleanup()
}
}
// Skip test if chart file doesn't exist and we're not expecting an error
if _, err := os.Stat(chartRef); err != nil && !tt.expectError {
t.Skipf("Test chart %s not found, skipping test", chartRef)
}
pusher, err := NewOCIPusher(tt.options...)
if err != nil {
t.Fatal(err)
}
err = pusher.Push(chartRef, tt.href)
if tt.expectError {
if err == nil {
t.Fatal("Expected error but got none")
}
if tt.errorContains != "" && !strings.Contains(err.Error(), tt.errorContains) {
t.Errorf("Expected error containing %q, got %q", tt.errorContains, err.Error())
}
} else {
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
}
})
}
}
func TestOCIPusher_Push_MultipleOptions(t *testing.T) {
chartPath := "../../pkg/cmd/testdata/testcharts/compressedchart-0.1.0.tgz"
// Skip test if chart file doesn't exist
if _, err := os.Stat(chartPath); err != nil {
t.Skipf("Test chart %s not found, skipping test", chartPath)
}
pusher, err := NewOCIPusher()
if err != nil {
t.Fatal(err)
}
// Test that multiple options are applied correctly
err = pusher.Push(chartPath, "oci://localhost:5000/test",
WithPlainHTTP(true),
WithInsecureSkipTLSVerify(true),
)
// We expect an error since we're not actually pushing to a registry
if err == nil {
t.Fatal("Expected error when pushing without a valid registry")
}
// Verify options were applied
op := pusher.(*OCIPusher)
if !op.opts.plainHTTP {
t.Error("Expected plainHTTP option to be applied")
}
if !op.opts.insecureSkipTLSVerify {
t.Error("Expected insecureSkipTLSVerify option to be applied")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/pusher/pusher_test.go | pkg/pusher/pusher_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 pusher
import (
"testing"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/registry"
)
func TestProvider(t *testing.T) {
p := Provider{
[]string{"one", "three"},
func(_ ...Option) (Pusher, 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) (Pusher, error) { return nil, nil }},
{[]string{"two", "four"}, func(_ ...Option) (Pusher, 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 TestAll(t *testing.T) {
env := cli.New()
all := All(env)
if len(all) != 1 {
t.Errorf("expected 1 provider (OCI), got %d", len(all))
}
}
func TestByScheme(t *testing.T) {
env := cli.New()
g := All(env)
if _, err := g.ByScheme(registry.OCIScheme); 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/pusher/ocipusher.go | pkg/pusher/ocipusher.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 pusher
import (
"errors"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"path"
"strings"
"time"
"helm.sh/helm/v4/internal/tlsutil"
"helm.sh/helm/v4/pkg/chart/v2/loader"
"helm.sh/helm/v4/pkg/registry"
)
// OCIPusher is the default OCI backend handler
type OCIPusher struct {
opts options
}
// Push performs a Push from repo.Pusher.
func (pusher *OCIPusher) Push(chartRef, href string, options ...Option) error {
for _, opt := range options {
opt(&pusher.opts)
}
return pusher.push(chartRef, href)
}
func (pusher *OCIPusher) push(chartRef, href string) error {
stat, err := os.Stat(chartRef)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("%s: no such file", chartRef)
}
return err
}
if stat.IsDir() {
return errors.New("cannot push directory, must provide chart archive (.tgz)")
}
meta, err := loader.Load(chartRef)
if err != nil {
return err
}
client := pusher.opts.registryClient
if client == nil {
c, err := pusher.newRegistryClient()
if err != nil {
return err
}
client = c
}
chartBytes, err := os.ReadFile(chartRef)
if err != nil {
return err
}
var pushOpts []registry.PushOption
provRef := fmt.Sprintf("%s.prov", chartRef)
if _, err := os.Stat(provRef); err == nil {
provBytes, err := os.ReadFile(provRef)
if err != nil {
return err
}
pushOpts = append(pushOpts, registry.PushOptProvData(provBytes))
}
ref := fmt.Sprintf("%s:%s",
path.Join(strings.TrimPrefix(href, fmt.Sprintf("%s://", registry.OCIScheme)), meta.Metadata.Name),
meta.Metadata.Version)
// The time the chart was "created" is semantically the time the chart archive file was last written(modified)
chartArchiveFileCreatedTime := stat.ModTime()
pushOpts = append(pushOpts, registry.PushOptCreationTime(chartArchiveFileCreatedTime.Format(time.RFC3339)))
_, err = client.Push(chartBytes, ref, pushOpts...)
return err
}
// NewOCIPusher constructs a valid OCI client as a Pusher
func NewOCIPusher(ops ...Option) (Pusher, error) {
var client OCIPusher
for _, opt := range ops {
opt(&client.opts)
}
return &client, nil
}
func (pusher *OCIPusher) newRegistryClient() (*registry.Client, error) {
if (pusher.opts.certFile != "" && pusher.opts.keyFile != "") || pusher.opts.caFile != "" || pusher.opts.insecureSkipTLSVerify {
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(pusher.opts.insecureSkipTLSVerify),
tlsutil.WithCertKeyPairFiles(pusher.opts.certFile, pusher.opts.keyFile),
tlsutil.WithCAFile(pusher.opts.caFile),
)
if err != nil {
return nil, fmt.Errorf("can't create TLS config for client: %w", err)
}
registryClient, err := registry.NewClient(
registry.ClientOptHTTPClient(&http.Client{
// From https://github.com/google/go-containerregistry/blob/31786c6cbb82d6ec4fb8eb79cd9387905130534e/pkg/v1/remote/options.go#L87
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
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,
TLSClientConfig: tlsConf,
},
}),
registry.ClientOptEnableCache(true),
)
if err != nil {
return nil, err
}
return registryClient, nil
}
opts := []registry.ClientOption{registry.ClientOptEnableCache(true)}
if pusher.opts.plainHTTP {
opts = append(opts, registry.ClientOptPlainHTTP())
}
registryClient, err := registry.NewClient(opts...)
if err != nil {
return nil, err
}
return registryClient, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/pusher/doc.go | pkg/pusher/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 pusher provides a generalized tool for uploading data by scheme.
This provides a method by which the plugin system can load arbitrary protocol
handlers based upon a URL scheme.
*/
package pusher
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/ignore/rules_test.go | pkg/ignore/rules_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 ignore
import (
"bytes"
"os"
"path/filepath"
"testing"
)
var testdata = "./testdata"
func TestParse(t *testing.T) {
rules := `#ignore
#ignore
foo
bar/*
baz/bar/foo.txt
one/more
`
r, err := parseString(rules)
if err != nil {
t.Fatalf("Error parsing rules: %s", err)
}
if len(r.patterns) != 4 {
t.Errorf("Expected 4 rules, got %d", len(r.patterns))
}
expects := []string{"foo", "bar/*", "baz/bar/foo.txt", "one/more"}
for i, p := range r.patterns {
if p.raw != expects[i] {
t.Errorf("Expected %q, got %q", expects[i], p.raw)
}
if p.match == nil {
t.Errorf("Expected %s to have a matcher function.", p.raw)
}
}
}
func TestParseFail(t *testing.T) {
shouldFail := []string{"foo/**/bar", "[z-"}
for _, fail := range shouldFail {
_, err := parseString(fail)
if err == nil {
t.Errorf("Rule %q should have failed", fail)
}
}
}
func TestParseFile(t *testing.T) {
f := filepath.Join(testdata, HelmIgnore)
if _, err := os.Stat(f); err != nil {
t.Fatalf("Fixture %s missing: %s", f, err)
}
r, err := ParseFile(f)
if err != nil {
t.Fatalf("Failed to parse rules file: %s", err)
}
if len(r.patterns) != 3 {
t.Errorf("Expected 3 patterns, got %d", len(r.patterns))
}
}
func TestIgnore(t *testing.T) {
// Test table: Given pattern and name, Ignore should return expect.
tests := []struct {
pattern string
name string
expect bool
}{
// Glob tests
{`helm.txt`, "helm.txt", true},
{`helm.*`, "helm.txt", true},
{`helm.*`, "rudder.txt", false},
{`*.txt`, "tiller.txt", true},
{`*.txt`, "cargo/a.txt", true},
{`cargo/*.txt`, "cargo/a.txt", true},
{`cargo/*.*`, "cargo/a.txt", true},
{`cargo/*.txt`, "mast/a.txt", false},
{`ru[c-e]?er.txt`, "rudder.txt", true},
{`templates/.?*`, "templates/.dotfile", true},
// "." should never get ignored. https://github.com/helm/helm/issues/1776
{`.*`, ".", false},
{`.*`, "./", false},
{`.*`, ".joonix", true},
{`.*`, "helm.txt", false},
{`.*`, "", false},
// Directory tests
{`cargo/`, "cargo", true},
{`cargo/`, "cargo/", true},
{`cargo/`, "mast/", false},
{`helm.txt/`, "helm.txt", false},
// Negation tests
{`!helm.txt`, "helm.txt", false},
{`!helm.txt`, "tiller.txt", true},
{`!*.txt`, "cargo", true},
{`!cargo/`, "mast/", true},
// Absolute path tests
{`/a.txt`, "a.txt", true},
{`/a.txt`, "cargo/a.txt", false},
{`/cargo/a.txt`, "cargo/a.txt", true},
}
for _, test := range tests {
r, err := parseString(test.pattern)
if err != nil {
t.Fatalf("Failed to parse: %s", err)
}
fi, err := os.Stat(filepath.Join(testdata, test.name))
if err != nil {
t.Fatalf("Fixture missing: %s", err)
}
if r.Ignore(test.name, fi) != test.expect {
t.Errorf("Expected %q to be %v for pattern %q", test.name, test.expect, test.pattern)
}
}
}
func TestAddDefaults(t *testing.T) {
r := Rules{}
r.AddDefaults()
if len(r.patterns) != 1 {
t.Errorf("Expected 1 default patterns, got %d", len(r.patterns))
}
}
func parseString(str string) (*Rules, error) {
b := bytes.NewBuffer([]byte(str))
return Parse(b)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/ignore/rules.go | pkg/ignore/rules.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 ignore
import (
"bufio"
"bytes"
"errors"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
)
// HelmIgnore default name of an ignorefile.
const HelmIgnore = ".helmignore"
// Rules is a collection of path matching rules.
//
// Parse() and ParseFile() will construct and populate new Rules.
// Empty() will create an immutable empty ruleset.
type Rules struct {
patterns []*pattern
}
// Empty builds an empty ruleset.
func Empty() *Rules {
return &Rules{patterns: []*pattern{}}
}
// AddDefaults adds default ignore patterns.
//
// Ignore all dotfiles in "templates/"
func (r *Rules) AddDefaults() {
r.parseRule(`templates/.?*`)
}
// ParseFile parses a helmignore file and returns the *Rules.
func ParseFile(file string) (*Rules, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
return Parse(f)
}
// Parse parses a rules file
func Parse(file io.Reader) (*Rules, error) {
r := &Rules{patterns: []*pattern{}}
s := bufio.NewScanner(file)
currentLine := 0
utf8bom := []byte{0xEF, 0xBB, 0xBF}
for s.Scan() {
scannedBytes := s.Bytes()
// We trim UTF8 BOM
if currentLine == 0 {
scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
}
line := string(scannedBytes)
currentLine++
if err := r.parseRule(line); err != nil {
return r, err
}
}
return r, s.Err()
}
// Ignore evaluates the file at the given path, and returns true if it should be ignored.
//
// Ignore evaluates path against the rules in order. Evaluation stops when a match
// is found. Matching a negative rule will stop evaluation.
func (r *Rules) Ignore(path string, fi os.FileInfo) bool {
// Don't match on empty dirs.
if path == "" {
return false
}
// Disallow ignoring the current working directory.
// See issue:
// 1776 (New York City) Hamilton: "Pardon me, are you Aaron Burr, sir?"
if path == "." || path == "./" {
return false
}
for _, p := range r.patterns {
if p.match == nil {
slog.Info("this will be ignored no matcher supplied", "patterns", p.raw)
return false
}
// For negative rules, we need to capture and return non-matches,
// and continue for matches.
if p.negate {
if p.mustDir && !fi.IsDir() {
return true
}
if !p.match(path, fi) {
return true
}
continue
}
// If the rule is looking for directories, and this is not a directory,
// skip it.
if p.mustDir && !fi.IsDir() {
continue
}
if p.match(path, fi) {
return true
}
}
return false
}
// parseRule parses a rule string and creates a pattern, which is then stored in the Rules object.
func (r *Rules) parseRule(rule string) error {
rule = strings.TrimSpace(rule)
// Ignore blank lines
if rule == "" {
return nil
}
// Comment
if strings.HasPrefix(rule, "#") {
return nil
}
// Fail any rules that contain **
if strings.Contains(rule, "**") {
return errors.New("double-star (**) syntax is not supported")
}
// Fail any patterns that can't compile. A non-empty string must be
// given to Match() to avoid optimization that skips rule evaluation.
if _, err := filepath.Match(rule, "abc"); err != nil {
return err
}
p := &pattern{raw: rule}
// Negation is handled at a higher level, so strip the leading ! from the
// string.
if strings.HasPrefix(rule, "!") {
p.negate = true
rule = rule[1:]
}
// Directory verification is handled by a higher level, so the trailing /
// is removed from the rule. That way, a directory named "foo" matches,
// even if the supplied string does not contain a literal slash character.
if strings.HasSuffix(rule, "/") {
p.mustDir = true
rule = strings.TrimSuffix(rule, "/")
}
if after, ok := strings.CutPrefix(rule, "/"); ok {
// Require path matches the root path.
p.match = func(n string, _ os.FileInfo) bool {
rule = after
ok, err := filepath.Match(rule, n)
if err != nil {
slog.Error("failed to compile", slog.String("rule", rule), slog.Any("error", err))
return false
}
return ok
}
} else if strings.Contains(rule, "/") {
// require structural match.
p.match = func(n string, _ os.FileInfo) bool {
ok, err := filepath.Match(rule, n)
if err != nil {
slog.Error(
"failed to compile",
slog.String("rule", rule),
slog.Any("error", err),
)
return false
}
return ok
}
} else {
p.match = func(n string, _ os.FileInfo) bool {
// When there is no slash in the pattern, we evaluate ONLY the
// filename.
n = filepath.Base(n)
ok, err := filepath.Match(rule, n)
if err != nil {
slog.Error("failed to compile", slog.String("rule", rule), slog.Any("error", err))
return false
}
return ok
}
}
r.patterns = append(r.patterns, p)
return nil
}
// matcher is a function capable of computing a match.
//
// It returns true if the rule matches.
type matcher func(name string, fi os.FileInfo) bool
// pattern describes a pattern to be matched in a rule set.
type pattern struct {
// raw is the unparsed string, with nothing stripped.
raw string
// match is the matcher function.
match matcher
// negate indicates that the rule's outcome should be negated.
negate bool
// mustDir indicates that the matched file must be a directory.
mustDir bool
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/ignore/doc.go | pkg/ignore/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 ignore provides tools for writing ignore files (a la .gitignore).
This provides both an ignore parser and a file-aware processor.
The format of ignore files closely follows, but does not exactly match, the
format for .gitignore files (https://git-scm.com/docs/gitignore).
The formatting rules are as follows:
- Parsing is line-by-line
- Empty lines are ignored
- Lines that begin with # (comments) will be ignored
- Leading and trailing spaces are always ignored
- Inline comments are NOT supported ('foo* # Any foo' does not contain a comment)
- There is no support for multi-line patterns
- Shell glob patterns are supported. See Go's "path/filepath".Match
- If a pattern begins with a leading !, the match will be negated.
- If a pattern begins with a leading /, only paths relatively rooted will match.
- If the pattern ends with a trailing /, only directories will match
- If a pattern contains no slashes, file basenames are tested (not paths)
- The pattern sequence "**", while legal in a glob, will cause an error here
(to indicate incompatibility with .gitignore).
Example:
# Match any file named foo.txt
foo.txt
# Match any text file
*.txt
# Match only directories named mydir
mydir/
# Match only text files in the top-level directory
/*.txt
# Match only the file foo.txt in the top-level directory
/foo.txt
# Match any file named ab.txt, ac.txt, or ad.txt
a[b-d].txt
Notable differences from .gitignore:
- The '**' syntax is not supported.
- The globbing library is Go's 'filepath.Match', not fnmatch(3)
- Trailing spaces are always ignored (there is no supported escape sequence)
- The evaluation of escape sequences has not been tested for compatibility
- There is no support for '\!' as a special leading sequence.
*/
package ignore // import "helm.sh/helm/v4/pkg/ignore"
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/index.go | pkg/repo/v1/index.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 repo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"log/slog"
"os"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/internal/fileutil"
"helm.sh/helm/v4/internal/urlutil"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
"helm.sh/helm/v4/pkg/provenance"
)
// APIVersionV1 is the v1 API version for index and repository files.
const APIVersionV1 = "v1"
var (
// ErrNoAPIVersion indicates that an API version was not specified.
ErrNoAPIVersion = errors.New("no API version specified")
// ErrNoChartVersion indicates that a chart with the given version is not found.
ErrNoChartVersion = errors.New("no chart version found")
// ErrNoChartName indicates that a chart with the given name is not found.
ErrNoChartName = errors.New("no chart name found")
// ErrEmptyIndexYaml indicates that the content of index.yaml is empty.
ErrEmptyIndexYaml = errors.New("empty index.yaml file")
)
// ChartVersions is a list of versioned chart references.
// Implements a sorter on Version.
type ChartVersions []*ChartVersion
// Len returns the length.
func (c ChartVersions) Len() int { return len(c) }
// Swap swaps the position of two items in the versions slice.
func (c ChartVersions) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
// Less returns true if the version of entry a is less than the version of entry b.
func (c ChartVersions) Less(a, b int) bool {
// Failed parse pushes to the back.
i, err := semver.NewVersion(c[a].Version)
if err != nil {
return true
}
j, err := semver.NewVersion(c[b].Version)
if err != nil {
return false
}
return i.LessThan(j)
}
// IndexFile represents the index file in a chart repository
type IndexFile struct {
// This is used ONLY for validation against chartmuseum's index files and is discarded after validation.
ServerInfo map[string]interface{} `json:"serverInfo,omitempty"`
APIVersion string `json:"apiVersion"`
Generated time.Time `json:"generated"`
Entries map[string]ChartVersions `json:"entries"`
PublicKeys []string `json:"publicKeys,omitempty"`
// Annotations are additional mappings uninterpreted by Helm. They are made available for
// other applications to add information to the index file.
Annotations map[string]string `json:"annotations,omitempty"`
}
// NewIndexFile initializes an index.
func NewIndexFile() *IndexFile {
return &IndexFile{
APIVersion: APIVersionV1,
Generated: time.Now(),
Entries: map[string]ChartVersions{},
PublicKeys: []string{},
}
}
// LoadIndexFile takes a file at the given path and returns an IndexFile object
func LoadIndexFile(path string) (*IndexFile, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
i, err := loadIndex(b, path)
if err != nil {
return nil, fmt.Errorf("error loading %s: %w", path, err)
}
return i, nil
}
// MustAdd adds a file to the index
// This can leave the index in an unsorted state
func (i IndexFile) MustAdd(md *chart.Metadata, filename, baseURL, digest string) error {
if i.Entries == nil {
return errors.New("entries not initialized")
}
if md.APIVersion == "" {
md.APIVersion = chart.APIVersionV1
}
if err := md.Validate(); err != nil {
return fmt.Errorf("validate failed for %s: %w", filename, err)
}
u := filename
if baseURL != "" {
_, file := filepath.Split(filename)
var err error
u, err = urlutil.URLJoin(baseURL, file)
if err != nil {
u = path.Join(baseURL, file)
}
}
cr := &ChartVersion{
URLs: []string{u},
Metadata: md,
Digest: digest,
Created: time.Now(),
}
ee := i.Entries[md.Name]
i.Entries[md.Name] = append(ee, cr)
return nil
}
// Add adds a file to the index and logs an error.
//
// Deprecated: Use index.MustAdd instead.
func (i IndexFile) Add(md *chart.Metadata, filename, baseURL, digest string) {
if err := i.MustAdd(md, filename, baseURL, digest); err != nil {
slog.Error("skipping loading invalid entry for chart %q %q from %s: %s", md.Name, md.Version, filename, err)
}
}
// Has returns true if the index has an entry for a chart with the given name and exact version.
func (i IndexFile) Has(name, version string) bool {
_, err := i.Get(name, version)
return err == nil
}
// SortEntries sorts the entries by version in descending order.
//
// In canonical form, the individual version records should be sorted so that
// the most recent release for every version is in the 0th slot in the
// Entries.ChartVersions array. That way, tooling can predict the newest
// version without needing to parse SemVers.
func (i IndexFile) SortEntries() {
for _, versions := range i.Entries {
sort.Sort(sort.Reverse(versions))
}
}
// Get returns the ChartVersion for the given name.
//
// If version is empty, this will return the chart with the latest stable version,
// prerelease versions will be skipped.
func (i IndexFile) Get(name, version string) (*ChartVersion, error) {
vs, ok := i.Entries[name]
if !ok {
return nil, ErrNoChartName
}
if len(vs) == 0 {
return nil, ErrNoChartVersion
}
var constraint *semver.Constraints
if version == "" {
constraint, _ = semver.NewConstraint("*")
} else {
var err error
constraint, err = semver.NewConstraint(version)
if err != nil {
return nil, err
}
}
// when customer inputs specific version, check whether there's an exact match first
if len(version) != 0 {
for _, ver := range vs {
if version == ver.Version {
return ver, nil
}
}
}
for _, ver := range vs {
test, err := semver.NewVersion(ver.Version)
if err != nil {
continue
}
if constraint.Check(test) {
if len(version) != 0 {
slog.Warn("unable to find exact version requested; falling back to closest available version", "chart", name, "requested", version, "selected", ver.Version)
}
return ver, nil
}
}
return nil, fmt.Errorf("no chart version found for %s-%s", name, version)
}
// WriteFile writes an index file to the given destination path.
//
// The mode on the file is set to 'mode'.
func (i IndexFile) WriteFile(dest string, mode os.FileMode) error {
b, err := yaml.Marshal(i)
if err != nil {
return err
}
return fileutil.AtomicWriteFile(dest, bytes.NewReader(b), mode)
}
// WriteJSONFile writes an index file in JSON format to the given destination
// path.
//
// The mode on the file is set to 'mode'.
func (i IndexFile) WriteJSONFile(dest string, mode os.FileMode) error {
b, err := json.MarshalIndent(i, "", " ")
if err != nil {
return err
}
return fileutil.AtomicWriteFile(dest, bytes.NewReader(b), mode)
}
// Merge merges the given index file into this index.
//
// This merges by name and version.
//
// If one of the entries in the given index does _not_ already exist, it is added.
// In all other cases, the existing record is preserved.
//
// This can leave the index in an unsorted state
func (i *IndexFile) Merge(f *IndexFile) {
for _, cvs := range f.Entries {
for _, cv := range cvs {
if !i.Has(cv.Name, cv.Version) {
e := i.Entries[cv.Name]
i.Entries[cv.Name] = append(e, cv)
}
}
}
}
// ChartVersion represents a chart entry in the IndexFile
type ChartVersion struct {
*chart.Metadata
URLs []string `json:"urls"`
Created time.Time `json:"created,omitempty"`
Removed bool `json:"removed,omitempty"`
Digest string `json:"digest,omitempty"`
// ChecksumDeprecated is deprecated in Helm 3, and therefore ignored. Helm 3 replaced
// this with Digest. However, with a strict YAML parser enabled, a field must be
// present on the struct for backwards compatibility.
ChecksumDeprecated string `json:"checksum,omitempty"`
// EngineDeprecated is deprecated in Helm 3, and therefore ignored. However, with a strict
// YAML parser enabled, this field must be present.
EngineDeprecated string `json:"engine,omitempty"`
// TillerVersionDeprecated is deprecated in Helm 3, and therefore ignored. However, with a strict
// YAML parser enabled, this field must be present.
TillerVersionDeprecated string `json:"tillerVersion,omitempty"`
// URLDeprecated is deprecated in Helm 3, superseded by URLs. It is ignored. However,
// with a strict YAML parser enabled, this must be present on the struct.
URLDeprecated string `json:"url,omitempty"`
}
// IndexDirectory reads a (flat) directory and generates an index.
//
// It indexes only charts that have been packaged (*.tgz).
//
// The index returned will be in an unsorted state
func IndexDirectory(dir, baseURL string) (*IndexFile, error) {
archives, err := filepath.Glob(filepath.Join(dir, "*.tgz"))
if err != nil {
return nil, err
}
moreArchives, err := filepath.Glob(filepath.Join(dir, "**/*.tgz"))
if err != nil {
return nil, err
}
archives = append(archives, moreArchives...)
index := NewIndexFile()
for _, arch := range archives {
fname, err := filepath.Rel(dir, arch)
if err != nil {
return index, err
}
var parentDir string
parentDir, fname = filepath.Split(fname)
// filepath.Split appends an extra slash to the end of parentDir. We want to strip that out.
parentDir = strings.TrimSuffix(parentDir, string(os.PathSeparator))
parentURL, err := urlutil.URLJoin(baseURL, parentDir)
if err != nil {
parentURL = path.Join(baseURL, parentDir)
}
c, err := loader.Load(arch)
if err != nil {
// Assume this is not a chart.
continue
}
hash, err := provenance.DigestFile(arch)
if err != nil {
return index, err
}
if err := index.MustAdd(c.Metadata, fname, parentURL, hash); err != nil {
return index, fmt.Errorf("failed adding to %s to index: %w", fname, err)
}
}
return index, nil
}
// loadIndex loads an index file and does minimal validity checking.
//
// The source parameter is only used for logging.
// This will fail if API Version is not set (ErrNoAPIVersion) or if the unmarshal fails.
func loadIndex(data []byte, source string) (*IndexFile, error) {
i := &IndexFile{}
if len(data) == 0 {
return i, ErrEmptyIndexYaml
}
if err := jsonOrYamlUnmarshal(data, i); err != nil {
return i, err
}
for name, cvs := range i.Entries {
for idx := len(cvs) - 1; idx >= 0; idx-- {
if cvs[idx] == nil {
slog.Warn(fmt.Sprintf("skipping loading invalid entry for chart %q from %s: empty entry", name, source))
cvs = append(cvs[:idx], cvs[idx+1:]...)
continue
}
// When metadata section missing, initialize with no data
if cvs[idx].Metadata == nil {
cvs[idx].Metadata = &chart.Metadata{}
}
if cvs[idx].APIVersion == "" {
cvs[idx].APIVersion = chart.APIVersionV1
}
if err := cvs[idx].Validate(); ignoreSkippableChartValidationError(err) != nil {
slog.Warn(fmt.Sprintf("skipping loading invalid entry for chart %q %q from %s: %s", name, cvs[idx].Version, source, err))
cvs = append(cvs[:idx], cvs[idx+1:]...)
}
}
// adjust slice to only contain a set of valid versions
i.Entries[name] = cvs
}
i.SortEntries()
if i.APIVersion == "" {
return i, ErrNoAPIVersion
}
return i, nil
}
// jsonOrYamlUnmarshal unmarshals the given byte slice containing JSON or YAML
// into the provided interface.
//
// It automatically detects whether the data is in JSON or YAML format by
// checking its validity as JSON. If the data is valid JSON, it will use the
// `encoding/json` package to unmarshal it. Otherwise, it will use the
// `sigs.k8s.io/yaml` package to unmarshal the YAML data.
func jsonOrYamlUnmarshal(b []byte, i interface{}) error {
if json.Valid(b) {
return json.Unmarshal(b, i)
}
return yaml.UnmarshalStrict(b, i)
}
// ignoreSkippableChartValidationError inspect the given error and returns nil if
// the error isn't important for index loading
//
// In particular, charts may introduce validations that don't impact repository indexes
// And repository indexes may be generated by older/non-compliant software, which doesn't
// conform to all validations.
func ignoreSkippableChartValidationError(err error) error {
verr, ok := err.(chart.ValidationError)
if !ok {
return err
}
// https://github.com/helm/helm/issues/12748 (JFrog repository strips alias field)
if strings.HasPrefix(verr.Error(), "validation: more than one dependency with name or alias") {
return nil
}
return err
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/error.go | pkg/repo/v1/error.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 repo
import (
"fmt"
)
type ChartNotFoundError struct {
RepoURL string
Chart string
}
func (e ChartNotFoundError) Error() string {
return fmt.Sprintf("%s not found in %s repository", e.Chart, e.RepoURL)
}
func (e ChartNotFoundError) Is(err error) bool {
_, ok := err.(ChartNotFoundError)
return ok
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/index_test.go | pkg/repo/v1/index_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 repo
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"testing"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/helmpath"
)
const (
testfile = "testdata/local-index.yaml"
annotationstestfile = "testdata/local-index-annotations.yaml"
chartmuseumtestfile = "testdata/chartmuseum-index.yaml"
unorderedTestfile = "testdata/local-index-unordered.yaml"
jsonTestfile = "testdata/local-index.json"
testRepo = "test-repo"
indexWithDuplicates = `
apiVersion: v1
entries:
nginx:
- urls:
- https://charts.helm.sh/stable/nginx-0.2.0.tgz
name: nginx
description: string
version: 0.2.0
home: https://github.com/something/else
digest: "sha256:1234567890abcdef"
nginx:
- urls:
- https://charts.helm.sh/stable/alpine-1.0.0.tgz
- http://storage2.googleapis.com/kubernetes-charts/alpine-1.0.0.tgz
name: alpine
description: string
version: 1.0.0
home: https://github.com/something
digest: "sha256:1234567890abcdef"
`
indexWithEmptyEntry = `
apiVersion: v1
entries:
grafana:
- apiVersion: v2
name: grafana
- null
foo:
-
bar:
- digest: "sha256:1234567890abcdef"
urls:
- https://charts.helm.sh/stable/alpine-1.0.0.tgz
`
)
func TestIndexFile(t *testing.T) {
i := NewIndexFile()
for _, x := range []struct {
md *chart.Metadata
filename string
baseURL string
digest string
}{
{&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"},
{&chart.Metadata{APIVersion: "v2", Name: "cutter", Version: "0.1.1"}, "cutter-0.1.1.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "cutter", Version: "0.1.0"}, "cutter-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "cutter", Version: "0.2.0"}, "cutter-0.2.0.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "setter", Version: "0.1.9+alpha"}, "setter-0.1.9+alpha.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "setter", Version: "0.1.9+beta"}, "setter-0.1.9+beta.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "setter", Version: "0.1.8"}, "setter-0.1.8.tgz", "http://example.com/charts", "sha256:1234567890abc"},
{&chart.Metadata{APIVersion: "v2", Name: "setter", Version: "0.1.8+beta"}, "setter-0.1.8+beta.tgz", "http://example.com/charts", "sha256:1234567890abc"},
} {
if err := i.MustAdd(x.md, x.filename, x.baseURL, x.digest); err != nil {
t.Errorf("unexpected error adding to index: %s", err)
}
}
i.SortEntries()
if i.APIVersion != APIVersionV1 {
t.Error("Expected API version v1")
}
if len(i.Entries) != 3 {
t.Errorf("Expected 3 charts. Got %d", len(i.Entries))
}
if i.Entries["clipper"][0].Name != "clipper" {
t.Errorf("Expected clipper, got %s", i.Entries["clipper"][0].Name)
}
if len(i.Entries["cutter"]) != 3 {
t.Error("Expected three cutters.")
}
// Test that the sort worked. 0.2 should be at the first index for Cutter.
if v := i.Entries["cutter"][0].Version; v != "0.2.0" {
t.Errorf("Unexpected first version: %s", v)
}
cv, err := i.Get("setter", "0.1.9")
if err == nil && !strings.Contains(cv.Version, "0.1.9") {
t.Errorf("Unexpected version: %s", cv.Version)
}
cv, err = i.Get("setter", "0.1.9+alpha")
if err != nil || cv.Version != "0.1.9+alpha" {
t.Errorf("Expected version: 0.1.9+alpha")
}
cv, err = i.Get("setter", "0.1.8")
if err != nil || cv.Version != "0.1.8" {
t.Errorf("Expected version: 0.1.8")
}
}
func TestLoadIndex(t *testing.T) {
tests := []struct {
Name string
Filename string
}{
{
Name: "regular index file",
Filename: testfile,
},
{
Name: "chartmuseum index file",
Filename: chartmuseumtestfile,
},
{
Name: "JSON index file",
Filename: jsonTestfile,
},
}
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
i, err := LoadIndexFile(tc.Filename)
if err != nil {
t.Fatal(err)
}
verifyLocalIndex(t, i)
})
}
}
// TestLoadIndex_Duplicates is a regression to make sure that we don't non-deterministically allow duplicate packages.
func TestLoadIndex_Duplicates(t *testing.T) {
if _, err := loadIndex([]byte(indexWithDuplicates), "indexWithDuplicates"); err == nil {
t.Errorf("Expected an error when duplicate entries are present")
}
}
func TestLoadIndex_EmptyEntry(t *testing.T) {
if _, err := loadIndex([]byte(indexWithEmptyEntry), "indexWithEmptyEntry"); err != nil {
t.Errorf("unexpected error: %s", err)
}
}
func TestLoadIndex_Empty(t *testing.T) {
if _, err := loadIndex([]byte(""), "indexWithEmpty"); err == nil {
t.Errorf("Expected an error when index.yaml is empty.")
}
}
func TestLoadIndexFileAnnotations(t *testing.T) {
i, err := LoadIndexFile(annotationstestfile)
if err != nil {
t.Fatal(err)
}
verifyLocalIndex(t, i)
if len(i.Annotations) != 1 {
t.Fatalf("Expected 1 annotation but got %d", len(i.Annotations))
}
if i.Annotations["helm.sh/test"] != "foo bar" {
t.Error("Did not get expected value for helm.sh/test annotation")
}
}
func TestLoadUnorderedIndex(t *testing.T) {
i, err := LoadIndexFile(unorderedTestfile)
if err != nil {
t.Fatal(err)
}
verifyLocalIndex(t, i)
}
func TestMerge(t *testing.T) {
ind1 := NewIndexFile()
if err := ind1.MustAdd(&chart.Metadata{APIVersion: "v2", Name: "dreadnought", Version: "0.1.0"}, "dreadnought-0.1.0.tgz", "http://example.com", "aaaa"); err != nil {
t.Fatalf("unexpected error: %s", err)
}
ind2 := NewIndexFile()
for _, x := range []struct {
md *chart.Metadata
filename string
baseURL string
digest string
}{
{&chart.Metadata{APIVersion: "v2", Name: "dreadnought", Version: "0.2.0"}, "dreadnought-0.2.0.tgz", "http://example.com", "aaaabbbb"},
{&chart.Metadata{APIVersion: "v2", Name: "doughnut", Version: "0.2.0"}, "doughnut-0.2.0.tgz", "http://example.com", "ccccbbbb"},
} {
if err := ind2.MustAdd(x.md, x.filename, x.baseURL, x.digest); err != nil {
t.Errorf("unexpected error: %s", err)
}
}
ind1.Merge(ind2)
if len(ind1.Entries) != 2 {
t.Errorf("Expected 2 entries, got %d", len(ind1.Entries))
}
vs := ind1.Entries["dreadnought"]
if len(vs) != 2 {
t.Errorf("Expected 2 versions, got %d", len(vs))
}
if v := vs[1]; v.Version != "0.2.0" {
t.Errorf("Expected %q version to be 0.2.0, got %s", v.Name, v.Version)
}
}
func TestDownloadIndexFile(t *testing.T) {
t.Run("should download index file", func(t *testing.T) {
srv, err := startLocalServerForTests(nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
r, err := NewChartRepository(&Entry{
Name: testRepo,
URL: srv.URL,
}, getter.All(&cli.EnvSettings{}))
if err != nil {
t.Errorf("Problem creating chart repository from %s: %v", testRepo, err)
}
idx, err := r.DownloadIndexFile()
if err != nil {
t.Fatalf("Failed to download index file to %s: %#v", idx, err)
}
if _, err := os.Stat(idx); err != nil {
t.Fatalf("error finding created index file: %#v", err)
}
i, err := LoadIndexFile(idx)
if err != nil {
t.Fatalf("Index %q failed to parse: %s", testfile, err)
}
verifyLocalIndex(t, i)
// Check that charts file is also created
idx = filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name))
if _, err := os.Stat(idx); err != nil {
t.Fatalf("error finding created charts file: %#v", err)
}
b, err := os.ReadFile(idx)
if err != nil {
t.Fatalf("error reading charts file: %#v", err)
}
verifyLocalChartsFile(t, b, i)
})
t.Run("should not decode the path in the repo url while downloading index", func(t *testing.T) {
chartRepoURLPath := "/some%2Fpath/test"
fileBytes, err := os.ReadFile("testdata/local-index.yaml")
if err != nil {
t.Fatal(err)
}
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.RawPath == chartRepoURLPath+"/index.yaml" {
w.Write(fileBytes)
}
})
srv, err := startLocalServerForTests(handler)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
r, err := NewChartRepository(&Entry{
Name: testRepo,
URL: srv.URL + chartRepoURLPath,
}, getter.All(&cli.EnvSettings{}))
if err != nil {
t.Errorf("Problem creating chart repository from %s: %v", testRepo, err)
}
idx, err := r.DownloadIndexFile()
if err != nil {
t.Fatalf("Failed to download index file to %s: %#v", idx, err)
}
if _, err := os.Stat(idx); err != nil {
t.Fatalf("error finding created index file: %#v", err)
}
i, err := LoadIndexFile(idx)
if err != nil {
t.Fatalf("Index %q failed to parse: %s", testfile, err)
}
verifyLocalIndex(t, i)
// Check that charts file is also created
idx = filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name))
if _, err := os.Stat(idx); err != nil {
t.Fatalf("error finding created charts file: %#v", err)
}
b, err := os.ReadFile(idx)
if err != nil {
t.Fatalf("error reading charts file: %#v", err)
}
verifyLocalChartsFile(t, b, i)
})
}
func verifyLocalIndex(t *testing.T, i *IndexFile) {
t.Helper()
numEntries := len(i.Entries)
if numEntries != 3 {
t.Errorf("Expected 3 entries in index file but got %d", numEntries)
}
alpine, ok := i.Entries["alpine"]
if !ok {
t.Fatalf("'alpine' section not found.")
}
if l := len(alpine); l != 1 {
t.Fatalf("'alpine' should have 1 chart, got %d", l)
}
nginx, ok := i.Entries["nginx"]
if !ok || len(nginx) != 2 {
t.Fatalf("Expected 2 nginx entries")
}
expects := []*ChartVersion{
{
Metadata: &chart.Metadata{
APIVersion: "v2",
Name: "alpine",
Description: "string",
Version: "1.0.0",
Keywords: []string{"linux", "alpine", "small", "sumtin"},
Home: "https://github.com/something",
},
URLs: []string{
"https://charts.helm.sh/stable/alpine-1.0.0.tgz",
"http://storage2.googleapis.com/kubernetes-charts/alpine-1.0.0.tgz",
},
Digest: "sha256:1234567890abcdef",
},
{
Metadata: &chart.Metadata{
APIVersion: "v2",
Name: "nginx",
Description: "string",
Version: "0.2.0",
Keywords: []string{"popular", "web server", "proxy"},
Home: "https://github.com/something/else",
},
URLs: []string{
"https://charts.helm.sh/stable/nginx-0.2.0.tgz",
},
Digest: "sha256:1234567890abcdef",
},
{
Metadata: &chart.Metadata{
APIVersion: "v2",
Name: "nginx",
Description: "string",
Version: "0.1.0",
Keywords: []string{"popular", "web server", "proxy"},
Home: "https://github.com/something",
},
URLs: []string{
"https://charts.helm.sh/stable/nginx-0.1.0.tgz",
},
Digest: "sha256:1234567890abcdef",
},
}
tests := []*ChartVersion{alpine[0], nginx[0], nginx[1]}
for i, tt := range tests {
expect := expects[i]
if tt.Name != expect.Name {
t.Errorf("Expected name %q, got %q", expect.Name, tt.Name)
}
if tt.Description != expect.Description {
t.Errorf("Expected description %q, got %q", expect.Description, tt.Description)
}
if tt.Version != expect.Version {
t.Errorf("Expected version %q, got %q", expect.Version, tt.Version)
}
if tt.Digest != expect.Digest {
t.Errorf("Expected digest %q, got %q", expect.Digest, tt.Digest)
}
if tt.Home != expect.Home {
t.Errorf("Expected home %q, got %q", expect.Home, tt.Home)
}
for i, url := range tt.URLs {
if url != expect.URLs[i] {
t.Errorf("Expected URL %q, got %q", expect.URLs[i], url)
}
}
for i, kw := range tt.Keywords {
if kw != expect.Keywords[i] {
t.Errorf("Expected keywords %q, got %q", expect.Keywords[i], kw)
}
}
}
}
func verifyLocalChartsFile(t *testing.T, chartsContent []byte, indexContent *IndexFile) {
t.Helper()
var expected, reald []string
for chart := range indexContent.Entries {
expected = append(expected, chart)
}
sort.Strings(expected)
scanner := bufio.NewScanner(bytes.NewReader(chartsContent))
for scanner.Scan() {
reald = append(reald, scanner.Text())
}
sort.Strings(reald)
if strings.Join(expected, " ") != strings.Join(reald, " ") {
t.Errorf("Cached charts file content unexpected. Expected:\n%s\ngot:\n%s", expected, reald)
}
}
func TestIndexDirectory(t *testing.T) {
dir := "testdata/repository"
index, err := IndexDirectory(dir, "http://localhost:8080")
if err != nil {
t.Fatal(err)
}
if l := len(index.Entries); l != 3 {
t.Fatalf("Expected 3 entries, got %d", l)
}
// Other things test the entry generation more thoroughly. We just test a
// few fields.
corpus := []struct{ chartName, downloadLink string }{
{"frobnitz", "http://localhost:8080/frobnitz-1.2.3.tgz"},
{"zarthal", "http://localhost:8080/universe/zarthal-1.0.0.tgz"},
}
for _, test := range corpus {
cname := test.chartName
frobs, ok := index.Entries[cname]
if !ok {
t.Fatalf("Could not read chart %s", cname)
}
frob := frobs[0]
if frob.Digest == "" {
t.Errorf("Missing digest of file %s.", frob.Name)
}
if frob.URLs[0] != test.downloadLink {
t.Errorf("Unexpected URLs: %v", frob.URLs)
}
if frob.Name != cname {
t.Errorf("Expected %q, got %q", cname, frob.Name)
}
}
}
func TestIndexAdd(t *testing.T) {
i := NewIndexFile()
for _, x := range []struct {
md *chart.Metadata
filename string
baseURL string
digest string
}{
{&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"},
{&chart.Metadata{APIVersion: "v2", Name: "alpine", Version: "0.1.0"}, "/home/charts/alpine-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"},
{&chart.Metadata{APIVersion: "v2", Name: "deis", Version: "0.1.0"}, "/home/charts/deis-0.1.0.tgz", "http://example.com/charts/", "sha256:1234567890"},
} {
if err := i.MustAdd(x.md, x.filename, x.baseURL, x.digest); err != nil {
t.Errorf("unexpected error adding to index: %s", err)
}
}
if i.Entries["clipper"][0].URLs[0] != "http://example.com/charts/clipper-0.1.0.tgz" {
t.Errorf("Expected http://example.com/charts/clipper-0.1.0.tgz, got %s", i.Entries["clipper"][0].URLs[0])
}
if i.Entries["alpine"][0].URLs[0] != "http://example.com/charts/alpine-0.1.0.tgz" {
t.Errorf("Expected http://example.com/charts/alpine-0.1.0.tgz, got %s", i.Entries["alpine"][0].URLs[0])
}
if i.Entries["deis"][0].URLs[0] != "http://example.com/charts/deis-0.1.0.tgz" {
t.Errorf("Expected http://example.com/charts/deis-0.1.0.tgz, got %s", i.Entries["deis"][0].URLs[0])
}
// test error condition
if err := i.MustAdd(&chart.Metadata{}, "error-0.1.0.tgz", "", ""); err == nil {
t.Fatal("expected error adding to index")
}
}
func TestIndexWrite(t *testing.T) {
i := NewIndexFile()
if err := i.MustAdd(&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"); err != nil {
t.Fatalf("unexpected error: %s", err)
}
dir := t.TempDir()
testpath := filepath.Join(dir, "test")
i.WriteFile(testpath, 0600)
got, err := os.ReadFile(testpath)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(got), "clipper-0.1.0.tgz") {
t.Fatal("Index files doesn't contain expected content")
}
}
func TestIndexJSONWrite(t *testing.T) {
i := NewIndexFile()
if err := i.MustAdd(&chart.Metadata{APIVersion: "v2", Name: "clipper", Version: "0.1.0"}, "clipper-0.1.0.tgz", "http://example.com/charts", "sha256:1234567890"); err != nil {
t.Fatalf("unexpected error: %s", err)
}
dir := t.TempDir()
testpath := filepath.Join(dir, "test")
i.WriteJSONFile(testpath, 0600)
got, err := os.ReadFile(testpath)
if err != nil {
t.Fatal(err)
}
if !json.Valid(got) {
t.Fatal("Index files doesn't contain valid JSON")
}
if !strings.Contains(string(got), "clipper-0.1.0.tgz") {
t.Fatal("Index files doesn't contain expected content")
}
}
func TestAddFileIndexEntriesNil(t *testing.T) {
i := NewIndexFile()
i.APIVersion = chart.APIVersionV1
i.Entries = nil
for _, x := range []struct {
md *chart.Metadata
filename string
baseURL string
digest string
}{
{&chart.Metadata{APIVersion: "v2", Name: " ", Version: "8033-5.apinie+s.r"}, "setter-0.1.9+beta.tgz", "http://example.com/charts", "sha256:1234567890abc"},
} {
if err := i.MustAdd(x.md, x.filename, x.baseURL, x.digest); err == nil {
t.Errorf("expected err to be non-nil when entries not initialized")
}
}
}
func TestIgnoreSkippableChartValidationError(t *testing.T) {
type TestCase struct {
Input error
ErrorSkipped bool
}
testCases := map[string]TestCase{
"nil": {
Input: nil,
},
"generic_error": {
Input: fmt.Errorf("foo"),
},
"non_skipped_validation_error": {
Input: chart.ValidationError("chart.metadata.type must be application or library"),
},
"skipped_validation_error": {
Input: chart.ValidationErrorf("more than one dependency with name or alias %q", "foo"),
ErrorSkipped: true,
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
result := ignoreSkippableChartValidationError(tc.Input)
if tc.Input == nil {
if result != nil {
t.Error("expected nil result for nil input")
}
return
}
if tc.ErrorSkipped {
if result != nil {
t.Error("expected nil result for skipped error")
}
return
}
if tc.Input != result {
t.Error("expected the result equal to input")
}
})
}
}
var indexWithDuplicatesInChartDeps = `
apiVersion: v1
entries:
nginx:
- urls:
- https://charts.helm.sh/stable/alpine-1.0.0.tgz
- http://storage2.googleapis.com/kubernetes-charts/alpine-1.0.0.tgz
name: alpine
description: string
home: https://github.com/something
digest: "sha256:1234567890abcdef"
- urls:
- https://charts.helm.sh/stable/nginx-0.2.0.tgz
name: nginx
description: string
version: 0.2.0
home: https://github.com/something/else
digest: "sha256:1234567890abcdef"
`
var indexWithDuplicatesInLastChartDeps = `
apiVersion: v1
entries:
nginx:
- urls:
- https://charts.helm.sh/stable/nginx-0.2.0.tgz
name: nginx
description: string
version: 0.2.0
home: https://github.com/something/else
digest: "sha256:1234567890abcdef"
- urls:
- https://charts.helm.sh/stable/alpine-1.0.0.tgz
- http://storage2.googleapis.com/kubernetes-charts/alpine-1.0.0.tgz
name: alpine
description: string
home: https://github.com/something
digest: "sha256:111"
`
func TestLoadIndex_DuplicateChartDeps(t *testing.T) {
tests := []struct {
source string
data string
}{
{
source: "indexWithDuplicatesInChartDeps",
data: indexWithDuplicatesInChartDeps,
},
{
source: "indexWithDuplicatesInLastChartDeps",
data: indexWithDuplicatesInLastChartDeps,
},
}
for _, tc := range tests {
t.Run(tc.source, func(t *testing.T) {
idx, err := loadIndex([]byte(tc.data), tc.source)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
cvs := idx.Entries["nginx"]
if cvs == nil {
t.Error("expected one chart version not to be filtered out")
}
for _, v := range cvs {
if v.Name == "alpine" {
t.Error("malformed version was not filtered out")
}
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/chartrepo_test.go | pkg/repo/v1/chartrepo_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 repo
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/helmpath"
)
type CustomGetter struct {
repoUrls []string
}
func (g *CustomGetter) Get(href string, _ ...getter.Option) (*bytes.Buffer, error) {
index := &IndexFile{
APIVersion: "v1",
Generated: time.Now(),
}
indexBytes, err := yaml.Marshal(index)
if err != nil {
return nil, err
}
g.repoUrls = append(g.repoUrls, href)
return bytes.NewBuffer(indexBytes), nil
}
func TestIndexCustomSchemeDownload(t *testing.T) {
repoName := "gcs-repo"
repoURL := "gs://some-gcs-bucket"
myCustomGetter := &CustomGetter{}
customGetterConstructor := func(_ ...getter.Option) (getter.Getter, error) {
return myCustomGetter, nil
}
providers := getter.Providers{{
Schemes: []string{"gs"},
New: customGetterConstructor,
}}
repo, err := NewChartRepository(&Entry{
Name: repoName,
URL: repoURL,
}, providers)
if err != nil {
t.Fatalf("Problem loading chart repository from %s: %v", repoURL, err)
}
repo.CachePath = t.TempDir()
tempIndexFile, err := os.CreateTemp(t.TempDir(), "test-repo")
if err != nil {
t.Fatalf("Failed to create temp index file: %v", err)
}
defer os.Remove(tempIndexFile.Name())
idx, err := repo.DownloadIndexFile()
if err != nil {
t.Fatalf("Failed to download index file to %s: %v", idx, err)
}
if len(myCustomGetter.repoUrls) != 1 {
t.Fatalf("Custom Getter.Get should be called once")
}
expectedRepoIndexURL := repoURL + "/index.yaml"
if myCustomGetter.repoUrls[0] != expectedRepoIndexURL {
t.Fatalf("Custom Getter.Get should be called with %s", expectedRepoIndexURL)
}
}
func TestConcurrencyDownloadIndex(t *testing.T) {
srv, err := startLocalServerForTests(nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
repo, err := NewChartRepository(&Entry{
Name: "nginx",
URL: srv.URL,
}, getter.All(&cli.EnvSettings{}))
if err != nil {
t.Fatalf("Problem loading chart repository from %s: %v", srv.URL, err)
}
repo.CachePath = t.TempDir()
// initial download index
idx, err := repo.DownloadIndexFile()
if err != nil {
t.Fatalf("Failed to download index file to %s: %v", idx, err)
}
indexFName := filepath.Join(repo.CachePath, helmpath.CacheIndexFile(repo.Config.Name))
var wg sync.WaitGroup
// Simultaneously start multiple goroutines that:
// 1) download index.yaml via DownloadIndexFile (write operation),
// 2) read index.yaml via LoadIndexFile (read operation).
// This checks for race conditions and ensures correct behavior under concurrent read/write access.
for range 150 {
wg.Add(1)
go func() {
defer wg.Done()
idx, err := repo.DownloadIndexFile()
if err != nil {
t.Errorf("Failed to download index file to %s: %v", idx, err)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
_, err := LoadIndexFile(indexFName)
if err != nil {
t.Errorf("Failed to load index file: %v", err)
}
}()
}
wg.Wait()
}
// startLocalServerForTests Start the local helm server
func startLocalServerForTests(handler http.Handler) (*httptest.Server, error) {
if handler == nil {
fileBytes, err := os.ReadFile("testdata/local-index.yaml")
if err != nil {
return nil, err
}
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write(fileBytes)
})
}
return httptest.NewServer(handler), nil
}
// startLocalTLSServerForTests Start the local helm server with TLS
func startLocalTLSServerForTests(handler http.Handler) (*httptest.Server, error) {
if handler == nil {
fileBytes, err := os.ReadFile("testdata/local-index.yaml")
if err != nil {
return nil, err
}
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Write(fileBytes)
})
}
return httptest.NewTLSServer(handler), nil
}
func TestFindChartInAuthAndTLSAndPassRepoURL(t *testing.T) {
srv, err := startLocalTLSServerForTests(nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
chartURL, err := FindChartInRepoURL(
srv.URL,
"nginx",
getter.All(&cli.EnvSettings{}),
WithInsecureSkipTLSVerify(true),
)
if err != nil {
t.Fatalf("%v", err)
}
if chartURL != "https://charts.helm.sh/stable/nginx-0.2.0.tgz" {
t.Errorf("%s is not the valid URL", chartURL)
}
// If the insecureSkipTLSVerify is false, it will return an error that contains "x509: certificate signed by unknown authority".
_, err = FindChartInRepoURL(srv.URL, "nginx", getter.All(&cli.EnvSettings{}), WithChartVersion("0.1.0"))
// Go communicates with the platform and different platforms return different messages. Go itself tests darwin
// differently for its message. On newer versions of Darwin the message includes the "Acme Co" portion while older
// versions of Darwin do not. As there are people developing Helm using both old and new versions of Darwin we test
// for both messages.
if runtime.GOOS == "darwin" {
if !strings.Contains(err.Error(), "x509: “Acme Co” certificate is not trusted") && !strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
t.Errorf("Expected TLS error for function FindChartInAuthAndTLSAndPassRepoURL not found, but got a different error (%v)", err)
}
} else if !strings.Contains(err.Error(), "x509: certificate signed by unknown authority") {
t.Errorf("Expected TLS error for function FindChartInAuthAndTLSAndPassRepoURL not found, but got a different error (%v)", err)
}
}
func TestFindChartInRepoURL(t *testing.T) {
srv, err := startLocalServerForTests(nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
chartURL, err := FindChartInRepoURL(srv.URL, "nginx", getter.All(&cli.EnvSettings{}))
if err != nil {
t.Fatalf("%v", err)
}
if chartURL != "https://charts.helm.sh/stable/nginx-0.2.0.tgz" {
t.Errorf("%s is not the valid URL", chartURL)
}
chartURL, err = FindChartInRepoURL(srv.URL, "nginx", getter.All(&cli.EnvSettings{}), WithChartVersion("0.1.0"))
if err != nil {
t.Errorf("%s", err)
}
if chartURL != "https://charts.helm.sh/stable/nginx-0.1.0.tgz" {
t.Errorf("%s is not the valid URL", chartURL)
}
}
func TestErrorFindChartInRepoURL(t *testing.T) {
g := getter.All(&cli.EnvSettings{
RepositoryCache: t.TempDir(),
})
if _, err := FindChartInRepoURL("http://someserver/something", "nginx", g); err == nil {
t.Errorf("Expected error for bad chart URL, but did not get any errors")
} else if !strings.Contains(err.Error(), `looks like "http://someserver/something" is not a valid chart repository or cannot be reached`) {
t.Errorf("Expected error for bad chart URL, but got a different error (%v)", err)
}
srv, err := startLocalServerForTests(nil)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
if _, err = FindChartInRepoURL(srv.URL, "nginx1", g); err == nil {
t.Errorf("Expected error for chart not found, but did not get any errors")
} else if err.Error() != `chart "nginx1" not found in `+srv.URL+` repository` {
t.Errorf("Expected error for chart not found, but got a different error (%v)", err)
}
if !errors.Is(err, ChartNotFoundError{}) {
t.Errorf("error is not of correct error type structure")
}
if _, err = FindChartInRepoURL(srv.URL, "nginx1", g, WithChartVersion("0.1.0")); err == nil {
t.Errorf("Expected error for chart not found, but did not get any errors")
} else if err.Error() != `chart "nginx1" version "0.1.0" not found in `+srv.URL+` repository` {
t.Errorf("Expected error for chart not found, but got a different error (%v)", err)
}
if _, err = FindChartInRepoURL(srv.URL, "chartWithNoURL", g); err == nil {
t.Errorf("Expected error for no chart URLs available, but did not get any errors")
} else if err.Error() != `chart "chartWithNoURL" has no downloadable URLs` {
t.Errorf("Expected error for chart not found, but got a different error (%v)", err)
}
}
func TestResolveReferenceURL(t *testing.T) {
for _, tt := range []struct {
baseURL, refURL, chartURL string
}{
{"http://localhost:8123/", "/nginx-0.2.0.tgz", "http://localhost:8123/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts/", "nginx-0.2.0.tgz", "http://localhost:8123/charts/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts/", "/nginx-0.2.0.tgz", "http://localhost:8123/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts-with-no-trailing-slash", "nginx-0.2.0.tgz", "http://localhost:8123/charts-with-no-trailing-slash/nginx-0.2.0.tgz"},
{"http://localhost:8123", "https://charts.helm.sh/stable/nginx-0.2.0.tgz", "https://charts.helm.sh/stable/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts%2fwith%2fescaped%2fslash", "nginx-0.2.0.tgz", "http://localhost:8123/charts%2fwith%2fescaped%2fslash/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts%2fwith%2fescaped%2fslash", "/nginx-0.2.0.tgz", "http://localhost:8123/nginx-0.2.0.tgz"},
{"http://localhost:8123/charts?with=queryparameter", "nginx-0.2.0.tgz", "http://localhost:8123/charts/nginx-0.2.0.tgz?with=queryparameter"},
{"http://localhost:8123/charts?with=queryparameter", "/nginx-0.2.0.tgz", "http://localhost:8123/nginx-0.2.0.tgz?with=queryparameter"},
} {
chartURL, err := ResolveReferenceURL(tt.baseURL, tt.refURL)
if err != nil {
t.Errorf("unexpected error in ResolveReferenceURL(%q, %q): %s", tt.baseURL, tt.refURL, err)
}
if chartURL != tt.chartURL {
t.Errorf("expected ResolveReferenceURL(%q, %q) to equal %q, got %q", tt.baseURL, tt.refURL, tt.chartURL, chartURL)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repo.go | pkg/repo/v1/repo.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 repo // import "helm.sh/helm/v4/pkg/repo/v1"
import (
"fmt"
"os"
"path/filepath"
"time"
"sigs.k8s.io/yaml"
)
// File represents the repositories.yaml file
type File struct {
APIVersion string `json:"apiVersion"`
Generated time.Time `json:"generated"`
Repositories []*Entry `json:"repositories"`
}
// NewFile generates an empty repositories file.
//
// Generated and APIVersion are automatically set.
func NewFile() *File {
return &File{
APIVersion: APIVersionV1,
Generated: time.Now(),
Repositories: []*Entry{},
}
}
// LoadFile takes a file at the given path and returns a File object
func LoadFile(path string) (*File, error) {
r := new(File)
b, err := os.ReadFile(path)
if err != nil {
return r, fmt.Errorf("couldn't load repositories file (%s): %w", path, err)
}
err = yaml.Unmarshal(b, r)
return r, err
}
// Add adds one or more repo entries to a repo file.
func (r *File) Add(re ...*Entry) {
r.Repositories = append(r.Repositories, re...)
}
// Update attempts to replace one or more repo entries in a repo file. If an
// entry with the same name doesn't exist in the repo file it will add it.
func (r *File) Update(re ...*Entry) {
for _, target := range re {
r.update(target)
}
}
func (r *File) update(e *Entry) {
for j, repo := range r.Repositories {
if repo.Name == e.Name {
r.Repositories[j] = e
return
}
}
r.Add(e)
}
// Has returns true if the given name is already a repository name.
func (r *File) Has(name string) bool {
entry := r.Get(name)
return entry != nil
}
// Get returns an entry with the given name if it exists, otherwise returns nil
func (r *File) Get(name string) *Entry {
for _, entry := range r.Repositories {
if entry.Name == name {
return entry
}
}
return nil
}
// Remove removes the entry from the list of repositories.
func (r *File) Remove(name string) bool {
cp := []*Entry{}
found := false
for _, rf := range r.Repositories {
if rf == nil {
continue
}
if rf.Name == name {
found = true
continue
}
cp = append(cp, rf)
}
r.Repositories = cp
return found
}
// WriteFile writes a repositories file to the given path.
func (r *File) WriteFile(path string, perm os.FileMode) error {
data, err := yaml.Marshal(r)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
return os.WriteFile(path, data, perm)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/chartrepo.go | pkg/repo/v1/chartrepo.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 repo // import "helm.sh/helm/v4/pkg/repo/v1"
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/url"
"os"
"path/filepath"
"strings"
"helm.sh/helm/v4/internal/fileutil"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/helmpath"
)
// Entry represents a collection of parameters for chart repository
type Entry struct {
Name string `json:"name"`
URL string `json:"url"`
Username string `json:"username"`
Password string `json:"password"`
CertFile string `json:"certFile"`
KeyFile string `json:"keyFile"`
CAFile string `json:"caFile"`
InsecureSkipTLSVerify bool `json:"insecure_skip_tls_verify"`
PassCredentialsAll bool `json:"pass_credentials_all"`
}
// ChartRepository represents a chart repository
type ChartRepository struct {
Config *Entry
IndexFile *IndexFile
Client getter.Getter
CachePath string
}
// NewChartRepository constructs ChartRepository
func NewChartRepository(cfg *Entry, getters getter.Providers) (*ChartRepository, error) {
u, err := url.Parse(cfg.URL)
if err != nil {
return nil, fmt.Errorf("invalid chart URL format: %s", cfg.URL)
}
client, err := getters.ByScheme(u.Scheme)
if err != nil {
return nil, fmt.Errorf("could not find protocol handler for: %s", u.Scheme)
}
return &ChartRepository{
Config: cfg,
IndexFile: NewIndexFile(),
Client: client,
CachePath: helmpath.CachePath("repository"),
}, nil
}
// DownloadIndexFile fetches the index from a repository.
func (r *ChartRepository) DownloadIndexFile() (string, error) {
indexURL, err := ResolveReferenceURL(r.Config.URL, "index.yaml")
if err != nil {
return "", err
}
resp, err := r.Client.Get(indexURL,
getter.WithURL(r.Config.URL),
getter.WithInsecureSkipVerifyTLS(r.Config.InsecureSkipTLSVerify),
getter.WithTLSClientConfig(r.Config.CertFile, r.Config.KeyFile, r.Config.CAFile),
getter.WithBasicAuth(r.Config.Username, r.Config.Password),
getter.WithPassCredentialsAll(r.Config.PassCredentialsAll),
)
if err != nil {
return "", err
}
index, err := io.ReadAll(resp)
if err != nil {
return "", err
}
indexFile, err := loadIndex(index, r.Config.URL)
if err != nil {
return "", err
}
// Create the chart list file in the cache directory
var charts strings.Builder
for name := range indexFile.Entries {
fmt.Fprintln(&charts, name)
}
chartsFile := filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name))
os.MkdirAll(filepath.Dir(chartsFile), 0755)
fileutil.AtomicWriteFile(chartsFile, bytes.NewReader([]byte(charts.String())), 0644)
// Create the index file in the cache directory
fname := filepath.Join(r.CachePath, helmpath.CacheIndexFile(r.Config.Name))
os.MkdirAll(filepath.Dir(fname), 0755)
return fname, fileutil.AtomicWriteFile(fname, bytes.NewReader(index), 0644)
}
type findChartInRepoURLOptions struct {
Username string
Password string
PassCredentialsAll bool
InsecureSkipTLSVerify bool
CertFile string
KeyFile string
CAFile string
ChartVersion string
}
type FindChartInRepoURLOption func(*findChartInRepoURLOptions)
// WithChartVersion specifies the chart version to find
func WithChartVersion(chartVersion string) FindChartInRepoURLOption {
return func(options *findChartInRepoURLOptions) {
options.ChartVersion = chartVersion
}
}
// WithUsernamePassword specifies the username/password credntials for the repository
func WithUsernamePassword(username, password string) FindChartInRepoURLOption {
return func(options *findChartInRepoURLOptions) {
options.Username = username
options.Password = password
}
}
// WithPassCredentialsAll flags whether credentials should be passed on to other domains
func WithPassCredentialsAll(passCredentialsAll bool) FindChartInRepoURLOption {
return func(options *findChartInRepoURLOptions) {
options.PassCredentialsAll = passCredentialsAll
}
}
// WithClientTLS species the cert, key, and CA files for client mTLS
func WithClientTLS(certFile, keyFile, caFile string) FindChartInRepoURLOption {
return func(options *findChartInRepoURLOptions) {
options.CertFile = certFile
options.KeyFile = keyFile
options.CAFile = caFile
}
}
// WithInsecureSkipTLSVerify skips TLS verification for repository communication
func WithInsecureSkipTLSVerify(insecureSkipTLSVerify bool) FindChartInRepoURLOption {
return func(options *findChartInRepoURLOptions) {
options.InsecureSkipTLSVerify = insecureSkipTLSVerify
}
}
// FindChartInRepoURL finds chart in chart repository pointed by repoURL
// without adding repo to repositories
func FindChartInRepoURL(repoURL string, chartName string, getters getter.Providers, options ...FindChartInRepoURLOption) (string, error) {
opts := findChartInRepoURLOptions{}
for _, option := range options {
option(&opts)
}
// Download and write the index file to a temporary location
buf := make([]byte, 20)
rand.Read(buf)
name := strings.ReplaceAll(base64.StdEncoding.EncodeToString(buf), "/", "-")
c := Entry{
URL: repoURL,
Username: opts.Username,
Password: opts.Password,
PassCredentialsAll: opts.PassCredentialsAll,
CertFile: opts.CertFile,
KeyFile: opts.KeyFile,
CAFile: opts.CAFile,
Name: name,
InsecureSkipTLSVerify: opts.InsecureSkipTLSVerify,
}
r, err := NewChartRepository(&c, getters)
if err != nil {
return "", err
}
idx, err := r.DownloadIndexFile()
if err != nil {
return "", fmt.Errorf("looks like %q is not a valid chart repository or cannot be reached: %w", repoURL, err)
}
defer func() {
os.RemoveAll(filepath.Join(r.CachePath, helmpath.CacheChartsFile(r.Config.Name)))
os.RemoveAll(filepath.Join(r.CachePath, helmpath.CacheIndexFile(r.Config.Name)))
}()
// Read the index file for the repository to get chart information and return chart URL
repoIndex, err := LoadIndexFile(idx)
if err != nil {
return "", err
}
errMsg := fmt.Sprintf("chart %q", chartName)
if opts.ChartVersion != "" {
errMsg = fmt.Sprintf("%s version %q", errMsg, opts.ChartVersion)
}
cv, err := repoIndex.Get(chartName, opts.ChartVersion)
if err != nil {
return "", ChartNotFoundError{
Chart: errMsg,
RepoURL: repoURL,
}
}
if len(cv.URLs) == 0 {
return "", fmt.Errorf("%s has no downloadable URLs", errMsg)
}
chartURL := cv.URLs[0]
absoluteChartURL, err := ResolveReferenceURL(repoURL, chartURL)
if err != nil {
return "", fmt.Errorf("failed to make chart URL absolute: %w", err)
}
return absoluteChartURL, nil
}
// ResolveReferenceURL resolves refURL relative to baseURL.
// If refURL is absolute, it simply returns refURL.
func ResolveReferenceURL(baseURL, refURL string) (string, error) {
parsedRefURL, err := url.Parse(refURL)
if err != nil {
return "", fmt.Errorf("failed to parse %s as URL: %w", refURL, err)
}
if parsedRefURL.IsAbs() {
return refURL, nil
}
parsedBaseURL, err := url.Parse(baseURL)
if err != nil {
return "", fmt.Errorf("failed to parse %s as URL: %w", baseURL, err)
}
// We need a trailing slash for ResolveReference to work, but make sure there isn't already one
parsedBaseURL.RawPath = strings.TrimSuffix(parsedBaseURL.RawPath, "/") + "/"
parsedBaseURL.Path = strings.TrimSuffix(parsedBaseURL.Path, "/") + "/"
resolvedURL := parsedBaseURL.ResolveReference(parsedRefURL)
resolvedURL.RawQuery = parsedBaseURL.RawQuery
return resolvedURL.String(), nil
}
func (e *Entry) String() string {
buf, err := json.Marshal(e)
if err != nil {
slog.Error("failed to marshal entry", slog.Any("error", err))
panic(err)
}
return string(buf)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repo_test.go | pkg/repo/v1/repo_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 repo
import (
"os"
"strings"
"testing"
)
const testRepositoriesFile = "testdata/repositories.yaml"
func TestFile(t *testing.T) {
rf := NewFile()
rf.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
)
if len(rf.Repositories) != 2 {
t.Fatal("Expected 2 repositories")
}
if rf.Has("nosuchrepo") {
t.Error("Found nonexistent repo")
}
if !rf.Has("incubator") {
t.Error("incubator repo is missing")
}
stable := rf.Repositories[0]
if stable.Name != "stable" {
t.Error("stable is not named stable")
}
if stable.URL != "https://example.com/stable/charts" {
t.Error("Wrong URL for stable")
}
}
func TestNewFile(t *testing.T) {
expects := NewFile()
expects.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
)
file, err := LoadFile(testRepositoriesFile)
if err != nil {
t.Errorf("%q could not be loaded: %s", testRepositoriesFile, err)
}
if len(expects.Repositories) != len(file.Repositories) {
t.Fatalf("Unexpected repo data: %#v", file.Repositories)
}
for i, expect := range expects.Repositories {
got := file.Repositories[i]
if expect.Name != got.Name {
t.Errorf("Expected name %q, got %q", expect.Name, got.Name)
}
if expect.URL != got.URL {
t.Errorf("Expected url %q, got %q", expect.URL, got.URL)
}
}
}
func TestRepoFile_Get(t *testing.T) {
repo := NewFile()
repo.Add(
&Entry{
Name: "first",
URL: "https://example.com/first",
},
&Entry{
Name: "second",
URL: "https://example.com/second",
},
&Entry{
Name: "third",
URL: "https://example.com/third",
},
&Entry{
Name: "fourth",
URL: "https://example.com/fourth",
},
)
name := "second"
entry := repo.Get(name)
if entry == nil { //nolint:staticcheck
t.Fatalf("Expected repo entry %q to be found", name)
}
if entry.URL != "https://example.com/second" { //nolint:staticcheck
t.Errorf("Expected repo URL to be %q but got %q", "https://example.com/second", entry.URL)
}
entry = repo.Get("nonexistent")
if entry != nil {
t.Errorf("Got unexpected entry %+v", entry)
}
}
func TestRemoveRepository(t *testing.T) {
sampleRepository := NewFile()
sampleRepository.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
)
removeRepository := "stable"
found := sampleRepository.Remove(removeRepository)
if !found {
t.Errorf("expected repository %s not found", removeRepository)
}
found = sampleRepository.Has(removeRepository)
if found {
t.Errorf("repository %s not deleted", removeRepository)
}
}
func TestUpdateRepository(t *testing.T) {
sampleRepository := NewFile()
sampleRepository.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
)
newRepoName := "sample"
sampleRepository.Update(&Entry{Name: newRepoName,
URL: "https://example.com/sample",
})
if !sampleRepository.Has(newRepoName) {
t.Errorf("expected repository %s not found", newRepoName)
}
repoCount := len(sampleRepository.Repositories)
sampleRepository.Update(&Entry{Name: newRepoName,
URL: "https://example.com/sample",
})
if repoCount != len(sampleRepository.Repositories) {
t.Errorf("invalid number of repositories found %d, expected number of repositories %d", len(sampleRepository.Repositories), repoCount)
}
}
func TestWriteFile(t *testing.T) {
sampleRepository := NewFile()
sampleRepository.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
)
file, err := os.CreateTemp(t.TempDir(), "helm-repo")
if err != nil {
t.Errorf("failed to create test-file (%v)", err)
}
defer os.Remove(file.Name())
if err := sampleRepository.WriteFile(file.Name(), 0600); err != nil {
t.Errorf("failed to write file (%v)", err)
}
repos, err := LoadFile(file.Name())
if err != nil {
t.Errorf("failed to load file (%v)", err)
}
for _, repo := range sampleRepository.Repositories {
if !repos.Has(repo.Name) {
t.Errorf("expected repository %s not found", repo.Name)
}
}
}
func TestRepoNotExists(t *testing.T) {
if _, err := LoadFile("/this/path/does/not/exist.yaml"); err == nil {
t.Errorf("expected err to be non-nil when path does not exist")
} else if !strings.Contains(err.Error(), "couldn't load repositories file") {
t.Errorf("expected prompt `couldn't load repositories file`")
}
}
func TestRemoveRepositoryInvalidEntries(t *testing.T) {
sampleRepository := NewFile()
sampleRepository.Add(
&Entry{
Name: "stable",
URL: "https://example.com/stable/charts",
},
&Entry{
Name: "incubator",
URL: "https://example.com/incubator",
},
&Entry{},
nil,
&Entry{
Name: "test",
URL: "https://example.com/test",
},
)
removeRepository := "stable"
found := sampleRepository.Remove(removeRepository)
if !found {
t.Errorf("expected repository %s not found", removeRepository)
}
found = sampleRepository.Has(removeRepository)
if found {
t.Errorf("repository %s not deleted", removeRepository)
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/doc.go | pkg/repo/v1/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 repo implements the Helm Chart Repository.
A chart repository is an HTTP server that provides information on charts. A local
repository cache is an on-disk representation of a chart repository.
There are two important file formats for chart repositories.
The first is the 'index.yaml' format, which is expressed like this:
apiVersion: v1
entries:
frobnitz:
- created: 2016-09-29T12:14:34.830161306-06:00
description: This is a frobnitz.
digest: 587bd19a9bd9d2bc4a6d25ab91c8c8e7042c47b4ac246e37bf8e1e74386190f4
home: http://example.com
keywords:
- frobnitz
- sprocket
- dodad
maintainers:
- email: helm@example.com
name: The Helm Team
- email: nobody@example.com
name: Someone Else
name: frobnitz
urls:
- http://example-charts.com/testdata/repository/frobnitz-1.2.3.tgz
version: 1.2.3
sprocket:
- created: 2016-09-29T12:14:34.830507606-06:00
description: This is a sprocket"
digest: 8505ff813c39502cc849a38e1e4a8ac24b8e6e1dcea88f4c34ad9b7439685ae6
home: http://example.com
keywords:
- frobnitz
- sprocket
- dodad
maintainers:
- email: helm@example.com
name: The Helm Team
- email: nobody@example.com
name: Someone Else
name: sprocket
urls:
- http://example-charts.com/testdata/repository/sprocket-1.2.0.tgz
version: 1.2.0
generated: 2016-09-29T12:14:34.829721375-06:00
An index.yaml file contains the necessary descriptive information about what
charts are available in a repository, and how to get them.
The second file format is the repositories.yaml file format. This file is for
facilitating local cached copies of one or more chart repositories.
The format of a repository.yaml file is:
apiVersion: v1
generated: TIMESTAMP
repositories:
- name: stable
url: http://example.com/charts
cache: stable-index.yaml
- name: incubator
url: http://example.com/incubator
cache: incubator-index.yaml
This file maps three bits of information about a repository:
- The name the user uses to refer to it
- The fully qualified URL to the repository (index.yaml will be appended)
- The name of the local cachefile
The format for both files was changed after Helm v2.0.0-Alpha.4. Helm is not
backwards compatible with those earlier versions.
*/
package repo
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repotest/server_test.go | pkg/repo/v1/repotest/server_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 repotest
import (
"io"
"net/http"
"path/filepath"
"strings"
"testing"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/internal/test/ensure"
"helm.sh/helm/v4/pkg/repo/v1"
)
// Young'n, in these here parts, we test our tests.
func TestServer(t *testing.T) {
ensure.HelmHome(t)
rootDir := t.TempDir()
srv := newServer(t, rootDir)
defer srv.Stop()
c, err := srv.CopyCharts("testdata/*.tgz")
if err != nil {
// Some versions of Go don't correctly fire defer on Fatal.
t.Fatal(err)
}
if len(c) != 1 {
t.Errorf("Unexpected chart count: %d", len(c))
}
if filepath.Base(c[0]) != "examplechart-0.1.0.tgz" {
t.Errorf("Unexpected chart: %s", c[0])
}
res, err := http.Get(srv.URL() + "/examplechart-0.1.0.tgz")
res.Body.Close()
if err != nil {
t.Fatal(err)
}
if res.ContentLength < 500 {
t.Errorf("Expected at least 500 bytes of data, got %d", res.ContentLength)
}
res, err = http.Get(srv.URL() + "/index.yaml")
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
m := repo.NewIndexFile()
if err := yaml.Unmarshal(data, m); err != nil {
t.Fatal(err)
}
if l := len(m.Entries); l != 1 {
t.Fatalf("Expected 1 entry, got %d", l)
}
expect := "examplechart"
if !m.Has(expect, "0.1.0") {
t.Errorf("missing %q", expect)
}
res, err = http.Get(srv.URL() + "/index.yaml-nosuchthing")
res.Body.Close()
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Fatalf("Expected 404, got %d", res.StatusCode)
}
}
func TestNewTempServer(t *testing.T) {
ensure.HelmHome(t)
type testCase struct {
options []ServerOption
}
testCases := map[string]testCase{
"plainhttp": {
options: []ServerOption{
WithChartSourceGlob("testdata/examplechart-0.1.0.tgz"),
},
},
"tls": {
options: []ServerOption{
WithChartSourceGlob("testdata/examplechart-0.1.0.tgz"),
WithTLSConfig(MakeTestTLSConfig(t, "../../../../testdata")),
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
srv := NewTempServer(
t,
tc.options...,
)
defer srv.Stop()
if srv.srv.URL == "" {
t.Fatal("unstarted server")
}
client := srv.Client()
{
res, err := client.Head(srv.URL() + "/repositories.yaml")
if err != nil {
t.Error(err)
}
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("Expected 200, got %d", res.StatusCode)
}
}
{
res, err := client.Head(srv.URL() + "/examplechart-0.1.0.tgz")
if err != nil {
t.Error(err)
}
res.Body.Close()
if res.StatusCode != http.StatusOK {
t.Errorf("Expected 200, got %d", res.StatusCode)
}
}
res, err := client.Get(srv.URL() + "/examplechart-0.1.0.tgz")
res.Body.Close()
if err != nil {
t.Fatal(err)
}
if res.ContentLength < 500 {
t.Errorf("Expected at least 500 bytes of data, got %d", res.ContentLength)
}
res, err = client.Get(srv.URL() + "/index.yaml")
if err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
t.Fatal(err)
}
m := repo.NewIndexFile()
if err := yaml.Unmarshal(data, m); err != nil {
t.Fatal(err)
}
if l := len(m.Entries); l != 1 {
t.Fatalf("Expected 1 entry, got %d", l)
}
expect := "examplechart"
if !m.Has(expect, "0.1.0") {
t.Errorf("missing %q", expect)
}
res, err = client.Get(srv.URL() + "/index.yaml-nosuchthing")
res.Body.Close()
if err != nil {
t.Fatal(err)
}
if res.StatusCode != http.StatusNotFound {
t.Fatalf("Expected 404, got %d", res.StatusCode)
}
})
}
}
func TestNewTempServer_TLS(t *testing.T) {
ensure.HelmHome(t)
srv := NewTempServer(
t,
WithChartSourceGlob("testdata/examplechart-0.1.0.tgz"),
WithTLSConfig(MakeTestTLSConfig(t, "../../../../testdata")),
)
defer srv.Stop()
if !strings.HasPrefix(srv.URL(), "https://") {
t.Fatal("non-TLS server")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repotest/server.go | pkg/repo/v1/repotest/server.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 repotest
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/distribution/distribution/v3/configuration"
"github.com/distribution/distribution/v3/registry"
_ "github.com/distribution/distribution/v3/registry/auth/htpasswd" // used for docker test registry
_ "github.com/distribution/distribution/v3/registry/storage/driver/inmemory" // used for docker test registry
"golang.org/x/crypto/bcrypt"
"sigs.k8s.io/yaml"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
ociRegistry "helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/repo/v1"
)
func BasicAuthMiddleware(t *testing.T) http.HandlerFunc {
t.Helper()
return http.HandlerFunc(func(_ 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)
}
})
}
type ServerOption func(*testing.T, *Server)
func WithTLSConfig(tlsConfig *tls.Config) ServerOption {
return func(_ *testing.T, server *Server) {
server.tlsConfig = tlsConfig
}
}
func WithMiddleware(middleware http.HandlerFunc) ServerOption {
return func(_ *testing.T, server *Server) {
server.middleware = middleware
}
}
func WithChartSourceGlob(glob string) ServerOption {
return func(_ *testing.T, server *Server) {
server.chartSourceGlob = glob
}
}
// Server is an implementation of a repository server for testing.
type Server struct {
docroot string
srv *httptest.Server
middleware http.HandlerFunc
tlsConfig *tls.Config
chartSourceGlob string
}
// NewTempServer creates a server inside of a temp dir.
//
// If the passed in string is not "", it will be treated as a shell glob, and files
// will be copied from that path to the server's docroot.
//
// The server is started automatically. The caller is responsible for stopping
// the server.
//
// The temp dir will be removed by testing package automatically when test finished.
func NewTempServer(t *testing.T, options ...ServerOption) *Server {
t.Helper()
docrootTempDir := t.TempDir()
srv := newServer(t, docrootTempDir, options...)
t.Cleanup(func() { os.RemoveAll(srv.docroot) })
if srv.chartSourceGlob != "" {
if _, err := srv.CopyCharts(srv.chartSourceGlob); err != nil {
t.Fatal(err)
}
}
return srv
}
// Create the server, but don't yet start it
func newServer(t *testing.T, docroot string, options ...ServerOption) *Server {
t.Helper()
absdocroot, err := filepath.Abs(docroot)
if err != nil {
t.Fatal(err)
}
s := &Server{
docroot: absdocroot,
}
for _, option := range options {
option(t, s)
}
s.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.middleware != nil {
s.middleware.ServeHTTP(w, r)
}
http.FileServer(http.Dir(s.Root())).ServeHTTP(w, r)
}))
s.start()
// Add the testing repository as the only repo. Server must be started for the server's URL to be valid
if err := setTestingRepository(s.URL(), filepath.Join(s.docroot, "repositories.yaml")); err != nil {
t.Fatal(err)
}
return s
}
type OCIServer struct {
*registry.Registry
RegistryURL string
Dir string
TestUsername string
TestPassword string
Client *ociRegistry.Client
}
type OCIServerRunConfig struct {
DependingChart *chart.Chart
}
type OCIServerOpt func(config *OCIServerRunConfig)
func WithDependingChart(c *chart.Chart) OCIServerOpt {
return func(config *OCIServerRunConfig) {
config.DependingChart = c
}
}
func NewOCIServer(t *testing.T, dir string) (*OCIServer, error) {
t.Helper()
testHtpasswdFileBasename := "authtest.htpasswd"
testUsername, testPassword := "username", "password"
pwBytes, err := bcrypt.GenerateFromPassword([]byte(testPassword), bcrypt.DefaultCost)
if err != nil {
t.Fatal("error generating bcrypt password for test htpasswd file")
}
htpasswdPath := filepath.Join(dir, testHtpasswdFileBasename)
err = os.WriteFile(htpasswdPath, fmt.Appendf(nil, "%s:%s\n", testUsername, string(pwBytes)), 0o644)
if err != nil {
t.Fatalf("error creating test htpasswd file")
}
// Registry config
config := &configuration.Configuration{}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("error finding free port for test registry")
}
defer ln.Close()
port := ln.Addr().(*net.TCPAddr).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,
},
}
registryURL := fmt.Sprintf("localhost:%d", port)
r, err := registry.NewRegistry(t.Context(), config)
if err != nil {
t.Fatal(err)
}
return &OCIServer{
Registry: r,
RegistryURL: registryURL,
TestUsername: testUsername,
TestPassword: testPassword,
Dir: dir,
}, nil
}
func (srv *OCIServer) Run(t *testing.T, opts ...OCIServerOpt) {
t.Helper()
cfg := &OCIServerRunConfig{}
for _, fn := range opts {
fn(cfg)
}
go srv.ListenAndServe()
credentialsFile := filepath.Join(srv.Dir, "config.json")
// init test client
registryClient, err := ociRegistry.NewClient(
ociRegistry.ClientOptDebug(true),
ociRegistry.ClientOptEnableCache(true),
ociRegistry.ClientOptWriter(os.Stdout),
ociRegistry.ClientOptCredentialsFile(credentialsFile),
)
if err != nil {
t.Fatalf("error creating registry client")
}
err = registryClient.Login(
srv.RegistryURL,
ociRegistry.LoginOptBasicAuth(srv.TestUsername, srv.TestPassword),
ociRegistry.LoginOptInsecure(true),
ociRegistry.LoginOptPlainText(true))
if err != nil {
t.Fatalf("error logging into registry with good credentials: %v", err)
}
ref := fmt.Sprintf("%s/u/ocitestuser/oci-dependent-chart:0.1.0", srv.RegistryURL)
err = chartutil.ExpandFile(srv.Dir, filepath.Join(srv.Dir, "oci-dependent-chart-0.1.0.tgz"))
if err != nil {
t.Fatal(err)
}
// valid chart
ch, err := loader.LoadDir(filepath.Join(srv.Dir, "oci-dependent-chart"))
if err != nil {
t.Fatal("error loading chart")
}
err = os.RemoveAll(filepath.Join(srv.Dir, "oci-dependent-chart"))
if err != nil {
t.Fatal("error removing chart before push")
}
// save it back to disk..
absPath, err := chartutil.Save(ch, srv.Dir)
if err != nil {
t.Fatal("could not create chart archive")
}
// load it into memory...
contentBytes, err := os.ReadFile(absPath)
if err != nil {
t.Fatal("could not load chart into memory")
}
result, err := registryClient.Push(contentBytes, ref)
if err != nil {
t.Fatalf("error pushing dependent chart: %s", err)
}
t.Logf("Manifest.Digest: %s, Manifest.Size: %d, "+
"Config.Digest: %s, Config.Size: %d, "+
"Chart.Digest: %s, Chart.Size: %d",
result.Manifest.Digest, result.Manifest.Size,
result.Config.Digest, result.Config.Size,
result.Chart.Digest, result.Chart.Size)
srv.Client = registryClient
c := cfg.DependingChart
if c == nil {
return
}
dependingRef := fmt.Sprintf("%s/u/ocitestuser/%s:%s",
srv.RegistryURL, c.Metadata.Name, c.Metadata.Version)
// load it into memory...
absPath = filepath.Join(srv.Dir,
fmt.Sprintf("%s-%s.tgz", c.Metadata.Name, c.Metadata.Version))
contentBytes, err = os.ReadFile(absPath)
if err != nil {
t.Fatal("could not load chart into memory")
}
result, err = registryClient.Push(contentBytes, dependingRef)
if err != nil {
t.Fatalf("error pushing depending chart: %s", err)
}
t.Logf("Manifest.Digest: %s, Manifest.Size: %d, "+
"Config.Digest: %s, Config.Size: %d, "+
"Chart.Digest: %s, Chart.Size: %d",
result.Manifest.Digest, result.Manifest.Size,
result.Config.Digest, result.Config.Size,
result.Chart.Digest, result.Chart.Size)
}
// Root gets the docroot for the server.
func (s *Server) Root() string {
return s.docroot
}
// CopyCharts takes a glob expression and copies those charts to the server root.
func (s *Server) CopyCharts(origin string) ([]string, error) {
files, err := filepath.Glob(origin)
if err != nil {
return []string{}, err
}
copied := make([]string, len(files))
for i, f := range files {
base := filepath.Base(f)
newname := filepath.Join(s.docroot, base)
data, err := os.ReadFile(f)
if err != nil {
return []string{}, err
}
if err := os.WriteFile(newname, data, 0o644); err != nil {
return []string{}, err
}
copied[i] = newname
}
err = s.CreateIndex()
return copied, err
}
// CreateIndex will read docroot and generate an index.yaml file.
func (s *Server) CreateIndex() error {
// generate the index
index, err := repo.IndexDirectory(s.docroot, s.URL())
if err != nil {
return err
}
d, err := yaml.Marshal(index)
if err != nil {
return err
}
ifile := filepath.Join(s.docroot, "index.yaml")
return os.WriteFile(ifile, d, 0o644)
}
func (s *Server) start() {
if s.tlsConfig != nil {
s.srv.TLS = s.tlsConfig
s.srv.StartTLS()
} else {
s.srv.Start()
}
}
// Stop stops the server and closes all connections.
//
// It should be called explicitly.
func (s *Server) Stop() {
s.srv.Close()
}
// URL returns the URL of the server.
//
// Example:
//
// http://localhost:1776
func (s *Server) URL() string {
return s.srv.URL
}
func (s *Server) Client() *http.Client {
return s.srv.Client()
}
// LinkIndices links the index created with CreateIndex and makes a symbolic link to the cache index.
//
// This makes it possible to simulate a local cache of a repository.
func (s *Server) LinkIndices() error {
lstart := filepath.Join(s.docroot, "index.yaml")
ldest := filepath.Join(s.docroot, "test-index.yaml")
return os.Symlink(lstart, ldest)
}
// setTestingRepository sets up a testing repository.yaml with only the given URL.
func setTestingRepository(url, fname string) error {
if url == "" {
panic("no url")
}
r := repo.NewFile()
r.Add(&repo.Entry{
Name: "test",
URL: url,
})
return r.WriteFile(fname, 0o640)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repotest/doc.go | pkg/repo/v1/repotest/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 repotest provides utilities for testing.
The server provides a testing server that can be set up and torn down quickly.
*/
package repotest
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/repo/v1/repotest/tlsconfig.go | pkg/repo/v1/repotest/tlsconfig.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 repotest
import (
"crypto/tls"
"path/filepath"
"testing"
"helm.sh/helm/v4/internal/tlsutil"
"github.com/stretchr/testify/require"
)
func MakeTestTLSConfig(t *testing.T, path string) *tls.Config {
t.Helper()
ca, pub, priv := filepath.Join(path, "rootca.crt"), filepath.Join(path, "crt.pem"), filepath.Join(path, "key.pem")
insecure := false
tlsConf, err := tlsutil.NewTLSConfig(
tlsutil.WithInsecureSkipVerify(insecure),
tlsutil.WithCertKeyPairFiles(pub, priv),
tlsutil.WithCAFile(ca),
)
//require.Nil(t, err, err.Error())
require.Nil(t, err)
tlsConf.ServerName = "helm.sh"
return tlsConf
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/manager_test.go | pkg/downloader/manager_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 downloader
import (
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"reflect"
"testing"
"time"
"github.com/stretchr/testify/assert"
"sigs.k8s.io/yaml"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest"
)
func TestVersionEquals(t *testing.T) {
tests := []struct {
name, v1, v2 string
expect bool
}{
{name: "semver match", v1: "1.2.3-beta.11", v2: "1.2.3-beta.11", expect: true},
{name: "semver match, build info", v1: "1.2.3-beta.11+a", v2: "1.2.3-beta.11+b", expect: true},
{name: "string match", v1: "abcdef123", v2: "abcdef123", expect: true},
{name: "semver mismatch", v1: "1.2.3-beta.11", v2: "1.2.3-beta.22", expect: false},
{name: "semver mismatch, invalid semver", v1: "1.2.3-beta.11", v2: "stinkycheese", expect: false},
}
for _, tt := range tests {
if versionEquals(tt.v1, tt.v2) != tt.expect {
t.Errorf("%s: failed comparison of %q and %q (expect equal: %t)", tt.name, tt.v1, tt.v2, tt.expect)
}
}
}
func TestFindChartURL(t *testing.T) {
var b bytes.Buffer
m := &Manager{
Out: &b,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
}
repos, err := m.loadChartRepositories()
if err != nil {
t.Fatal(err)
}
name := "alpine"
version := "0.1.0"
repoURL := "http://example.com/charts"
churl, username, password, insecureSkipTLSVerify, passcredentialsall, _, _, _, err := m.findChartURL(name, version, repoURL, repos)
if err != nil {
t.Fatal(err)
}
if churl != "https://charts.helm.sh/stable/alpine-0.1.0.tgz" {
t.Errorf("Unexpected URL %q", churl)
}
if username != "" {
t.Errorf("Unexpected username %q", username)
}
if password != "" {
t.Errorf("Unexpected password %q", password)
}
if passcredentialsall != false {
t.Errorf("Unexpected passcredentialsall %t", passcredentialsall)
}
if insecureSkipTLSVerify {
t.Errorf("Unexpected insecureSkipTLSVerify %t", insecureSkipTLSVerify)
}
name = "tlsfoo"
version = "1.2.3"
repoURL = "https://example-https-insecureskiptlsverify.com"
churl, username, password, insecureSkipTLSVerify, passcredentialsall, _, _, _, err = m.findChartURL(name, version, repoURL, repos)
if err != nil {
t.Fatal(err)
}
if !insecureSkipTLSVerify {
t.Errorf("Unexpected insecureSkipTLSVerify %t", insecureSkipTLSVerify)
}
if churl != "https://example.com/tlsfoo-1.2.3.tgz" {
t.Errorf("Unexpected URL %q", churl)
}
if username != "" {
t.Errorf("Unexpected username %q", username)
}
if password != "" {
t.Errorf("Unexpected password %q", password)
}
if passcredentialsall != false {
t.Errorf("Unexpected passcredentialsall %t", passcredentialsall)
}
name = "foo"
version = "1.2.3"
repoURL = "http://example.com/helm"
churl, username, password, insecureSkipTLSVerify, passcredentialsall, _, _, _, err = m.findChartURL(name, version, repoURL, repos)
if err != nil {
t.Fatal(err)
}
if churl != "http://example.com/helm/charts/foo-1.2.3.tgz" {
t.Errorf("Unexpected URL %q", churl)
}
if username != "" {
t.Errorf("Unexpected username %q", username)
}
if password != "" {
t.Errorf("Unexpected password %q", password)
}
if passcredentialsall != false {
t.Errorf("Unexpected passcredentialsall %t", passcredentialsall)
}
if insecureSkipTLSVerify {
t.Errorf("Unexpected insecureSkipTLSVerify %t", insecureSkipTLSVerify)
}
}
func TestGetRepoNames(t *testing.T) {
b := bytes.NewBuffer(nil)
m := &Manager{
Out: b,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
}
tests := []struct {
name string
req []*chart.Dependency
expect map[string]string
err bool
}{
{
name: "no repo definition, but references a url",
req: []*chart.Dependency{
{Name: "oedipus-rex", Repository: "http://example.com/test"},
},
expect: map[string]string{"http://example.com/test": "http://example.com/test"},
},
{
name: "no repo definition failure -- stable repo",
req: []*chart.Dependency{
{Name: "oedipus-rex", Repository: "stable"},
},
err: true,
},
{
name: "no repo definition failure",
req: []*chart.Dependency{
{Name: "oedipus-rex", Repository: "http://example.com"},
},
expect: map[string]string{"oedipus-rex": "testing"},
},
{
name: "repo from local path",
req: []*chart.Dependency{
{Name: "local-dep", Repository: "file://./testdata/signtest"},
},
expect: map[string]string{"local-dep": "file://./testdata/signtest"},
},
{
name: "repo alias (alias:)",
req: []*chart.Dependency{
{Name: "oedipus-rex", Repository: "alias:testing"},
},
expect: map[string]string{"oedipus-rex": "testing"},
},
{
name: "repo alias (@)",
req: []*chart.Dependency{
{Name: "oedipus-rex", Repository: "@testing"},
},
expect: map[string]string{"oedipus-rex": "testing"},
},
{
name: "repo from local chart under charts path",
req: []*chart.Dependency{
{Name: "local-subchart", Repository: ""},
},
expect: map[string]string{},
},
}
for _, tt := range tests {
l, err := m.resolveRepoNames(tt.req)
if err != nil {
if tt.err {
continue
}
t.Fatal(err)
}
if tt.err {
t.Fatalf("Expected error in test %q", tt.name)
}
// m1 and m2 are the maps we want to compare
eq := reflect.DeepEqual(l, tt.expect)
if !eq {
t.Errorf("%s: expected map %v, got %v", tt.name, l, tt.name)
}
}
}
func TestDownloadAll(t *testing.T) {
chartPath := t.TempDir()
m := &Manager{
Out: new(bytes.Buffer),
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ChartPath: chartPath,
}
signtest, err := loader.LoadDir(filepath.Join("testdata", "signtest"))
if err != nil {
t.Fatal(err)
}
if err := chartutil.SaveDir(signtest, filepath.Join(chartPath, "testdata")); err != nil {
t.Fatal(err)
}
local, err := loader.LoadDir(filepath.Join("testdata", "local-subchart"))
if err != nil {
t.Fatal(err)
}
if err := chartutil.SaveDir(local, filepath.Join(chartPath, "charts")); err != nil {
t.Fatal(err)
}
signDep := &chart.Dependency{
Name: signtest.Name(),
Repository: "file://./testdata/signtest",
Version: signtest.Metadata.Version,
}
localDep := &chart.Dependency{
Name: local.Name(),
Repository: "",
Version: local.Metadata.Version,
}
// create a 'tmpcharts' directory to test #5567
if err := os.MkdirAll(filepath.Join(chartPath, "tmpcharts"), 0755); err != nil {
t.Fatal(err)
}
if err := m.downloadAll([]*chart.Dependency{signDep, localDep}); err != nil {
t.Error(err)
}
if _, err := os.Stat(filepath.Join(chartPath, "charts", "signtest-0.1.0.tgz")); errors.Is(err, fs.ErrNotExist) {
t.Error(err)
}
// A chart with a bad name like this cannot be loaded and saved. Handling in
// the loading and saving will return an error about the invalid name. In
// this case, the chart needs to be created directly.
badchartyaml := `apiVersion: v2
description: A Helm chart for Kubernetes
name: ../bad-local-subchart
version: 0.1.0`
if err := os.MkdirAll(filepath.Join(chartPath, "testdata", "bad-local-subchart"), 0755); err != nil {
t.Fatal(err)
}
err = os.WriteFile(filepath.Join(chartPath, "testdata", "bad-local-subchart", "Chart.yaml"), []byte(badchartyaml), 0644)
if err != nil {
t.Fatal(err)
}
badLocalDep := &chart.Dependency{
Name: "../bad-local-subchart",
Repository: "file://./testdata/bad-local-subchart",
Version: "0.1.0",
}
err = m.downloadAll([]*chart.Dependency{badLocalDep})
if err == nil {
t.Fatal("Expected error for bad dependency name")
}
}
func TestUpdateBeforeBuild(t *testing.T) {
// Set up a fake repo
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
)
defer srv.Stop()
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
// Save dep
d := &chart.Chart{
Metadata: &chart.Metadata{
Name: "dep-chart",
Version: "0.1.0",
APIVersion: "v1",
},
}
if err := chartutil.SaveDir(d, dir()); err != nil {
t.Fatal(err)
}
// Save a chart
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "with-dependency",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{{
Name: d.Metadata.Name,
Version: ">=0.1.0",
Repository: "file://../dep-chart",
}},
},
}
if err := chartutil.SaveDir(c, dir()); err != nil {
t.Fatal(err)
}
// Set-up a manager
b := bytes.NewBuffer(nil)
g := getter.Providers{getter.Provider{
Schemes: []string{"http", "https"},
New: getter.NewHTTPGetter,
}}
m := &Manager{
ChartPath: dir(c.Metadata.Name),
Out: b,
Getters: g,
RepositoryConfig: dir("repositories.yaml"),
RepositoryCache: dir(),
}
// Update before Build. see issue: https://github.com/helm/helm/issues/7101
if err := m.Update(); err != nil {
t.Fatal(err)
}
if err := m.Build(); err != nil {
t.Fatal(err)
}
}
// TestUpdateWithNoRepo is for the case of a dependency that has no repo listed.
// This happens when the dependency is in the charts directory and does not need
// to be fetched.
func TestUpdateWithNoRepo(t *testing.T) {
// Set up a fake repo
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
)
defer srv.Stop()
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
// Setup the dependent chart
d := &chart.Chart{
Metadata: &chart.Metadata{
Name: "dep-chart",
Version: "0.1.0",
APIVersion: "v1",
},
}
// Save a chart with the dependency
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: "with-dependency",
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{{
Name: d.Metadata.Name,
Version: "0.1.0",
}},
},
}
if err := chartutil.SaveDir(c, dir()); err != nil {
t.Fatal(err)
}
// Save dependent chart into the parents charts directory. If the chart is
// not in the charts directory Helm will return an error that it is not
// found.
if err := chartutil.SaveDir(d, dir(c.Metadata.Name, "charts")); err != nil {
t.Fatal(err)
}
// Set-up a manager
b := bytes.NewBuffer(nil)
g := getter.Providers{getter.Provider{
Schemes: []string{"http", "https"},
New: getter.NewHTTPGetter,
}}
m := &Manager{
ChartPath: dir(c.Metadata.Name),
Out: b,
Getters: g,
RepositoryConfig: dir("repositories.yaml"),
RepositoryCache: dir(),
}
// Test the update
if err := m.Update(); err != nil {
t.Fatal(err)
}
}
// This function is the skeleton test code of failing tests for #6416 and #6871 and bugs due to #5874.
//
// This function is used by below tests that ensures success of build operation
// with optional fields, alias, condition, tags, and even with ranged version.
// Parent chart includes local-subchart 0.1.0 subchart from a fake repository, by default.
// If each of these main fields (name, version, repository) is not supplied by dep param, default value will be used.
func checkBuildWithOptionalFields(t *testing.T, chartName string, dep chart.Dependency) {
t.Helper()
// Set up a fake repo
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
)
defer srv.Stop()
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
dir := func(p ...string) string {
return filepath.Join(append([]string{srv.Root()}, p...)...)
}
// Set main fields if not exist
if dep.Name == "" {
dep.Name = "local-subchart"
}
if dep.Version == "" {
dep.Version = "0.1.0"
}
if dep.Repository == "" {
dep.Repository = srv.URL()
}
// Save a chart
c := &chart.Chart{
Metadata: &chart.Metadata{
Name: chartName,
Version: "0.1.0",
APIVersion: "v2",
Dependencies: []*chart.Dependency{&dep},
},
}
if err := chartutil.SaveDir(c, dir()); err != nil {
t.Fatal(err)
}
// Set-up a manager
b := bytes.NewBuffer(nil)
g := getter.Providers{getter.Provider{
Schemes: []string{"http", "https"},
New: getter.NewHTTPGetter,
}}
contentCache := t.TempDir()
m := &Manager{
ChartPath: dir(chartName),
Out: b,
Getters: g,
RepositoryConfig: dir("repositories.yaml"),
RepositoryCache: dir(),
ContentCache: contentCache,
}
// First build will update dependencies and create Chart.lock file.
if err := m.Build(); err != nil {
t.Fatal(err)
}
// Second build should be passed. See PR #6655.
if err := m.Build(); err != nil {
t.Fatal(err)
}
}
func TestBuild_WithoutOptionalFields(t *testing.T) {
// Dependency has main fields only (name/version/repository)
checkBuildWithOptionalFields(t, "without-optional-fields", chart.Dependency{})
}
func TestBuild_WithSemVerRange(t *testing.T) {
// Dependency version is the form of SemVer range
checkBuildWithOptionalFields(t, "with-semver-range", chart.Dependency{
Version: ">=0.1.0",
})
}
func TestBuild_WithAlias(t *testing.T) {
// Dependency has an alias
checkBuildWithOptionalFields(t, "with-alias", chart.Dependency{
Alias: "local-subchart-alias",
})
}
func TestBuild_WithCondition(t *testing.T) {
// Dependency has a condition
checkBuildWithOptionalFields(t, "with-condition", chart.Dependency{
Condition: "some.condition",
})
}
func TestBuild_WithTags(t *testing.T) {
// Dependency has several tags
checkBuildWithOptionalFields(t, "with-tags", chart.Dependency{
Tags: []string{"tag1", "tag2"},
})
}
// Failing test for #6871
func TestBuild_WithRepositoryAlias(t *testing.T) {
// Dependency repository is aliased in Chart.yaml
checkBuildWithOptionalFields(t, "with-repository-alias", chart.Dependency{
Repository: "@test",
})
}
func TestErrRepoNotFound_Error(t *testing.T) {
type fields struct {
Repos []string
}
tests := []struct {
name string
fields fields
want string
}{
{
name: "OK",
fields: fields{
Repos: []string{"https://charts1.example.com", "https://charts2.example.com"},
},
want: "no repository definition for https://charts1.example.com, https://charts2.example.com",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := ErrRepoNotFound{
Repos: tt.fields.Repos,
}
if got := e.Error(); got != tt.want {
t.Errorf("Error() = %v, want %v", got, tt.want)
}
})
}
}
func TestKey(t *testing.T) {
tests := []struct {
name string
expect string
}{
{
name: "file:////tmp",
expect: "afeed3459e92a874f6373aca264ce1459bfa91f9c1d6612f10ae3dc2ee955df3",
},
{
name: "https://example.com/charts",
expect: "7065c57c94b2411ad774638d76823c7ccb56415441f5ab2f5ece2f3845728e5d",
},
{
name: "foo/bar/baz",
expect: "15c46a4f8a189ae22f36f201048881d6c090c93583bedcf71f5443fdef224c82",
},
}
for _, tt := range tests {
o, err := key(tt.name)
if err != nil {
t.Fatalf("unable to generate key for %q with error: %s", tt.name, err)
}
if o != tt.expect {
t.Errorf("wrong key name generated for %q, expected %q but got %q", tt.name, tt.expect, o)
}
}
}
// Test dedupeRepos tests that the dedupeRepos function correctly deduplicates
func TestDedupeRepos(t *testing.T) {
tests := []struct {
name string
repos []*repo.Entry
want []*repo.Entry
}{
{
name: "no duplicates",
repos: []*repo.Entry{
{
URL: "https://example.com/charts",
},
{
URL: "https://example.com/charts2",
},
},
want: []*repo.Entry{
{
URL: "https://example.com/charts",
},
{
URL: "https://example.com/charts2",
},
},
},
{
name: "duplicates",
repos: []*repo.Entry{
{
URL: "https://example.com/charts",
},
{
URL: "https://example.com/charts",
},
},
want: []*repo.Entry{
{
URL: "https://example.com/charts",
},
},
},
{
name: "duplicates with trailing slash",
repos: []*repo.Entry{
{
URL: "https://example.com/charts",
},
{
URL: "https://example.com/charts/",
},
},
want: []*repo.Entry{
{
// the last one wins
URL: "https://example.com/charts/",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := dedupeRepos(tt.repos)
assert.ElementsMatch(t, tt.want, got)
})
}
}
func TestWriteLock(t *testing.T) {
fixedTime, err := time.Parse(time.RFC3339, "2025-07-04T00:00:00Z")
assert.NoError(t, err)
lock := &chart.Lock{
Generated: fixedTime,
Digest: "sha256:12345",
Dependencies: []*chart.Dependency{
{
Name: "fantastic-chart",
Version: "1.2.3",
Repository: "https://example.com/charts",
},
},
}
expectedContent, err := yaml.Marshal(lock)
assert.NoError(t, err)
t.Run("v2 lock file", func(t *testing.T) {
dir := t.TempDir()
err := writeLock(dir, lock, false)
assert.NoError(t, err)
lockfilePath := filepath.Join(dir, "Chart.lock")
_, err = os.Stat(lockfilePath)
assert.NoError(t, err, "Chart.lock should exist")
content, err := os.ReadFile(lockfilePath)
assert.NoError(t, err)
assert.Equal(t, expectedContent, content)
// Check that requirements.lock does not exist
_, err = os.Stat(filepath.Join(dir, "requirements.lock"))
assert.Error(t, err)
assert.True(t, os.IsNotExist(err))
})
t.Run("v1 lock file", func(t *testing.T) {
dir := t.TempDir()
err := writeLock(dir, lock, true)
assert.NoError(t, err)
lockfilePath := filepath.Join(dir, "requirements.lock")
_, err = os.Stat(lockfilePath)
assert.NoError(t, err, "requirements.lock should exist")
content, err := os.ReadFile(lockfilePath)
assert.NoError(t, err)
assert.Equal(t, expectedContent, content)
// Check that Chart.lock does not exist
_, err = os.Stat(filepath.Join(dir, "Chart.lock"))
assert.Error(t, err)
assert.True(t, os.IsNotExist(err))
})
t.Run("overwrite existing lock file", func(t *testing.T) {
dir := t.TempDir()
lockfilePath := filepath.Join(dir, "Chart.lock")
assert.NoError(t, os.WriteFile(lockfilePath, []byte("old content"), 0644))
err = writeLock(dir, lock, false)
assert.NoError(t, err)
content, err := os.ReadFile(lockfilePath)
assert.NoError(t, err)
assert.Equal(t, expectedContent, content)
})
t.Run("lock file is a symlink", func(t *testing.T) {
dir := t.TempDir()
dummyFile := filepath.Join(dir, "dummy.txt")
assert.NoError(t, os.WriteFile(dummyFile, []byte("dummy"), 0644))
lockfilePath := filepath.Join(dir, "Chart.lock")
assert.NoError(t, os.Symlink(dummyFile, lockfilePath))
err = writeLock(dir, lock, false)
assert.Error(t, err)
assert.Contains(t, err.Error(), "the Chart.lock file is a symlink to")
})
t.Run("chart path is not a directory", func(t *testing.T) {
dir := t.TempDir()
filePath := filepath.Join(dir, "not-a-dir")
assert.NoError(t, os.WriteFile(filePath, []byte("file"), 0644))
err = writeLock(filePath, lock, false)
assert.Error(t, err)
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/cache.go | pkg/downloader/cache.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 downloader
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"helm.sh/helm/v4/internal/fileutil"
)
// Cache describes a cache that can get and put chart data.
// The cache key is the sha256 has of the content. sha256 is used in Helm for
// digests in index files providing a common key for checking content.
type Cache interface {
// Get returns a reader for the given key.
Get(key [sha256.Size]byte, cacheType string) (string, error)
// Put stores the given reader for the given key.
Put(key [sha256.Size]byte, data io.Reader, cacheType string) (string, error)
}
// CacheChart specifies the content is a chart
var CacheChart = ".chart"
// CacheProv specifies the content is a provenance file
var CacheProv = ".prov"
// TODO: The cache assumes files because much of Helm assumes files. Convert
// Helm to pass content around instead of file locations.
// DiskCache is a cache that stores data on disk.
type DiskCache struct {
Root string
}
// Get returns a reader for the given key.
func (c *DiskCache) Get(key [sha256.Size]byte, cacheType string) (string, error) {
p := c.fileName(key, cacheType)
fi, err := os.Stat(p)
if err != nil {
return "", err
}
// Empty files treated as not exist because there is no content.
if fi.Size() == 0 {
return p, os.ErrNotExist
}
// directories should never happen unless something outside helm is operating
// on this content.
if fi.IsDir() {
return p, errors.New("is a directory")
}
return p, nil
}
// Put stores the given reader for the given key.
// It returns the path to the stored file.
func (c *DiskCache) Put(key [sha256.Size]byte, data io.Reader, cacheType string) (string, error) {
// TODO: verify the key and digest of the key are the same.
p := c.fileName(key, cacheType)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
slog.Error("failed to create cache directory")
return p, err
}
return p, fileutil.AtomicWriteFile(p, data, 0644)
}
// fileName generates the filename in a structured manner where the first part is the
// directory and the full hash is the filename.
func (c *DiskCache) fileName(id [sha256.Size]byte, cacheType string) string {
return filepath.Join(c.Root, fmt.Sprintf("%02x", id[0]), fmt.Sprintf("%x", id)+cacheType)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/cache_test.go | pkg/downloader/cache_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 downloader
import (
"bytes"
"crypto/sha256"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// compiler check to ensure DiskCache implements the Cache interface.
var _ Cache = (*DiskCache)(nil)
func TestDiskCache_PutAndGet(t *testing.T) {
// Setup a temporary directory for the cache
tmpDir := t.TempDir()
cache := &DiskCache{Root: tmpDir}
// Test data
content := []byte("hello world")
key := sha256.Sum256(content)
// --- Test case 1: Put and Get a regular file (prov=false) ---
t.Run("PutAndGetTgz", func(t *testing.T) {
// Put the data into the cache
path, err := cache.Put(key, bytes.NewReader(content), CacheChart)
require.NoError(t, err, "Put should not return an error")
// Verify the file exists at the returned path
_, err = os.Stat(path)
require.NoError(t, err, "File should exist after Put")
// Get the file from the cache
retrievedPath, err := cache.Get(key, CacheChart)
require.NoError(t, err, "Get should not return an error for existing file")
assert.Equal(t, path, retrievedPath, "Get should return the same path as Put")
// Verify content
data, err := os.ReadFile(retrievedPath)
require.NoError(t, err)
assert.Equal(t, content, data, "Content of retrieved file should match original content")
})
// --- Test case 2: Put and Get a provenance file (prov=true) ---
t.Run("PutAndGetProv", func(t *testing.T) {
provContent := []byte("provenance data")
provKey := sha256.Sum256(provContent)
path, err := cache.Put(provKey, bytes.NewReader(provContent), CacheProv)
require.NoError(t, err)
retrievedPath, err := cache.Get(provKey, CacheProv)
require.NoError(t, err)
assert.Equal(t, path, retrievedPath)
data, err := os.ReadFile(retrievedPath)
require.NoError(t, err)
assert.Equal(t, provContent, data)
})
// --- Test case 3: Get a non-existent file ---
t.Run("GetNonExistent", func(t *testing.T) {
nonExistentKey := sha256.Sum256([]byte("does not exist"))
_, err := cache.Get(nonExistentKey, CacheChart)
assert.ErrorIs(t, err, os.ErrNotExist, "Get for a non-existent key should return os.ErrNotExist")
})
// --- Test case 4: Put an empty file ---
t.Run("PutEmptyFile", func(t *testing.T) {
emptyContent := []byte{}
emptyKey := sha256.Sum256(emptyContent)
path, err := cache.Put(emptyKey, bytes.NewReader(emptyContent), CacheChart)
require.NoError(t, err)
// Get should return ErrNotExist for empty files
_, err = cache.Get(emptyKey, CacheChart)
assert.ErrorIs(t, err, os.ErrNotExist, "Get for an empty file should return os.ErrNotExist")
// But the file should exist
_, err = os.Stat(path)
require.NoError(t, err, "Empty file should still exist on disk")
})
// --- Test case 5: Get a directory ---
t.Run("GetDirectory", func(t *testing.T) {
dirKey := sha256.Sum256([]byte("i am a directory"))
dirPath := cache.fileName(dirKey, CacheChart)
err := os.MkdirAll(dirPath, 0755)
require.NoError(t, err)
_, err = cache.Get(dirKey, CacheChart)
assert.EqualError(t, err, "is a directory")
})
}
func TestDiskCache_fileName(t *testing.T) {
cache := &DiskCache{Root: "/tmp/cache"}
key := sha256.Sum256([]byte("some data"))
assert.Equal(t, filepath.Join("/tmp/cache", "13", "1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.chart"), cache.fileName(key, CacheChart))
assert.Equal(t, filepath.Join("/tmp/cache", "13", "1307990e6ba5ca145eb35e99182a9bec46531bc54ddf656a602c780fa0240dee.prov"), cache.fileName(key, CacheProv))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/chart_downloader.go | pkg/downloader/chart_downloader.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 downloader
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"net/url"
"os"
"path/filepath"
"strings"
"helm.sh/helm/v4/internal/fileutil"
ifs "helm.sh/helm/v4/internal/third_party/dep/fs"
"helm.sh/helm/v4/internal/urlutil"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/provenance"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/repo/v1"
)
// VerificationStrategy describes a strategy for determining whether to verify a chart.
type VerificationStrategy int
const (
// VerifyNever will skip all verification of a chart.
VerifyNever VerificationStrategy = iota
// VerifyIfPossible will attempt a verification, it will not error if verification
// data is missing. But it will not stop processing if verification fails.
VerifyIfPossible
// VerifyAlways will always attempt a verification, and will fail if the
// verification fails.
VerifyAlways
// VerifyLater will fetch verification data, but not do any verification.
// This is to accommodate the case where another step of the process will
// perform verification.
VerifyLater
)
// ErrNoOwnerRepo indicates that a given chart URL can't be found in any repos.
var ErrNoOwnerRepo = errors.New("could not find a repo containing the given URL")
// ChartDownloader handles downloading a chart.
//
// It is capable of performing verifications on charts as well.
type ChartDownloader struct {
// Out is the location to write warning and info messages.
Out io.Writer
// Verify indicates what verification strategy to use.
Verify VerificationStrategy
// Keyring is the keyring file used for verification.
Keyring string
// Getter collection for the operation
Getters getter.Providers
// Options provide parameters to be passed along to the Getter being initialized.
Options []getter.Option
RegistryClient *registry.Client
RepositoryConfig string
RepositoryCache string
// ContentCache is the location where Cache stores its files by default
// In previous versions of Helm the charts were put in the RepositoryCache. The
// repositories and charts are stored in 2 different caches.
ContentCache string
// Cache specifies the cache implementation to use.
Cache Cache
}
// DownloadTo retrieves a chart. Depending on the settings, it may also download a provenance file.
//
// If Verify is set to VerifyNever, the verification will be nil.
// If Verify is set to VerifyIfPossible, this will return a verification (or nil on failure), and print a warning on failure.
// If Verify is set to VerifyAlways, this will return a verification or an error if the verification fails.
// If Verify is set to VerifyLater, this will download the prov file (if it exists), but not verify it.
//
// For VerifyNever and VerifyIfPossible, the Verification may be empty.
//
// Returns a string path to the location where the file was downloaded and a verification
// (if provenance was verified), or an error if something bad happened.
func (c *ChartDownloader) DownloadTo(ref, version, dest string) (string, *provenance.Verification, error) {
if c.Cache == nil {
if c.ContentCache == "" {
return "", nil, errors.New("content cache must be set")
}
c.Cache = &DiskCache{Root: c.ContentCache}
slog.Debug("set up default downloader cache")
}
hash, u, err := c.ResolveChartVersion(ref, version)
if err != nil {
return "", nil, err
}
g, err := c.Getters.ByScheme(u.Scheme)
if err != nil {
return "", nil, err
}
// Check the cache for the content. Otherwise download it.
// Note, this process will pull from the cache but does not automatically populate
// the cache with the file it downloads.
var data *bytes.Buffer
var found bool
var digest []byte
var digest32 [32]byte
if hash != "" {
// if there is a hash, populate the other formats
digest, err = hex.DecodeString(hash)
if err != nil {
return "", nil, err
}
copy(digest32[:], digest)
if pth, err := c.Cache.Get(digest32, CacheChart); err == nil {
fdata, err := os.ReadFile(pth)
if err == nil {
found = true
data = bytes.NewBuffer(fdata)
slog.Debug("found chart in cache", "id", hash)
}
}
}
if !found {
c.Options = append(c.Options, getter.WithAcceptHeader("application/gzip,application/octet-stream"))
data, err = g.Get(u.String(), c.Options...)
if err != nil {
return "", nil, err
}
}
name := filepath.Base(u.Path)
if u.Scheme == registry.OCIScheme {
idx := strings.LastIndexByte(name, ':')
name = fmt.Sprintf("%s-%s.tgz", name[:idx], name[idx+1:])
}
destfile := filepath.Join(dest, name)
if err := fileutil.AtomicWriteFile(destfile, data, 0644); err != nil {
return destfile, nil, err
}
// If provenance is requested, verify it.
ver := &provenance.Verification{}
if c.Verify > VerifyNever {
found = false
var body *bytes.Buffer
if hash != "" {
if pth, err := c.Cache.Get(digest32, CacheProv); err == nil {
fdata, err := os.ReadFile(pth)
if err == nil {
found = true
body = bytes.NewBuffer(fdata)
slog.Debug("found provenance in cache", "id", hash)
}
}
}
if !found {
body, err = g.Get(u.String() + ".prov")
if err != nil {
if c.Verify == VerifyAlways {
return destfile, ver, fmt.Errorf("failed to fetch provenance %q", u.String()+".prov")
}
fmt.Fprintf(c.Out, "WARNING: Verification not found for %s: %s\n", ref, err)
return destfile, ver, nil
}
}
provfile := destfile + ".prov"
if err := fileutil.AtomicWriteFile(provfile, body, 0644); err != nil {
return destfile, nil, err
}
if c.Verify != VerifyLater {
ver, err = VerifyChart(destfile, destfile+".prov", c.Keyring)
if err != nil {
// Fail always in this case, since it means the verification step
// failed.
return destfile, ver, err
}
}
}
return destfile, ver, nil
}
// DownloadToCache retrieves resources while using a content based cache.
func (c *ChartDownloader) DownloadToCache(ref, version string) (string, *provenance.Verification, error) {
if c.Cache == nil {
if c.ContentCache == "" {
return "", nil, errors.New("content cache must be set")
}
c.Cache = &DiskCache{Root: c.ContentCache}
slog.Debug("set up default downloader cache")
}
digestString, u, err := c.ResolveChartVersion(ref, version)
if err != nil {
return "", nil, err
}
g, err := c.Getters.ByScheme(u.Scheme)
if err != nil {
return "", nil, err
}
c.Options = append(c.Options, getter.WithAcceptHeader("application/gzip,application/octet-stream"))
// Check the cache for the file
digest, err := hex.DecodeString(digestString)
if err != nil {
return "", nil, fmt.Errorf("unable to decode digest: %w", err)
}
var digest32 [32]byte
copy(digest32[:], digest)
var pth string
// only fetch from the cache if we have a digest
if len(digest) > 0 {
pth, err = c.Cache.Get(digest32, CacheChart)
if err == nil {
slog.Debug("found chart in cache", "id", digestString)
}
}
if len(digest) == 0 || err != nil {
slog.Debug("attempting to download chart", "ref", ref, "version", version)
if err != nil && !os.IsNotExist(err) {
return "", nil, err
}
// Get file not in the cache
data, gerr := g.Get(u.String(), c.Options...)
if gerr != nil {
return "", nil, gerr
}
// Generate the digest
if len(digest) == 0 {
digest32 = sha256.Sum256(data.Bytes())
}
pth, err = c.Cache.Put(digest32, data, CacheChart)
if err != nil {
return "", nil, err
}
slog.Debug("put downloaded chart in cache", "id", hex.EncodeToString(digest32[:]))
}
// If provenance is requested, verify it.
ver := &provenance.Verification{}
if c.Verify > VerifyNever {
ppth, err := c.Cache.Get(digest32, CacheProv)
if err == nil {
slog.Debug("found provenance in cache", "id", digestString)
} else {
if !os.IsNotExist(err) {
return pth, ver, err
}
body, err := g.Get(u.String() + ".prov")
if err != nil {
if c.Verify == VerifyAlways {
return pth, ver, fmt.Errorf("failed to fetch provenance %q", u.String()+".prov")
}
fmt.Fprintf(c.Out, "WARNING: Verification not found for %s: %s\n", ref, err)
return pth, ver, nil
}
ppth, err = c.Cache.Put(digest32, body, CacheProv)
if err != nil {
return "", nil, err
}
slog.Debug("put downloaded provenance file in cache", "id", hex.EncodeToString(digest32[:]))
}
if c.Verify != VerifyLater {
// provenance files pin to a specific name so this needs to be accounted for
// when verifying.
// Note, this does make an assumption that the name/version is unique to a
// hash when a provenance file is used. If this isn't true, this section of code
// will need to be reworked.
name := filepath.Base(u.Path)
if u.Scheme == registry.OCIScheme {
idx := strings.LastIndexByte(name, ':')
name = fmt.Sprintf("%s-%s.tgz", name[:idx], name[idx+1:])
}
// Copy chart to a known location with the right name for verification and then
// clean it up.
tmpdir := filepath.Dir(filepath.Join(c.ContentCache, "tmp"))
if err := os.MkdirAll(tmpdir, 0755); err != nil {
return pth, ver, err
}
tmpfile := filepath.Join(tmpdir, name)
err = ifs.CopyFile(pth, tmpfile)
if err != nil {
return pth, ver, err
}
// Not removing the tmp dir itself because a concurrent process may be using it
defer os.RemoveAll(tmpfile)
ver, err = VerifyChart(tmpfile, ppth, c.Keyring)
if err != nil {
// Fail always in this case, since it means the verification step
// failed.
return pth, ver, err
}
}
}
return pth, ver, nil
}
// ResolveChartVersion resolves a chart reference to a URL.
//
// It returns:
// - A hash of the content if available
// - The URL and sets the ChartDownloader's Options that can fetch the URL using the appropriate Getter.
// - An error if there is one
//
// A reference may be an HTTP URL, an oci reference URL, a 'reponame/chartname'
// reference, or a local path.
//
// A version is a SemVer string (1.2.3-beta.1+f334a6789).
//
// - For fully qualified URLs, the version will be ignored (since URLs aren't versioned)
// - For a chart reference
// - If version is non-empty, this will return the URL for that version
// - If version is empty, this will return the URL for the latest version
// - If no version can be found, an error is returned
//
// TODO: support OCI hash
func (c *ChartDownloader) ResolveChartVersion(ref, version string) (string, *url.URL, error) {
u, err := url.Parse(ref)
if err != nil {
return "", nil, fmt.Errorf("invalid chart URL format: %s", ref)
}
if registry.IsOCI(u.String()) {
if c.RegistryClient == nil {
return "", nil, fmt.Errorf("unable to lookup ref %s at version '%s', missing registry client", ref, version)
}
digest, OCIref, err := c.RegistryClient.ValidateReference(ref, version, u)
return digest, OCIref, err
}
rf, err := loadRepoConfig(c.RepositoryConfig)
if err != nil {
return "", u, err
}
if u.IsAbs() && len(u.Host) > 0 && len(u.Path) > 0 {
// In this case, we have to find the parent repo that contains this chart
// URL. And this is an unfortunate problem, as it requires actually going
// through each repo cache file and finding a matching URL. But basically
// we want to find the repo in case we have special SSL cert config
// for that repo.
rc, err := c.scanReposForURL(ref, rf)
if err != nil {
// If there is no special config, return the default HTTP client and
// swallow the error.
if err == ErrNoOwnerRepo {
// Make sure to add the ref URL as the URL for the getter
c.Options = append(c.Options, getter.WithURL(ref))
return "", u, nil
}
return "", u, err
}
// If we get here, we don't need to go through the next phase of looking
// up the URL. We have it already. So we just set the parameters and return.
c.Options = append(
c.Options,
getter.WithURL(rc.URL),
)
if rc.CertFile != "" || rc.KeyFile != "" || rc.CAFile != "" {
c.Options = append(c.Options, getter.WithTLSClientConfig(rc.CertFile, rc.KeyFile, rc.CAFile))
}
if rc.Username != "" && rc.Password != "" {
c.Options = append(
c.Options,
getter.WithBasicAuth(rc.Username, rc.Password),
getter.WithPassCredentialsAll(rc.PassCredentialsAll),
)
}
return "", u, nil
}
// See if it's of the form: repo/path_to_chart
p := strings.SplitN(u.Path, "/", 2)
if len(p) < 2 {
return "", u, fmt.Errorf("non-absolute URLs should be in form of repo_name/path_to_chart, got: %s", u)
}
repoName := p[0]
chartName := p[1]
rc, err := pickChartRepositoryConfigByName(repoName, rf.Repositories)
if err != nil {
return "", u, err
}
// Now that we have the chart repository information we can use that URL
// to set the URL for the getter.
c.Options = append(c.Options, getter.WithURL(rc.URL))
r, err := repo.NewChartRepository(rc, c.Getters)
if err != nil {
return "", u, err
}
if r != nil && r.Config != nil {
if r.Config.CertFile != "" || r.Config.KeyFile != "" || r.Config.CAFile != "" {
c.Options = append(c.Options, getter.WithTLSClientConfig(r.Config.CertFile, r.Config.KeyFile, r.Config.CAFile))
}
if r.Config.Username != "" && r.Config.Password != "" {
c.Options = append(c.Options,
getter.WithBasicAuth(r.Config.Username, r.Config.Password),
getter.WithPassCredentialsAll(r.Config.PassCredentialsAll),
)
}
}
// Next, we need to load the index, and actually look up the chart.
idxFile := filepath.Join(c.RepositoryCache, helmpath.CacheIndexFile(r.Config.Name))
i, err := repo.LoadIndexFile(idxFile)
if err != nil {
return "", u, fmt.Errorf("no cached repo found. (try 'helm repo update'): %w", err)
}
cv, err := i.Get(chartName, version)
if err != nil {
return "", u, fmt.Errorf("chart %q matching %s not found in %s index. (try 'helm repo update'): %w", chartName, version, r.Config.Name, err)
}
if len(cv.URLs) == 0 {
return "", u, fmt.Errorf("chart %q has no downloadable URLs", ref)
}
// TODO: Seems that picking first URL is not fully correct
resolvedURL, err := repo.ResolveReferenceURL(rc.URL, cv.URLs[0])
if err != nil {
return cv.Digest, u, fmt.Errorf("invalid chart URL format: %s", ref)
}
loc, err := url.Parse(resolvedURL)
return cv.Digest, loc, err
}
// VerifyChart takes a path to a chart archive and a keyring, and verifies the chart.
//
// It assumes that a chart archive file is accompanied by a provenance file whose
// name is the archive file name plus the ".prov" extension.
func VerifyChart(path, provfile, keyring string) (*provenance.Verification, error) {
// For now, error out if it's not a tar file.
switch fi, err := os.Stat(path); {
case err != nil:
return nil, err
case fi.IsDir():
return nil, errors.New("unpacked charts cannot be verified")
case !isTar(path):
return nil, errors.New("chart must be a tgz file")
}
if _, err := os.Stat(provfile); err != nil {
return nil, fmt.Errorf("could not load provenance file %s: %w", provfile, err)
}
sig, err := provenance.NewFromKeyring(keyring, "")
if err != nil {
return nil, fmt.Errorf("failed to load keyring: %w", err)
}
// Read archive and provenance files
archiveData, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read chart archive: %w", err)
}
provData, err := os.ReadFile(provfile)
if err != nil {
return nil, fmt.Errorf("failed to read provenance file: %w", err)
}
return sig.Verify(archiveData, provData, filepath.Base(path))
}
// isTar tests whether the given file is a tar file.
//
// Currently, this simply checks extension, since a subsequent function will
// untar the file and validate its binary format.
func isTar(filename string) bool {
return strings.EqualFold(filepath.Ext(filename), ".tgz")
}
func pickChartRepositoryConfigByName(name string, cfgs []*repo.Entry) (*repo.Entry, error) {
for _, rc := range cfgs {
if rc.Name == name {
if rc.URL == "" {
return nil, fmt.Errorf("no URL found for repository %s", name)
}
return rc, nil
}
}
return nil, fmt.Errorf("repo %s not found", name)
}
// scanReposForURL scans all repos to find which repo contains the given URL.
//
// This will attempt to find the given URL in all of the known repositories files.
//
// If the URL is found, this will return the repo entry that contained that URL.
//
// If all of the repos are checked, but the URL is not found, an ErrNoOwnerRepo
// error is returned.
//
// Other errors may be returned when repositories cannot be loaded or searched.
//
// Technically, the fact that a URL is not found in a repo is not a failure indication.
// Charts are not required to be included in an index before they are valid. So
// be mindful of this case.
//
// The same URL can technically exist in two or more repositories. This algorithm
// will return the first one it finds. Order is determined by the order of repositories
// in the repositories.yaml file.
func (c *ChartDownloader) scanReposForURL(u string, rf *repo.File) (*repo.Entry, error) {
// FIXME: This is far from optimal. Larger installations and index files will
// incur a performance hit for this type of scanning.
for _, rc := range rf.Repositories {
r, err := repo.NewChartRepository(rc, c.Getters)
if err != nil {
return nil, err
}
idxFile := filepath.Join(c.RepositoryCache, helmpath.CacheIndexFile(r.Config.Name))
i, err := repo.LoadIndexFile(idxFile)
if err != nil {
return nil, fmt.Errorf("no cached repo found. (try 'helm repo update'): %w", err)
}
for _, entry := range i.Entries {
for _, ver := range entry {
for _, dl := range ver.URLs {
if urlutil.Equal(u, dl) {
return rc, nil
}
}
}
}
}
// This means that there is no repo file for the given URL.
return nil, ErrNoOwnerRepo
}
func loadRepoConfig(file string) (*repo.File, error) {
r, err := repo.LoadFile(file)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return nil, err
}
return r, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/chart_downloader_test.go | pkg/downloader/chart_downloader_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 downloader
import (
"crypto/sha256"
"encoding/hex"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"helm.sh/helm/v4/internal/test/ensure"
"helm.sh/helm/v4/pkg/cli"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/repo/v1"
"helm.sh/helm/v4/pkg/repo/v1/repotest"
)
const (
repoConfig = "testdata/repositories.yaml"
repoCache = "testdata/repository"
)
func TestResolveChartRef(t *testing.T) {
tests := []struct {
name, ref, expect, version string
fail bool
}{
{name: "full URL", ref: "http://example.com/foo-1.2.3.tgz", expect: "http://example.com/foo-1.2.3.tgz"},
{name: "full URL, HTTPS", ref: "https://example.com/foo-1.2.3.tgz", expect: "https://example.com/foo-1.2.3.tgz"},
{name: "full URL, with authentication", ref: "http://username:password@example.com/foo-1.2.3.tgz", expect: "http://username:password@example.com/foo-1.2.3.tgz"},
{name: "reference, testing repo", ref: "testing/alpine", expect: "http://example.com/alpine-1.2.3.tgz"},
{name: "reference, version, testing repo", ref: "testing/alpine", version: "0.2.0", expect: "http://example.com/alpine-0.2.0.tgz"},
{name: "reference, version, malformed repo", ref: "malformed/alpine", version: "1.2.3", expect: "http://dl.example.com/alpine-1.2.3.tgz"},
{name: "reference, querystring repo", ref: "testing-querystring/alpine", expect: "http://example.com/alpine-1.2.3.tgz?key=value"},
{name: "reference, testing-relative repo", ref: "testing-relative/foo", expect: "http://example.com/helm/charts/foo-1.2.3.tgz"},
{name: "reference, testing-relative repo", ref: "testing-relative/bar", expect: "http://example.com/helm/bar-1.2.3.tgz"},
{name: "reference, testing-relative repo", ref: "testing-relative/baz", expect: "http://example.com/path/to/baz-1.2.3.tgz"},
{name: "reference, testing-relative-trailing-slash repo", ref: "testing-relative-trailing-slash/foo", expect: "http://example.com/helm/charts/foo-1.2.3.tgz"},
{name: "reference, testing-relative-trailing-slash repo", ref: "testing-relative-trailing-slash/bar", expect: "http://example.com/helm/bar-1.2.3.tgz"},
{name: "encoded URL", ref: "encoded-url/foobar", expect: "http://example.com/with%2Fslash/charts/foobar-4.2.1.tgz"},
{name: "full URL, HTTPS, irrelevant version", ref: "https://example.com/foo-1.2.3.tgz", version: "0.1.0", expect: "https://example.com/foo-1.2.3.tgz", fail: true},
{name: "full URL, file", ref: "file:///foo-1.2.3.tgz", fail: true},
{name: "invalid", ref: "invalid-1.2.3", fail: true},
{name: "not found", ref: "nosuchthing/invalid-1.2.3", fail: true},
{name: "ref with tag", ref: "oci://example.com/helm-charts/nginx:15.4.2", expect: "oci://example.com/helm-charts/nginx:15.4.2"},
{name: "no repository", ref: "oci://", fail: true},
{name: "oci ref", ref: "oci://example.com/helm-charts/nginx", version: "15.4.2", expect: "oci://example.com/helm-charts/nginx:15.4.2"},
{name: "oci ref with sha256 and version mismatch", ref: "oci://example.com/install/by/sha:0.1.1@sha256:d234555386402a5867ef0169fefe5486858b6d8d209eaf32fd26d29b16807fd6", version: "0.1.2", fail: true},
}
// Create a mock registry client for OCI references
registryClient, err := registry.NewClient()
if err != nil {
t.Fatal(err)
}
c := ChartDownloader{
Out: os.Stderr,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
RegistryClient: registryClient,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
}),
}
for _, tt := range tests {
_, u, err := c.ResolveChartVersion(tt.ref, tt.version)
if err != nil {
if tt.fail {
continue
}
t.Errorf("%s: failed with error %q", tt.name, err)
continue
}
if got := u.String(); got != tt.expect {
t.Errorf("%s: expected %s, got %s", tt.name, tt.expect, got)
}
}
}
func TestResolveChartOpts(t *testing.T) {
tests := []struct {
name, ref, version string
expect []getter.Option
}{
{
name: "repo with CA-file",
ref: "testing-ca-file/foo",
expect: []getter.Option{
getter.WithURL("https://example.com/foo-1.2.3.tgz"),
getter.WithTLSClientConfig("cert", "key", "ca"),
},
},
}
c := ChartDownloader{
Out: os.Stderr,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
}),
}
// snapshot options
snapshotOpts := c.Options
for _, tt := range tests {
// reset chart downloader options for each test case
c.Options = snapshotOpts
expect, err := getter.NewHTTPGetter(tt.expect...)
if err != nil {
t.Errorf("%s: failed to setup http client: %s", tt.name, err)
continue
}
_, u, err := c.ResolveChartVersion(tt.ref, tt.version)
if err != nil {
t.Errorf("%s: failed with error %s", tt.name, err)
continue
}
got, err := getter.NewHTTPGetter(
append(
c.Options,
getter.WithURL(u.String()),
)...,
)
if err != nil {
t.Errorf("%s: failed to create http client: %s", tt.name, err)
continue
}
if *(got.(*getter.HTTPGetter)) != *(expect.(*getter.HTTPGetter)) {
t.Errorf("%s: expected %s, got %s", tt.name, expect, got)
}
}
}
func TestVerifyChart(t *testing.T) {
v, err := VerifyChart("testdata/signtest-0.1.0.tgz", "testdata/signtest-0.1.0.tgz.prov", "testdata/helm-test-key.pub")
if err != nil {
t.Fatal(err)
}
// The verification is tested at length in the provenance package. Here,
// we just want a quick sanity check that the v is not empty.
if len(v.FileHash) == 0 {
t.Error("Digest missing")
}
}
func TestIsTar(t *testing.T) {
tests := map[string]bool{
"foo.tgz": true,
"foo/bar/baz.tgz": true,
"foo-1.2.3.4.5.tgz": true,
"foo.tar.gz": false, // for our purposes
"foo.tgz.1": false,
"footgz": false,
}
for src, expect := range tests {
if isTar(src) != expect {
t.Errorf("%q should be %t", src, expect)
}
}
}
func TestDownloadTo(t *testing.T) {
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
repotest.WithMiddleware(repotest.BasicAuthMiddleware(t)),
)
defer srv.Stop()
if err := srv.CreateIndex(); err != nil {
t.Fatal(err)
}
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
contentCache := t.TempDir()
c := ChartDownloader{
Out: os.Stderr,
Verify: VerifyAlways,
Keyring: "testdata/helm-test-key.pub",
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
}),
Options: []getter.Option{
getter.WithBasicAuth("username", "password"),
getter.WithPassCredentialsAll(false),
},
}
cname := "/signtest-0.1.0.tgz"
dest := srv.Root()
where, v, err := c.DownloadTo(srv.URL()+cname, "", dest)
if err != nil {
t.Fatal(err)
}
if expect := filepath.Join(dest, cname); where != expect {
t.Errorf("Expected download to %s, got %s", expect, where)
}
if v.FileHash == "" {
t.Error("File hash was empty, but verification is required.")
}
if _, err := os.Stat(filepath.Join(dest, cname)); err != nil {
t.Error(err)
}
}
func TestDownloadTo_TLS(t *testing.T) {
// Set up mock server w/ tls enabled
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
repotest.WithTLSConfig(repotest.MakeTestTLSConfig(t, "../../testdata")),
)
defer srv.Stop()
if err := srv.CreateIndex(); err != nil {
t.Fatal(err)
}
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
repoConfig := filepath.Join(srv.Root(), "repositories.yaml")
repoCache := srv.Root()
contentCache := t.TempDir()
c := ChartDownloader{
Out: os.Stderr,
Verify: VerifyAlways,
Keyring: "testdata/helm-test-key.pub",
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
}),
Options: []getter.Option{
getter.WithTLSClientConfig(
"",
"",
filepath.Join("../../testdata/rootca.crt"),
),
},
}
cname := "test/signtest"
dest := srv.Root()
where, v, err := c.DownloadTo(cname, "", dest)
if err != nil {
t.Fatal(err)
}
target := filepath.Join(dest, "signtest-0.1.0.tgz")
if expect := target; where != expect {
t.Errorf("Expected download to %s, got %s", expect, where)
}
if v.FileHash == "" {
t.Error("File hash was empty, but verification is required.")
}
if _, err := os.Stat(target); err != nil {
t.Error(err)
}
}
func TestDownloadTo_VerifyLater(t *testing.T) {
ensure.HelmHome(t)
dest := t.TempDir()
// Set up a fake repo
srv := repotest.NewTempServer(
t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
)
defer srv.Stop()
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
contentCache := t.TempDir()
c := ChartDownloader{
Out: os.Stderr,
Verify: VerifyLater,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
ContentCache: contentCache,
}),
}
cname := "/signtest-0.1.0.tgz"
where, _, err := c.DownloadTo(srv.URL()+cname, "", dest)
if err != nil {
t.Fatal(err)
}
if expect := filepath.Join(dest, cname); where != expect {
t.Errorf("Expected download to %s, got %s", expect, where)
}
if _, err := os.Stat(filepath.Join(dest, cname)); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dest, cname+".prov")); err != nil {
t.Fatal(err)
}
}
func TestScanReposForURL(t *testing.T) {
c := ChartDownloader{
Out: os.Stderr,
Verify: VerifyLater,
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoConfig,
RepositoryCache: repoCache,
}),
}
u := "http://example.com/alpine-0.2.0.tgz"
rf, err := repo.LoadFile(repoConfig)
if err != nil {
t.Fatal(err)
}
entry, err := c.scanReposForURL(u, rf)
if err != nil {
t.Fatal(err)
}
if entry.Name != "testing" {
t.Errorf("Unexpected repo %q for URL %q", entry.Name, u)
}
// A lookup failure should produce an ErrNoOwnerRepo
u = "https://no.such.repo/foo/bar-1.23.4.tgz"
if _, err = c.scanReposForURL(u, rf); err != ErrNoOwnerRepo {
t.Fatalf("expected ErrNoOwnerRepo, got %v", err)
}
}
func TestDownloadToCache(t *testing.T) {
srv := repotest.NewTempServer(t,
repotest.WithChartSourceGlob("testdata/*.tgz*"),
)
defer srv.Stop()
if err := srv.CreateIndex(); err != nil {
t.Fatal(err)
}
if err := srv.LinkIndices(); err != nil {
t.Fatal(err)
}
// The repo file needs to point to our server.
repoFile := filepath.Join(srv.Root(), "repositories.yaml")
repoCache := srv.Root()
contentCache := t.TempDir()
c := ChartDownloader{
Out: os.Stderr,
Verify: VerifyNever,
RepositoryConfig: repoFile,
RepositoryCache: repoCache,
Getters: getter.All(&cli.EnvSettings{
RepositoryConfig: repoFile,
RepositoryCache: repoCache,
ContentCache: contentCache,
}),
Cache: &DiskCache{Root: contentCache},
}
// Case 1: Chart not in cache, download it.
t.Run("download and cache chart", func(t *testing.T) {
// Clear cache for this test
os.RemoveAll(contentCache)
os.MkdirAll(contentCache, 0755)
c.Cache = &DiskCache{Root: contentCache}
pth, v, err := c.DownloadToCache("test/signtest", "0.1.0")
require.NoError(t, err)
require.NotNil(t, v)
// Check that the file exists at the returned path
_, err = os.Stat(pth)
require.NoError(t, err, "chart should exist at returned path")
// Check that it's in the cache
digest, _, err := c.ResolveChartVersion("test/signtest", "0.1.0")
require.NoError(t, err)
digestBytes, err := hex.DecodeString(digest)
require.NoError(t, err)
var digestArray [sha256.Size]byte
copy(digestArray[:], digestBytes)
cachePath, err := c.Cache.Get(digestArray, CacheChart)
require.NoError(t, err, "chart should now be in cache")
require.Equal(t, pth, cachePath)
})
// Case 2: Chart is in cache, get from cache.
t.Run("get chart from cache", func(t *testing.T) {
// The cache should be populated from the previous test.
// To prove it's coming from cache, we can stop the server.
// But repotest doesn't support restarting.
// Let's just call it again and assume it works if it's fast and doesn't error.
pth, v, err := c.DownloadToCache("test/signtest", "0.1.0")
require.NoError(t, err)
require.NotNil(t, v)
_, err = os.Stat(pth)
require.NoError(t, err, "chart should exist at returned path")
})
// Case 3: Download with verification
t.Run("download and verify", func(t *testing.T) {
// Clear cache
os.RemoveAll(contentCache)
os.MkdirAll(contentCache, 0755)
c.Cache = &DiskCache{Root: contentCache}
c.Verify = VerifyAlways
c.Keyring = "testdata/helm-test-key.pub"
_, v, err := c.DownloadToCache("test/signtest", "0.1.0")
require.NoError(t, err)
require.NotNil(t, v)
require.NotEmpty(t, v.FileHash, "verification should have a file hash")
// Check that both chart and prov are in cache
digest, _, err := c.ResolveChartVersion("test/signtest", "0.1.0")
require.NoError(t, err)
digestBytes, err := hex.DecodeString(digest)
require.NoError(t, err)
var digestArray [sha256.Size]byte
copy(digestArray[:], digestBytes)
_, err = c.Cache.Get(digestArray, CacheChart)
require.NoError(t, err, "chart should be in cache")
_, err = c.Cache.Get(digestArray, CacheProv)
require.NoError(t, err, "provenance file should be in cache")
// Reset for other tests
c.Verify = VerifyNever
c.Keyring = ""
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/doc.go | pkg/downloader/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 downloader provides a library for downloading charts.
This package contains various tools for downloading charts from repository
servers, and then storing them in Helm-specific directory structures. This
library contains many functions that depend on a specific
filesystem layout.
*/
package downloader
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/downloader/manager.go | pkg/downloader/manager.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 downloader
import (
"crypto"
"encoding/hex"
"errors"
"fmt"
"io"
stdfs "io/fs"
"log"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"github.com/Masterminds/semver/v3"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/internal/resolver"
"helm.sh/helm/v4/internal/third_party/dep/fs"
"helm.sh/helm/v4/internal/urlutil"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
chartutil "helm.sh/helm/v4/pkg/chart/v2/util"
"helm.sh/helm/v4/pkg/getter"
"helm.sh/helm/v4/pkg/helmpath"
"helm.sh/helm/v4/pkg/registry"
"helm.sh/helm/v4/pkg/repo/v1"
)
// ErrRepoNotFound indicates that chart repositories can't be found in local repo cache.
// The value of Repos is missing repos.
type ErrRepoNotFound struct {
Repos []string
}
// Error implements the error interface.
func (e ErrRepoNotFound) Error() string {
return fmt.Sprintf("no repository definition for %s", strings.Join(e.Repos, ", "))
}
// Manager handles the lifecycle of fetching, resolving, and storing dependencies.
type Manager struct {
// Out is used to print warnings and notifications.
Out io.Writer
// ChartPath is the path to the unpacked base chart upon which this operates.
ChartPath string
// Verification indicates whether the chart should be verified.
Verify VerificationStrategy
// Debug is the global "--debug" flag
Debug bool
// Keyring is the key ring file.
Keyring string
// SkipUpdate indicates that the repository should not be updated first.
SkipUpdate bool
// Getter collection for the operation
Getters []getter.Provider
RegistryClient *registry.Client
RepositoryConfig string
RepositoryCache string
// ContentCache is a location where a cache of charts can be stored
ContentCache string
}
// Build rebuilds a local charts directory from a lockfile.
//
// If the lockfile is not present, this will run a Manager.Update()
//
// If SkipUpdate is set, this will not update the repository.
func (m *Manager) Build() error {
c, err := m.loadChartDir()
if err != nil {
return err
}
// If a lock file is found, run a build from that. Otherwise, just do
// an update.
lock := c.Lock
if lock == nil {
return m.Update()
}
// Check that all of the repos we're dependent on actually exist.
req := c.Metadata.Dependencies
// If using apiVersion v1, calculate the hash before resolve repo names
// because resolveRepoNames will change req if req uses repo alias
// and Helm 2 calculate the digest from the original req
// Fix for: https://github.com/helm/helm/issues/7619
var v2Sum string
if c.Metadata.APIVersion == chart.APIVersionV1 {
v2Sum, err = resolver.HashV2Req(req)
if err != nil {
return errors.New("the lock file (requirements.lock) is out of sync with the dependencies file (requirements.yaml). Please update the dependencies")
}
}
if _, err := m.resolveRepoNames(req); err != nil {
return err
}
if sum, err := resolver.HashReq(req, lock.Dependencies); err != nil || sum != lock.Digest {
// If lock digest differs and chart is apiVersion v1, it maybe because the lock was built
// with Helm 2 and therefore should be checked with Helm v2 hash
// Fix for: https://github.com/helm/helm/issues/7233
if c.Metadata.APIVersion == chart.APIVersionV1 {
log.Println("warning: a valid Helm v3 hash was not found. Checking against Helm v2 hash...")
if v2Sum != lock.Digest {
return errors.New("the lock file (requirements.lock) is out of sync with the dependencies file (requirements.yaml). Please update the dependencies")
}
} else {
return errors.New("the lock file (Chart.lock) is out of sync with the dependencies file (Chart.yaml). Please update the dependencies")
}
}
// Check that all of the repos we're dependent on actually exist.
if err := m.hasAllRepos(lock.Dependencies); err != nil {
return err
}
if !m.SkipUpdate {
// For each repo in the file, update the cached copy of that repo
if err := m.UpdateRepositories(); err != nil {
return err
}
}
// Now we need to fetch every package here into charts/
return m.downloadAll(lock.Dependencies)
}
// Update updates a local charts directory.
//
// It first reads the Chart.yaml file, and then attempts to
// negotiate versions based on that. It will download the versions
// from remote chart repositories unless SkipUpdate is true.
func (m *Manager) Update() error {
c, err := m.loadChartDir()
if err != nil {
return err
}
// If no dependencies are found, we consider this a successful
// completion.
req := c.Metadata.Dependencies
if req == nil {
return nil
}
// Get the names of the repositories the dependencies need that Helm is
// configured to know about.
repoNames, err := m.resolveRepoNames(req)
if err != nil {
return err
}
// For the repositories Helm is not configured to know about, ensure Helm
// has some information about them and, when possible, the index files
// locally.
// TODO(mattfarina): Repositories should be explicitly added by end users
// rather than automatic. In Helm v4 require users to add repositories. They
// should have to add them in order to make sure they are aware of the
// repositories and opt-in to any locations, for security.
repoNames, err = m.ensureMissingRepos(repoNames, req)
if err != nil {
return err
}
// For each of the repositories Helm is configured to know about, update
// the index information locally.
if !m.SkipUpdate {
if err := m.UpdateRepositories(); err != nil {
return err
}
}
// Now we need to find out which version of a chart best satisfies the
// dependencies in the Chart.yaml
lock, err := m.resolve(req, repoNames)
if err != nil {
return err
}
// Now we need to fetch every package here into charts/
if err := m.downloadAll(lock.Dependencies); err != nil {
return err
}
// downloadAll might overwrite dependency version, recalculate lock digest
newDigest, err := resolver.HashReq(req, lock.Dependencies)
if err != nil {
return err
}
lock.Digest = newDigest
// If the lock file hasn't changed, don't write a new one.
oldLock := c.Lock
if oldLock != nil && oldLock.Digest == lock.Digest {
return nil
}
// Finally, we need to write the lockfile.
return writeLock(m.ChartPath, lock, c.Metadata.APIVersion == chart.APIVersionV1)
}
func (m *Manager) loadChartDir() (*chart.Chart, error) {
if fi, err := os.Stat(m.ChartPath); err != nil {
return nil, fmt.Errorf("could not find %s: %w", m.ChartPath, err)
} else if !fi.IsDir() {
return nil, errors.New("only unpacked charts can be updated")
}
return loader.LoadDir(m.ChartPath)
}
// resolve takes a list of dependencies and translates them into an exact version to download.
//
// This returns a lock file, which has all of the dependencies normalized to a specific version.
func (m *Manager) resolve(req []*chart.Dependency, repoNames map[string]string) (*chart.Lock, error) {
res := resolver.New(m.ChartPath, m.RepositoryCache, m.RegistryClient)
return res.Resolve(req, repoNames)
}
// downloadAll takes a list of dependencies and downloads them into charts/
//
// It will delete versions of the chart that exist on disk and might cause
// a conflict.
func (m *Manager) downloadAll(deps []*chart.Dependency) error {
repos, err := m.loadChartRepositories()
if err != nil {
return err
}
destPath := filepath.Join(m.ChartPath, "charts")
tmpPath := filepath.Join(m.ChartPath, fmt.Sprintf("tmpcharts-%d", os.Getpid()))
// Check if 'charts' directory is not actually a directory. If it does not exist, create it.
if fi, err := os.Stat(destPath); err == nil {
if !fi.IsDir() {
return fmt.Errorf("%q is not a directory", destPath)
}
} else if errors.Is(err, stdfs.ErrNotExist) {
if err := os.MkdirAll(destPath, 0755); err != nil {
return err
}
} else {
return fmt.Errorf("unable to retrieve file info for '%s': %v", destPath, err)
}
// Prepare tmpPath
if err := os.MkdirAll(tmpPath, 0755); err != nil {
return err
}
defer os.RemoveAll(tmpPath)
fmt.Fprintf(m.Out, "Saving %d charts\n", len(deps))
var saveError error
churls := make(map[string]struct{})
for _, dep := range deps {
// No repository means the chart is in charts directory
if dep.Repository == "" {
fmt.Fprintf(m.Out, "Dependency %s did not declare a repository. Assuming it exists in the charts directory\n", dep.Name)
// NOTE: we are only validating the local dependency conforms to the constraints. No copying to tmpPath is necessary.
chartPath := filepath.Join(destPath, dep.Name)
ch, err := loader.LoadDir(chartPath)
if err != nil {
return fmt.Errorf("unable to load chart '%s': %v", chartPath, err)
}
constraint, err := semver.NewConstraint(dep.Version)
if err != nil {
return fmt.Errorf("dependency %s has an invalid version/constraint format: %s", dep.Name, err)
}
v, err := semver.NewVersion(ch.Metadata.Version)
if err != nil {
return fmt.Errorf("invalid version %s for dependency %s: %s", dep.Version, dep.Name, err)
}
if !constraint.Check(v) {
saveError = fmt.Errorf("dependency %s at version %s does not satisfy the constraint %s", dep.Name, ch.Metadata.Version, dep.Version)
break
}
continue
}
if strings.HasPrefix(dep.Repository, "file://") {
if m.Debug {
fmt.Fprintf(m.Out, "Archiving %s from repo %s\n", dep.Name, dep.Repository)
}
ver, err := tarFromLocalDir(m.ChartPath, dep.Name, dep.Repository, dep.Version, tmpPath)
if err != nil {
saveError = err
break
}
dep.Version = ver
continue
}
// Any failure to resolve/download a chart should fail:
// https://github.com/helm/helm/issues/1439
churl, username, password, insecureSkipTLSVerify, passCredentialsAll, caFile, certFile, keyFile, err := m.findChartURL(dep.Name, dep.Version, dep.Repository, repos)
if err != nil {
saveError = fmt.Errorf("could not find %s: %w", churl, err)
break
}
if _, ok := churls[churl]; ok {
fmt.Fprintf(m.Out, "Already downloaded %s from repo %s\n", dep.Name, dep.Repository)
continue
}
fmt.Fprintf(m.Out, "Downloading %s from repo %s\n", dep.Name, dep.Repository)
dl := ChartDownloader{
Out: m.Out,
Verify: m.Verify,
Keyring: m.Keyring,
RepositoryConfig: m.RepositoryConfig,
RepositoryCache: m.RepositoryCache,
ContentCache: m.ContentCache,
RegistryClient: m.RegistryClient,
Getters: m.Getters,
Options: []getter.Option{
getter.WithBasicAuth(username, password),
getter.WithPassCredentialsAll(passCredentialsAll),
getter.WithInsecureSkipVerifyTLS(insecureSkipTLSVerify),
getter.WithTLSClientConfig(certFile, keyFile, caFile),
},
}
version := ""
if registry.IsOCI(churl) {
churl, version, err = parseOCIRef(churl)
if err != nil {
return fmt.Errorf("could not parse OCI reference: %w", err)
}
dl.Options = append(dl.Options,
getter.WithRegistryClient(m.RegistryClient),
getter.WithTagName(version))
}
if _, _, err = dl.DownloadTo(churl, version, tmpPath); err != nil {
saveError = fmt.Errorf("could not download %s: %w", churl, err)
break
}
churls[churl] = struct{}{}
}
// TODO: this should probably be refactored to be a []error, so we can capture and provide more information rather than "last error wins".
if saveError == nil {
// now we can move all downloaded charts to destPath and delete outdated dependencies
if err := m.safeMoveDeps(deps, tmpPath, destPath); err != nil {
return err
}
} else {
fmt.Fprintln(m.Out, "Save error occurred: ", saveError)
return saveError
}
return nil
}
func parseOCIRef(chartRef string) (string, string, error) {
refTagRegexp := regexp.MustCompile(`^(oci://[^:]+(:[0-9]{1,5})?[^:]+):(.*)$`)
caps := refTagRegexp.FindStringSubmatch(chartRef)
if len(caps) != 4 {
return "", "", fmt.Errorf("improperly formatted oci chart reference: %s", chartRef)
}
chartRef = caps[1]
tag := caps[3]
return chartRef, tag, nil
}
// safeMoveDeps moves all dependencies in the source and moves them into dest.
//
// It does this by first matching the file name to an expected pattern, then loading
// the file to verify that it is a chart.
//
// Any charts in dest that do not exist in source are removed (barring local dependencies)
//
// Because it requires tar file introspection, it is more intensive than a basic move.
//
// This will only return errors that should stop processing entirely. Other errors
// will emit log messages or be ignored.
func (m *Manager) safeMoveDeps(deps []*chart.Dependency, source, dest string) error {
existsInSourceDirectory := map[string]bool{}
isLocalDependency := map[string]bool{}
sourceFiles, err := os.ReadDir(source)
if err != nil {
return err
}
// attempt to read destFiles; fail fast if we can't
destFiles, err := os.ReadDir(dest)
if err != nil {
return err
}
for _, dep := range deps {
if dep.Repository == "" {
isLocalDependency[dep.Name] = true
}
}
for _, file := range sourceFiles {
if file.IsDir() {
continue
}
filename := file.Name()
sourcefile := filepath.Join(source, filename)
destfile := filepath.Join(dest, filename)
existsInSourceDirectory[filename] = true
if _, err := loader.LoadFile(sourcefile); err != nil {
fmt.Fprintf(m.Out, "Could not verify %s for moving: %s (Skipping)", sourcefile, err)
continue
}
// NOTE: no need to delete the dest; os.Rename replaces it.
if err := fs.RenameWithFallback(sourcefile, destfile); err != nil {
fmt.Fprintf(m.Out, "Unable to move %s to charts dir %s (Skipping)", sourcefile, err)
continue
}
}
fmt.Fprintln(m.Out, "Deleting outdated charts")
// find all files that exist in dest that do not exist in source; delete them (outdated dependencies)
for _, file := range destFiles {
if !file.IsDir() && !existsInSourceDirectory[file.Name()] {
fname := filepath.Join(dest, file.Name())
ch, err := loader.LoadFile(fname)
if err != nil {
fmt.Fprintf(m.Out, "Could not verify %s for deletion: %s (Skipping)\n", fname, err)
continue
}
// local dependency - skip
if isLocalDependency[ch.Name()] {
continue
}
if err := os.Remove(fname); err != nil {
fmt.Fprintf(m.Out, "Could not delete %s: %s (Skipping)", fname, err)
continue
}
}
}
return nil
}
// hasAllRepos ensures that all of the referenced deps are in the local repo cache.
func (m *Manager) hasAllRepos(deps []*chart.Dependency) error {
rf, err := loadRepoConfig(m.RepositoryConfig)
if err != nil {
return err
}
repos := rf.Repositories
// Verify that all repositories referenced in the deps are actually known
// by Helm.
missing := []string{}
Loop:
for _, dd := range deps {
// If repo is from local path or OCI, continue
if strings.HasPrefix(dd.Repository, "file://") || registry.IsOCI(dd.Repository) {
continue
}
if dd.Repository == "" {
continue
}
for _, repo := range repos {
if urlutil.Equal(repo.URL, strings.TrimSuffix(dd.Repository, "/")) {
continue Loop
}
}
missing = append(missing, dd.Repository)
}
if len(missing) > 0 {
return ErrRepoNotFound{missing}
}
return nil
}
// ensureMissingRepos attempts to ensure the repository information for repos
// not managed by Helm is present. This takes in the repoNames Helm is configured
// to work with along with the chart dependencies. It will find the deps not
// in a known repo and attempt to ensure the data is present for steps like
// version resolution.
func (m *Manager) ensureMissingRepos(repoNames map[string]string, deps []*chart.Dependency) (map[string]string, error) {
var ru []*repo.Entry
for _, dd := range deps {
// If the chart is in the local charts directory no repository needs
// to be specified.
if dd.Repository == "" {
continue
}
// When the repoName for a dependency is known we can skip ensuring
if _, ok := repoNames[dd.Name]; ok {
continue
}
// The generated repository name, which will result in an index being
// locally cached, has a name pattern of "helm-manager-" followed by a
// sha256 of the repo name. This assumes end users will never create
// repositories with these names pointing to other repositories. Using
// this method of naming allows the existing repository pulling and
// resolution code to do most of the work.
rn, err := key(dd.Repository)
if err != nil {
return repoNames, err
}
rn = managerKeyPrefix + rn
repoNames[dd.Name] = rn
// Assuming the repository is generally available. For Helm managed
// access controls the repository needs to be added through the user
// managed system. This path will work for public charts, like those
// supplied by Bitnami, but not for protected charts, like corp ones
// behind a username and pass.
ri := &repo.Entry{
Name: rn,
URL: dd.Repository,
}
ru = append(ru, ri)
}
// Calls to UpdateRepositories (a public function) will only update
// repositories configured by the user. Here we update repos found in
// the dependencies that are not known to the user if update skipping
// is not configured.
if !m.SkipUpdate && len(ru) > 0 {
fmt.Fprintln(m.Out, "Getting updates for unmanaged Helm repositories...")
if err := m.parallelRepoUpdate(ru); err != nil {
return repoNames, err
}
}
return repoNames, nil
}
// resolveRepoNames returns the repo names of the referenced deps which can be used to fetch the cached index file
// and replaces aliased repository URLs into resolved URLs in dependencies.
func (m *Manager) resolveRepoNames(deps []*chart.Dependency) (map[string]string, error) {
rf, err := loadRepoConfig(m.RepositoryConfig)
if err != nil {
if errors.Is(err, stdfs.ErrNotExist) {
return make(map[string]string), nil
}
return nil, err
}
repos := rf.Repositories
reposMap := make(map[string]string)
// Verify that all repositories referenced in the deps are actually known
// by Helm.
missing := []string{}
for _, dd := range deps {
// Don't map the repository, we don't need to download chart from charts directory
if dd.Repository == "" {
continue
}
// if dep chart is from local path, verify the path is valid
if strings.HasPrefix(dd.Repository, "file://") {
if _, err := resolver.GetLocalPath(dd.Repository, m.ChartPath); err != nil {
return nil, err
}
if m.Debug {
fmt.Fprintf(m.Out, "Repository from local path: %s\n", dd.Repository)
}
reposMap[dd.Name] = dd.Repository
continue
}
if registry.IsOCI(dd.Repository) {
reposMap[dd.Name] = dd.Repository
continue
}
found := false
for _, repo := range repos {
if (strings.HasPrefix(dd.Repository, "@") && strings.TrimPrefix(dd.Repository, "@") == repo.Name) ||
(strings.HasPrefix(dd.Repository, "alias:") && strings.TrimPrefix(dd.Repository, "alias:") == repo.Name) {
found = true
dd.Repository = repo.URL
reposMap[dd.Name] = repo.Name
break
} else if urlutil.Equal(repo.URL, dd.Repository) {
found = true
reposMap[dd.Name] = repo.Name
break
}
}
if !found {
repository := dd.Repository
// Add if URL
_, err := url.ParseRequestURI(repository)
if err == nil {
reposMap[repository] = repository
continue
}
missing = append(missing, repository)
}
}
if len(missing) > 0 {
errorMessage := fmt.Sprintf("no repository definition for %s. Please add them via 'helm repo add'", strings.Join(missing, ", "))
// It is common for people to try to enter "stable" as a repository instead of the actual URL.
// For this case, let's give them a suggestion.
containsNonURL := false
for _, repo := range missing {
if !strings.Contains(repo, "//") && !strings.HasPrefix(repo, "@") && !strings.HasPrefix(repo, "alias:") {
containsNonURL = true
}
}
if containsNonURL {
errorMessage += `
Note that repositories must be URLs or aliases. For example, to refer to the "example"
repository, use "https://charts.example.com/" or "@example" instead of
"example". Don't forget to add the repo, too ('helm repo add').`
}
return nil, errors.New(errorMessage)
}
return reposMap, nil
}
// UpdateRepositories updates all of the local repos to the latest.
func (m *Manager) UpdateRepositories() error {
rf, err := loadRepoConfig(m.RepositoryConfig)
if err != nil {
return err
}
repos := rf.Repositories
if len(repos) > 0 {
fmt.Fprintln(m.Out, "Hang tight while we grab the latest from your chart repositories...")
// This prints warnings straight to out.
if err := m.parallelRepoUpdate(repos); err != nil {
return err
}
fmt.Fprintln(m.Out, "Update Complete. ⎈Happy Helming!⎈")
}
return nil
}
// Filter out duplicate repos by URL, including those with trailing slashes.
func dedupeRepos(repos []*repo.Entry) []*repo.Entry {
seen := make(map[string]*repo.Entry)
for _, r := range repos {
// Normalize URL by removing trailing slashes.
seenURL := strings.TrimSuffix(r.URL, "/")
seen[seenURL] = r
}
var unique []*repo.Entry
for _, r := range seen {
unique = append(unique, r)
}
return unique
}
func (m *Manager) parallelRepoUpdate(repos []*repo.Entry) error {
var wg sync.WaitGroup
localRepos := dedupeRepos(repos)
for _, c := range localRepos {
r, err := repo.NewChartRepository(c, m.Getters)
if err != nil {
return err
}
r.CachePath = m.RepositoryCache
wg.Add(1)
go func(r *repo.ChartRepository) {
if _, err := r.DownloadIndexFile(); err != nil {
// For those dependencies that are not known to helm and using a
// generated key name we display the repo url.
if strings.HasPrefix(r.Config.Name, managerKeyPrefix) {
fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository:\n\t%s\n", r.Config.URL, err)
} else {
fmt.Fprintf(m.Out, "...Unable to get an update from the %q chart repository (%s):\n\t%s\n", r.Config.Name, r.Config.URL, err)
}
} else {
// For those dependencies that are not known to helm and using a
// generated key name we display the repo url.
if strings.HasPrefix(r.Config.Name, managerKeyPrefix) {
fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.URL)
} else {
fmt.Fprintf(m.Out, "...Successfully got an update from the %q chart repository\n", r.Config.Name)
}
}
wg.Done()
}(r)
}
wg.Wait()
return nil
}
// findChartURL searches the cache of repo data for a chart that has the name and the repoURL specified.
//
// 'name' is the name of the chart. Version is an exact semver, or an empty string. If empty, the
// newest version will be returned.
//
// repoURL is the repository to search
//
// If it finds a URL that is "relative", it will prepend the repoURL.
func (m *Manager) findChartURL(name, version, repoURL string, repos map[string]*repo.ChartRepository) (url, username, password string, insecureSkipTLSVerify, passCredentialsAll bool, caFile, certFile, keyFile string, err error) {
if registry.IsOCI(repoURL) {
return fmt.Sprintf("%s/%s:%s", repoURL, name, version), "", "", false, false, "", "", "", nil
}
for _, cr := range repos {
if urlutil.Equal(repoURL, cr.Config.URL) {
var entry repo.ChartVersions
entry, err = findEntryByName(name, cr)
if err != nil {
// TODO: Where linting is skipped in this function we should
// refactor to remove naked returns while ensuring the same
// behavior
//nolint:nakedret
return
}
var ve *repo.ChartVersion
ve, err = findVersionedEntry(version, entry)
if err != nil {
//nolint:nakedret
return
}
url, err = repo.ResolveReferenceURL(repoURL, ve.URLs[0])
if err != nil {
//nolint:nakedret
return
}
username = cr.Config.Username
password = cr.Config.Password
passCredentialsAll = cr.Config.PassCredentialsAll
insecureSkipTLSVerify = cr.Config.InsecureSkipTLSVerify
caFile = cr.Config.CAFile
certFile = cr.Config.CertFile
keyFile = cr.Config.KeyFile
//nolint:nakedret
return
}
}
url, err = repo.FindChartInRepoURL(repoURL, name, m.Getters, repo.WithChartVersion(version), repo.WithClientTLS(certFile, keyFile, caFile))
if err == nil {
return url, username, password, false, false, "", "", "", err
}
err = fmt.Errorf("chart %s not found in %s: %w", name, repoURL, err)
return url, username, password, false, false, "", "", "", err
}
// findEntryByName finds an entry in the chart repository whose name matches the given name.
//
// It returns the ChartVersions for that entry.
func findEntryByName(name string, cr *repo.ChartRepository) (repo.ChartVersions, error) {
for ename, entry := range cr.IndexFile.Entries {
if ename == name {
return entry, nil
}
}
return nil, errors.New("entry not found")
}
// findVersionedEntry takes a ChartVersions list and returns a single chart version that satisfies the version constraints.
//
// If version is empty, the first chart found is returned.
func findVersionedEntry(version string, vers repo.ChartVersions) (*repo.ChartVersion, error) {
for _, verEntry := range vers {
if len(verEntry.URLs) == 0 {
// Not a legit entry.
continue
}
if version == "" || versionEquals(version, verEntry.Version) {
return verEntry, nil
}
}
return nil, errors.New("no matching version")
}
func versionEquals(v1, v2 string) bool {
sv1, err := semver.NewVersion(v1)
if err != nil {
// Fallback to string comparison.
return v1 == v2
}
sv2, err := semver.NewVersion(v2)
if err != nil {
return false
}
return sv1.Equal(sv2)
}
// loadChartRepositories reads the repositories.yaml, and then builds a map of
// ChartRepositories.
//
// The key is the local name (which is only present in the repositories.yaml).
func (m *Manager) loadChartRepositories() (map[string]*repo.ChartRepository, error) {
indices := map[string]*repo.ChartRepository{}
// Load repositories.yaml file
rf, err := loadRepoConfig(m.RepositoryConfig)
if err != nil {
return indices, fmt.Errorf("failed to load %s: %w", m.RepositoryConfig, err)
}
for _, re := range rf.Repositories {
lname := re.Name
idxFile := filepath.Join(m.RepositoryCache, helmpath.CacheIndexFile(lname))
index, err := repo.LoadIndexFile(idxFile)
if err != nil {
return indices, err
}
// TODO: use constructor
cr := &repo.ChartRepository{
Config: re,
IndexFile: index,
}
indices[lname] = cr
}
return indices, nil
}
// writeLock writes a lockfile to disk
func writeLock(chartpath string, lock *chart.Lock, legacyLockfile bool) error {
data, err := yaml.Marshal(lock)
if err != nil {
return err
}
lockfileName := "Chart.lock"
if legacyLockfile {
lockfileName = "requirements.lock"
}
dest := filepath.Join(chartpath, lockfileName)
info, err := os.Lstat(dest)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("error getting info for %q: %w", dest, err)
} else if err == nil {
if info.Mode()&os.ModeSymlink != 0 {
link, err := os.Readlink(dest)
if err != nil {
return fmt.Errorf("error reading symlink for %q: %w", dest, err)
}
return fmt.Errorf("the %s file is a symlink to %q", lockfileName, link)
}
}
return os.WriteFile(dest, data, 0644)
}
// archive a dep chart from local directory and save it into destPath
func tarFromLocalDir(chartpath, name, repo, version, destPath string) (string, error) {
if !strings.HasPrefix(repo, "file://") {
return "", fmt.Errorf("wrong format: chart %s repository %s", name, repo)
}
origPath, err := resolver.GetLocalPath(repo, chartpath)
if err != nil {
return "", err
}
ch, err := loader.LoadDir(origPath)
if err != nil {
return "", err
}
constraint, err := semver.NewConstraint(version)
if err != nil {
return "", fmt.Errorf("dependency %s has an invalid version/constraint format: %w", name, err)
}
v, err := semver.NewVersion(ch.Metadata.Version)
if err != nil {
return "", err
}
if constraint.Check(v) {
_, err = chartutil.Save(ch, destPath)
return ch.Metadata.Version, err
}
return "", fmt.Errorf("can't get a valid version for dependency %s", name)
}
// The prefix to use for cache keys created by the manager for repo names
const managerKeyPrefix = "helm-manager-"
// key is used to turn a name, such as a repository url, into a filesystem
// safe name that is unique for querying. To accomplish this a unique hash of
// the string is used.
func key(name string) (string, error) {
in := strings.NewReader(name)
hash := crypto.SHA256.New()
if _, err := io.Copy(hash, in); err != nil {
return "", nil
}
return hex.EncodeToString(hash.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/gates/gates_test.go | pkg/gates/gates_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 gates
import (
"os"
"testing"
)
const name string = "HELM_EXPERIMENTAL_FEATURE"
func TestIsEnabled(t *testing.T) {
g := Gate(name)
if g.IsEnabled() {
t.Errorf("feature gate shows as available, but the environment variable %s was not set", name)
}
t.Setenv(name, "1")
if !g.IsEnabled() {
t.Errorf("feature gate shows as disabled, but the environment variable %s was set", name)
}
}
func TestError(t *testing.T) {
os.Unsetenv(name)
g := Gate(name)
if g.Error().Error() != "this feature has been marked as experimental and is not enabled by default. Please set HELM_EXPERIMENTAL_FEATURE=1 in your environment to use this feature" {
t.Errorf("incorrect error message. Received %s", g.Error().Error())
}
}
func TestString(t *testing.T) {
os.Unsetenv(name)
g := Gate(name)
if g.String() != "HELM_EXPERIMENTAL_FEATURE" {
t.Errorf("incorrect string representation. Received %s", g.String())
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/gates/gates.go | pkg/gates/gates.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 gates
import (
"fmt"
"os"
)
// Gate is the name of the feature gate.
type Gate string
// String returns the string representation of this feature gate.
func (g Gate) String() string {
return string(g)
}
// IsEnabled determines whether a certain feature gate is enabled.
func (g Gate) IsEnabled() bool {
return os.Getenv(string(g)) != ""
}
func (g Gate) Error() error {
return fmt.Errorf("this feature has been marked as experimental and is not enabled by default. Please set %s=1 in your environment to use this feature", g.String())
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/gates/doc.go | pkg/gates/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 gates provides a general tool for working with experimental feature gates.
This provides convenience methods where the user can determine if certain experimental features are enabled.
*/
package gates
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/parser.go | pkg/strvals/parser.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 strvals
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"unicode"
"sigs.k8s.io/yaml"
)
// ErrNotList indicates that a non-list was treated as a list.
var ErrNotList = errors.New("not a list")
// MaxIndex is the maximum index that will be allowed by setIndex.
// The default value 65536 = 1024 * 64
var MaxIndex = 65536
// MaxNestedNameLevel is the maximum level of nesting for a value name that
// will be allowed.
var MaxNestedNameLevel = 30
// ToYAML takes a string of arguments and converts to a YAML document.
func ToYAML(s string) (string, error) {
m, err := Parse(s)
if err != nil {
return "", err
}
d, err := yaml.Marshal(m)
return strings.TrimSuffix(string(d), "\n"), err
}
// Parse parses a set line.
//
// A set line is of the form name1=value1,name2=value2
func Parse(s string) (map[string]interface{}, error) {
vals := map[string]interface{}{}
scanner := bytes.NewBufferString(s)
t := newParser(scanner, vals, false)
err := t.parse()
return vals, err
}
// ParseString parses a set line and forces a string value.
//
// A set line is of the form name1=value1,name2=value2
func ParseString(s string) (map[string]interface{}, error) {
vals := map[string]interface{}{}
scanner := bytes.NewBufferString(s)
t := newParser(scanner, vals, true)
err := t.parse()
return vals, err
}
// ParseInto parses a strvals line and merges the result into dest.
//
// If the strval string has a key that exists in dest, it overwrites the
// dest version.
func ParseInto(s string, dest map[string]interface{}) error {
scanner := bytes.NewBufferString(s)
t := newParser(scanner, dest, false)
return t.parse()
}
// ParseFile parses a set line, but its final value is loaded from the file at the path specified by the original value.
//
// A set line is of the form name1=path1,name2=path2
//
// When the files at path1 and path2 contained "val1" and "val2" respectively, the set line is consumed as
// name1=val1,name2=val2
func ParseFile(s string, reader RunesValueReader) (map[string]interface{}, error) {
vals := map[string]interface{}{}
scanner := bytes.NewBufferString(s)
t := newFileParser(scanner, vals, reader)
err := t.parse()
return vals, err
}
// ParseIntoString parses a strvals line and merges the result into dest.
//
// This method always returns a string as the value.
func ParseIntoString(s string, dest map[string]interface{}) error {
scanner := bytes.NewBufferString(s)
t := newParser(scanner, dest, true)
return t.parse()
}
// ParseJSON parses a string with format key1=val1, key2=val2, ...
// where values are json strings (null, or scalars, or arrays, or objects).
// An empty val is treated as null.
//
// If a key exists in dest, the new value overwrites the dest version.
func ParseJSON(s string, dest map[string]interface{}) error {
scanner := bytes.NewBufferString(s)
t := newJSONParser(scanner, dest)
return t.parse()
}
// ParseIntoFile parses a filevals line and merges the result into dest.
//
// This method always returns a string as the value.
func ParseIntoFile(s string, dest map[string]interface{}, reader RunesValueReader) error {
scanner := bytes.NewBufferString(s)
t := newFileParser(scanner, dest, reader)
return t.parse()
}
// RunesValueReader is a function that takes the given value (a slice of runes)
// and returns the parsed value
type RunesValueReader func([]rune) (interface{}, error)
// parser is a simple parser that takes a strvals line and parses it into a
// map representation.
//
// where sc is the source of the original data being parsed
// where data is the final parsed data from the parses with correct types
type parser struct {
sc *bytes.Buffer
data map[string]interface{}
reader RunesValueReader
isjsonval bool
}
func newParser(sc *bytes.Buffer, data map[string]interface{}, stringBool bool) *parser {
stringConverter := func(rs []rune) (interface{}, error) {
return typedVal(rs, stringBool), nil
}
return &parser{sc: sc, data: data, reader: stringConverter}
}
func newJSONParser(sc *bytes.Buffer, data map[string]interface{}) *parser {
return &parser{sc: sc, data: data, reader: nil, isjsonval: true}
}
func newFileParser(sc *bytes.Buffer, data map[string]interface{}, reader RunesValueReader) *parser {
return &parser{sc: sc, data: data, reader: reader}
}
func (t *parser) parse() error {
for {
err := t.key(t.data, 0)
if err == nil {
continue
}
if errors.Is(err, io.EOF) {
return nil
}
return err
}
}
func runeSet(r []rune) map[rune]bool {
s := make(map[rune]bool, len(r))
for _, rr := range r {
s[rr] = true
}
return s
}
func (t *parser) key(data map[string]interface{}, nestedNameLevel int) (reterr error) {
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("unable to parse key: %s", r)
}
}()
stop := runeSet([]rune{'=', '[', ',', '.'})
for {
switch k, last, err := runesUntil(t.sc, stop); {
case err != nil:
if len(k) == 0 {
return err
}
return fmt.Errorf("key %q has no value", string(k))
//set(data, string(k), "")
//return err
case last == '[':
// We are in a list index context, so we need to set an index.
i, err := t.keyIndex()
if err != nil {
return fmt.Errorf("error parsing index: %w", err)
}
kk := string(k)
// Find or create target list
list := []interface{}{}
if _, ok := data[kk]; ok {
list = data[kk].([]interface{})
}
// Now we need to get the value after the ].
list, err = t.listItem(list, i, nestedNameLevel)
set(data, kk, list)
return err
case last == '=':
if t.isjsonval {
empval, err := t.emptyVal()
if err != nil {
return err
}
if empval {
set(data, string(k), nil)
return nil
}
// parse jsonvals by using Go’s JSON standard library
// Decode is preferred to Unmarshal in order to parse just the json parts of the list key1=jsonval1,key2=jsonval2,...
// Since Decode has its own buffer that consumes more characters (from underlying t.sc) than the ones actually decoded,
// we invoke Decode on a separate reader built with a copy of what is left in t.sc. After Decode is executed, we
// discard in t.sc the chars of the decoded json value (the number of those characters is returned by InputOffset).
var jsonval interface{}
dec := json.NewDecoder(strings.NewReader(t.sc.String()))
if err = dec.Decode(&jsonval); err != nil {
return err
}
set(data, string(k), jsonval)
if _, err = io.CopyN(io.Discard, t.sc, dec.InputOffset()); err != nil {
return err
}
// skip possible blanks and comma
_, err = t.emptyVal()
return err
}
// End of key. Consume =, Get value.
// FIXME: Get value list first
vl, e := t.valList()
switch e {
case nil:
set(data, string(k), vl)
return nil
case io.EOF:
set(data, string(k), "")
return e
case ErrNotList:
rs, e := t.val()
if e != nil && e != io.EOF {
return e
}
v, e := t.reader(rs)
set(data, string(k), v)
return e
default:
return e
}
case last == ',':
// No value given. Set the value to empty string. Return error.
set(data, string(k), "")
return fmt.Errorf("key %q has no value (cannot end with ,)", string(k))
case last == '.':
// Check value name is within the maximum nested name level
nestedNameLevel++
if nestedNameLevel > MaxNestedNameLevel {
return fmt.Errorf("value name nested level is greater than maximum supported nested level of %d", MaxNestedNameLevel)
}
// First, create or find the target map.
inner := map[string]interface{}{}
if _, ok := data[string(k)]; ok {
inner = data[string(k)].(map[string]interface{})
}
// Recurse
e := t.key(inner, nestedNameLevel)
if e == nil && len(inner) == 0 {
return fmt.Errorf("key map %q has no value", string(k))
}
if len(inner) != 0 {
set(data, string(k), inner)
}
return e
}
}
}
func set(data map[string]interface{}, key string, val interface{}) {
// If key is empty, don't set it.
if len(key) == 0 {
return
}
data[key] = val
}
func setIndex(list []interface{}, index int, val interface{}) (l2 []interface{}, err error) {
// There are possible index values that are out of range on a target system
// causing a panic. This will catch the panic and return an error instead.
// The value of the index that causes a panic varies from system to system.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error processing index %d: %s", index, r)
}
}()
if index < 0 {
return list, fmt.Errorf("negative %d index not allowed", index)
}
if index > MaxIndex {
return list, fmt.Errorf("index of %d is greater than maximum supported index of %d", index, MaxIndex)
}
if len(list) <= index {
newlist := make([]interface{}, index+1)
copy(newlist, list)
list = newlist
}
list[index] = val
return list, nil
}
func (t *parser) keyIndex() (int, error) {
// First, get the key.
stop := runeSet([]rune{']'})
v, _, err := runesUntil(t.sc, stop)
if err != nil {
return 0, err
}
// v should be the index
return strconv.Atoi(string(v))
}
func (t *parser) listItem(list []interface{}, i, nestedNameLevel int) ([]interface{}, error) {
if i < 0 {
return list, fmt.Errorf("negative %d index not allowed", i)
}
stop := runeSet([]rune{'[', '.', '='})
switch k, last, err := runesUntil(t.sc, stop); {
case len(k) > 0:
return list, fmt.Errorf("unexpected data at end of array index: %q", k)
case err != nil:
return list, err
case last == '=':
if t.isjsonval {
empval, err := t.emptyVal()
if err != nil {
return list, err
}
if empval {
return setIndex(list, i, nil)
}
// parse jsonvals by using Go’s JSON standard library
// Decode is preferred to Unmarshal in order to parse just the json parts of the list key1=jsonval1,key2=jsonval2,...
// Since Decode has its own buffer that consumes more characters (from underlying t.sc) than the ones actually decoded,
// we invoke Decode on a separate reader built with a copy of what is left in t.sc. After Decode is executed, we
// discard in t.sc the chars of the decoded json value (the number of those characters is returned by InputOffset).
var jsonval interface{}
dec := json.NewDecoder(strings.NewReader(t.sc.String()))
if err = dec.Decode(&jsonval); err != nil {
return list, err
}
if list, err = setIndex(list, i, jsonval); err != nil {
return list, err
}
if _, err = io.CopyN(io.Discard, t.sc, dec.InputOffset()); err != nil {
return list, err
}
// skip possible blanks and comma
_, err = t.emptyVal()
return list, err
}
vl, e := t.valList()
switch e {
case nil:
return setIndex(list, i, vl)
case io.EOF:
return setIndex(list, i, "")
case ErrNotList:
rs, e := t.val()
if e != nil && e != io.EOF {
return list, e
}
v, e := t.reader(rs)
if e != nil {
return list, e
}
return setIndex(list, i, v)
default:
return list, e
}
case last == '[':
// now we have a nested list. Read the index and handle.
nextI, err := t.keyIndex()
if err != nil {
return list, fmt.Errorf("error parsing index: %w", err)
}
var crtList []interface{}
if len(list) > i {
// If nested list already exists, take the value of list to next cycle.
existed := list[i]
if existed != nil {
crtList = list[i].([]interface{})
}
}
// Now we need to get the value after the ].
list2, err := t.listItem(crtList, nextI, nestedNameLevel)
if err != nil {
return list, err
}
return setIndex(list, i, list2)
case last == '.':
// We have a nested object. Send to t.key
inner := map[string]interface{}{}
if len(list) > i {
var ok bool
inner, ok = list[i].(map[string]interface{})
if !ok {
// We have indices out of order. Initialize empty value.
list[i] = map[string]interface{}{}
inner = list[i].(map[string]interface{})
}
}
// Recurse
e := t.key(inner, nestedNameLevel)
if e != nil {
return list, e
}
return setIndex(list, i, inner)
default:
return nil, fmt.Errorf("parse error: unexpected token %v", last)
}
}
// check for an empty value
// read and consume optional spaces until comma or EOF (empty val) or any other char (not empty val)
// comma and spaces are consumed, while any other char is not consumed
func (t *parser) emptyVal() (bool, error) {
for {
r, _, e := t.sc.ReadRune()
if e == io.EOF {
return true, nil
}
if e != nil {
return false, e
}
if r == ',' {
return true, nil
}
if !unicode.IsSpace(r) {
t.sc.UnreadRune()
return false, nil
}
}
}
func (t *parser) val() ([]rune, error) {
stop := runeSet([]rune{','})
v, _, err := runesUntil(t.sc, stop)
return v, err
}
func (t *parser) valList() ([]interface{}, error) {
r, _, e := t.sc.ReadRune()
if e != nil {
return []interface{}{}, e
}
if r != '{' {
t.sc.UnreadRune()
return []interface{}{}, ErrNotList
}
list := []interface{}{}
stop := runeSet([]rune{',', '}'})
for {
switch rs, last, err := runesUntil(t.sc, stop); {
case err != nil:
if err == io.EOF {
err = errors.New("list must terminate with '}'")
}
return list, err
case last == '}':
// If this is followed by ',', consume it.
if r, _, e := t.sc.ReadRune(); e == nil && r != ',' {
t.sc.UnreadRune()
}
v, e := t.reader(rs)
list = append(list, v)
return list, e
case last == ',':
v, e := t.reader(rs)
if e != nil {
return list, e
}
list = append(list, v)
}
}
}
func runesUntil(in io.RuneReader, stop map[rune]bool) ([]rune, rune, error) {
v := []rune{}
for {
switch r, _, e := in.ReadRune(); {
case e != nil:
return v, r, e
case inMap(r, stop):
return v, r, nil
case r == '\\':
next, _, e := in.ReadRune()
if e != nil {
return v, next, e
}
v = append(v, next)
default:
v = append(v, r)
}
}
}
func inMap(k rune, m map[rune]bool) bool {
_, ok := m[k]
return ok
}
func typedVal(v []rune, st bool) interface{} {
val := string(v)
if st {
return val
}
if strings.EqualFold(val, "true") {
return true
}
if strings.EqualFold(val, "false") {
return false
}
if strings.EqualFold(val, "null") {
return nil
}
if strings.EqualFold(val, "0") {
return int64(0)
}
// If this value does not start with zero, try parsing it to an int
if len(val) != 0 && val[0] != '0' {
if iv, err := strconv.ParseInt(val, 10, 64); err == nil {
return iv
}
}
return val
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/fuzz_test.go | pkg/strvals/fuzz_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 strvals
import (
"testing"
)
func FuzzParse(f *testing.F) {
f.Fuzz(func(_ *testing.T, data string) {
_, _ = Parse(data)
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/parser_test.go | pkg/strvals/parser_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 strvals
import (
"fmt"
"strings"
"testing"
"sigs.k8s.io/yaml"
)
func TestSetIndex(t *testing.T) {
tests := []struct {
name string
initial []interface{}
expect []interface{}
add int
val int
err bool
}{
{
name: "short",
initial: []interface{}{0, 1},
expect: []interface{}{0, 1, 2},
add: 2,
val: 2,
err: false,
},
{
name: "equal",
initial: []interface{}{0, 1},
expect: []interface{}{0, 2},
add: 1,
val: 2,
err: false,
},
{
name: "long",
initial: []interface{}{0, 1, 2, 3, 4, 5},
expect: []interface{}{0, 1, 2, 4, 4, 5},
add: 3,
val: 4,
err: false,
},
{
name: "negative",
initial: []interface{}{0, 1, 2, 3, 4, 5},
expect: []interface{}{0, 1, 2, 3, 4, 5},
add: -1,
val: 4,
err: true,
},
{
name: "large",
initial: []interface{}{0, 1, 2, 3, 4, 5},
expect: []interface{}{0, 1, 2, 3, 4, 5},
add: MaxIndex + 1,
val: 4,
err: true,
},
}
for _, tt := range tests {
got, err := setIndex(tt.initial, tt.add, tt.val)
if err != nil && tt.err == false {
t.Fatalf("%s: Expected no error but error returned", tt.name)
} else if err == nil && tt.err == true {
t.Fatalf("%s: Expected error but no error returned", tt.name)
}
if len(got) != len(tt.expect) {
t.Fatalf("%s: Expected length %d, got %d", tt.name, len(tt.expect), len(got))
}
if !tt.err {
if gg := got[tt.add].(int); gg != tt.val {
t.Errorf("%s, Expected value %d, got %d", tt.name, tt.val, gg)
}
}
for k, v := range got {
if v != tt.expect[k] {
t.Errorf("%s, Expected value %d, got %d", tt.name, tt.expect[k], v)
}
}
}
}
func TestParseSet(t *testing.T) {
testsString := []struct {
str string
expect map[string]interface{}
err bool
}{
{
str: "long_int_string=1234567890",
expect: map[string]interface{}{"long_int_string": "1234567890"},
err: false,
},
{
str: "boolean=true",
expect: map[string]interface{}{"boolean": "true"},
err: false,
},
{
str: "is_null=null",
expect: map[string]interface{}{"is_null": "null"},
err: false,
},
{
str: "zero=0",
expect: map[string]interface{}{"zero": "0"},
err: false,
},
}
tests := []struct {
str string
expect map[string]interface{}
err bool
}{
{
"name1=null,f=false,t=true",
map[string]interface{}{"name1": nil, "f": false, "t": true},
false,
},
{
"name1=value1",
map[string]interface{}{"name1": "value1"},
false,
},
{
"name1=value1,name2=value2",
map[string]interface{}{"name1": "value1", "name2": "value2"},
false,
},
{
"name1=value1,name2=value2,",
map[string]interface{}{"name1": "value1", "name2": "value2"},
false,
},
{
str: "name1=value1,,,,name2=value2,",
err: true,
},
{
str: "name1=,name2=value2",
expect: map[string]interface{}{"name1": "", "name2": "value2"},
},
{
str: "leading_zeros=00009",
expect: map[string]interface{}{"leading_zeros": "00009"},
},
{
str: "zero_int=0",
expect: map[string]interface{}{"zero_int": 0},
},
{
str: "long_int=1234567890",
expect: map[string]interface{}{"long_int": 1234567890},
},
{
str: "boolean=true",
expect: map[string]interface{}{"boolean": true},
},
{
str: "is_null=null",
expect: map[string]interface{}{"is_null": nil},
err: false,
},
{
str: "name1,name2=",
err: true,
},
{
str: "name1,name2=value2",
err: true,
},
{
str: "name1,name2=value2\\",
err: true,
},
{
str: "name1,name2",
err: true,
},
{
"name1=one\\,two,name2=three\\,four",
map[string]interface{}{"name1": "one,two", "name2": "three,four"},
false,
},
{
"name1=one\\=two,name2=three\\=four",
map[string]interface{}{"name1": "one=two", "name2": "three=four"},
false,
},
{
"name1=one two three,name2=three two one",
map[string]interface{}{"name1": "one two three", "name2": "three two one"},
false,
},
{
"outer.inner=value",
map[string]interface{}{"outer": map[string]interface{}{"inner": "value"}},
false,
},
{
"outer.middle.inner=value",
map[string]interface{}{"outer": map[string]interface{}{"middle": map[string]interface{}{"inner": "value"}}},
false,
},
{
"outer.inner1=value,outer.inner2=value2",
map[string]interface{}{"outer": map[string]interface{}{"inner1": "value", "inner2": "value2"}},
false,
},
{
"outer.inner1=value,outer.middle.inner=value",
map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "value",
"middle": map[string]interface{}{
"inner": "value",
},
},
},
false,
},
{
str: "name1.name2",
err: true,
},
{
str: "name1.name2,name1.name3",
err: true,
},
{
str: "name1.name2=",
expect: map[string]interface{}{"name1": map[string]interface{}{"name2": ""}},
},
{
str: "name1.=name2",
err: true,
},
{
str: "name1.,name2",
err: true,
},
{
"name1={value1,value2}",
map[string]interface{}{"name1": []string{"value1", "value2"}},
false,
},
{
"name1={value1,value2},name2={value1,value2}",
map[string]interface{}{
"name1": []string{"value1", "value2"},
"name2": []string{"value1", "value2"},
},
false,
},
{
"name1={1021,902}",
map[string]interface{}{"name1": []int{1021, 902}},
false,
},
{
"name1.name2={value1,value2}",
map[string]interface{}{"name1": map[string]interface{}{"name2": []string{"value1", "value2"}}},
false,
},
{
str: "name1={1021,902",
err: true,
},
// List support
{
str: "list[0]=foo",
expect: map[string]interface{}{"list": []string{"foo"}},
},
{
str: "list[0].foo=bar",
expect: map[string]interface{}{
"list": []interface{}{
map[string]interface{}{"foo": "bar"},
},
},
},
{
str: "list[0].foo=bar,list[0].hello=world",
expect: map[string]interface{}{
"list": []interface{}{
map[string]interface{}{"foo": "bar", "hello": "world"},
},
},
},
{
str: "list[0].foo=bar,list[-30].hello=world",
err: true,
},
{
str: "list[0]=foo,list[1]=bar",
expect: map[string]interface{}{"list": []string{"foo", "bar"}},
},
{
str: "list[0]=foo,list[1]=bar,",
expect: map[string]interface{}{"list": []string{"foo", "bar"}},
},
{
str: "list[0]=foo,list[3]=bar",
expect: map[string]interface{}{"list": []interface{}{"foo", nil, nil, "bar"}},
},
{
str: "list[0]=foo,list[-20]=bar",
err: true,
},
{
str: "illegal[0]name.foo=bar",
err: true,
},
{
str: "noval[0]",
expect: map[string]interface{}{"noval": []interface{}{}},
},
{
str: "noval[0]=",
expect: map[string]interface{}{"noval": []interface{}{""}},
},
{
str: "nested[0][0]=1",
expect: map[string]interface{}{"nested": []interface{}{[]interface{}{1}}},
},
{
str: "nested[1][1]=1",
expect: map[string]interface{}{"nested": []interface{}{nil, []interface{}{nil, 1}}},
},
{
str: "name1.name2[0].foo=bar,name1.name2[1].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{{"foo": "bar"}, {"foo": "bar"}},
},
},
},
{
str: "name1.name2[1].foo=bar,name1.name2[0].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{{"foo": "bar"}, {"foo": "bar"}},
},
},
},
{
str: "name1.name2[1].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{nil, {"foo": "bar"}},
},
},
},
{
str: "]={}].",
err: true,
},
}
for _, tt := range tests {
got, err := Parse(tt.str)
if err != nil {
if tt.err {
continue
}
t.Fatalf("%s: %s", tt.str, err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.str)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
}
}
for _, tt := range testsString {
got, err := ParseString(tt.str)
if err != nil {
if tt.err {
continue
}
t.Fatalf("%s: %s", tt.str, err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.str)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
}
}
}
func TestParseInto(t *testing.T) {
tests := []struct {
input string
input2 string
got map[string]interface{}
expect map[string]interface{}
err bool
}{
{
input: "outer.inner1=value1,outer.inner3=value3,outer.inner4=4",
got: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "overwrite",
"inner2": "value2",
},
},
expect: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "value1",
"inner2": "value2",
"inner3": "value3",
"inner4": 4,
}},
err: false,
},
{
input: "listOuter[0][0].type=listValue",
input2: "listOuter[0][0].status=alive",
got: map[string]interface{}{},
expect: map[string]interface{}{
"listOuter": [][]interface{}{{map[string]string{
"type": "listValue",
"status": "alive",
}}},
},
err: false,
},
{
input: "listOuter[0][0].type=listValue",
input2: "listOuter[1][0].status=alive",
got: map[string]interface{}{},
expect: map[string]interface{}{
"listOuter": [][]interface{}{
{
map[string]string{"type": "listValue"},
},
{
map[string]string{"status": "alive"},
},
},
},
err: false,
},
{
input: "listOuter[0][1][0].type=listValue",
input2: "listOuter[0][0][1].status=alive",
got: map[string]interface{}{
"listOuter": []interface{}{
[]interface{}{
[]interface{}{
map[string]string{"exited": "old"},
},
},
},
},
expect: map[string]interface{}{
"listOuter": [][][]interface{}{
{
{
map[string]string{"exited": "old"},
map[string]string{"status": "alive"},
},
{
map[string]string{"type": "listValue"},
},
},
},
},
err: false,
},
}
for _, tt := range tests {
if err := ParseInto(tt.input, tt.got); err != nil {
t.Fatal(err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.input)
}
if tt.input2 != "" {
if err := ParseInto(tt.input2, tt.got); err != nil {
t.Fatal(err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.input2)
}
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(tt.got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2)
}
}
}
func TestParseIntoString(t *testing.T) {
got := map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "overwrite",
"inner2": "value2",
},
}
input := "outer.inner1=1,outer.inner3=3"
expect := map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "1",
"inner2": "value2",
"inner3": "3",
},
}
if err := ParseIntoString(input, got); err != nil {
t.Fatal(err)
}
y1, err := yaml.Marshal(expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
}
}
func TestParseJSON(t *testing.T) {
tests := []struct {
input string
got map[string]interface{}
expect map[string]interface{}
err bool
}{
{ // set json scalars values, and replace one existing key
input: "outer.inner1=\"1\",outer.inner3=3,outer.inner4=true,outer.inner5=\"true\"",
got: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "overwrite",
"inner2": "value2",
},
},
expect: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "1",
"inner2": "value2",
"inner3": 3,
"inner4": true,
"inner5": "true",
},
},
err: false,
},
{ // set json objects and arrays, and replace one existing key
input: "outer.inner1={\"a\":\"1\",\"b\":2,\"c\":[1,2,3]},outer.inner3=[\"new value 1\",\"new value 2\"],outer.inner4={\"aa\":\"1\",\"bb\":2,\"cc\":[1,2,3]},outer.inner5=[{\"A\":\"1\",\"B\":2,\"C\":[1,2,3]}]",
got: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": map[string]interface{}{
"x": "overwrite",
},
"inner2": "value2",
"inner3": []interface{}{
"overwrite",
},
},
},
expect: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": map[string]interface{}{"a": "1", "b": 2, "c": []interface{}{1, 2, 3}},
"inner2": "value2",
"inner3": []interface{}{"new value 1", "new value 2"},
"inner4": map[string]interface{}{"aa": "1", "bb": 2, "cc": []interface{}{1, 2, 3}},
"inner5": []interface{}{map[string]interface{}{"A": "1", "B": 2, "C": []interface{}{1, 2, 3}}},
},
},
err: false,
},
{ // null assignment, and no value assigned (equivalent to null)
input: "outer.inner1=,outer.inner3={\"aa\":\"1\",\"bb\":2,\"cc\":[1,2,3]},outer.inner3.cc[1]=null",
got: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": map[string]interface{}{
"x": "overwrite",
},
"inner2": "value2",
},
},
expect: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": nil,
"inner2": "value2",
"inner3": map[string]interface{}{"aa": "1", "bb": 2, "cc": []interface{}{1, nil, 3}},
},
},
err: false,
},
{ // syntax error
input: "outer.inner1={\"a\":\"1\",\"b\":2,\"c\":[1,2,3]},outer.inner3=[\"new value 1\",\"new value 2\"],outer.inner4={\"aa\":\"1\",\"bb\":2,\"cc\":[1,2,3]},outer.inner5={\"A\":\"1\",\"B\":2,\"C\":[1,2,3]}]",
got: nil,
expect: nil,
err: true,
},
}
for _, tt := range tests {
if err := ParseJSON(tt.input, tt.got); err != nil {
if tt.err {
continue
}
t.Fatalf("%s: %s", tt.input, err)
}
if tt.err {
t.Fatalf("%s: Expected error. Got nil", tt.input)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatalf("Error serializing expected value: %s", err)
}
y2, err := yaml.Marshal(tt.got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2)
}
}
}
func TestParseFile(t *testing.T) {
input := "name1=path1"
expect := map[string]interface{}{
"name1": "value1",
}
rs2v := func(rs []rune) (interface{}, error) {
v := string(rs)
if v != "path1" {
t.Errorf("%s: runesToVal: Expected value path1, got %s", input, v)
return "", nil
}
return "value1", nil
}
got, err := ParseFile(input, rs2v)
if err != nil {
t.Fatal(err)
}
y1, err := yaml.Marshal(expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
}
}
func TestParseIntoFile(t *testing.T) {
got := map[string]interface{}{}
input := "name1=path1"
expect := map[string]interface{}{
"name1": "value1",
}
rs2v := func(rs []rune) (interface{}, error) {
v := string(rs)
if v != "path1" {
t.Errorf("%s: runesToVal: Expected value path1, got %s", input, v)
return "", nil
}
return "value1", nil
}
if err := ParseIntoFile(input, got, rs2v); err != nil {
t.Fatal(err)
}
y1, err := yaml.Marshal(expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", input, y1, y2)
}
}
func TestToYAML(t *testing.T) {
// The TestParse does the hard part. We just verify that YAML formatting is
// happening.
o, err := ToYAML("name=value")
if err != nil {
t.Fatal(err)
}
expect := "name: value"
if o != expect {
t.Errorf("Expected %q, got %q", expect, o)
}
}
func TestParseSetNestedLevels(t *testing.T) {
var keyMultipleNestedLevels strings.Builder
for i := 1; i <= MaxNestedNameLevel+2; i++ {
tmpStr := fmt.Sprintf("name%d", i)
if i <= MaxNestedNameLevel+1 {
tmpStr = tmpStr + "."
}
keyMultipleNestedLevels.WriteString(tmpStr)
}
tests := []struct {
str string
expect map[string]interface{}
err bool
errStr string
}{
{
"outer.middle.inner=value",
map[string]interface{}{"outer": map[string]interface{}{"middle": map[string]interface{}{"inner": "value"}}},
false,
"",
},
{
str: keyMultipleNestedLevels.String() + "=value",
err: true,
errStr: fmt.Sprintf("value name nested level is greater than maximum supported nested level of %d",
MaxNestedNameLevel),
},
}
for _, tt := range tests {
got, err := Parse(tt.str)
if err != nil {
if tt.err {
if tt.errStr != "" {
if err.Error() != tt.errStr {
t.Errorf("Expected error: %s. Got error: %s", tt.errStr, err.Error())
}
}
continue
}
t.Fatalf("%s: %s", tt.str, err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.str)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/literal_parser_test.go | pkg/strvals/literal_parser_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 strvals
import (
"fmt"
"strings"
"testing"
"sigs.k8s.io/yaml"
)
func TestParseLiteral(t *testing.T) {
cases := []struct {
str string
expect map[string]interface{}
err bool
}{
{
str: "name",
err: true,
},
{
str: "name=",
expect: map[string]interface{}{"name": ""},
},
{
str: "name=value",
expect: map[string]interface{}{"name": "value"},
err: false,
},
{
str: "long_int_string=1234567890",
expect: map[string]interface{}{"long_int_string": "1234567890"},
err: false,
},
{
str: "boolean=true",
expect: map[string]interface{}{"boolean": "true"},
err: false,
},
{
str: "is_null=null",
expect: map[string]interface{}{"is_null": "null"},
err: false,
},
{
str: "zero=0",
expect: map[string]interface{}{"zero": "0"},
err: false,
},
{
str: "name1=null,name2=value2",
expect: map[string]interface{}{"name1": "null,name2=value2"},
err: false,
},
{
str: "name1=value,,,tail",
expect: map[string]interface{}{"name1": "value,,,tail"},
err: false,
},
{
str: "leading_zeros=00009",
expect: map[string]interface{}{"leading_zeros": "00009"},
err: false,
},
{
str: "name=one two three",
expect: map[string]interface{}{"name": "one two three"},
err: false,
},
{
str: "outer.inner=value",
expect: map[string]interface{}{"outer": map[string]interface{}{"inner": "value"}},
err: false,
},
{
str: "outer.middle.inner=value",
expect: map[string]interface{}{"outer": map[string]interface{}{"middle": map[string]interface{}{"inner": "value"}}},
err: false,
},
{
str: "name1.name2",
err: true,
},
{
str: "name1.name2=",
expect: map[string]interface{}{"name1": map[string]interface{}{"name2": ""}},
err: false,
},
{
str: "name1.=name2",
err: true,
},
{
str: "name1.,name2",
err: true,
},
{
str: "name1={value1,value2}",
expect: map[string]interface{}{"name1": "{value1,value2}"},
},
// List support
{
str: "list[0]=foo",
expect: map[string]interface{}{"list": []string{"foo"}},
err: false,
},
{
str: "list[0].foo=bar",
expect: map[string]interface{}{
"list": []interface{}{
map[string]interface{}{"foo": "bar"},
},
},
err: false,
},
{
str: "list[-30].hello=world",
err: true,
},
{
str: "list[3]=bar",
expect: map[string]interface{}{"list": []interface{}{nil, nil, nil, "bar"}},
err: false,
},
{
str: "illegal[0]name.foo=bar",
err: true,
},
{
str: "noval[0]",
expect: map[string]interface{}{"noval": []interface{}{}},
err: false,
},
{
str: "noval[0]=",
expect: map[string]interface{}{"noval": []interface{}{""}},
err: false,
},
{
str: "nested[0][0]=1",
expect: map[string]interface{}{"nested": []interface{}{[]interface{}{"1"}}},
err: false,
},
{
str: "nested[1][1]=1",
expect: map[string]interface{}{"nested": []interface{}{nil, []interface{}{nil, "1"}}},
err: false,
},
{
str: "name1.name2[0].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{{"foo": "bar"}},
},
},
},
{
str: "name1.name2[1].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{nil, {"foo": "bar"}},
},
},
},
{
str: "name1.name2[1].foo=bar",
expect: map[string]interface{}{
"name1": map[string]interface{}{
"name2": []map[string]interface{}{nil, {"foo": "bar"}},
},
},
},
{
str: "]={}].",
expect: map[string]interface{}{"]": "{}]."},
err: false,
},
// issue test cases: , = $ ( ) { } . \ \\
{
str: "name=val,val",
expect: map[string]interface{}{"name": "val,val"},
err: false,
},
{
str: "name=val.val",
expect: map[string]interface{}{"name": "val.val"},
err: false,
},
{
str: "name=val=val",
expect: map[string]interface{}{"name": "val=val"},
err: false,
},
{
str: "name=val$val",
expect: map[string]interface{}{"name": "val$val"},
err: false,
},
{
str: "name=(value",
expect: map[string]interface{}{"name": "(value"},
err: false,
},
{
str: "name=value)",
expect: map[string]interface{}{"name": "value)"},
err: false,
},
{
str: "name=(value)",
expect: map[string]interface{}{"name": "(value)"},
err: false,
},
{
str: "name={value",
expect: map[string]interface{}{"name": "{value"},
err: false,
},
{
str: "name=value}",
expect: map[string]interface{}{"name": "value}"},
err: false,
},
{
str: "name={value}",
expect: map[string]interface{}{"name": "{value}"},
err: false,
},
{
str: "name={value1,value2}",
expect: map[string]interface{}{"name": "{value1,value2}"},
err: false,
},
{
str: `name=val\val`,
expect: map[string]interface{}{"name": `val\val`},
err: false,
},
{
str: `name=val\\val`,
expect: map[string]interface{}{"name": `val\\val`},
err: false,
},
{
str: `name=val\\\val`,
expect: map[string]interface{}{"name": `val\\\val`},
err: false,
},
{
str: `name={val,.?*v\0a!l)some`,
expect: map[string]interface{}{"name": `{val,.?*v\0a!l)some`},
err: false,
},
{
str: `name=em%GT)tqUDqz,i-\h+Mbqs-!:.m\\rE=mkbM#rR}@{-k@`,
expect: map[string]interface{}{"name": `em%GT)tqUDqz,i-\h+Mbqs-!:.m\\rE=mkbM#rR}@{-k@`},
},
}
for _, tt := range cases {
got, err := ParseLiteral(tt.str)
if err != nil {
if !tt.err {
t.Fatalf("%s: %s", tt.str, err)
}
continue
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.str)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
}
}
}
func TestParseLiteralInto(t *testing.T) {
tests := []struct {
input string
input2 string
got map[string]interface{}
expect map[string]interface{}
err bool
}{
{
input: "outer.inner1=value1,outer.inner3=value3,outer.inner4=4",
got: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "overwrite",
"inner2": "value2",
},
},
expect: map[string]interface{}{
"outer": map[string]interface{}{
"inner1": "value1,outer.inner3=value3,outer.inner4=4",
"inner2": "value2",
}},
err: false,
},
{
input: "listOuter[0][0].type=listValue",
input2: "listOuter[0][0].status=alive",
got: map[string]interface{}{},
expect: map[string]interface{}{
"listOuter": [][]interface{}{{map[string]string{
"type": "listValue",
"status": "alive",
}}},
},
err: false,
},
{
input: "listOuter[0][0].type=listValue",
input2: "listOuter[1][0].status=alive",
got: map[string]interface{}{},
expect: map[string]interface{}{
"listOuter": [][]interface{}{
{
map[string]string{"type": "listValue"},
},
{
map[string]string{"status": "alive"},
},
},
},
err: false,
},
{
input: "listOuter[0][1][0].type=listValue",
input2: "listOuter[0][0][1].status=alive",
got: map[string]interface{}{
"listOuter": []interface{}{
[]interface{}{
[]interface{}{
map[string]string{"exited": "old"},
},
},
},
},
expect: map[string]interface{}{
"listOuter": [][][]interface{}{
{
{
map[string]string{"exited": "old"},
map[string]string{"status": "alive"},
},
{
map[string]string{"type": "listValue"},
},
},
},
},
err: false,
},
}
for _, tt := range tests {
if err := ParseLiteralInto(tt.input, tt.got); err != nil {
t.Fatal(err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.input)
}
if tt.input2 != "" {
if err := ParseLiteralInto(tt.input2, tt.got); err != nil {
t.Fatal(err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.input2)
}
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(tt.got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.input, y1, y2)
}
}
}
func TestParseLiteralNestedLevels(t *testing.T) {
var keyMultipleNestedLevels strings.Builder
for i := 1; i <= MaxNestedNameLevel+2; i++ {
tmpStr := fmt.Sprintf("name%d", i)
if i <= MaxNestedNameLevel+1 {
tmpStr = tmpStr + "."
}
keyMultipleNestedLevels.WriteString(tmpStr)
}
tests := []struct {
str string
expect map[string]interface{}
err bool
errStr string
}{
{
"outer.middle.inner=value",
map[string]interface{}{"outer": map[string]interface{}{"middle": map[string]interface{}{"inner": "value"}}},
false,
"",
},
{
str: keyMultipleNestedLevels.String() + "=value",
err: true,
errStr: fmt.Sprintf("value name nested level is greater than maximum supported nested level of %d", MaxNestedNameLevel),
},
}
for _, tt := range tests {
got, err := ParseLiteral(tt.str)
if err != nil {
if tt.err {
if tt.errStr != "" {
if err.Error() != tt.errStr {
t.Errorf("Expected error: %s. Got error: %s", tt.errStr, err.Error())
}
}
continue
}
t.Fatalf("%s: %s", tt.str, err)
}
if tt.err {
t.Errorf("%s: Expected error. Got nil", tt.str)
}
y1, err := yaml.Marshal(tt.expect)
if err != nil {
t.Fatal(err)
}
y2, err := yaml.Marshal(got)
if err != nil {
t.Fatalf("Error serializing parsed value: %s", err)
}
if string(y1) != string(y2) {
t.Errorf("%s: Expected:\n%s\nGot:\n%s", tt.str, y1, y2)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/doc.go | pkg/strvals/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 strvals provides tools for working with strval lines.
Helm supports a compressed format for YAML settings which we call strvals.
The format is roughly like this:
name=value,topname.subname=value
The above is equivalent to the YAML document
name: value
topname:
subname: value
This package provides a parser and utilities for converting the strvals format
to other formats.
*/
package strvals
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/strvals/literal_parser.go | pkg/strvals/literal_parser.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 strvals
import (
"bytes"
"errors"
"fmt"
"io"
"strconv"
)
// ParseLiteral parses a set line interpreting the value as a literal string.
//
// A set line is of the form name1=value1
func ParseLiteral(s string) (map[string]interface{}, error) {
vals := map[string]interface{}{}
scanner := bytes.NewBufferString(s)
t := newLiteralParser(scanner, vals)
err := t.parse()
return vals, err
}
// ParseLiteralInto parses a strvals line and merges the result into dest.
// The value is interpreted as a literal string.
//
// If the strval string has a key that exists in dest, it overwrites the
// dest version.
func ParseLiteralInto(s string, dest map[string]interface{}) error {
scanner := bytes.NewBufferString(s)
t := newLiteralParser(scanner, dest)
return t.parse()
}
// literalParser is a simple parser that takes a strvals line and parses
// it into a map representation.
//
// Values are interpreted as a literal string.
//
// where sc is the source of the original data being parsed
// where data is the final parsed data from the parses with correct types
type literalParser struct {
sc *bytes.Buffer
data map[string]interface{}
}
func newLiteralParser(sc *bytes.Buffer, data map[string]interface{}) *literalParser {
return &literalParser{sc: sc, data: data}
}
func (t *literalParser) parse() error {
for {
err := t.key(t.data, 0)
if err == nil {
continue
}
if errors.Is(err, io.EOF) {
return nil
}
return err
}
}
func runesUntilLiteral(in io.RuneReader, stop map[rune]bool) ([]rune, rune, error) {
v := []rune{}
for {
switch r, _, e := in.ReadRune(); {
case e != nil:
return v, r, e
case inMap(r, stop):
return v, r, nil
default:
v = append(v, r)
}
}
}
func (t *literalParser) key(data map[string]interface{}, nestedNameLevel int) (reterr error) {
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("unable to parse key: %s", r)
}
}()
stop := runeSet([]rune{'=', '[', '.'})
for {
switch key, lastRune, err := runesUntilLiteral(t.sc, stop); {
case err != nil:
if len(key) == 0 {
return err
}
return fmt.Errorf("key %q has no value", string(key))
case lastRune == '=':
// found end of key: swallow the '=' and get the value
value, err := t.val()
if err == nil && err != io.EOF {
return err
}
set(data, string(key), string(value))
return nil
case lastRune == '.':
// Check value name is within the maximum nested name level
nestedNameLevel++
if nestedNameLevel > MaxNestedNameLevel {
return fmt.Errorf("value name nested level is greater than maximum supported nested level of %d", MaxNestedNameLevel)
}
// first, create or find the target map in the given data
inner := map[string]interface{}{}
if _, ok := data[string(key)]; ok {
inner = data[string(key)].(map[string]interface{})
}
// recurse on sub-tree with remaining data
err := t.key(inner, nestedNameLevel)
if err == nil && len(inner) == 0 {
return fmt.Errorf("key map %q has no value", string(key))
}
if len(inner) != 0 {
set(data, string(key), inner)
}
return err
case lastRune == '[':
// We are in a list index context, so we need to set an index.
i, err := t.keyIndex()
if err != nil {
return fmt.Errorf("error parsing index: %w", err)
}
kk := string(key)
// find or create target list
list := []interface{}{}
if _, ok := data[kk]; ok {
list = data[kk].([]interface{})
}
// now we need to get the value after the ]
list, err = t.listItem(list, i, nestedNameLevel)
set(data, kk, list)
return err
}
}
}
func (t *literalParser) keyIndex() (int, error) {
// First, get the key.
stop := runeSet([]rune{']'})
v, _, err := runesUntilLiteral(t.sc, stop)
if err != nil {
return 0, err
}
// v should be the index
return strconv.Atoi(string(v))
}
func (t *literalParser) listItem(list []interface{}, i, nestedNameLevel int) ([]interface{}, error) {
if i < 0 {
return list, fmt.Errorf("negative %d index not allowed", i)
}
stop := runeSet([]rune{'[', '.', '='})
switch key, lastRune, err := runesUntilLiteral(t.sc, stop); {
case len(key) > 0:
return list, fmt.Errorf("unexpected data at end of array index: %q", key)
case err != nil:
return list, err
case lastRune == '=':
value, err := t.val()
if err != nil && !errors.Is(err, io.EOF) {
return list, err
}
return setIndex(list, i, string(value))
case lastRune == '.':
// we have a nested object. Send to t.key
inner := map[string]interface{}{}
if len(list) > i {
var ok bool
inner, ok = list[i].(map[string]interface{})
if !ok {
// We have indices out of order. Initialize empty value.
list[i] = map[string]interface{}{}
inner = list[i].(map[string]interface{})
}
}
// recurse
err := t.key(inner, nestedNameLevel)
if err != nil {
return list, err
}
return setIndex(list, i, inner)
case lastRune == '[':
// now we have a nested list. Read the index and handle.
nextI, err := t.keyIndex()
if err != nil {
return list, fmt.Errorf("error parsing index: %w", err)
}
var crtList []interface{}
if len(list) > i {
// If nested list already exists, take the value of list to next cycle.
existed := list[i]
if existed != nil {
crtList = list[i].([]interface{})
}
}
// Now we need to get the value after the ].
list2, err := t.listItem(crtList, nextI, nestedNameLevel)
if err != nil {
return list, err
}
return setIndex(list, i, list2)
default:
return nil, fmt.Errorf("parse error: unexpected token %v", lastRune)
}
}
func (t *literalParser) val() ([]rune, error) {
stop := runeSet([]rune{})
v, _, err := runesUntilLiteral(t.sc, stop)
return v, err
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/dependency.go | pkg/chart/dependency.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 chart
import (
"errors"
v3chart "helm.sh/helm/v4/internal/chart/v3"
v2chart "helm.sh/helm/v4/pkg/chart/v2"
)
var NewDependencyAccessor func(dep Dependency) (DependencyAccessor, error) = NewDefaultDependencyAccessor //nolint:revive
func NewDefaultDependencyAccessor(dep Dependency) (DependencyAccessor, error) {
switch v := dep.(type) {
case v2chart.Dependency:
return &v2DependencyAccessor{&v}, nil
case *v2chart.Dependency:
return &v2DependencyAccessor{v}, nil
case v3chart.Dependency:
return &v3DependencyAccessor{&v}, nil
case *v3chart.Dependency:
return &v3DependencyAccessor{v}, nil
default:
return nil, errors.New("unsupported chart dependency type")
}
}
type v2DependencyAccessor struct {
dep *v2chart.Dependency
}
func (r *v2DependencyAccessor) Name() string {
return r.dep.Name
}
func (r *v2DependencyAccessor) Alias() string {
return r.dep.Alias
}
type v3DependencyAccessor struct {
dep *v3chart.Dependency
}
func (r *v3DependencyAccessor) Name() string {
return r.dep.Name
}
func (r *v3DependencyAccessor) Alias() string {
return r.dep.Alias
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/interfaces.go | pkg/chart/interfaces.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 chart
import (
common "helm.sh/helm/v4/pkg/chart/common"
)
type Charter interface{}
type Dependency interface{}
type Accessor interface {
Name() string
IsRoot() bool
MetadataAsMap() map[string]interface{}
Files() []*common.File
Templates() []*common.File
ChartFullPath() string
IsLibraryChart() bool
Dependencies() []Charter
MetaDependencies() []Dependency
Values() map[string]interface{}
Schema() []byte
Deprecated() bool
}
type DependencyAccessor interface {
Name() string
Alias() string
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common.go | pkg/chart/common.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 chart
import (
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
v3chart "helm.sh/helm/v4/internal/chart/v3"
common "helm.sh/helm/v4/pkg/chart/common"
v2chart "helm.sh/helm/v4/pkg/chart/v2"
)
var NewAccessor func(chrt Charter) (Accessor, error) = NewDefaultAccessor //nolint:revive
func NewDefaultAccessor(chrt Charter) (Accessor, error) {
switch v := chrt.(type) {
case v2chart.Chart:
return &v2Accessor{&v}, nil
case *v2chart.Chart:
return &v2Accessor{v}, nil
case v3chart.Chart:
return &v3Accessor{&v}, nil
case *v3chart.Chart:
return &v3Accessor{v}, nil
default:
return nil, errors.New("unsupported chart type")
}
}
type v2Accessor struct {
chrt *v2chart.Chart
}
func (r *v2Accessor) Name() string {
return r.chrt.Metadata.Name
}
func (r *v2Accessor) IsRoot() bool {
return r.chrt.IsRoot()
}
func (r *v2Accessor) MetadataAsMap() map[string]interface{} {
var ret map[string]interface{}
if r.chrt.Metadata == nil {
return ret
}
ret, err := structToMap(r.chrt.Metadata)
if err != nil {
slog.Error("error converting metadata to map", "error", err)
}
return ret
}
func (r *v2Accessor) Files() []*common.File {
return r.chrt.Files
}
func (r *v2Accessor) Templates() []*common.File {
return r.chrt.Templates
}
func (r *v2Accessor) ChartFullPath() string {
return r.chrt.ChartFullPath()
}
func (r *v2Accessor) IsLibraryChart() bool {
return strings.EqualFold(r.chrt.Metadata.Type, "library")
}
func (r *v2Accessor) Dependencies() []Charter {
var deps = make([]Charter, len(r.chrt.Dependencies()))
for i, c := range r.chrt.Dependencies() {
deps[i] = c
}
return deps
}
func (r *v2Accessor) MetaDependencies() []Dependency {
var deps = make([]Dependency, len(r.chrt.Metadata.Dependencies))
for i, c := range r.chrt.Metadata.Dependencies {
deps[i] = c
}
return deps
}
func (r *v2Accessor) Values() map[string]interface{} {
return r.chrt.Values
}
func (r *v2Accessor) Schema() []byte {
return r.chrt.Schema
}
func (r *v2Accessor) Deprecated() bool {
return r.chrt.Metadata.Deprecated
}
type v3Accessor struct {
chrt *v3chart.Chart
}
func (r *v3Accessor) Name() string {
return r.chrt.Metadata.Name
}
func (r *v3Accessor) IsRoot() bool {
return r.chrt.IsRoot()
}
func (r *v3Accessor) MetadataAsMap() map[string]interface{} {
var ret map[string]interface{}
if r.chrt.Metadata == nil {
return ret
}
ret, err := structToMap(r.chrt.Metadata)
if err != nil {
slog.Error("error converting metadata to map", "error", err)
}
return ret
}
func (r *v3Accessor) Files() []*common.File {
return r.chrt.Files
}
func (r *v3Accessor) Templates() []*common.File {
return r.chrt.Templates
}
func (r *v3Accessor) ChartFullPath() string {
return r.chrt.ChartFullPath()
}
func (r *v3Accessor) IsLibraryChart() bool {
return strings.EqualFold(r.chrt.Metadata.Type, "library")
}
func (r *v3Accessor) Dependencies() []Charter {
var deps = make([]Charter, len(r.chrt.Dependencies()))
for i, c := range r.chrt.Dependencies() {
deps[i] = c
}
return deps
}
func (r *v3Accessor) MetaDependencies() []Dependency {
var deps = make([]Dependency, len(r.chrt.Dependencies()))
for i, c := range r.chrt.Metadata.Dependencies {
deps[i] = c
}
return deps
}
func (r *v3Accessor) Values() map[string]interface{} {
return r.chrt.Values
}
func (r *v3Accessor) Schema() []byte {
return r.chrt.Schema
}
func (r *v3Accessor) Deprecated() bool {
return r.chrt.Metadata.Deprecated
}
func structToMap(obj interface{}) (map[string]interface{}, error) {
objValue := reflect.ValueOf(obj)
// If the value is a pointer, dereference it
if objValue.Kind() == reflect.Pointer {
objValue = objValue.Elem()
}
// Check if the input is a struct
if objValue.Kind() != reflect.Struct {
return nil, fmt.Errorf("input must be a struct or a pointer to a struct")
}
result := make(map[string]interface{})
objType := objValue.Type()
for i := 0; i < objValue.NumField(); i++ {
field := objType.Field(i)
value := objValue.Field(i)
switch value.Kind() {
case reflect.Struct:
nestedMap, err := structToMap(value.Interface())
if err != nil {
return nil, err
}
result[field.Name] = nestedMap
case reflect.Pointer:
// Recurse for pointers by dereferencing
if value.IsNil() {
result[field.Name] = nil
} else {
nestedMap, err := structToMap(value.Interface())
if err != nil {
return nil, err
}
result[field.Name] = nestedMap
}
case reflect.Slice:
sliceOfMaps := make([]interface{}, value.Len())
for j := 0; j < value.Len(); j++ {
sliceElement := value.Index(j)
if sliceElement.Kind() == reflect.Struct || sliceElement.Kind() == reflect.Pointer {
nestedMap, err := structToMap(sliceElement.Interface())
if err != nil {
return nil, err
}
sliceOfMaps[j] = nestedMap
} else {
sliceOfMaps[j] = sliceElement.Interface()
}
}
result[field.Name] = sliceOfMaps
default:
result[field.Name] = value.Interface()
}
}
return result, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/loader/load.go | pkg/chart/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 (
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sigs.k8s.io/yaml"
c3 "helm.sh/helm/v4/internal/chart/v3"
c3load "helm.sh/helm/v4/internal/chart/v3/loader"
"helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/loader/archive"
c2 "helm.sh/helm/v4/pkg/chart/v2"
c2load "helm.sh/helm/v4/pkg/chart/v2/loader"
)
// ChartLoader loads a chart.
type ChartLoader interface {
Load() (chart.Charter, 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.Charter, error) {
l, err := Loader(name)
if err != nil {
return nil, err
}
return l.Load()
}
// DirLoader loads a chart from a directory
type DirLoader string
// Load loads the chart
func (l DirLoader) Load() (chart.Charter, error) {
return LoadDir(string(l))
}
func LoadDir(dir string) (chart.Charter, error) {
topdir, err := filepath.Abs(dir)
if err != nil {
return nil, err
}
name := filepath.Join(topdir, "Chart.yaml")
data, err := os.ReadFile(name)
if err != nil {
return nil, fmt.Errorf("unable to detect chart at %s: %w", name, err)
}
c := new(chartBase)
err = yaml.Unmarshal(data, c)
if err != nil {
return nil, fmt.Errorf("cannot load Chart.yaml: %w", err)
}
switch c.APIVersion {
case c2.APIVersionV1, c2.APIVersionV2, "":
return c2load.Load(dir)
case c3.APIVersionV3:
return c3load.Load(dir)
default:
return nil, errors.New("unsupported chart version")
}
}
// FileLoader loads a chart from a file
type FileLoader string
// Load loads a chart
func (l FileLoader) Load() (chart.Charter, error) {
return LoadFile(string(l))
}
func LoadFile(name string) (chart.Charter, 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
}
files, err := archive.LoadArchiveFiles(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 nil, errors.New("unable to load chart archive")
}
for _, f := range files {
if f.Name == "Chart.yaml" {
c := new(chartBase)
if err := yaml.Unmarshal(f.Data, c); err != nil {
return c, fmt.Errorf("cannot load Chart.yaml: %w", err)
}
switch c.APIVersion {
case c2.APIVersionV1, c2.APIVersionV2, "":
return c2load.Load(name)
case c3.APIVersionV3:
return c3load.Load(name)
default:
return nil, errors.New("unsupported chart version")
}
}
}
return nil, errors.New("unable to detect chart version, no Chart.yaml found")
}
// LoadArchive loads from a reader containing a compressed tar archive.
func LoadArchive(in io.Reader) (chart.Charter, error) {
// Note: This function is for use by SDK users such as Flux.
files, err := archive.LoadArchiveFiles(in)
if err != nil {
if errors.Is(err, gzip.ErrHeader) {
return nil, fmt.Errorf("stream does not appear to be a valid chart file (details: %w)", err)
}
return nil, fmt.Errorf("unable to load chart archive: %w", err)
}
for _, f := range files {
if f.Name == "Chart.yaml" {
c := new(chartBase)
if err := yaml.Unmarshal(f.Data, c); err != nil {
return c, fmt.Errorf("cannot load Chart.yaml: %w", err)
}
switch c.APIVersion {
case c2.APIVersionV1, c2.APIVersionV2, "":
return c2load.LoadFiles(files)
case c3.APIVersionV3:
return c3load.LoadFiles(files)
default:
return nil, errors.New("unsupported chart version")
}
}
}
return nil, errors.New("unable to detect chart version, no Chart.yaml found")
}
// chartBase is used to detect the API Version for the chart to run it through the
// loader for that type.
type chartBase struct {
APIVersion string `json:"apiVersion,omitempty"`
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/loader/load_test.go | pkg/chart/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"
"fmt"
"io"
"maps"
"path/filepath"
"strings"
"testing"
"time"
c3 "helm.sh/helm/v4/internal/chart/v3"
"helm.sh/helm/v4/pkg/chart"
c2 "helm.sh/helm/v4/pkg/chart/v2"
)
// createChartArchive is a helper function to create a gzipped tar archive in memory
func createChartArchive(t *testing.T, chartName, apiVersion string, extraFiles map[string][]byte, createChartYaml bool) io.Reader {
t.Helper()
var buf bytes.Buffer
gw := gzip.NewWriter(&buf)
tw := tar.NewWriter(gw)
files := make(map[string][]byte)
maps.Copy(files, extraFiles)
if createChartYaml {
chartYAMLContent := fmt.Sprintf(`apiVersion: %s
name: %s
version: 0.1.0
description: A test chart
`, apiVersion, chartName)
files["Chart.yaml"] = []byte(chartYAMLContent)
}
for name, data := range files {
header := &tar.Header{
Name: filepath.Join(chartName, name),
Mode: 0644,
Size: int64(len(data)),
ModTime: time.Now(),
}
if err := tw.WriteHeader(header); err != nil {
t.Fatalf("Failed to write tar header for %s: %v", name, err)
}
if _, err := tw.Write(data); err != nil {
t.Fatalf("Failed to write tar data for %s: %v", name, err)
}
}
if err := tw.Close(); err != nil {
t.Fatalf("Failed to close tar writer: %v", err)
}
if err := gw.Close(); err != nil {
t.Fatalf("Failed to close gzip writer: %v", err)
}
return &buf
}
func TestLoadArchive(t *testing.T) {
testCases := []struct {
name string
chartName string
apiVersion string
extraFiles map[string][]byte
inputReader io.Reader
expectedChart chart.Charter
expectedError string
createChartYaml bool
}{
{
name: "valid v2 chart archive",
chartName: "mychart-v2",
apiVersion: c2.APIVersionV2,
extraFiles: map[string][]byte{"templates/config.yaml": []byte("key: value")},
expectedChart: &c2.Chart{
Metadata: &c2.Metadata{APIVersion: c2.APIVersionV2, Name: "mychart-v2", Version: "0.1.0", Description: "A test chart"},
},
createChartYaml: true,
},
{
name: "valid v3 chart archive",
chartName: "mychart-v3",
apiVersion: c3.APIVersionV3,
extraFiles: map[string][]byte{"templates/config.yaml": []byte("key: value")},
expectedChart: &c3.Chart{
Metadata: &c3.Metadata{APIVersion: c3.APIVersionV3, Name: "mychart-v3", Version: "0.1.0", Description: "A test chart"},
},
createChartYaml: true,
},
{
name: "invalid gzip header",
inputReader: bytes.NewBufferString("not a gzip file"),
expectedError: "stream does not appear to be a valid chart file (details: gzip: invalid header)",
},
{
name: "archive without Chart.yaml",
chartName: "no-chart-yaml",
apiVersion: c2.APIVersionV2, // This will be ignored as Chart.yaml is missing
extraFiles: map[string][]byte{"values.yaml": []byte("foo: bar")},
expectedError: "unable to detect chart version, no Chart.yaml found",
createChartYaml: false,
},
{
name: "archive with malformed Chart.yaml",
chartName: "malformed-chart-yaml",
apiVersion: c2.APIVersionV2,
extraFiles: map[string][]byte{"Chart.yaml": []byte("apiVersion: v2\nname: mychart\nversion: 0.1.0\ndescription: A test chart\ninvalid: :")},
expectedError: "cannot load Chart.yaml: error converting YAML to JSON: yaml: line 5: mapping values are not allowed in this context",
createChartYaml: false,
},
{
name: "unsupported API version",
chartName: "unsupported-api",
apiVersion: "v99",
expectedError: "unsupported chart version",
createChartYaml: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
var reader io.Reader
if tc.inputReader != nil {
reader = tc.inputReader
} else {
reader = createChartArchive(t, tc.chartName, tc.apiVersion, tc.extraFiles, tc.createChartYaml)
}
loadedChart, err := LoadArchive(reader)
if tc.expectedError != "" {
if err == nil || !strings.Contains(err.Error(), tc.expectedError) {
t.Errorf("Expected error containing %q, but got %v", tc.expectedError, err)
}
return
}
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
lac, err := chart.NewAccessor(loadedChart)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
eac, err := chart.NewAccessor(tc.expectedChart)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if lac.Name() != eac.Name() {
t.Errorf("Expected chart name %q, got %q", eac.Name(), lac.Name())
}
var loadedAPIVersion string
switch lc := loadedChart.(type) {
case *c2.Chart:
loadedAPIVersion = lc.Metadata.APIVersion
case *c3.Chart:
loadedAPIVersion = lc.Metadata.APIVersion
}
if loadedAPIVersion != tc.apiVersion {
t.Errorf("Expected API version %q, got %q", tc.apiVersion, loadedAPIVersion)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/loader/archive/archive.go | pkg/chart/loader/archive/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.
*/
// archive provides utility functions for working with Helm chart archive files
package archive
import (
"archive/tar"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"regexp"
"strings"
"time"
)
// MaxDecompressedChartSize is the maximum size of a chart archive that will be
// decompressed. This is the decompressed size of all the files.
// The default value is 100 MiB.
var MaxDecompressedChartSize int64 = 100 * 1024 * 1024 // Default 100 MiB
// MaxDecompressedFileSize is the size of the largest file that Helm will attempt to load.
// The size of the file is the decompressed version of it when it is stored in an archive.
var MaxDecompressedFileSize int64 = 5 * 1024 * 1024 // Default 5 MiB
var drivePathPattern = regexp.MustCompile(`^[a-zA-Z]:/`)
var utf8bom = []byte{0xEF, 0xBB, 0xBF}
// BufferedFile represents an archive file buffered for later processing.
type BufferedFile struct {
Name string
ModTime time.Time
Data []byte
}
// LoadArchiveFiles reads in files out of an archive into memory. This function
// performs important path security checks and should always be used before
// expanding a tarball
func LoadArchiveFiles(in io.Reader) ([]*BufferedFile, error) {
unzipped, err := gzip.NewReader(in)
if err != nil {
return nil, err
}
defer unzipped.Close()
files := []*BufferedFile{}
tr := tar.NewReader(unzipped)
remainingSize := MaxDecompressedChartSize
for {
b := bytes.NewBuffer(nil)
hd, err := tr.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
if hd.FileInfo().IsDir() {
// Use this instead of hd.Typeflag because we don't have to do any
// inference chasing.
continue
}
switch hd.Typeflag {
// We don't want to process these extension header files.
case tar.TypeXGlobalHeader, tar.TypeXHeader:
continue
}
// Archive could contain \ if generated on Windows
delimiter := "/"
if strings.ContainsRune(hd.Name, '\\') {
delimiter = "\\"
}
parts := strings.Split(hd.Name, delimiter)
n := strings.Join(parts[1:], delimiter)
// Normalize the path to the / delimiter
n = strings.ReplaceAll(n, delimiter, "/")
if path.IsAbs(n) {
return nil, errors.New("chart illegally contains absolute paths")
}
n = path.Clean(n)
if n == "." {
// In this case, the original path was relative when it should have been absolute.
return nil, fmt.Errorf("chart illegally contains content outside the base directory: %q", hd.Name)
}
if strings.HasPrefix(n, "..") {
return nil, errors.New("chart illegally references parent directory")
}
// In some particularly arcane acts of path creativity, it is possible to intermix
// UNIX and Windows style paths in such a way that you produce a result of the form
// c:/foo even after all the built-in absolute path checks. So we explicitly check
// for this condition.
if drivePathPattern.MatchString(n) {
return nil, errors.New("chart contains illegally named files")
}
if parts[0] == "Chart.yaml" {
return nil, errors.New("chart yaml not in base directory")
}
if hd.Size > remainingSize {
return nil, fmt.Errorf("decompressed chart is larger than the maximum size %d", MaxDecompressedChartSize)
}
if hd.Size > MaxDecompressedFileSize {
return nil, fmt.Errorf("decompressed chart file %q is larger than the maximum file size %d", hd.Name, MaxDecompressedFileSize)
}
limitedReader := io.LimitReader(tr, remainingSize)
bytesWritten, err := io.Copy(b, limitedReader)
if err != nil {
return nil, err
}
remainingSize -= bytesWritten
// When the bytesWritten are less than the file size it means the limit reader ended
// copying early. Here we report that error. This is important if the last file extracted
// is the one that goes over the limit. It assumes the Size stored in the tar header
// is correct, something many applications do.
if bytesWritten < hd.Size || remainingSize <= 0 {
return nil, fmt.Errorf("decompressed chart is larger than the maximum size %d", MaxDecompressedChartSize)
}
data := bytes.TrimPrefix(b.Bytes(), utf8bom)
files = append(files, &BufferedFile{Name: n, ModTime: hd.ModTime, Data: data})
b.Reset()
}
if len(files) == 0 {
return nil, errors.New("no files in chart archive")
}
return files, nil
}
// ensureArchive's job is to return an informative error if the file does not appear to be a gzipped archive.
//
// Sometimes users will provide a values.yaml for an argument where a chart is expected. One common occurrence
// of this is invoking `helm template values.yaml mychart` which would otherwise produce a confusing error
// if we didn't check for this.
func EnsureArchive(name string, raw *os.File) error {
defer raw.Seek(0, 0) // reset read offset to allow archive loading to proceed.
// Check the file format to give us a chance to provide the user with more actionable feedback.
buffer := make([]byte, 512)
_, err := raw.Read(buffer)
if err != nil && err != io.EOF {
return fmt.Errorf("file '%s' cannot be read: %s", name, err)
}
// Helm may identify achieve of the application/x-gzip as application/vnd.ms-fontobject.
// Fix for: https://github.com/helm/helm/issues/12261
if contentType := http.DetectContentType(buffer); contentType != "application/x-gzip" && !isGZipApplication(buffer) {
// TODO: Is there a way to reliably test if a file content is YAML? ghodss/yaml accepts a wide
// variety of content (Makefile, .zshrc) as valid YAML without errors.
// Wrong content type. Let's check if it's yaml and give an extra hint?
if strings.HasSuffix(name, ".yml") || strings.HasSuffix(name, ".yaml") {
return fmt.Errorf("file '%s' seems to be a YAML file, but expected a gzipped archive", name)
}
return fmt.Errorf("file '%s' does not appear to be a gzipped archive; got '%s'", name, contentType)
}
return nil
}
// isGZipApplication checks whether the archive is of the application/x-gzip type.
func isGZipApplication(data []byte) bool {
sig := []byte("\x1F\x8B\x08")
return bytes.HasPrefix(data, sig)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/loader/archive/archive_test.go | pkg/chart/loader/archive/archive_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 archive
import (
"archive/tar"
"bytes"
"compress/gzip"
"testing"
)
func TestLoadArchiveFiles(t *testing.T) {
tcs := []struct {
name string
generate func(w *tar.Writer)
check func(t *testing.T, files []*BufferedFile, err error)
}{
{
name: "empty input should return no files",
generate: func(_ *tar.Writer) {},
check: func(t *testing.T, _ []*BufferedFile, err error) {
t.Helper()
if err.Error() != "no files in chart archive" {
t.Fatalf(`expected "no files in chart archive", got [%#v]`, err)
}
},
},
{
name: "should ignore files with XGlobalHeader type",
generate: func(w *tar.Writer) {
// simulate the presence of a `pax_global_header` file like you would get when
// processing a GitHub release archive.
err := w.WriteHeader(&tar.Header{
Typeflag: tar.TypeXGlobalHeader,
Name: "pax_global_header",
})
if err != nil {
t.Fatal(err)
}
// we need to have at least one file, otherwise we'll get the "no files in chart archive" error
err = w.WriteHeader(&tar.Header{
Typeflag: tar.TypeReg,
Name: "dir/empty",
})
if err != nil {
t.Fatal(err)
}
},
check: func(t *testing.T, files []*BufferedFile, err error) {
t.Helper()
if err != nil {
t.Fatalf(`got unwanted error [%#v] for tar file with pax_global_header content`, err)
}
if len(files) != 1 {
t.Fatalf(`expected to get one file but got [%v]`, files)
}
},
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
buf := &bytes.Buffer{}
gzw := gzip.NewWriter(buf)
tw := tar.NewWriter(gzw)
tc.generate(tw)
_ = tw.Close()
_ = gzw.Close()
files, err := LoadArchiveFiles(buf)
tc.check(t, files, err)
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/file.go | pkg/chart/common/file.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 common
import "time"
// File represents a file as a name/value pair.
//
// By convention, name is a relative path within the scope of the chart's
// base directory.
type File struct {
// Name is the path-like name of the template.
Name string `json:"name"`
// Data is the template as byte data.
Data []byte `json:"data"`
// ModTime is the file's mod-time
ModTime time.Time `json:"modtime,omitzero"`
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/capabilities.go | pkg/chart/common/capabilities.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 common
import (
"fmt"
"slices"
"strconv"
"strings"
"testing"
"github.com/Masterminds/semver/v3"
"k8s.io/client-go/kubernetes/scheme"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
k8sversion "k8s.io/apimachinery/pkg/util/version"
helmversion "helm.sh/helm/v4/internal/version"
)
const (
kubeVersionMajorTesting = 1
kubeVersionMinorTesting = 20
)
var (
// DefaultVersionSet is the default version set, which includes only Core V1 ("v1").
DefaultVersionSet = allKnownVersions()
DefaultCapabilities = func() *Capabilities {
caps, err := makeDefaultCapabilities()
if err != nil {
panic(fmt.Sprintf("failed to create default capabilities: %v", err))
}
return caps
}()
)
// Capabilities describes the capabilities of the Kubernetes cluster.
type Capabilities struct {
// KubeVersion is the Kubernetes version.
KubeVersion KubeVersion
// APIVersions are supported Kubernetes API versions.
APIVersions VersionSet
// HelmVersion is the build information for this helm version
HelmVersion helmversion.BuildInfo
}
func (capabilities *Capabilities) Copy() *Capabilities {
return &Capabilities{
KubeVersion: capabilities.KubeVersion,
APIVersions: capabilities.APIVersions,
HelmVersion: capabilities.HelmVersion,
}
}
// KubeVersion is the Kubernetes version.
type KubeVersion struct {
Version string // Full version (e.g., v1.33.4-gke.1245000)
normalizedVersion string // Normalized for constraint checking (e.g., v1.33.4)
Major string // Kubernetes major version
Minor string // Kubernetes minor version
}
// String implements fmt.Stringer.
// Returns the normalized version used for constraint checking.
func (kv *KubeVersion) String() string {
if kv.normalizedVersion != "" {
return kv.normalizedVersion
}
return kv.Version
}
// GitVersion returns the full Kubernetes version string.
//
// Deprecated: use KubeVersion.Version.
func (kv *KubeVersion) GitVersion() string { return kv.Version }
// ParseKubeVersion parses kubernetes version from string
func ParseKubeVersion(version string) (*KubeVersion, error) {
// Based on the original k8s version parser.
// https://github.com/kubernetes/kubernetes/blob/b266ac2c3e42c2c4843f81e20213d2b2f43e450a/staging/src/k8s.io/apimachinery/pkg/util/version/version.go#L137
sv, err := k8sversion.ParseGeneric(version)
if err != nil {
return nil, err
}
// Preserve original input (e.g., v1.33.4-gke.1245000)
gitVersion := version
if !strings.HasPrefix(version, "v") {
gitVersion = "v" + version
}
// Normalize for constraint checking (strips all suffixes)
normalizedVer := "v" + sv.String()
return &KubeVersion{
Version: gitVersion,
normalizedVersion: normalizedVer,
Major: strconv.FormatUint(uint64(sv.Major()), 10),
Minor: strconv.FormatUint(uint64(sv.Minor()), 10),
}, nil
}
// VersionSet is a set of Kubernetes API versions.
type VersionSet []string
// Has returns true if the version string is in the set.
//
// vs.Has("apps/v1")
func (v VersionSet) Has(apiVersion string) bool {
return slices.Contains(v, apiVersion)
}
func allKnownVersions() VersionSet {
// We should register the built in extension APIs as well so CRDs are
// supported in the default version set. This has caused problems with `helm
// template` in the past, so let's be safe
apiextensionsv1beta1.AddToScheme(scheme.Scheme)
apiextensionsv1.AddToScheme(scheme.Scheme)
groups := scheme.Scheme.PrioritizedVersionsAllGroups()
vs := make(VersionSet, 0, len(groups))
for _, gv := range groups {
vs = append(vs, gv.String())
}
return vs
}
func makeDefaultCapabilities() (*Capabilities, error) {
// Test builds don't include debug info / module info
// (And even if they did, we probably want stable capabilities for tests anyway)
// Return a default value for test builds
if testing.Testing() {
return newCapabilities(kubeVersionMajorTesting, kubeVersionMinorTesting)
}
vstr, err := helmversion.K8sIOClientGoModVersion()
if err != nil {
return nil, fmt.Errorf("failed to retrieve k8s.io/client-go version: %w", err)
}
v, err := semver.NewVersion(vstr)
if err != nil {
return nil, fmt.Errorf("unable to parse k8s.io/client-go version %q: %v", vstr, err)
}
kubeVersionMajor := v.Major() + 1
kubeVersionMinor := v.Minor()
return newCapabilities(kubeVersionMajor, kubeVersionMinor)
}
func newCapabilities(kubeVersionMajor, kubeVersionMinor uint64) (*Capabilities, error) {
version := fmt.Sprintf("v%d.%d.0", kubeVersionMajor, kubeVersionMinor)
return &Capabilities{
KubeVersion: KubeVersion{
Version: version,
normalizedVersion: version,
Major: fmt.Sprintf("%d", kubeVersionMajor),
Minor: fmt.Sprintf("%d", kubeVersionMinor),
},
APIVersions: DefaultVersionSet,
HelmVersion: helmversion.Get(),
}, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/errors_test.go | pkg/chart/common/errors_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 common
import (
"testing"
)
func TestErrorNoTableDoesNotPanic(t *testing.T) {
x := "empty"
y := ErrNoTable{x}
t.Logf("error is: %s", y)
}
func TestErrorNoValueDoesNotPanic(t *testing.T) {
x := "empty"
y := ErrNoValue{x}
t.Logf("error is: %s", y)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/capabilities_test.go | pkg/chart/common/capabilities_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 common
import (
"testing"
)
func TestVersionSet(t *testing.T) {
vs := VersionSet{"v1", "apps/v1"}
if d := len(vs); d != 2 {
t.Errorf("Expected 2 versions, got %d", d)
}
if !vs.Has("apps/v1") {
t.Error("Expected to find apps/v1")
}
if vs.Has("Spanish/inquisition") {
t.Error("No one expects the Spanish/inquisition")
}
}
func TestDefaultVersionSet(t *testing.T) {
if !DefaultVersionSet.Has("v1") {
t.Error("Expected core v1 version set")
}
}
func TestDefaultCapabilities(t *testing.T) {
caps := DefaultCapabilities
kv := caps.KubeVersion
if kv.String() != "v1.20.0" {
t.Errorf("Expected default KubeVersion.String() to be v1.20.0, got %q", kv.String())
}
if kv.Version != "v1.20.0" {
t.Errorf("Expected default KubeVersion.Version to be v1.20.0, got %q", kv.Version)
}
if kv.GitVersion() != "v1.20.0" {
t.Errorf("Expected default KubeVersion.GitVersion() to be v1.20.0, got %q", kv.Version)
}
if kv.Major != "1" {
t.Errorf("Expected default KubeVersion.Major to be 1, got %q", kv.Major)
}
if kv.Minor != "20" {
t.Errorf("Expected default KubeVersion.Minor to be 20, got %q", kv.Minor)
}
hv := caps.HelmVersion
if hv.Version != "v4.1" {
t.Errorf("Expected default HelmVersion to be v4.1, got %q", hv.Version)
}
}
func TestParseKubeVersion(t *testing.T) {
kv, err := ParseKubeVersion("v1.16.0")
if err != nil {
t.Errorf("Expected v1.16.0 to parse successfully")
}
if kv.Version != "v1.16.0" {
t.Errorf("Expected parsed KubeVersion.Version to be v1.16.0, got %q", kv.String())
}
if kv.Major != "1" {
t.Errorf("Expected parsed KubeVersion.Major to be 1, got %q", kv.Major)
}
if kv.Minor != "16" {
t.Errorf("Expected parsed KubeVersion.Minor to be 16, got %q", kv.Minor)
}
}
func TestParseKubeVersionWithVendorSuffixes(t *testing.T) {
tests := []struct {
name string
input string
wantVer string
wantString string
wantMajor string
wantMinor string
}{
{"GKE vendor suffix", "v1.33.4-gke.1245000", "v1.33.4-gke.1245000", "v1.33.4", "1", "33"},
{"GKE without v", "1.30.2-gke.1587003", "v1.30.2-gke.1587003", "v1.30.2", "1", "30"},
{"EKS trailing +", "v1.28+", "v1.28+", "v1.28", "1", "28"},
{"EKS + without v", "1.28+", "v1.28+", "v1.28", "1", "28"},
{"Standard version", "v1.31.0", "v1.31.0", "v1.31.0", "1", "31"},
{"Standard without v", "1.29.0", "v1.29.0", "v1.29.0", "1", "29"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kv, err := ParseKubeVersion(tt.input)
if err != nil {
t.Fatalf("ParseKubeVersion() error = %v", err)
}
if kv.Version != tt.wantVer {
t.Errorf("Version = %q, want %q", kv.Version, tt.wantVer)
}
if kv.String() != tt.wantString {
t.Errorf("String() = %q, want %q", kv.String(), tt.wantString)
}
if kv.Major != tt.wantMajor {
t.Errorf("Major = %q, want %q", kv.Major, tt.wantMajor)
}
if kv.Minor != tt.wantMinor {
t.Errorf("Minor = %q, want %q", kv.Minor, tt.wantMinor)
}
})
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/errors.go | pkg/chart/common/errors.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 common
import (
"fmt"
)
// ErrNoTable indicates that a chart does not have a matching table.
type ErrNoTable struct {
Key string
}
func (e ErrNoTable) Error() string { return fmt.Sprintf("%q is not a table", e.Key) }
// ErrNoValue indicates that Values does not contain a key with a value
type ErrNoValue struct {
Key string
}
func (e ErrNoValue) Error() string { return fmt.Sprintf("%q is not a value", e.Key) }
type ErrInvalidChartName struct {
Name string
}
func (e ErrInvalidChartName) Error() string {
return fmt.Sprintf("%q is not a valid chart name", e.Name)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/values.go | pkg/chart/common/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 common
import (
"errors"
"io"
"os"
"strings"
"sigs.k8s.io/yaml"
)
// GlobalKey is the name of the Values key that is used for storing global vars.
const GlobalKey = "global"
// Values represents a collection of chart values.
type Values map[string]interface{}
// YAML encodes the Values into a YAML string.
func (v Values) YAML() (string, error) {
b, err := yaml.Marshal(v)
return string(b), err
}
// Table gets a table (YAML subsection) from a Values object.
//
// The table is returned as a Values.
//
// Compound table names may be specified with dots:
//
// foo.bar
//
// The above will be evaluated as "The table bar inside the table
// foo".
//
// An ErrNoTable is returned if the table does not exist.
func (v Values) Table(name string) (Values, error) {
table := v
var err error
for _, n := range parsePath(name) {
if table, err = tableLookup(table, n); err != nil {
break
}
}
return table, err
}
// AsMap is a utility function for converting Values to a map[string]interface{}.
//
// It protects against nil map panics.
func (v Values) AsMap() map[string]interface{} {
if len(v) == 0 {
return map[string]interface{}{}
}
return v
}
// Encode writes serialized Values information to the given io.Writer.
func (v Values) Encode(w io.Writer) error {
out, err := yaml.Marshal(v)
if err != nil {
return err
}
_, err = w.Write(out)
return err
}
func tableLookup(v Values, simple string) (Values, error) {
v2, ok := v[simple]
if !ok {
return v, ErrNoTable{simple}
}
if vv, ok := v2.(map[string]interface{}); ok {
return vv, nil
}
// This catches a case where a value is of type Values, but doesn't (for some
// reason) match the map[string]interface{}. This has been observed in the
// wild, and might be a result of a nil map of type Values.
if vv, ok := v2.(Values); ok {
return vv, nil
}
return Values{}, ErrNoTable{simple}
}
// ReadValues will parse YAML byte data into a Values.
func ReadValues(data []byte) (vals Values, err error) {
err = yaml.Unmarshal(data, &vals)
if len(vals) == 0 {
vals = Values{}
}
return vals, err
}
// ReadValuesFile will parse a YAML file into a map of values.
func ReadValuesFile(filename string) (Values, error) {
data, err := os.ReadFile(filename)
if err != nil {
return map[string]interface{}{}, err
}
return ReadValues(data)
}
// ReleaseOptions represents the additional release options needed
// for the composition of the final values struct
type ReleaseOptions struct {
Name string
Namespace string
Revision int
IsUpgrade bool
IsInstall bool
}
// 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
}
// PathValue takes a path that traverses a YAML structure and returns the value at the end of that path.
// The path starts at the root of the YAML structure and is comprised of YAML keys separated by periods.
// Given the following YAML data the value at path "chapter.one.title" is "Loomings".
//
// chapter:
// one:
// title: "Loomings"
func (v Values) PathValue(path string) (interface{}, error) {
if path == "" {
return nil, errors.New("YAML path cannot be empty")
}
return v.pathValue(parsePath(path))
}
func (v Values) pathValue(path []string) (interface{}, error) {
if len(path) == 1 {
// if exists must be root key not table
if _, ok := v[path[0]]; ok && !istable(v[path[0]]) {
return v[path[0]], nil
}
return nil, ErrNoValue{path[0]}
}
key, path := path[len(path)-1], path[:len(path)-1]
// get our table for table path
t, err := v.Table(joinPath(path...))
if err != nil {
return nil, ErrNoValue{key}
}
// check table for key and ensure value is not a table
if k, ok := t[key]; ok && !istable(k) {
return k, nil
}
return nil, ErrNoValue{key}
}
func parsePath(key string) []string { return strings.Split(key, ".") }
func joinPath(path ...string) string { return strings.Join(path, ".") }
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/values_test.go | pkg/chart/common/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 common
import (
"bytes"
"fmt"
"testing"
"text/template"
)
func TestReadValues(t *testing.T) {
doc := `# Test YAML parse
poet: "Coleridge"
title: "Rime of the Ancient Mariner"
stanza:
- "at"
- "length"
- "did"
- cross
- an
- Albatross
mariner:
with: "crossbow"
shot: "ALBATROSS"
water:
water:
where: "everywhere"
nor: "any drop to drink"
`
data, err := ReadValues([]byte(doc))
if err != nil {
t.Fatalf("Error parsing bytes: %s", err)
}
matchValues(t, data)
tests := []string{`poet: "Coleridge"`, "# Just a comment", ""}
for _, tt := range tests {
data, err = ReadValues([]byte(tt))
if err != nil {
t.Fatalf("Error parsing bytes (%s): %s", tt, err)
}
if data == nil {
t.Errorf(`YAML string "%s" gave a nil map`, tt)
}
}
}
func TestReadValuesFile(t *testing.T) {
data, err := ReadValuesFile("./testdata/coleridge.yaml")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
matchValues(t, data)
}
func ExampleValues() {
doc := `
title: "Moby Dick"
chapter:
one:
title: "Loomings"
two:
title: "The Carpet-Bag"
three:
title: "The Spouter Inn"
`
d, err := ReadValues([]byte(doc))
if err != nil {
panic(err)
}
ch1, err := d.Table("chapter.one")
if err != nil {
panic("could not find chapter one")
}
fmt.Print(ch1["title"])
// Output:
// Loomings
}
func TestTable(t *testing.T) {
doc := `
title: "Moby Dick"
chapter:
one:
title: "Loomings"
two:
title: "The Carpet-Bag"
three:
title: "The Spouter Inn"
`
d, err := ReadValues([]byte(doc))
if err != nil {
t.Fatalf("Failed to parse the White Whale: %s", err)
}
if _, err := d.Table("title"); err == nil {
t.Fatalf("Title is not a table.")
}
if _, err := d.Table("chapter"); err != nil {
t.Fatalf("Failed to get the chapter table: %s\n%v", err, d)
}
if v, err := d.Table("chapter.one"); err != nil {
t.Errorf("Failed to get chapter.one: %s", err)
} else if v["title"] != "Loomings" {
t.Errorf("Unexpected title: %s", v["title"])
}
if _, err := d.Table("chapter.three"); err != nil {
t.Errorf("Chapter three is missing: %s\n%v", err, d)
}
if _, err := d.Table("chapter.OneHundredThirtySix"); err == nil {
t.Errorf("I think you mean 'Epilogue'")
}
}
func matchValues(t *testing.T, data map[string]interface{}) {
t.Helper()
if data["poet"] != "Coleridge" {
t.Errorf("Unexpected poet: %s", data["poet"])
}
if o, err := ttpl("{{len .stanza}}", data); err != nil {
t.Errorf("len stanza: %s", err)
} else if o != "6" {
t.Errorf("Expected 6, got %s", o)
}
if o, err := ttpl("{{.mariner.shot}}", data); err != nil {
t.Errorf(".mariner.shot: %s", err)
} else if o != "ALBATROSS" {
t.Errorf("Expected that mariner shot ALBATROSS")
}
if o, err := ttpl("{{.water.water.where}}", data); err != nil {
t.Errorf(".water.water.where: %s", err)
} else if o != "everywhere" {
t.Errorf("Expected water water everywhere")
}
}
func ttpl(tpl string, v map[string]interface{}) (string, error) {
var b bytes.Buffer
tt := template.Must(template.New("t").Parse(tpl))
err := tt.Execute(&b, v)
return b.String(), err
}
func TestPathValue(t *testing.T) {
doc := `
title: "Moby Dick"
chapter:
one:
title: "Loomings"
two:
title: "The Carpet-Bag"
three:
title: "The Spouter Inn"
`
d, err := ReadValues([]byte(doc))
if err != nil {
t.Fatalf("Failed to parse the White Whale: %s", err)
}
if v, err := d.PathValue("chapter.one.title"); err != nil {
t.Errorf("Got error instead of title: %s\n%v", err, d)
} else if v != "Loomings" {
t.Errorf("No error but got wrong value for title: %s\n%v", err, d)
}
if _, err := d.PathValue("chapter.one.doesnotexist"); err == nil {
t.Errorf("Non-existent key should return error: %s\n%v", err, d)
}
if _, err := d.PathValue("chapter.doesnotexist.one"); err == nil {
t.Errorf("Non-existent key in middle of path should return error: %s\n%v", err, d)
}
if _, err := d.PathValue(""); err == nil {
t.Error("Asking for the value from an empty path should yield an error")
}
if v, err := d.PathValue("title"); err == nil {
if v != "Moby Dick" {
t.Errorf("Failed to return values for root key title")
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/jsonschema.go | pkg/chart/common/util/jsonschema.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"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"sync"
"time"
"github.com/santhosh-tekuri/jsonschema/v6"
"helm.sh/helm/v4/internal/version"
chart "helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/common"
)
// HTTPURLLoader implements a loader for HTTP/HTTPS URLs
type HTTPURLLoader http.Client
func (l *HTTPURLLoader) Load(urlStr string) (any, error) {
client := (*http.Client)(l)
req, err := http.NewRequest(http.MethodGet, urlStr, nil)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request for %s: %w", urlStr, err)
}
req.Header.Set("User-Agent", version.GetUserAgent())
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed for %s: %w", urlStr, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request to %s returned status %d (%s)", urlStr, resp.StatusCode, http.StatusText(resp.StatusCode))
}
return jsonschema.UnmarshalJSON(resp.Body)
}
// newHTTPURLLoader creates a HTTP URL loader with proxy support.
func newHTTPURLLoader() *HTTPURLLoader {
httpLoader := HTTPURLLoader(http.Client{
Timeout: 15 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{},
},
})
return &httpLoader
}
// ValidateAgainstSchema checks that values does not violate the structure laid out in schema
func ValidateAgainstSchema(ch chart.Charter, values map[string]interface{}) error {
chrt, err := chart.NewAccessor(ch)
if err != nil {
return err
}
var sb strings.Builder
if chrt.Schema() != nil {
slog.Debug("chart name", "chart-name", chrt.Name())
err := ValidateAgainstSingleSchema(values, chrt.Schema())
if err != nil {
sb.WriteString(fmt.Sprintf("%s:\n", chrt.Name()))
sb.WriteString(err.Error())
}
}
slog.Debug("number of dependencies in the chart", "chart", chrt.Name(), "dependencies", len(chrt.Dependencies()))
// For each dependency, recursively call this function with the coalesced values
for _, subchart := range chrt.Dependencies() {
sub, err := chart.NewAccessor(subchart)
if err != nil {
return err
}
raw, exists := values[sub.Name()]
if !exists || raw == nil {
// No values provided for this subchart; nothing to validate
continue
}
subchartValues, ok := raw.(map[string]any)
if !ok {
sb.WriteString(fmt.Sprintf(
"%s:\ninvalid type for values: expected object (map), got %T\n",
sub.Name(), raw,
))
continue
}
if err := ValidateAgainstSchema(subchart, subchartValues); err != nil {
sb.WriteString(err.Error())
}
}
if sb.Len() > 0 {
return errors.New(sb.String())
}
return nil
}
// ValidateAgainstSingleSchema checks that values does not violate the structure laid out in this schema
func ValidateAgainstSingleSchema(values common.Values, schemaJSON []byte) (reterr error) {
defer func() {
if r := recover(); r != nil {
reterr = fmt.Errorf("unable to validate schema: %s", r)
}
}()
// This unmarshal function leverages UseNumber() for number precision. The parser
// used for values does this as well.
schema, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaJSON))
if err != nil {
return err
}
slog.Debug("unmarshalled JSON schema", "schema", schemaJSON)
// Configure compiler with loaders for different URL schemes
loader := jsonschema.SchemeURLLoader{
"file": jsonschema.FileLoader{},
"http": newHTTPURLLoader(),
"https": newHTTPURLLoader(),
"urn": urnLoader{},
}
compiler := jsonschema.NewCompiler()
compiler.UseLoader(loader)
err = compiler.AddResource("file:///values.schema.json", schema)
if err != nil {
return err
}
validator, err := compiler.Compile("file:///values.schema.json")
if err != nil {
return err
}
err = validator.Validate(values.AsMap())
if err != nil {
return JSONSchemaValidationError{err}
}
return nil
}
// URNResolverFunc allows SDK to plug a URN resolver. It must return a
// schema document compatible with the validator (e.g., result of
// jsonschema.UnmarshalJSON).
type URNResolverFunc func(urn string) (any, error)
// URNResolver is the default resolver used by the URN loader. By default it
// returns a clear error.
var URNResolver URNResolverFunc = func(urn string) (any, error) {
return nil, fmt.Errorf("URN not resolved: %s", urn)
}
// urnLoader implements resolution for the urn: scheme by delegating to
// URNResolver. If unresolved, it logs a warning and returns a permissive
// boolean-true schema to avoid hard failures (back-compat behavior).
type urnLoader struct{}
// warnedURNs ensures we log the unresolved-URN warning only once per URN.
var warnedURNs sync.Map
func (l urnLoader) Load(urlStr string) (any, error) {
if doc, err := URNResolver(urlStr); err == nil && doc != nil {
return doc, nil
}
if _, loaded := warnedURNs.LoadOrStore(urlStr, struct{}{}); !loaded {
slog.Warn("unresolved URN reference ignored; using permissive schema", "urn", urlStr)
}
return jsonschema.UnmarshalJSON(strings.NewReader("true"))
}
// Note, JSONSchemaValidationError is used to wrap the error from the underlying
// validation package so that Helm has a clean interface and the validation package
// could be replaced without changing the Helm SDK API.
// JSONSchemaValidationError is the error returned when there is a schema validation
// error.
type JSONSchemaValidationError struct {
embeddedErr error
}
// Error prints the error message
func (e JSONSchemaValidationError) Error() string {
errStr := e.embeddedErr.Error()
// This string prefixes all of our error details. Further up the stack of helm error message
// building more detail is provided to users. This is removed.
errStr = strings.TrimPrefix(errStr, "jsonschema validation failed with 'file:///values.schema.json#'\n")
// The extra new line is needed for when there are sub-charts.
return errStr + "\n"
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/jsonschema_test.go | pkg/chart/common/util/jsonschema_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 (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
func TestValidateAgainstSingleSchema(t *testing.T) {
values, err := common.ReadValuesFile("./testdata/test-values.yaml")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
schema, err := os.ReadFile("./testdata/test-values.schema.json")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
if err := ValidateAgainstSingleSchema(values, schema); err != nil {
t.Errorf("Error validating Values against Schema: %s", err)
}
}
func TestValidateAgainstInvalidSingleSchema(t *testing.T) {
values, err := common.ReadValuesFile("./testdata/test-values.yaml")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
schema, err := os.ReadFile("./testdata/test-values-invalid.schema.json")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
var errString string
if err := ValidateAgainstSingleSchema(values, schema); err == nil {
t.Fatalf("Expected an error, but got nil")
} else {
errString = err.Error()
}
expectedErrString := `"file:///values.schema.json#" is not valid against metaschema: jsonschema validation failed with 'https://json-schema.org/draft/2020-12/schema#'
- at '': got number, want boolean or object`
if errString != expectedErrString {
t.Errorf("Error string :\n`%s`\ndoes not match expected\n`%s`", errString, expectedErrString)
}
}
func TestValidateAgainstSingleSchemaNegative(t *testing.T) {
values, err := common.ReadValuesFile("./testdata/test-values-negative.yaml")
if err != nil {
t.Fatalf("Error reading YAML file: %s", err)
}
schema, err := os.ReadFile("./testdata/test-values.schema.json")
if err != nil {
t.Fatalf("Error reading JSON file: %s", err)
}
var errString string
if err := ValidateAgainstSingleSchema(values, schema); err == nil {
t.Fatalf("Expected an error, but got nil")
} else {
errString = err.Error()
}
expectedErrString := `- at '': missing property 'employmentInfo'
- at '/age': minimum: got -5, want 0
`
if errString != expectedErrString {
t.Errorf("Error string :\n`%s`\ndoes not match expected\n`%s`", errString, expectedErrString)
}
}
const subchartSchema = `{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Values",
"type": "object",
"properties": {
"age": {
"description": "Age",
"minimum": 0,
"type": "integer"
}
},
"required": [
"age"
]
}
`
const subchartSchema2020 = `{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Values",
"type": "object",
"properties": {
"data": {
"type": "array",
"contains": { "type": "string" },
"unevaluatedItems": { "type": "number" }
}
},
"required": ["data"]
}
`
func TestValidateAgainstSchema(t *testing.T) {
subchartJSON := []byte(subchartSchema)
subchart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "subchart",
},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{
Name: "chrt",
},
}
chrt.AddDependency(subchart)
vals := map[string]interface{}{
"name": "John",
"subchart": map[string]interface{}{
"age": 25,
},
}
if err := ValidateAgainstSchema(chrt, vals); err != nil {
t.Errorf("Error validating Values against Schema: %s", err)
}
}
func TestValidateAgainstSchemaNegative(t *testing.T) {
subchartJSON := []byte(subchartSchema)
subchart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "subchart",
},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{
Name: "chrt",
},
}
chrt.AddDependency(subchart)
vals := map[string]interface{}{
"name": "John",
"subchart": map[string]interface{}{},
}
var errString string
if err := ValidateAgainstSchema(chrt, vals); err == nil {
t.Fatalf("Expected an error, but got nil")
} else {
errString = err.Error()
}
expectedErrString := `subchart:
- at '': missing property 'age'
`
if errString != expectedErrString {
t.Errorf("Error string :\n`%s`\ndoes not match expected\n`%s`", errString, expectedErrString)
}
}
func TestValidateAgainstSchema2020(t *testing.T) {
subchartJSON := []byte(subchartSchema2020)
subchart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "subchart",
},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{
Name: "chrt",
},
}
chrt.AddDependency(subchart)
vals := map[string]interface{}{
"name": "John",
"subchart": map[string]interface{}{
"data": []any{"hello", 12},
},
}
if err := ValidateAgainstSchema(chrt, vals); err != nil {
t.Errorf("Error validating Values against Schema: %s", err)
}
}
func TestValidateAgainstSchema2020Negative(t *testing.T) {
subchartJSON := []byte(subchartSchema2020)
subchart := &chart.Chart{
Metadata: &chart.Metadata{
Name: "subchart",
},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{
Name: "chrt",
},
}
chrt.AddDependency(subchart)
vals := map[string]interface{}{
"name": "John",
"subchart": map[string]interface{}{
"data": []any{12},
},
}
var errString string
if err := ValidateAgainstSchema(chrt, vals); err == nil {
t.Fatalf("Expected an error, but got nil")
} else {
errString = err.Error()
}
expectedErrString := `subchart:
- at '/data': no items match contains schema
- at '/data/0': got number, want string
`
if errString != expectedErrString {
t.Errorf("Error string :\n`%s`\ndoes not match expected\n`%s`", errString, expectedErrString)
}
}
func TestHTTPURLLoader_Load(t *testing.T) {
// Test successful JSON schema loading
t.Run("successful load", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"type": "object", "properties": {"name": {"type": "string"}}}`))
}))
defer server.Close()
loader := newHTTPURLLoader()
result, err := loader.Load(server.URL)
if err != nil {
t.Fatalf("Expected no error, got: %v", err)
}
if result == nil {
t.Fatal("Expected result to be non-nil")
}
})
t.Run("HTTP error status", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
}))
defer server.Close()
loader := newHTTPURLLoader()
_, err := loader.Load(server.URL)
if err == nil {
t.Fatal("Expected error for HTTP 404")
}
if !strings.Contains(err.Error(), "404") {
t.Errorf("Expected error message to contain '404', got: %v", err)
}
})
}
// Test that an unresolved URN $ref is soft-ignored and validation succeeds.
// it mimics the behavior of Helm 3.18.4
func TestValidateAgainstSingleSchema_UnresolvedURN_Ignored(t *testing.T) {
schema := []byte(`{
"$schema": "https://json-schema.org/draft-07/schema#",
"$ref": "urn:example:helm:schemas:v1:helm-schema-validation-conditions:v1/helmSchemaValidation-true"
}`)
vals := map[string]interface{}{"any": "value"}
if err := ValidateAgainstSingleSchema(vals, schema); err != nil {
t.Fatalf("expected no error when URN unresolved is ignored, got: %v", err)
}
}
// Non-regression tests for https://github.com/helm/helm/issues/31202
// Ensure ValidateAgainstSchema does not panic when:
// - subchart key is missing
// - subchart value is nil
// - subchart value has an invalid type
func TestValidateAgainstSchema_MissingSubchartValues_NoPanic(t *testing.T) {
subchartJSON := []byte(subchartSchema)
subchart := &chart.Chart{
Metadata: &chart.Metadata{Name: "subchart"},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{Name: "chrt"},
}
chrt.AddDependency(subchart)
// No "subchart" key present in values
vals := map[string]any{
"name": "John",
}
defer func() {
if r := recover(); r != nil {
t.Fatalf("ValidateAgainstSchema panicked (missing subchart values): %v", r)
}
}()
if err := ValidateAgainstSchema(chrt, vals); err != nil {
t.Fatalf("expected no error when subchart values are missing, got: %v", err)
}
}
func TestValidateAgainstSchema_SubchartNil_NoPanic(t *testing.T) {
subchartJSON := []byte(subchartSchema)
subchart := &chart.Chart{
Metadata: &chart.Metadata{Name: "subchart"},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{Name: "chrt"},
}
chrt.AddDependency(subchart)
// "subchart" key present but nil
vals := map[string]any{
"name": "John",
"subchart": nil,
}
defer func() {
if r := recover(); r != nil {
t.Fatalf("ValidateAgainstSchema panicked (nil subchart values): %v", r)
}
}()
if err := ValidateAgainstSchema(chrt, vals); err != nil {
t.Fatalf("expected no error when subchart values are nil, got: %v", err)
}
}
func TestValidateAgainstSchema_InvalidSubchartValuesType_NoPanic(t *testing.T) {
subchartJSON := []byte(subchartSchema)
subchart := &chart.Chart{
Metadata: &chart.Metadata{Name: "subchart"},
Schema: subchartJSON,
}
chrt := &chart.Chart{
Metadata: &chart.Metadata{Name: "chrt"},
}
chrt.AddDependency(subchart)
// "subchart" is the wrong type (string instead of map)
vals := map[string]any{
"name": "John",
"subchart": "oops",
}
defer func() {
if r := recover(); r != nil {
t.Fatalf("ValidateAgainstSchema panicked (invalid subchart values type): %v", r)
}
}()
// We expect a non-nil error (invalid type), but crucially no panic.
if err := ValidateAgainstSchema(chrt, vals); err == nil {
t.Fatalf("expected an error when subchart values have invalid type, got nil")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/coalesce.go | pkg/chart/common/util/coalesce.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"
"maps"
"helm.sh/helm/v4/internal/copystructure"
chart "helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/common"
)
func concatPrefix(a, b string) string {
if a == "" {
return b
}
return fmt.Sprintf("%s.%s", a, b)
}
// CoalesceValues coalesces all of the values in a chart (and its subcharts).
//
// Values are coalesced together using the following rules:
//
// - Values in a higher level chart always override values in a lower-level
// dependency chart
// - Scalar values and arrays are replaced, maps are merged
// - A chart has access to all of the variables for it, as well as all of
// the values destined for its dependencies.
func CoalesceValues(chrt chart.Charter, vals map[string]interface{}) (common.Values, error) {
valsCopy, err := copyValues(vals)
if err != nil {
return vals, err
}
return coalesce(log.Printf, chrt, valsCopy, "", false)
}
// MergeValues is used to merge the values in a chart and its subcharts. This
// is different from Coalescing as nil/null values are preserved.
//
// Values are coalesced together using the following rules:
//
// - Values in a higher level chart always override values in a lower-level
// dependency chart
// - Scalar values and arrays are replaced, maps are merged
// - A chart has access to all of the variables for it, as well as all of
// the values destined for its dependencies.
//
// Retaining Nils is useful when processes early in a Helm action or business
// logic need to retain them for when Coalescing will happen again later in the
// business logic.
func MergeValues(chrt chart.Charter, vals map[string]interface{}) (common.Values, error) {
valsCopy, err := copyValues(vals)
if err != nil {
return vals, err
}
return coalesce(log.Printf, chrt, valsCopy, "", true)
}
func copyValues(vals map[string]interface{}) (common.Values, error) {
v, err := copystructure.Copy(vals)
if err != nil {
return vals, err
}
valsCopy := v.(map[string]interface{})
// if we have an empty map, make sure it is initialized
if valsCopy == nil {
valsCopy = make(map[string]interface{})
}
return valsCopy, nil
}
type printFn func(format string, v ...interface{})
// coalesce coalesces the dest values and the chart values, giving priority to the dest values.
//
// This is a helper function for CoalesceValues and MergeValues.
//
// Note, the merge argument specifies whether this is being used by MergeValues
// or CoalesceValues. Coalescing removes null values and their keys in some
// situations while merging keeps the null values.
func coalesce(printf printFn, ch chart.Charter, dest map[string]interface{}, prefix string, merge bool) (map[string]interface{}, error) {
coalesceValues(printf, ch, dest, prefix, merge)
return coalesceDeps(printf, ch, dest, prefix, merge)
}
// coalesceDeps coalesces the dependencies of the given chart.
func coalesceDeps(printf printFn, chrt chart.Charter, dest map[string]interface{}, prefix string, merge bool) (map[string]interface{}, error) {
ch, err := chart.NewAccessor(chrt)
if err != nil {
return dest, err
}
for _, subchart := range ch.Dependencies() {
sub, err := chart.NewAccessor(subchart)
if err != nil {
return dest, err
}
if c, ok := dest[sub.Name()]; !ok {
// If dest doesn't already have the key, create it.
dest[sub.Name()] = make(map[string]interface{})
} else if !istable(c) {
return dest, fmt.Errorf("type mismatch on %s: %t", sub.Name(), c)
}
if dv, ok := dest[sub.Name()]; ok {
dvmap := dv.(map[string]interface{})
subPrefix := concatPrefix(prefix, ch.Name())
// Get globals out of dest and merge them into dvmap.
coalesceGlobals(printf, dvmap, dest, subPrefix, merge)
// Now coalesce the rest of the values.
var err error
dest[sub.Name()], err = coalesce(printf, subchart, dvmap, subPrefix, merge)
if err != nil {
return dest, err
}
}
}
return dest, nil
}
// coalesceGlobals copies the globals out of src and merges them into dest.
//
// For convenience, returns dest.
func coalesceGlobals(printf printFn, dest, src map[string]interface{}, prefix string, _ bool) {
var dg, sg map[string]interface{}
if destglob, ok := dest[common.GlobalKey]; !ok {
dg = make(map[string]interface{})
} else if dg, ok = destglob.(map[string]interface{}); !ok {
printf("warning: skipping globals because destination %s is not a table.", common.GlobalKey)
return
}
if srcglob, ok := src[common.GlobalKey]; !ok {
sg = make(map[string]interface{})
} else if sg, ok = srcglob.(map[string]interface{}); !ok {
printf("warning: skipping globals because source %s is not a table.", common.GlobalKey)
return
}
// EXPERIMENTAL: In the past, we have disallowed globals to test tables. This
// reverses that decision. It may somehow be possible to introduce a loop
// here, but I haven't found a way. So for the time being, let's allow
// tables in globals.
for key, val := range sg {
if istable(val) {
vv := copyMap(val.(map[string]interface{}))
if destv, ok := dg[key]; !ok {
// Here there is no merge. We're just adding.
dg[key] = vv
} else {
if destvmap, ok := destv.(map[string]interface{}); !ok {
printf("Conflict: cannot merge map onto non-map for %q. Skipping.", key)
} else {
// Basically, we reverse order of coalesce here to merge
// top-down.
subPrefix := concatPrefix(prefix, key)
// In this location coalesceTablesFullKey should always have
// merge set to true. The output of coalesceGlobals is run
// through coalesce where any nils will be removed.
coalesceTablesFullKey(printf, vv, destvmap, subPrefix, true)
dg[key] = vv
}
}
} else if dv, ok := dg[key]; ok && istable(dv) {
// It's not clear if this condition can actually ever trigger.
printf("key %s is table. Skipping", key)
} else {
// TODO: Do we need to do any additional checking on the value?
dg[key] = val
}
}
dest[common.GlobalKey] = dg
}
func copyMap(src map[string]interface{}) map[string]interface{} {
m := make(map[string]interface{}, len(src))
maps.Copy(m, src)
return m
}
// coalesceValues builds up a values map for a particular chart.
//
// Values in v will override the values in the chart.
func coalesceValues(printf printFn, c chart.Charter, v map[string]interface{}, prefix string, merge bool) {
ch, err := chart.NewAccessor(c)
if err != nil {
return
}
subPrefix := concatPrefix(prefix, ch.Name())
// Using c.Values directly when coalescing a table can cause problems where
// the original c.Values is altered. Creating a deep copy stops the problem.
// This section is fault-tolerant as there is no ability to return an error.
valuesCopy, err := copystructure.Copy(ch.Values())
var vc map[string]interface{}
var ok bool
if err != nil {
// If there is an error something is wrong with copying c.Values it
// means there is a problem in the deep copying package or something
// wrong with c.Values. In this case we will use c.Values and report
// an error.
printf("warning: unable to copy values, err: %s", err)
vc = ch.Values()
} else {
vc, ok = valuesCopy.(map[string]interface{})
if !ok {
// c.Values has a map[string]interface{} structure. If the copy of
// it cannot be treated as map[string]interface{} there is something
// strangely wrong. Log it and use c.Values
printf("warning: unable to convert values copy to values type")
vc = ch.Values()
}
}
for key, val := range vc {
if value, ok := v[key]; ok {
if value == nil && !merge {
// When the YAML value is null and we are coalescing instead of
// merging, we remove the value's key.
// This allows Helm's various sources of values (value files or --set) to
// remove incompatible keys from any previous chart, file, or set values.
delete(v, key)
} else if dest, ok := value.(map[string]interface{}); ok {
// if v[key] is a table, merge nv's val table into v[key].
src, ok := val.(map[string]interface{})
if !ok {
// If the original value is nil, there is nothing to coalesce, so we don't print
// the warning
if val != nil {
printf("warning: skipped value for %s.%s: Not a table.", subPrefix, key)
}
} else {
// If the key is a child chart, coalesce tables with Merge set to true
merge := childChartMergeTrue(c, key, merge)
// Because v has higher precedence than nv, dest values override src
// values.
coalesceTablesFullKey(printf, dest, src, concatPrefix(subPrefix, key), merge)
}
}
} else {
// If the key is not in v, copy it from nv.
v[key] = val
}
}
}
func childChartMergeTrue(chrt chart.Charter, key string, merge bool) bool {
ch, err := chart.NewAccessor(chrt)
if err != nil {
return merge
}
for _, subchart := range ch.Dependencies() {
sub, err := chart.NewAccessor(subchart)
if err != nil {
return merge
}
if sub.Name() == key {
return true
}
}
return merge
}
// CoalesceTables merges a source map into a destination map.
//
// dest is considered authoritative.
func CoalesceTables(dst, src map[string]interface{}) map[string]interface{} {
return coalesceTablesFullKey(log.Printf, dst, src, "", false)
}
func MergeTables(dst, src map[string]interface{}) map[string]interface{} {
return coalesceTablesFullKey(log.Printf, dst, src, "", true)
}
// coalesceTablesFullKey merges a source map into a destination map.
//
// dest is considered authoritative.
func coalesceTablesFullKey(printf printFn, dst, src map[string]interface{}, prefix string, merge bool) map[string]interface{} {
// When --reuse-values is set but there are no modifications yet, return new values
if src == nil {
return dst
}
if dst == nil {
return src
}
for key, val := range dst {
if val == nil {
src[key] = nil
}
}
// Because dest has higher precedence than src, dest values override src
// values.
for key, val := range src {
fullkey := concatPrefix(prefix, key)
if dv, ok := dst[key]; ok && !merge && dv == nil {
delete(dst, key)
} else if !ok {
dst[key] = val
} else if istable(val) {
if istable(dv) {
coalesceTablesFullKey(printf, dv.(map[string]interface{}), val.(map[string]interface{}), fullkey, merge)
} else {
printf("warning: cannot overwrite table with non table for %s (%v)", fullkey, val)
}
} else if istable(dv) && val != nil {
printf("warning: destination for %s is a table. Ignoring non-table value (%v)", fullkey, val)
}
}
return dst
}
// 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
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/values.go | pkg/chart/common/util/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 util
import (
"fmt"
"helm.sh/helm/v4/pkg/chart"
"helm.sh/helm/v4/pkg/chart/common"
)
// ToRenderValues composes the struct from the data coming from the Releases, Charts and Values files
//
// This takes both ReleaseOptions and Capabilities to merge into the render values.
func ToRenderValues(chrt chart.Charter, chrtVals map[string]interface{}, options common.ReleaseOptions, caps *common.Capabilities) (common.Values, error) {
return ToRenderValuesWithSchemaValidation(chrt, chrtVals, options, caps, false)
}
// ToRenderValuesWithSchemaValidation composes the struct from the data coming from the Releases, Charts and Values files
//
// This takes both ReleaseOptions and Capabilities to merge into the render values.
func ToRenderValuesWithSchemaValidation(chrt chart.Charter, chrtVals map[string]interface{}, options common.ReleaseOptions, caps *common.Capabilities, skipSchemaValidation bool) (common.Values, error) {
if caps == nil {
caps = common.DefaultCapabilities
}
accessor, err := chart.NewAccessor(chrt)
if err != nil {
return nil, err
}
top := map[string]interface{}{
"Chart": accessor.MetadataAsMap(),
"Capabilities": caps,
"Release": map[string]interface{}{
"Name": options.Name,
"Namespace": options.Namespace,
"IsUpgrade": options.IsUpgrade,
"IsInstall": options.IsInstall,
"Revision": options.Revision,
"Service": "Helm",
},
}
vals, err := CoalesceValues(chrt, chrtVals)
if err != nil {
return common.Values(top), err
}
if !skipSchemaValidation {
if err := ValidateAgainstSchema(chrt, vals); err != nil {
return top, fmt.Errorf("values don't meet the specifications of the schema(s) in the following chart(s):\n%w", err)
}
}
top["Values"] = vals
return top, nil
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/coalesce_test.go | pkg/chart/common/util/coalesce_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"
"encoding/json"
"fmt"
"maps"
"testing"
"text/template"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
// ref: http://www.yaml.org/spec/1.2/spec.html#id2803362
var testCoalesceValuesYaml = []byte(`
top: yup
bottom: null
right: Null
left: NULL
front: ~
back: ""
nested:
boat: null
global:
name: Ishmael
subject: Queequeg
nested:
boat: true
pequod:
boat: null
global:
name: Stinky
harpooner: Tashtego
nested:
boat: false
sail: true
foo2: null
ahab:
scope: whale
boat: null
nested:
foo: true
boat: null
object: null
`)
func withDeps(c *chart.Chart, deps ...*chart.Chart) *chart.Chart {
c.AddDependency(deps...)
return c
}
func TestCoalesceValues(t *testing.T) {
is := assert.New(t)
c := withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "moby"},
Values: map[string]interface{}{
"back": "exists",
"bottom": "exists",
"front": "exists",
"left": "exists",
"name": "moby",
"nested": map[string]interface{}{"boat": true},
"override": "bad",
"right": "exists",
"scope": "moby",
"top": "nope",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l0": "moby"},
},
"pequod": map[string]interface{}{
"boat": "maybe",
"ahab": map[string]interface{}{
"boat": "maybe",
"nested": map[string]interface{}{"boat": "maybe"},
},
},
},
},
withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "pequod"},
Values: map[string]interface{}{
"name": "pequod",
"scope": "pequod",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l1": "pequod"},
},
"boat": false,
"ahab": map[string]interface{}{
"boat": false,
"nested": map[string]interface{}{"boat": false},
},
},
},
&chart.Chart{
Metadata: &chart.Metadata{Name: "ahab"},
Values: map[string]interface{}{
"global": map[string]interface{}{
"nested": map[string]interface{}{"foo": "bar", "foo2": "bar2"},
"nested2": map[string]interface{}{"l2": "ahab"},
},
"scope": "ahab",
"name": "ahab",
"boat": true,
"nested": map[string]interface{}{"foo": false, "boat": true},
"object": map[string]interface{}{"foo": "bar"},
},
},
),
&chart.Chart{
Metadata: &chart.Metadata{Name: "spouter"},
Values: map[string]interface{}{
"scope": "spouter",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l1": "spouter"},
},
},
},
)
vals, err := common.ReadValues(testCoalesceValuesYaml)
if err != nil {
t.Fatal(err)
}
// taking a copy of the values before passing it
// to CoalesceValues as argument, so that we can
// use it for asserting later
valsCopy := make(common.Values, len(vals))
maps.Copy(valsCopy, vals)
v, err := CoalesceValues(c, vals)
if err != nil {
t.Fatal(err)
}
j, _ := json.MarshalIndent(v, "", " ")
t.Logf("Coalesced Values: %s", string(j))
tests := []struct {
tpl string
expect string
}{
{"{{.top}}", "yup"},
{"{{.back}}", ""},
{"{{.name}}", "moby"},
{"{{.global.name}}", "Ishmael"},
{"{{.global.subject}}", "Queequeg"},
{"{{.global.harpooner}}", "<no value>"},
{"{{.pequod.name}}", "pequod"},
{"{{.pequod.ahab.name}}", "ahab"},
{"{{.pequod.ahab.scope}}", "whale"},
{"{{.pequod.ahab.nested.foo}}", "true"},
{"{{.pequod.ahab.global.name}}", "Ishmael"},
{"{{.pequod.ahab.global.nested.foo}}", "bar"},
{"{{.pequod.ahab.global.nested.foo2}}", "<no value>"},
{"{{.pequod.ahab.global.subject}}", "Queequeg"},
{"{{.pequod.ahab.global.harpooner}}", "Tashtego"},
{"{{.pequod.global.name}}", "Ishmael"},
{"{{.pequod.global.nested.foo}}", "<no value>"},
{"{{.pequod.global.subject}}", "Queequeg"},
{"{{.spouter.global.name}}", "Ishmael"},
{"{{.spouter.global.harpooner}}", "<no value>"},
{"{{.global.nested.boat}}", "true"},
{"{{.pequod.global.nested.boat}}", "true"},
{"{{.spouter.global.nested.boat}}", "true"},
{"{{.pequod.global.nested.sail}}", "true"},
{"{{.spouter.global.nested.sail}}", "<no value>"},
{"{{.global.nested2.l0}}", "moby"},
{"{{.global.nested2.l1}}", "<no value>"},
{"{{.global.nested2.l2}}", "<no value>"},
{"{{.pequod.global.nested2.l0}}", "moby"},
{"{{.pequod.global.nested2.l1}}", "pequod"},
{"{{.pequod.global.nested2.l2}}", "<no value>"},
{"{{.pequod.ahab.global.nested2.l0}}", "moby"},
{"{{.pequod.ahab.global.nested2.l1}}", "pequod"},
{"{{.pequod.ahab.global.nested2.l2}}", "ahab"},
{"{{.spouter.global.nested2.l0}}", "moby"},
{"{{.spouter.global.nested2.l1}}", "spouter"},
{"{{.spouter.global.nested2.l2}}", "<no value>"},
}
for _, tt := range tests {
if o, err := ttpl(tt.tpl, v); err != nil || o != tt.expect {
t.Errorf("Expected %q to expand to %q, got %q", tt.tpl, tt.expect, o)
}
}
nullKeys := []string{"bottom", "right", "left", "front"}
for _, nullKey := range nullKeys {
if _, ok := v[nullKey]; ok {
t.Errorf("Expected key %q to be removed, still present", nullKey)
}
}
if _, ok := v["nested"].(map[string]interface{})["boat"]; ok {
t.Error("Expected nested boat key to be removed, still present")
}
subchart := v["pequod"].(map[string]interface{})
if _, ok := subchart["boat"]; ok {
t.Error("Expected subchart boat key to be removed, still present")
}
subsubchart := subchart["ahab"].(map[string]interface{})
if _, ok := subsubchart["boat"]; ok {
t.Error("Expected sub-subchart ahab boat key to be removed, still present")
}
if _, ok := subsubchart["nested"].(map[string]interface{})["boat"]; ok {
t.Error("Expected sub-subchart nested boat key to be removed, still present")
}
if _, ok := subsubchart["object"]; ok {
t.Error("Expected sub-subchart object map to be removed, still present")
}
// CoalesceValues should not mutate the passed arguments
is.Equal(valsCopy, vals)
}
func ttpl(tpl string, v map[string]interface{}) (string, error) {
var b bytes.Buffer
tt := template.Must(template.New("t").Parse(tpl))
err := tt.Execute(&b, v)
return b.String(), err
}
func TestMergeValues(t *testing.T) {
is := assert.New(t)
c := withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "moby"},
Values: map[string]interface{}{
"back": "exists",
"bottom": "exists",
"front": "exists",
"left": "exists",
"name": "moby",
"nested": map[string]interface{}{"boat": true},
"override": "bad",
"right": "exists",
"scope": "moby",
"top": "nope",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l0": "moby"},
},
},
},
withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "pequod"},
Values: map[string]interface{}{
"name": "pequod",
"scope": "pequod",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l1": "pequod"},
},
},
},
&chart.Chart{
Metadata: &chart.Metadata{Name: "ahab"},
Values: map[string]interface{}{
"global": map[string]interface{}{
"nested": map[string]interface{}{"foo": "bar"},
"nested2": map[string]interface{}{"l2": "ahab"},
},
"scope": "ahab",
"name": "ahab",
"boat": true,
"nested": map[string]interface{}{"foo": false, "bar": true},
},
},
),
&chart.Chart{
Metadata: &chart.Metadata{Name: "spouter"},
Values: map[string]interface{}{
"scope": "spouter",
"global": map[string]interface{}{
"nested2": map[string]interface{}{"l1": "spouter"},
},
},
},
)
vals, err := common.ReadValues(testCoalesceValuesYaml)
if err != nil {
t.Fatal(err)
}
// taking a copy of the values before passing it
// to MergeValues as argument, so that we can
// use it for asserting later
valsCopy := make(common.Values, len(vals))
maps.Copy(valsCopy, vals)
v, err := MergeValues(c, vals)
if err != nil {
t.Fatal(err)
}
j, _ := json.MarshalIndent(v, "", " ")
t.Logf("Coalesced Values: %s", string(j))
tests := []struct {
tpl string
expect string
}{
{"{{.top}}", "yup"},
{"{{.back}}", ""},
{"{{.name}}", "moby"},
{"{{.global.name}}", "Ishmael"},
{"{{.global.subject}}", "Queequeg"},
{"{{.global.harpooner}}", "<no value>"},
{"{{.pequod.name}}", "pequod"},
{"{{.pequod.ahab.name}}", "ahab"},
{"{{.pequod.ahab.scope}}", "whale"},
{"{{.pequod.ahab.nested.foo}}", "true"},
{"{{.pequod.ahab.global.name}}", "Ishmael"},
{"{{.pequod.ahab.global.nested.foo}}", "bar"},
{"{{.pequod.ahab.global.subject}}", "Queequeg"},
{"{{.pequod.ahab.global.harpooner}}", "Tashtego"},
{"{{.pequod.global.name}}", "Ishmael"},
{"{{.pequod.global.nested.foo}}", "<no value>"},
{"{{.pequod.global.subject}}", "Queequeg"},
{"{{.spouter.global.name}}", "Ishmael"},
{"{{.spouter.global.harpooner}}", "<no value>"},
{"{{.global.nested.boat}}", "true"},
{"{{.pequod.global.nested.boat}}", "true"},
{"{{.spouter.global.nested.boat}}", "true"},
{"{{.pequod.global.nested.sail}}", "true"},
{"{{.spouter.global.nested.sail}}", "<no value>"},
{"{{.global.nested2.l0}}", "moby"},
{"{{.global.nested2.l1}}", "<no value>"},
{"{{.global.nested2.l2}}", "<no value>"},
{"{{.pequod.global.nested2.l0}}", "moby"},
{"{{.pequod.global.nested2.l1}}", "pequod"},
{"{{.pequod.global.nested2.l2}}", "<no value>"},
{"{{.pequod.ahab.global.nested2.l0}}", "moby"},
{"{{.pequod.ahab.global.nested2.l1}}", "pequod"},
{"{{.pequod.ahab.global.nested2.l2}}", "ahab"},
{"{{.spouter.global.nested2.l0}}", "moby"},
{"{{.spouter.global.nested2.l1}}", "spouter"},
{"{{.spouter.global.nested2.l2}}", "<no value>"},
}
for _, tt := range tests {
if o, err := ttpl(tt.tpl, v); err != nil || o != tt.expect {
t.Errorf("Expected %q to expand to %q, got %q", tt.tpl, tt.expect, o)
}
}
// nullKeys is different from coalescing. Here the null/nil values are not
// removed.
nullKeys := []string{"bottom", "right", "left", "front"}
for _, nullKey := range nullKeys {
if vv, ok := v[nullKey]; !ok {
t.Errorf("Expected key %q to be present but it was removed", nullKey)
} else if vv != nil {
t.Errorf("Expected key %q to be null but it has a value of %v", nullKey, vv)
}
}
if _, ok := v["nested"].(map[string]interface{})["boat"]; !ok {
t.Error("Expected nested boat key to be present but it was removed")
}
subchart := v["pequod"].(map[string]interface{})["ahab"].(map[string]interface{})
if _, ok := subchart["boat"]; !ok {
t.Error("Expected subchart boat key to be present but it was removed")
}
if _, ok := subchart["nested"].(map[string]interface{})["bar"]; !ok {
t.Error("Expected subchart nested bar key to be present but it was removed")
}
// CoalesceValues should not mutate the passed arguments
is.Equal(valsCopy, vals)
}
func TestCoalesceTables(t *testing.T) {
dst := map[string]interface{}{
"name": "Ishmael",
"address": map[string]interface{}{
"street": "123 Spouter Inn Ct.",
"city": "Nantucket",
"country": nil,
},
"details": map[string]interface{}{
"friends": []string{"Tashtego"},
},
"boat": "pequod",
"hole": nil,
}
src := map[string]interface{}{
"occupation": "whaler",
"address": map[string]interface{}{
"state": "MA",
"street": "234 Spouter Inn Ct.",
"country": "US",
},
"details": "empty",
"boat": map[string]interface{}{
"mast": true,
},
"hole": "black",
}
// What we expect is that anything in dst overrides anything in src, but that
// otherwise the values are coalesced.
CoalesceTables(dst, src)
if dst["name"] != "Ishmael" {
t.Errorf("Unexpected name: %s", dst["name"])
}
if dst["occupation"] != "whaler" {
t.Errorf("Unexpected occupation: %s", dst["occupation"])
}
addr, ok := dst["address"].(map[string]interface{})
if !ok {
t.Fatal("Address went away.")
}
if addr["street"].(string) != "123 Spouter Inn Ct." {
t.Errorf("Unexpected address: %v", addr["street"])
}
if addr["city"].(string) != "Nantucket" {
t.Errorf("Unexpected city: %v", addr["city"])
}
if addr["state"].(string) != "MA" {
t.Errorf("Unexpected state: %v", addr["state"])
}
if _, ok = addr["country"]; ok {
t.Error("The country is not left out.")
}
if det, ok := dst["details"].(map[string]interface{}); !ok {
t.Fatalf("Details is the wrong type: %v", dst["details"])
} else if _, ok := det["friends"]; !ok {
t.Error("Could not find your friends. Maybe you don't have any. :-(")
}
if dst["boat"].(string) != "pequod" {
t.Errorf("Expected boat string, got %v", dst["boat"])
}
if _, ok = dst["hole"]; ok {
t.Error("The hole still exists.")
}
dst2 := map[string]interface{}{
"name": "Ishmael",
"address": map[string]interface{}{
"street": "123 Spouter Inn Ct.",
"city": "Nantucket",
"country": "US",
},
"details": map[string]interface{}{
"friends": []string{"Tashtego"},
},
"boat": "pequod",
"hole": "black",
}
// What we expect is that anything in dst should have all values set,
// this happens when the --reuse-values flag is set but the chart has no modifications yet
CoalesceTables(dst2, nil)
if dst2["name"] != "Ishmael" {
t.Errorf("Unexpected name: %s", dst2["name"])
}
addr2, ok := dst2["address"].(map[string]interface{})
if !ok {
t.Fatal("Address went away.")
}
if addr2["street"].(string) != "123 Spouter Inn Ct." {
t.Errorf("Unexpected address: %v", addr2["street"])
}
if addr2["city"].(string) != "Nantucket" {
t.Errorf("Unexpected city: %v", addr2["city"])
}
if addr2["country"].(string) != "US" {
t.Errorf("Unexpected Country: %v", addr2["country"])
}
if det2, ok := dst2["details"].(map[string]interface{}); !ok {
t.Fatalf("Details is the wrong type: %v", dst2["details"])
} else if _, ok := det2["friends"]; !ok {
t.Error("Could not find your friends. Maybe you don't have any. :-(")
}
if dst2["boat"].(string) != "pequod" {
t.Errorf("Expected boat string, got %v", dst2["boat"])
}
if dst2["hole"].(string) != "black" {
t.Errorf("Expected hole string, got %v", dst2["boat"])
}
}
func TestMergeTables(t *testing.T) {
dst := map[string]interface{}{
"name": "Ishmael",
"address": map[string]interface{}{
"street": "123 Spouter Inn Ct.",
"city": "Nantucket",
"country": nil,
},
"details": map[string]interface{}{
"friends": []string{"Tashtego"},
},
"boat": "pequod",
"hole": nil,
}
src := map[string]interface{}{
"occupation": "whaler",
"address": map[string]interface{}{
"state": "MA",
"street": "234 Spouter Inn Ct.",
"country": "US",
},
"details": "empty",
"boat": map[string]interface{}{
"mast": true,
},
"hole": "black",
}
// What we expect is that anything in dst overrides anything in src, but that
// otherwise the values are coalesced.
MergeTables(dst, src)
if dst["name"] != "Ishmael" {
t.Errorf("Unexpected name: %s", dst["name"])
}
if dst["occupation"] != "whaler" {
t.Errorf("Unexpected occupation: %s", dst["occupation"])
}
addr, ok := dst["address"].(map[string]interface{})
if !ok {
t.Fatal("Address went away.")
}
if addr["street"].(string) != "123 Spouter Inn Ct." {
t.Errorf("Unexpected address: %v", addr["street"])
}
if addr["city"].(string) != "Nantucket" {
t.Errorf("Unexpected city: %v", addr["city"])
}
if addr["state"].(string) != "MA" {
t.Errorf("Unexpected state: %v", addr["state"])
}
// This is one test that is different from CoalesceTables. Because country
// is a nil value and it's not removed it's still present.
if _, ok = addr["country"]; !ok {
t.Error("The country is left out.")
}
if det, ok := dst["details"].(map[string]interface{}); !ok {
t.Fatalf("Details is the wrong type: %v", dst["details"])
} else if _, ok := det["friends"]; !ok {
t.Error("Could not find your friends. Maybe you don't have any. :-(")
}
if dst["boat"].(string) != "pequod" {
t.Errorf("Expected boat string, got %v", dst["boat"])
}
// This is one test that is different from CoalesceTables. Because hole
// is a nil value and it's not removed it's still present.
if _, ok = dst["hole"]; !ok {
t.Error("The hole no longer exists.")
}
dst2 := map[string]interface{}{
"name": "Ishmael",
"address": map[string]interface{}{
"street": "123 Spouter Inn Ct.",
"city": "Nantucket",
"country": "US",
},
"details": map[string]interface{}{
"friends": []string{"Tashtego"},
},
"boat": "pequod",
"hole": "black",
"nilval": nil,
}
// What we expect is that anything in dst should have all values set,
// this happens when the --reuse-values flag is set but the chart has no modifications yet
MergeTables(dst2, nil)
if dst2["name"] != "Ishmael" {
t.Errorf("Unexpected name: %s", dst2["name"])
}
addr2, ok := dst2["address"].(map[string]interface{})
if !ok {
t.Fatal("Address went away.")
}
if addr2["street"].(string) != "123 Spouter Inn Ct." {
t.Errorf("Unexpected address: %v", addr2["street"])
}
if addr2["city"].(string) != "Nantucket" {
t.Errorf("Unexpected city: %v", addr2["city"])
}
if addr2["country"].(string) != "US" {
t.Errorf("Unexpected Country: %v", addr2["country"])
}
if det2, ok := dst2["details"].(map[string]interface{}); !ok {
t.Fatalf("Details is the wrong type: %v", dst2["details"])
} else if _, ok := det2["friends"]; !ok {
t.Error("Could not find your friends. Maybe you don't have any. :-(")
}
if dst2["boat"].(string) != "pequod" {
t.Errorf("Expected boat string, got %v", dst2["boat"])
}
if dst2["hole"].(string) != "black" {
t.Errorf("Expected hole string, got %v", dst2["boat"])
}
if dst2["nilval"] != nil {
t.Error("Expected nilvalue to have nil value but it does not")
}
}
func TestCoalesceValuesWarnings(t *testing.T) {
c := withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "level1"},
Values: map[string]interface{}{
"name": "moby",
},
},
withDeps(&chart.Chart{
Metadata: &chart.Metadata{Name: "level2"},
Values: map[string]interface{}{
"name": "pequod",
},
},
&chart.Chart{
Metadata: &chart.Metadata{Name: "level3"},
Values: map[string]interface{}{
"name": "ahab",
"boat": true,
"spear": map[string]interface{}{
"tip": true,
"sail": map[string]interface{}{
"cotton": true,
},
},
},
},
),
)
vals := map[string]interface{}{
"level2": map[string]interface{}{
"level3": map[string]interface{}{
"boat": map[string]interface{}{"mast": true},
"spear": map[string]interface{}{
"tip": map[string]interface{}{
"sharp": true,
},
"sail": true,
},
},
},
}
warnings := make([]string, 0)
printf := func(format string, v ...interface{}) {
t.Logf(format, v...)
warnings = append(warnings, fmt.Sprintf(format, v...))
}
_, err := coalesce(printf, c, vals, "", false)
if err != nil {
t.Fatal(err)
}
t.Logf("vals: %v", vals)
assert.Contains(t, warnings, "warning: skipped value for level1.level2.level3.boat: Not a table.")
assert.Contains(t, warnings, "warning: destination for level1.level2.level3.spear.tip is a table. Ignoring non-table value (true)")
assert.Contains(t, warnings, "warning: cannot overwrite table with non table for level1.level2.level3.spear.sail (map[cotton:true])")
}
func TestConcatPrefix(t *testing.T) {
assert.Equal(t, "b", concatPrefix("", "b"))
assert.Equal(t, "a.b", concatPrefix("a", "b"))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/common/util/values_test.go | pkg/chart/common/util/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 util
import (
"testing"
"time"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
)
func TestToRenderValues(t *testing.T) {
chartValues := map[string]interface{}{
"name": "al Rashid",
"where": map[string]interface{}{
"city": "Basrah",
"title": "caliph",
},
}
overrideValues := map[string]interface{}{
"name": "Haroun",
"where": map[string]interface{}{
"city": "Baghdad",
"date": "809 CE",
},
}
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "test"},
Templates: []*common.File{},
Values: chartValues,
Files: []*common.File{
{Name: "scheherazade/shahryar.txt", ModTime: time.Now(), Data: []byte("1,001 Nights")},
},
}
c.AddDependency(&chart.Chart{
Metadata: &chart.Metadata{Name: "where"},
})
o := common.ReleaseOptions{
Name: "Seven Voyages",
Namespace: "default",
Revision: 1,
IsInstall: true,
}
res, err := ToRenderValuesWithSchemaValidation(c, overrideValues, o, nil, false)
if err != nil {
t.Fatal(err)
}
// Ensure that the top-level values are all set.
metamap := res["Chart"].(map[string]interface{})
if name := metamap["Name"]; name.(string) != "test" {
t.Errorf("Expected chart name 'test', got %q", name)
}
relmap := res["Release"].(map[string]interface{})
if name := relmap["Name"]; name.(string) != "Seven Voyages" {
t.Errorf("Expected release name 'Seven Voyages', got %q", name)
}
if namespace := relmap["Namespace"]; namespace.(string) != "default" {
t.Errorf("Expected namespace 'default', got %q", namespace)
}
if revision := relmap["Revision"]; revision.(int) != 1 {
t.Errorf("Expected revision '1', got %d", revision)
}
if relmap["IsUpgrade"].(bool) {
t.Error("Expected upgrade to be false.")
}
if !relmap["IsInstall"].(bool) {
t.Errorf("Expected install to be true.")
}
if !res["Capabilities"].(*common.Capabilities).APIVersions.Has("v1") {
t.Error("Expected Capabilities to have v1 as an API")
}
if res["Capabilities"].(*common.Capabilities).KubeVersion.Major != "1" {
t.Error("Expected Capabilities to have a Kube version")
}
vals := res["Values"].(common.Values)
if vals["name"] != "Haroun" {
t.Errorf("Expected 'Haroun', got %q (%v)", vals["name"], vals)
}
where := vals["where"].(map[string]interface{})
expects := map[string]string{
"city": "Baghdad",
"date": "809 CE",
"title": "caliph",
}
for field, expect := range expects {
if got := where[field]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, where)
}
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/chart.go | pkg/chart/v2/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 v2
import (
"path/filepath"
"regexp"
"strings"
"time"
"helm.sh/helm/v4/pkg/chart/common"
)
// APIVersionV1 is the API version number for version 1.
const APIVersionV1 = "v1"
// APIVersionV2 is the API version number for version 2.
const APIVersionV2 = "v2"
// aliasNameFormat defines the characters that are legal in an alias name.
var aliasNameFormat = regexp.MustCompile("^[a-zA-Z0-9_-]+$")
// Chart is a helm package that contains metadata, a default config, zero or more
// optionally parameterizable templates, and zero or more charts (dependencies).
type Chart struct {
// Raw contains the raw contents of the files originally contained in the chart archive.
//
// This should not be used except in special cases like `helm show values`,
// where we want to display the raw values, comments and all.
Raw []*common.File `json:"-"`
// Metadata is the contents of the Chartfile.
Metadata *Metadata `json:"metadata"`
// Lock is the contents of Chart.lock.
Lock *Lock `json:"lock"`
// Templates for this chart.
Templates []*common.File `json:"templates"`
// Values are default config for this chart.
Values map[string]interface{} `json:"values"`
// Schema is an optional JSON schema for imposing structure on Values
Schema []byte `json:"schema"`
// SchemaModTime the schema was last modified
SchemaModTime time.Time `json:"schemamodtime,omitempty"`
// Files are miscellaneous files in a chart archive,
// e.g. README, LICENSE, etc.
Files []*common.File `json:"files"`
// ModTime the chart metadata was last modified
ModTime time.Time `json:"modtime,omitzero"`
parent *Chart
dependencies []*Chart
}
type CRD struct {
// Name is the File.Name for the crd file
Name string
// Filename is the File obj Name including (sub-)chart.ChartFullPath
Filename string
// File is the File obj for the crd
File *common.File
}
// SetDependencies replaces the chart dependencies.
func (ch *Chart) SetDependencies(charts ...*Chart) {
ch.dependencies = nil
ch.AddDependency(charts...)
}
// Name returns the name of the chart.
func (ch *Chart) Name() string {
if ch.Metadata == nil {
return ""
}
return ch.Metadata.Name
}
// AddDependency determines if the chart is a subchart.
func (ch *Chart) AddDependency(charts ...*Chart) {
for i, x := range charts {
charts[i].parent = ch
ch.dependencies = append(ch.dependencies, x)
}
}
// Root finds the root chart.
func (ch *Chart) Root() *Chart {
if ch.IsRoot() {
return ch
}
return ch.Parent().Root()
}
// Dependencies are the charts that this chart depends on.
func (ch *Chart) Dependencies() []*Chart { return ch.dependencies }
// IsRoot determines if the chart is the root chart.
func (ch *Chart) IsRoot() bool { return ch.parent == nil }
// Parent returns a subchart's parent chart.
func (ch *Chart) Parent() *Chart { return ch.parent }
// ChartPath returns the full path to this chart in dot notation.
func (ch *Chart) ChartPath() string {
if !ch.IsRoot() {
return ch.Parent().ChartPath() + "." + ch.Name()
}
return ch.Name()
}
// ChartFullPath returns the full path to this chart.
// Note that the path may not correspond to the path where the file can be found on the file system if the path
// points to an aliased subchart.
func (ch *Chart) ChartFullPath() string {
if !ch.IsRoot() {
return ch.Parent().ChartFullPath() + "/charts/" + ch.Name()
}
return ch.Name()
}
// Validate validates the metadata.
func (ch *Chart) Validate() error {
return ch.Metadata.Validate()
}
// AppVersion returns the appversion of the chart.
func (ch *Chart) AppVersion() string {
if ch.Metadata == nil {
return ""
}
return ch.Metadata.AppVersion
}
// CRDs returns a list of File objects in the 'crds/' directory of a Helm chart.
// Deprecated: use CRDObjects()
func (ch *Chart) CRDs() []*common.File {
files := []*common.File{}
// Find all resources in the crds/ directory
for _, f := range ch.Files {
if strings.HasPrefix(f.Name, "crds/") && hasManifestExtension(f.Name) {
files = append(files, f)
}
}
// Get CRDs from dependencies, too.
for _, dep := range ch.Dependencies() {
files = append(files, dep.CRDs()...)
}
return files
}
// CRDObjects returns a list of CRD objects in the 'crds/' directory of a Helm chart & subcharts
func (ch *Chart) CRDObjects() []CRD {
crds := []CRD{}
// Find all resources in the crds/ directory
for _, f := range ch.Files {
if strings.HasPrefix(f.Name, "crds/") && hasManifestExtension(f.Name) {
mycrd := CRD{Name: f.Name, Filename: filepath.Join(ch.ChartFullPath(), f.Name), File: f}
crds = append(crds, mycrd)
}
}
// Get CRDs from dependencies, too.
for _, dep := range ch.Dependencies() {
crds = append(crds, dep.CRDObjects()...)
}
return crds
}
func hasManifestExtension(fname string) bool {
ext := filepath.Ext(fname)
return strings.EqualFold(ext, ".yaml") || strings.EqualFold(ext, ".yml") || strings.EqualFold(ext, ".json")
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/fuzz_test.go | pkg/chart/v2/fuzz_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 v2
import (
"testing"
fuzz "github.com/AdaLogics/go-fuzz-headers"
)
func FuzzMetadataValidate(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte) {
fdp := fuzz.NewConsumer(data)
// Add random values to the metadata
md := &Metadata{}
err := fdp.GenerateStruct(md)
if err != nil {
t.Skip()
}
md.Validate()
})
}
func FuzzDependencyValidate(f *testing.F) {
f.Fuzz(func(t *testing.T, data []byte) {
f := fuzz.NewConsumer(data)
// Add random values to the dependenci
d := &Dependency{}
err := f.GenerateStruct(d)
if err != nil {
t.Skip()
}
d.Validate()
})
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/dependency.go | pkg/chart/v2/dependency.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 v2
import "time"
// Dependency describes a chart upon which another chart depends.
//
// Dependencies can be used to express developer intent, or to capture the state
// of a chart.
type Dependency struct {
// Name is the name of the dependency.
//
// This must mach the name in the dependency's Chart.yaml.
Name string `json:"name" yaml:"name"`
// Version is the version (range) of this chart.
//
// A lock file will always produce a single version, while a dependency
// may contain a semantic version range.
Version string `json:"version,omitempty" yaml:"version,omitempty"`
// The URL to the repository.
//
// Appending `index.yaml` to this string should result in a URL that can be
// used to fetch the repository index.
Repository string `json:"repository" yaml:"repository"`
// A yaml path that resolves to a boolean, used for enabling/disabling charts (e.g. subchart1.enabled )
Condition string `json:"condition,omitempty" yaml:"condition,omitempty"`
// Tags can be used to group charts for enabling/disabling together
Tags []string `json:"tags,omitempty" yaml:"tags,omitempty"`
// Enabled bool determines if chart should be loaded
Enabled bool `json:"enabled,omitempty" yaml:"enabled,omitempty"`
// ImportValues holds the mapping of source values to parent key to be imported. Each item can be a
// string or pair of child/parent sublist items.
ImportValues []interface{} `json:"import-values,omitempty" yaml:"import-values,omitempty"`
// Alias usable alias to be used for the chart
Alias string `json:"alias,omitempty" yaml:"alias,omitempty"`
}
// Validate checks for common problems with the dependency datastructure in
// the chart. This check must be done at load time before the dependency's charts are
// loaded.
func (d *Dependency) Validate() error {
if d == nil {
return ValidationError("dependencies must not contain empty or null nodes")
}
d.Name = sanitizeString(d.Name)
d.Version = sanitizeString(d.Version)
d.Repository = sanitizeString(d.Repository)
d.Condition = sanitizeString(d.Condition)
for i := range d.Tags {
d.Tags[i] = sanitizeString(d.Tags[i])
}
if d.Alias != "" && !aliasNameFormat.MatchString(d.Alias) {
return ValidationErrorf("dependency %q has disallowed characters in the alias", d.Name)
}
return nil
}
// Lock is a lock file for dependencies.
//
// It represents the state that the dependencies should be in.
type Lock struct {
// Generated is the date the lock file was last generated.
Generated time.Time `json:"generated"`
// Digest is a hash of the dependencies in Chart.yaml.
Digest string `json:"digest"`
// Dependencies is the list of dependencies that this lock file has locked.
Dependencies []*Dependency `json:"dependencies"`
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/errors.go | pkg/chart/v2/errors.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 v2
import "fmt"
// ValidationError represents a data validation error.
type ValidationError string
func (v ValidationError) Error() string {
return "validation: " + string(v)
}
// ValidationErrorf takes a message and formatting options and creates a ValidationError
func ValidationErrorf(msg string, args ...interface{}) ValidationError {
return ValidationError(fmt.Sprintf(msg, args...))
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/metadata.go | pkg/chart/v2/metadata.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 v2
import (
"path/filepath"
"strings"
"unicode"
"github.com/Masterminds/semver/v3"
)
// Maintainer describes a Chart maintainer.
type Maintainer struct {
// Name is a user name or organization name
Name string `json:"name,omitempty"`
// Email is an optional email address to contact the named maintainer
Email string `json:"email,omitempty"`
// URL is an optional URL to an address for the named maintainer
URL string `json:"url,omitempty"`
}
// Validate checks valid data and sanitizes string characters.
func (m *Maintainer) Validate() error {
if m == nil {
return ValidationError("maintainers must not contain empty or null nodes")
}
m.Name = sanitizeString(m.Name)
m.Email = sanitizeString(m.Email)
m.URL = sanitizeString(m.URL)
return nil
}
// Metadata for a Chart file. This models the structure of a Chart.yaml file.
type Metadata struct {
// The name of the chart. Required.
Name string `json:"name,omitempty"`
// The URL to a relevant project page, git repo, or contact person
Home string `json:"home,omitempty"`
// Source is the URL to the source code of this chart
Sources []string `json:"sources,omitempty"`
// A version string of the chart. Required.
Version string `json:"version,omitempty"`
// A one-sentence description of the chart
Description string `json:"description,omitempty"`
// A list of string keywords
Keywords []string `json:"keywords,omitempty"`
// A list of name and URL/email address combinations for the maintainer(s)
Maintainers []*Maintainer `json:"maintainers,omitempty"`
// The URL to an icon file.
Icon string `json:"icon,omitempty"`
// The API Version of this chart. Required.
APIVersion string `json:"apiVersion,omitempty"`
// The condition to check to enable chart
Condition string `json:"condition,omitempty"`
// The tags to check to enable chart
Tags string `json:"tags,omitempty"`
// The version of the application enclosed inside of this chart.
AppVersion string `json:"appVersion,omitempty"`
// Whether or not this chart is deprecated
Deprecated bool `json:"deprecated,omitempty"`
// Annotations are additional mappings uninterpreted by Helm,
// made available for inspection by other applications.
Annotations map[string]string `json:"annotations,omitempty"`
// KubeVersion is a SemVer constraint specifying the version of Kubernetes required.
KubeVersion string `json:"kubeVersion,omitempty"`
// Dependencies are a list of dependencies for a chart.
Dependencies []*Dependency `json:"dependencies,omitempty"`
// Specifies the chart type: application or library
Type string `json:"type,omitempty"`
}
// Validate checks the metadata for known issues and sanitizes string
// characters.
func (md *Metadata) Validate() error {
if md == nil {
return ValidationError("chart.metadata is required")
}
md.Name = sanitizeString(md.Name)
md.Description = sanitizeString(md.Description)
md.Home = sanitizeString(md.Home)
md.Icon = sanitizeString(md.Icon)
md.Condition = sanitizeString(md.Condition)
md.Tags = sanitizeString(md.Tags)
md.AppVersion = sanitizeString(md.AppVersion)
md.KubeVersion = sanitizeString(md.KubeVersion)
for i := range md.Sources {
md.Sources[i] = sanitizeString(md.Sources[i])
}
for i := range md.Keywords {
md.Keywords[i] = sanitizeString(md.Keywords[i])
}
if md.APIVersion == "" {
return ValidationError("chart.metadata.apiVersion is required")
}
if md.Name == "" {
return ValidationError("chart.metadata.name is required")
}
if md.Name != filepath.Base(md.Name) {
return ValidationErrorf("chart.metadata.name %q is invalid", md.Name)
}
if md.Version == "" {
return ValidationError("chart.metadata.version is required")
}
if !isValidSemver(md.Version) {
return ValidationErrorf("chart.metadata.version %q is invalid", md.Version)
}
if !isValidChartType(md.Type) {
return ValidationError("chart.metadata.type must be application or library")
}
for _, m := range md.Maintainers {
if err := m.Validate(); err != nil {
return err
}
}
// Aliases need to be validated here to make sure that the alias name does
// not contain any illegal characters.
dependencies := map[string]*Dependency{}
for _, dependency := range md.Dependencies {
if err := dependency.Validate(); err != nil {
return err
}
key := dependency.Name
if dependency.Alias != "" {
key = dependency.Alias
}
if dependencies[key] != nil {
return ValidationErrorf("more than one dependency with name or alias %q", key)
}
dependencies[key] = dependency
}
return nil
}
func isValidChartType(in string) bool {
switch in {
case "", "application", "library":
return true
}
return false
}
func isValidSemver(v string) bool {
_, err := semver.NewVersion(v)
return err == nil
}
// sanitizeString normalize spaces and removes non-printable characters.
func sanitizeString(str string) string {
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return ' '
}
if unicode.IsPrint(r) {
return r
}
return -1
}, str)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/metadata_test.go | pkg/chart/v2/metadata_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 v2
import (
"testing"
)
func TestValidate(t *testing.T) {
tests := []struct {
name string
md *Metadata
err error
}{
{
"chart without metadata",
nil,
ValidationError("chart.metadata is required"),
},
{
"chart without apiVersion",
&Metadata{Name: "test", Version: "1.0"},
ValidationError("chart.metadata.apiVersion is required"),
},
{
"chart without name",
&Metadata{APIVersion: "v2", Version: "1.0"},
ValidationError("chart.metadata.name is required"),
},
{
"chart without name",
&Metadata{Name: "../../test", APIVersion: "v2", Version: "1.0"},
ValidationError("chart.metadata.name \"../../test\" is invalid"),
},
{
"chart without version",
&Metadata{Name: "test", APIVersion: "v2"},
ValidationError("chart.metadata.version is required"),
},
{
"chart with bad type",
&Metadata{Name: "test", APIVersion: "v2", Version: "1.0", Type: "test"},
ValidationError("chart.metadata.type must be application or library"),
},
{
"chart without dependency",
&Metadata{Name: "test", APIVersion: "v2", Version: "1.0", Type: "application"},
nil,
},
{
"dependency with valid alias",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "dependency", Alias: "legal-alias"},
},
},
nil,
},
{
"dependency with bad characters in alias",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "bad", Alias: "illegal alias"},
},
},
ValidationError("dependency \"bad\" has disallowed characters in the alias"),
},
{
"same dependency twice",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "foo", Alias: ""},
{Name: "foo", Alias: ""},
},
},
ValidationError("more than one dependency with name or alias \"foo\""),
},
{
"two dependencies with alias from second dependency shadowing first one",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "foo", Alias: ""},
{Name: "bar", Alias: "foo"},
},
},
ValidationError("more than one dependency with name or alias \"foo\""),
},
{
// this case would make sense and could work in future versions of Helm, currently template rendering would
// result in undefined behaviour
"same dependency twice with different version",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "foo", Alias: "", Version: "1.2.3"},
{Name: "foo", Alias: "", Version: "1.0.0"},
},
},
ValidationError("more than one dependency with name or alias \"foo\""),
},
{
// this case would make sense and could work in future versions of Helm, currently template rendering would
// result in undefined behaviour
"two dependencies with same name but different repos",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
{Name: "foo", Repository: "repo-0"},
{Name: "foo", Repository: "repo-1"},
},
},
ValidationError("more than one dependency with name or alias \"foo\""),
},
{
"dependencies has nil",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Dependencies: []*Dependency{
nil,
},
},
ValidationError("dependencies must not contain empty or null nodes"),
},
{
"maintainer not empty",
&Metadata{
Name: "test",
APIVersion: "v2",
Version: "1.0",
Type: "application",
Maintainers: []*Maintainer{
nil,
},
},
ValidationError("maintainers must not contain empty or null nodes"),
},
{
"version invalid",
&Metadata{APIVersion: "v2", Name: "test", Version: "1.2.3.4"},
ValidationError("chart.metadata.version \"1.2.3.4\" is invalid"),
},
}
for _, tt := range tests {
result := tt.md.Validate()
if result != tt.err {
t.Errorf("expected %q, got %q in test %q", tt.err, result, tt.name)
}
}
}
func TestValidate_sanitize(t *testing.T) {
md := &Metadata{APIVersion: "v2", Name: "test", Version: "1.0", Description: "\adescr\u0081iption\rtest", Maintainers: []*Maintainer{{Name: "\r"}}}
if err := md.Validate(); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if md.Description != "description test" {
t.Fatalf("description was not sanitized: %q", md.Description)
}
if md.Maintainers[0].Name != " " {
t.Fatal("maintainer name was not sanitized")
}
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/doc.go | pkg/chart/v2/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 v2 provides chart handling for apiVersion v1 and v2 charts
This package and its sub-packages provide handling for apiVersion v1 and v2 charts.
The changes from v1 to v2 charts are minor and were able to be handled with minor
switches based on characteristics.
*/
package v2
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/chart_test.go | pkg/chart/v2/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 v2
import (
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"helm.sh/helm/v4/pkg/chart/common"
)
func TestCRDs(t *testing.T) {
modTime := time.Now()
chrt := Chart{
Files: []*common.File{
{
Name: "crds/foo.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "bar.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crds/foo/bar/baz.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crdsfoo/bar/baz.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crds/README.md",
ModTime: modTime,
Data: []byte("# hello"),
},
},
}
is := assert.New(t)
crds := chrt.CRDs()
is.Equal(2, len(crds))
is.Equal("crds/foo.yaml", crds[0].Name)
is.Equal("crds/foo/bar/baz.yaml", crds[1].Name)
}
func TestSaveChartNoRawData(t *testing.T) {
chrt := Chart{
Raw: []*common.File{
{
Name: "fhqwhgads.yaml",
ModTime: time.Now(),
Data: []byte("Everybody to the Limit"),
},
},
}
is := assert.New(t)
data, err := json.Marshal(chrt)
if err != nil {
t.Fatal(err)
}
res := &Chart{}
if err := json.Unmarshal(data, res); err != nil {
t.Fatal(err)
}
is.Equal([]*common.File(nil), res.Raw)
}
func TestMetadata(t *testing.T) {
chrt := Chart{
Metadata: &Metadata{
Name: "foo.yaml",
AppVersion: "1.0.0",
APIVersion: "v2",
Version: "1.0.0",
Type: "application",
},
}
is := assert.New(t)
is.Equal("foo.yaml", chrt.Name())
is.Equal("1.0.0", chrt.AppVersion())
is.Equal(nil, chrt.Validate())
}
func TestIsRoot(t *testing.T) {
chrt1 := Chart{
parent: &Chart{
Metadata: &Metadata{
Name: "foo",
},
},
}
chrt2 := Chart{
Metadata: &Metadata{
Name: "foo",
},
}
is := assert.New(t)
is.Equal(false, chrt1.IsRoot())
is.Equal(true, chrt2.IsRoot())
}
func TestChartPath(t *testing.T) {
chrt1 := Chart{
parent: &Chart{
Metadata: &Metadata{
Name: "foo",
},
},
}
chrt2 := Chart{
Metadata: &Metadata{
Name: "foo",
},
}
is := assert.New(t)
is.Equal("foo.", chrt1.ChartPath())
is.Equal("foo", chrt2.ChartPath())
}
func TestChartFullPath(t *testing.T) {
chrt1 := Chart{
parent: &Chart{
Metadata: &Metadata{
Name: "foo",
},
},
}
chrt2 := Chart{
Metadata: &Metadata{
Name: "foo",
},
}
is := assert.New(t)
is.Equal("foo/charts/", chrt1.ChartFullPath())
is.Equal("foo", chrt2.ChartFullPath())
}
func TestCRDObjects(t *testing.T) {
modTime := time.Now()
chrt := Chart{
Files: []*common.File{
{
Name: "crds/foo.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "bar.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crds/foo/bar/baz.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crdsfoo/bar/baz.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
{
Name: "crds/README.md",
ModTime: modTime,
Data: []byte("# hello"),
},
},
}
expected := []CRD{
{
Name: "crds/foo.yaml",
Filename: "crds/foo.yaml",
File: &common.File{
Name: "crds/foo.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
},
{
Name: "crds/foo/bar/baz.yaml",
Filename: "crds/foo/bar/baz.yaml",
File: &common.File{
Name: "crds/foo/bar/baz.yaml",
ModTime: modTime,
Data: []byte("hello"),
},
},
}
is := assert.New(t)
crds := chrt.CRDObjects()
is.Equal(expected, crds)
}
| go | Apache-2.0 | 08f17fc9474ca51006427319bfa35e7630961a70 | 2026-01-07T08:36:55.903988Z | false |
helm/helm | https://github.com/helm/helm/blob/08f17fc9474ca51006427319bfa35e7630961a70/pkg/chart/v2/dependency_test.go | pkg/chart/v2/dependency_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 v2
import (
"testing"
)
func TestValidateDependency(t *testing.T) {
dep := &Dependency{
Name: "example",
}
for value, shouldFail := range map[string]bool{
"abcdefghijklmenopQRSTUVWXYZ-0123456780_": false,
"-okay": false,
"_okay": false,
"- bad": true,
" bad": true,
"bad\nvalue": true,
"bad ": true,
"bad$": true,
} {
dep.Alias = value
res := dep.Validate()
if res != nil && !shouldFail {
t.Errorf("Failed on case %q", dep.Alias)
} else if res == nil && shouldFail {
t.Errorf("Expected failure for %q", dep.Alias)
}
}
}
| 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.go | pkg/chart/v2/util/create.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"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"sigs.k8s.io/yaml"
"helm.sh/helm/v4/pkg/chart/common"
chart "helm.sh/helm/v4/pkg/chart/v2"
"helm.sh/helm/v4/pkg/chart/v2/loader"
)
// chartName is a regular expression for testing the supplied name of a chart.
// This regular expression is probably stricter than it needs to be. We can relax it
// somewhat. Newline characters, as well as $, quotes, +, parens, and % are known to be
// problematic.
var chartName = regexp.MustCompile("^[a-zA-Z0-9._-]+$")
const (
// ChartfileName is the default Chart file name.
ChartfileName = "Chart.yaml"
// ValuesfileName is the default values file name.
ValuesfileName = "values.yaml"
// SchemafileName is the default values schema file name.
SchemafileName = "values.schema.json"
// TemplatesDir is the relative directory name for templates.
TemplatesDir = "templates"
// ChartsDir is the relative directory name for charts dependencies.
ChartsDir = "charts"
// TemplatesTestsDir is the relative directory name for tests.
TemplatesTestsDir = TemplatesDir + sep + "tests"
// IgnorefileName is the name of the Helm ignore file.
IgnorefileName = ".helmignore"
// IngressFileName is the name of the example ingress file.
IngressFileName = TemplatesDir + sep + "ingress.yaml"
// HTTPRouteFileName is the name of the example HTTPRoute file.
HTTPRouteFileName = TemplatesDir + sep + "httproute.yaml"
// DeploymentName is the name of the example deployment file.
DeploymentName = TemplatesDir + sep + "deployment.yaml"
// ServiceName is the name of the example service file.
ServiceName = TemplatesDir + sep + "service.yaml"
// ServiceAccountName is the name of the example serviceaccount file.
ServiceAccountName = TemplatesDir + sep + "serviceaccount.yaml"
// HorizontalPodAutoscalerName is the name of the example hpa file.
HorizontalPodAutoscalerName = TemplatesDir + sep + "hpa.yaml"
// NotesName is the name of the example NOTES.txt file.
NotesName = TemplatesDir + sep + "NOTES.txt"
// HelpersName is the name of the example helpers file.
HelpersName = TemplatesDir + sep + "_helpers.tpl"
// TestConnectionName is the name of the example test file.
TestConnectionName = TemplatesTestsDir + sep + "test-connection.yaml"
)
// maxChartNameLength is lower than the limits we know of with certain file systems,
// and with certain Kubernetes fields.
const maxChartNameLength = 250
const sep = string(filepath.Separator)
const defaultChartfile = `apiVersion: v2
name: %s
description: A Helm chart for Kubernetes
# A chart can be either an 'application' or a 'library' chart.
#
# Application charts are a collection of templates that can be packaged into versioned archives
# to be deployed.
#
# Library charts provide useful utilities or functions for the chart developer. They're included as
# a dependency of application charts to inject those utilities and functions into the rendering
# pipeline. Library charts do not define any templates and therefore cannot be deployed.
type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
version: 0.1.0
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
# It is recommended to use it with quotes.
appVersion: "1.16.0"
`
const defaultValues = `# Default values for %s.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.
# This will set the replicaset count more information can be found here: https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
replicaCount: 1
# This sets the container image more information can be found here: https://kubernetes.io/docs/concepts/containers/images/
image:
repository: nginx
# This sets the pull policy for images.
pullPolicy: IfNotPresent
# Overrides the image tag whose default is the chart appVersion.
tag: ""
# This is for the secrets for pulling an image from a private repository more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/pull-image-private-registry/
imagePullSecrets: []
# This is to override the chart name.
nameOverride: ""
fullnameOverride: ""
# This section builds out the service account more information can be found here: https://kubernetes.io/docs/concepts/security/service-accounts/
serviceAccount:
# Specifies whether a service account should be created.
create: true
# Automatically mount a ServiceAccount's API credentials?
automount: true
# Annotations to add to the service account.
annotations: {}
# The name of the service account to use.
# If not set and create is true, a name is generated using the fullname template.
name: ""
# This is for setting Kubernetes Annotations to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/
podAnnotations: {}
# This is for setting Kubernetes Labels to a Pod.
# For more information checkout: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
podLabels: {}
podSecurityContext: {}
# fsGroup: 2000
securityContext: {}
# capabilities:
# drop:
# - ALL
# readOnlyRootFilesystem: true
# runAsNonRoot: true
# runAsUser: 1000
# This is for setting up a service more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/
service:
# This sets the service type more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types
type: ClusterIP
# This sets the ports more information can be found here: https://kubernetes.io/docs/concepts/services-networking/service/#field-spec-ports
port: 80
# This block is for setting up the ingress for more information can be found here: https://kubernetes.io/docs/concepts/services-networking/ingress/
ingress:
enabled: false
className: ""
annotations: {}
# kubernetes.io/ingress.class: nginx
# kubernetes.io/tls-acme: "true"
hosts:
- host: chart-example.local
paths:
- path: /
pathType: ImplementationSpecific
tls: []
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
# -- Expose the service via gateway-api HTTPRoute
# Requires Gateway API resources and suitable controller installed within the cluster
# (see: https://gateway-api.sigs.k8s.io/guides/)
httpRoute:
# HTTPRoute enabled.
enabled: false
# HTTPRoute annotations.
annotations: {}
# Which Gateways this Route is attached to.
parentRefs:
- name: gateway
sectionName: http
# namespace: default
# Hostnames matching HTTP header.
hostnames:
- chart-example.local
# List of rules and filters applied.
rules:
- matches:
- path:
type: PathPrefix
value: /headers
# filters:
# - type: RequestHeaderModifier
# requestHeaderModifier:
# set:
# - name: My-Overwrite-Header
# value: this-is-the-only-value
# remove:
# - User-Agent
# - matches:
# - path:
# type: PathPrefix
# value: /echo
# headers:
# - name: version
# value: v2
resources: {}
# We usually recommend not to specify default resources and to leave this as a conscious
# choice for the user. This also increases chances charts run on environments with little
# resources, such as Minikube. If you do want to specify resources, uncomment the following
# lines, adjust them as necessary, and remove the curly braces after 'resources:'.
# limits:
# cpu: 100m
# memory: 128Mi
# requests:
# cpu: 100m
# memory: 128Mi
# This is to setup the liveness and readiness probes more information can be found here: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
livenessProbe:
httpGet:
path: /
port: http
readinessProbe:
httpGet:
path: /
port: http
# This section is for setting up autoscaling more information can be found here: https://kubernetes.io/docs/concepts/workloads/autoscaling/
autoscaling:
enabled: false
minReplicas: 1
maxReplicas: 100
targetCPUUtilizationPercentage: 80
# targetMemoryUtilizationPercentage: 80
# Additional volumes on the output Deployment definition.
volumes: []
# - name: foo
# secret:
# secretName: mysecret
# optional: false
# Additional volumeMounts on the output Deployment definition.
volumeMounts: []
# - name: foo
# mountPath: "/etc/foo"
# readOnly: true
nodeSelector: {}
tolerations: []
affinity: {}
`
const defaultIgnore = `# Patterns to ignore when building packages.
# This supports shell glob matching, relative path matching, and
# negation (prefixed with !). Only one pattern per line.
.DS_Store
# Common VCS dirs
.git/
.gitignore
.bzr/
.bzrignore
.hg/
.hgignore
.svn/
# Common backup files
*.swp
*.bak
*.tmp
*.orig
*~
# Various IDEs
.project
.idea/
*.tmproj
.vscode/
`
const defaultIngress = `{{- if .Values.ingress.enabled -}}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "<CHARTNAME>.fullname" . }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
{{- with .Values.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
- hosts:
{{- range .hosts }}
- {{ . | quote }}
{{- end }}
secretName: {{ .secretName }}
{{- end }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
{{- with .pathType }}
pathType: {{ . }}
{{- end }}
backend:
service:
name: {{ include "<CHARTNAME>.fullname" $ }}
port:
number: {{ $.Values.service.port }}
{{- end }}
{{- end }}
{{- end }}
`
const defaultHTTPRoute = `{{- if .Values.httpRoute.enabled -}}
{{- $fullName := include "<CHARTNAME>.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ $fullName }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
{{- with .Values.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
parentRefs:
{{- with .Values.httpRoute.parentRefs }}
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range .Values.httpRoute.rules }}
{{- with .matches }}
- matches:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .filters }}
filters:
{{- toYaml . | nindent 8 }}
{{- end }}
backendRefs:
- name: {{ $fullName }}
port: {{ $svcPort }}
weight: 1
{{- end }}
{{- end }}
`
const defaultDeployment = `apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "<CHARTNAME>.fullname" . }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "<CHARTNAME>.selectorLabels" . | nindent 6 }}
template:
metadata:
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "<CHARTNAME>.serviceAccountName" . }}
{{- with .Values.podSecurityContext }}
securityContext:
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: {{ .Chart.Name }}
{{- with .Values.securityContext }}
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
ports:
- name: http
containerPort: {{ .Values.service.port }}
protocol: TCP
{{- with .Values.livenessProbe }}
livenessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.readinessProbe }}
readinessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumeMounts }}
volumeMounts:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.volumes }}
volumes:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
`
const defaultService = `apiVersion: v1
kind: Service
metadata:
name: {{ include "<CHARTNAME>.fullname" . }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
spec:
type: {{ .Values.service.type }}
ports:
- port: {{ .Values.service.port }}
targetPort: http
protocol: TCP
name: http
selector:
{{- include "<CHARTNAME>.selectorLabels" . | nindent 4 }}
`
const defaultServiceAccount = `{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
name: {{ include "<CHARTNAME>.serviceAccountName" . }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
{{- with .Values.serviceAccount.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
{{- end }}
`
const defaultHorizontalPodAutoscaler = `{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include "<CHARTNAME>.fullname" . }}
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include "<CHARTNAME>.fullname" . }}
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
{{- if .Values.autoscaling.targetCPUUtilizationPercentage }}
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
{{- if .Values.autoscaling.targetMemoryUtilizationPercentage }}
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetMemoryUtilizationPercentage }}
{{- end }}
{{- end }}
`
const defaultNotes = `1. Get the application URL by running these commands:
{{- if .Values.httpRoute.enabled }}
{{- if .Values.httpRoute.hostnames }}
export APP_HOSTNAME={{ .Values.httpRoute.hostnames | first }}
{{- else }}
export APP_HOSTNAME=$(kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o jsonpath="{.spec.listeners[0].hostname}")
{{- end }}
{{- if and .Values.httpRoute.rules (first .Values.httpRoute.rules).matches (first (first .Values.httpRoute.rules).matches).path.value }}
echo "Visit http://$APP_HOSTNAME{{ (first (first .Values.httpRoute.rules).matches).path.value }} to use your application"
NOTE: Your HTTPRoute depends on the listener configuration of your gateway and your HTTPRoute rules.
The rules can be set for path, method, header and query parameters.
You can check the gateway configuration with 'kubectl get --namespace {{(first .Values.httpRoute.parentRefs).namespace | default .Release.Namespace }} gateway/{{ (first .Values.httpRoute.parentRefs).name }} -o yaml'
{{- end }}
{{- else if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
{{- range .paths }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }}
{{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "<CHARTNAME>.fullname" . }})
export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
NOTE: It may take a few minutes for the LoadBalancer IP to be available.
You can watch its status by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "<CHARTNAME>.fullname" . }}'
export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "<CHARTNAME>.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "<CHARTNAME>.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
export CONTAINER_PORT=$(kubectl get pod --namespace {{ .Release.Namespace }} $POD_NAME -o jsonpath="{.spec.containers[0].ports[0].containerPort}")
echo "Visit http://127.0.0.1:8080 to use your application"
kubectl --namespace {{ .Release.Namespace }} port-forward $POD_NAME 8080:$CONTAINER_PORT
{{- end }}
`
const defaultHelpers = `{{/*
Expand the name of the chart.
*/}}
{{- define "<CHARTNAME>.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "<CHARTNAME>.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "<CHARTNAME>.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{/*
Common labels
*/}}
{{- define "<CHARTNAME>.labels" -}}
helm.sh/chart: {{ include "<CHARTNAME>.chart" . }}
{{ include "<CHARTNAME>.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "<CHARTNAME>.selectorLabels" -}}
app.kubernetes.io/name: {{ include "<CHARTNAME>.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{/*
Create the name of the service account to use
*/}}
{{- define "<CHARTNAME>.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "<CHARTNAME>.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}
`
const defaultTestConnection = `apiVersion: v1
kind: Pod
metadata:
name: "{{ include "<CHARTNAME>.fullname" . }}-test-connection"
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}
annotations:
"helm.sh/hook": test
spec:
containers:
- name: wget
image: busybox
command: ['wget']
args: ['{{ include "<CHARTNAME>.fullname" . }}:{{ .Values.service.port }}']
restartPolicy: Never
`
// Stderr is an io.Writer to which error messages can be written
//
// In Helm 4, this will be replaced. It is needed in Helm 3 to preserve API backward
// compatibility.
var Stderr io.Writer = os.Stderr
// CreateFrom creates a new chart, but scaffolds it from the src chart.
func CreateFrom(chartfile *chart.Metadata, dest, src string) error {
schart, err := loader.Load(src)
if err != nil {
return fmt.Errorf("could not load %s: %w", src, err)
}
schart.Metadata = chartfile
var updatedTemplates []*common.File
for _, template := range schart.Templates {
newData := transform(string(template.Data), schart.Name())
updatedTemplates = append(updatedTemplates, &common.File{Name: template.Name, ModTime: template.ModTime, Data: newData})
}
schart.Templates = updatedTemplates
b, err := yaml.Marshal(schart.Values)
if err != nil {
return fmt.Errorf("reading values file: %w", err)
}
var m map[string]interface{}
if err := yaml.Unmarshal(transform(string(b), schart.Name()), &m); err != nil {
return fmt.Errorf("transforming values file: %w", err)
}
schart.Values = m
// SaveDir looks for the file values.yaml when saving rather than the values
// key in order to preserve the comments in the YAML. The name placeholder
// needs to be replaced on that file.
for _, f := range schart.Raw {
if f.Name == ValuesfileName {
f.Data = transform(string(f.Data), schart.Name())
}
}
return SaveDir(schart, dest)
}
// Create creates a new chart in a directory.
//
// Inside of dir, this will create a directory based on the name of
// chartfile.Name. It will then write the Chart.yaml into this directory and
// create the (empty) appropriate directories.
//
// The returned string will point to the newly created directory. It will be
// an absolute path, even if the provided base directory was relative.
//
// If dir does not exist, this will return an error.
// If Chart.yaml or any directories cannot be created, this will return an
// error. In such a case, this will attempt to clean up by removing the
// new chart directory.
func Create(name, dir string) (string, error) {
// Sanity-check the name of a chart so user doesn't create one that causes problems.
if err := validateChartName(name); err != nil {
return "", err
}
path, err := filepath.Abs(dir)
if err != nil {
return path, err
}
if fi, err := os.Stat(path); err != nil {
return path, err
} else if !fi.IsDir() {
return path, fmt.Errorf("no such directory %s", path)
}
cdir := filepath.Join(path, name)
if fi, err := os.Stat(cdir); err == nil && !fi.IsDir() {
return cdir, fmt.Errorf("file %s already exists and is not a directory", cdir)
}
// Note: If adding a new template below (i.e., to `helm create`) which is disabled by default (similar to hpa and
// ingress below); or making an existing template disabled by default, add the enabling condition in
// `TestHelmCreateChart_CheckDeprecatedWarnings` in `pkg/lint/lint_test.go` to make it run through deprecation checks
// with latest Kubernetes version.
files := []struct {
path string
content []byte
}{
{
// Chart.yaml
path: filepath.Join(cdir, ChartfileName),
content: fmt.Appendf(nil, defaultChartfile, name),
},
{
// values.yaml
path: filepath.Join(cdir, ValuesfileName),
content: fmt.Appendf(nil, defaultValues, name),
},
{
// .helmignore
path: filepath.Join(cdir, IgnorefileName),
content: []byte(defaultIgnore),
},
{
// ingress.yaml
path: filepath.Join(cdir, IngressFileName),
content: transform(defaultIngress, name),
},
{
// httproute.yaml
path: filepath.Join(cdir, HTTPRouteFileName),
content: transform(defaultHTTPRoute, name),
},
{
// deployment.yaml
path: filepath.Join(cdir, DeploymentName),
content: transform(defaultDeployment, name),
},
{
// service.yaml
path: filepath.Join(cdir, ServiceName),
content: transform(defaultService, name),
},
{
// serviceaccount.yaml
path: filepath.Join(cdir, ServiceAccountName),
content: transform(defaultServiceAccount, name),
},
{
// hpa.yaml
path: filepath.Join(cdir, HorizontalPodAutoscalerName),
content: transform(defaultHorizontalPodAutoscaler, name),
},
{
// NOTES.txt
path: filepath.Join(cdir, NotesName),
content: transform(defaultNotes, name),
},
{
// _helpers.tpl
path: filepath.Join(cdir, HelpersName),
content: transform(defaultHelpers, name),
},
{
// test-connection.yaml
path: filepath.Join(cdir, TestConnectionName),
content: transform(defaultTestConnection, name),
},
}
for _, file := range files {
if _, err := os.Stat(file.path); err == nil {
// There is no handle to a preferred output stream here.
fmt.Fprintf(Stderr, "WARNING: File %q already exists. Overwriting.\n", file.path)
}
if err := writeFile(file.path, file.content); err != nil {
return cdir, err
}
}
// Need to add the ChartsDir explicitly as it does not contain any file OOTB
if err := os.MkdirAll(filepath.Join(cdir, ChartsDir), 0755); err != nil {
return cdir, err
}
return cdir, nil
}
// transform performs a string replacement of the specified source for
// a given key with the replacement string
func transform(src, replacement string) []byte {
return []byte(strings.ReplaceAll(src, "<CHARTNAME>", replacement))
}
func writeFile(name string, content []byte) error {
if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
return err
}
return os.WriteFile(name, content, 0644)
}
func validateChartName(name string) error {
if name == "" || len(name) > maxChartNameLength {
return fmt.Errorf("chart name must be between 1 and %d characters", maxChartNameLength)
}
if !chartName.MatchString(name) {
return fmt.Errorf("chart name must match the regular expression %q", chartName.String())
}
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/util/validate_name.go | pkg/chart/v2/util/validate_name.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"
"regexp"
)
// validName is a regular expression for resource names.
//
// According to the Kubernetes help text, the regular expression it uses is:
//
// [a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*
//
// This follows the above regular expression (but requires a full string match, not partial).
//
// The Kubernetes documentation is here, though it is not entirely correct:
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
var validName = regexp.MustCompile(`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`)
var (
// errMissingName indicates that a release (name) was not provided.
errMissingName = errors.New("no name provided")
// errInvalidName indicates that an invalid release name was provided
errInvalidName = fmt.Errorf(
"invalid release name, must match regex %s and the length must not be longer than 53",
validName.String())
// errInvalidKubernetesName indicates that the name does not meet the Kubernetes
// restrictions on metadata names.
errInvalidKubernetesName = fmt.Errorf(
"invalid metadata name, must match regex %s and the length must not be longer than 253",
validName.String())
)
const (
// According to the Kubernetes docs (https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#rfc-1035-label-names)
// some resource names have a max length of 63 characters while others have a max
// length of 253 characters. As we cannot be sure the resources used in a chart, we
// therefore need to limit it to 63 chars and reserve 10 chars for additional part to name
// of the resource. The reason is that chart maintainers can use release name as part of
// the resource name (and some additional chars).
maxReleaseNameLen = 53
// maxMetadataNameLen is the maximum length Kubernetes allows for any name.
maxMetadataNameLen = 253
)
// ValidateReleaseName performs checks for an entry for a Helm release name
//
// For Helm to allow a name, it must be below a certain character count (53) and also match
// a regular expression.
//
// According to the Kubernetes help text, the regular expression it uses is:
//
// [a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*
//
// This follows the above regular expression (but requires a full string match, not partial).
//
// The Kubernetes documentation is here, though it is not entirely correct:
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
func ValidateReleaseName(name string) error {
// This case is preserved for backwards compatibility
if name == "" {
return errMissingName
}
if len(name) > maxReleaseNameLen || !validName.MatchString(name) {
return errInvalidName
}
return nil
}
// ValidateMetadataName validates the name field of a Kubernetes metadata object.
//
// Empty strings, strings longer than 253 chars, or strings that don't match the regexp
// will fail.
//
// According to the Kubernetes help text, the regular expression it uses is:
//
// [a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*
//
// This follows the above regular expression (but requires a full string match, not partial).
//
// The Kubernetes documentation is here, though it is not entirely correct:
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
//
// Deprecated: remove in Helm 4. Name validation now uses rules defined in
// pkg/lint/rules.validateMetadataNameFunc()
func ValidateMetadataName(name string) error {
if name == "" || len(name) > maxMetadataNameLen || !validName.MatchString(name) {
return errInvalidKubernetesName
}
return nil
}
| 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.