Files
cozystack/hack/values-injection/decode.go
T
Myasnikov Daniil fb00301f0b test(hack): check chart output for arbitrary tenant values in unit-tests
hack/values-injection renders every chart under packages/apps and
packages/extra with generated values for each string field and map
key its schema allows, including the charts its HelmReleases install,
and fails when a value changes the structure of the output rather
than only its content. Fields multiline by design are listed in
hack/testdata/values-injection/allowlist.txt.

It runs as values-injection-check, a prerequisite of unit-tests, and
the Helm Charts conventions in docs/agents/overview.md gain the rule it
enforces.

Assisted-by: LLM
Signed-off-by: Myasnikov Daniil <myasnikovdaniil2001@gmail.com>
2026-12-03 10:03:22 +00:00

179 lines
4.0 KiB
Go

package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
"sort"
"strings"
"sigs.k8s.io/yaml"
)
// The separator Helm's releaseutil.SplitManifests uses.
var docSeparator = regexp.MustCompile(`(?:^|\s*\n)---\s*`)
var sourceComment = regexp.MustCompile(`(?m)^# Source: (.+)$`)
// doc is one decoded document of a rendered stream and the template it came
// from.
type doc struct {
source string
obj any
}
// decodeYAML decodes one YAML document the way the Kubernetes client does:
// sigs.k8s.io/yaml to JSON, then encoding/json. ok is false for a blank one.
// Numbers are float64, as the client sees them.
func decodeYAML(chunk string) (v any, ok bool, err error) {
if strings.TrimSpace(chunk) == "" {
return nil, false, nil
}
j, err := yaml.YAMLToJSON([]byte(chunk))
if err != nil {
return nil, false, err
}
if err := json.Unmarshal(j, &v); err != nil {
return nil, false, err
}
return v, true, nil
}
// decodeStream is every non-null document of a manifest stream, split as Helm
// splits it, or the first error of a document that does not decode.
func decodeStream(text string) ([]doc, error) {
var out []doc
for _, chunk := range docSeparator.Split(text, -1) {
v, ok, err := decodeYAML(chunk)
if err != nil {
return nil, err
}
if !ok || v == nil {
continue
}
src := "?"
if m := sourceComment.FindStringSubmatch(chunk); m != nil {
src = m[1]
}
out = append(out, doc{source: src, obj: v})
}
return out, nil
}
var errManyDocs = errors.New("more than one document")
// decodeOne decodes a string as a single YAML document; one that splits into
// more than one is an error, as it is to a consumer that reads one.
func decodeOne(text string) (any, error) {
n := 0
for _, chunk := range docSeparator.Split(text, -1) {
if strings.TrimSpace(chunk) != "" {
n++
}
}
if n > 1 {
return nil, errManyDocs
}
v, _, err := decodeYAML(text)
return v, err
}
// structured is the map or list a string holds as JSON or YAML, or nil.
func structured(text string) any {
s := strip(text)
if s == "" {
return nil
}
var v any
if s[0] == '{' || s[0] == '[' {
// UseNumber keeps 1 and 1.0 apart, as json.loads does.
d := json.NewDecoder(strings.NewReader(s))
d.UseNumber()
if d.Decode(&v) != nil {
return nil
}
if _, err := d.Token(); err != io.EOF {
return nil
}
} else {
var err error
if v, err = decodeOne(text); err != nil {
return nil
}
}
switch v.(type) {
case map[string]any, []any:
return v
}
return nil
}
// encodeValues writes values as JSON for helm's --values, with sorted keys and
// every non-ASCII character escaped. Raw, U+0085 would be a line break to the
// YAML parser and fold into a space inside the quoted string. helm reads the
// file as YAML, which takes \U for a character outside the BMP where JSON
// would need a surrogate pair YAML refuses.
func encodeValues(v any) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
if err := enc.Encode(v); err != nil {
return nil, err
}
raw := bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
out := make([]byte, 0, len(raw))
for _, r := range string(raw) {
switch {
case r < 0x80:
out = append(out, byte(r))
case r < 0x10000:
out = fmt.Appendf(out, `\u%04x`, r)
default:
out = fmt.Appendf(out, `\U%08x`, r)
}
}
return out, nil
}
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// typeName is the Python type name the first version of this check reported
// for a decoded value, so shape findings read the same.
func typeName(v any) string {
switch x := v.(type) {
case nil:
return "NoneType"
case string:
return "str"
case bool:
return "bool"
case int:
return "int"
case float64:
if isInt(x) {
return "int"
}
return "float"
case json.Number:
if strings.ContainsAny(string(x), ".eE") {
return "float"
}
return "int"
case []any:
return "list"
case map[string]any:
return "dict"
}
return "object"
}