Files
cozystack/hack/values-injection/fuzz.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

409 lines
11 KiB
Go

package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"strconv"
"strings"
)
type payload struct {
id string
value string
}
// payloads keep {c}, the per-field canary, so the sink can be found, and most
// carry a second token, "{c}x", that must never become structure.
var payloads = []payload{
{"nl", "{c}\n{c}x: y"},
{"docsep", "{c}\n---\napiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {c}x\n"},
{"cr", "{c}\r{c}x: y"},
{"nel", "{c}\u0085{c}x: y"},
{"ls", "{c}\u2028{c}x: y"},
{"dq", `{c}"{c}x`},
{"dq-nl", "{c}\"\n{c}x: \"y"},
{"sq-nl", "{c}'\n{c}x: 'y"},
{"dq-json", `{c}", "{c}x": "y`},
{"colon", "{c}: {c}x"},
{"bs", `{c}\`},
{"sh-sub", "{c}$(true {c}x)"},
{"sh-bt", "{c}`true {c}x`"},
{"sh-semi", "{c};true {c}x;"},
{"sh-space", "{c} {c}x"},
{"tpl", `{c}{{print "{c}tp" "leval"}}`},
}
// keyPayloads are map keys that a chart downstream treats as an instruction
// rather than data: the NATS chart renders the value under $tplYaml or
// $tplYamlSpread with tpl. Tried on free-form map keys only.
var keyPayloads = []struct {
id, key, value string
}{
{"tplyaml", "$tplYaml", `{c}: {{print "{c}tp" "leval"}}`},
{"tplyamlspread", "$tplYamlSpread", `{c}: {{print "{c}tp" "leval"}}`},
}
type findingJSON struct {
Payload string `json:"payload"`
Schema string `json:"schema"`
Type string `json:"type"`
Source string `json:"source"`
Detail string `json:"detail"`
}
type result struct {
Chart string `json:"chart"`
Slot string `json:"slot"`
Kind string `json:"kind"`
Status string `json:"status"`
Findings []findingJSON `json:"findings"`
Notes []string `json:"notes"`
}
type accepted struct {
finding
accepted bool
}
// chart is what every field of one chart is fuzzed with.
type chart struct {
name string // the chart's directory name, which seeds the canaries
path string // the chart's directory as reported
render renderFunc
schema map[string]any
profiles []map[string]any
arts map[string]string
// sub is the renderer of an in-tree chart a HelmRelease installs.
sub func(chart, release, namespace string) renderFunc
}
// fuzzer is the state of one field: its renders, and the charts that the
// HelmReleases of its renders install.
type fuzzer struct {
*chart
slot slot
c string
r *renderCache
subs map[string]*renderCache
refs map[string]*reference
memo memo
}
func canary(chart, field string) string {
sum := sha256.Sum256([]byte(chart + field))
return "cnry" + hex.EncodeToString(sum[:])[:6]
}
// values puts leaf in the field under the profile base and the variant; for a
// key, it puts leaf as a key of the map, with keyValue under it if given.
func (f *fuzzer) values(base map[string]any, variant int, leaf string, keyValue *string) (map[string]any, error) {
s := f.slot
var v any
switch {
case s.kind == "key":
v = build(f.schema, s.path, nil, &leaf, min(variant, 2), false, 0, keyValue)
case variant < 3:
v = build(f.schema, s.path, leaf, nil, variant, false, 0, nil)
default:
v = build(f.schema, s.path, leaf, nil, 1, false, 0, nil)
}
if variant < 3 || s.kind == "key" {
return asMap(merge(substitute(base, f.c), v)), nil
}
// Variant 3 lets the profile win over what build filled in beside the
// field, such as a guess a chart refuses for a sibling it needs, and then
// puts the field back.
out := asMap(merge(v, substitute(base, f.c)))
return out, put(out, s.path, leaf)
}
type attempt struct {
base map[string]any
variant int
}
func fuzzSlot(ch *chart, s slot) (*result, error) {
field := dotted(s.path, s.kind)
f := &fuzzer{chart: ch, slot: s, c: canary(ch.name, field), r: newRenderCache(ch.render),
subs: map[string]*renderCache{}, refs: map[string]*reference{}, memo: memo{}}
c := f.c
res := &result{Chart: ch.path, Slot: field, Kind: s.kind, Findings: []findingJSON{}, Notes: []string{}}
var attempts []attempt
for _, b := range ch.profiles {
for v := 0; v < 4; v++ {
attempts = append(attempts, attempt{b, v})
}
}
render := func(a attempt, leaf string) (renderResult, error) {
vals, err := f.values(a.base, a.variant, leaf, nil)
if err != nil {
return renderResult{}, err
}
return f.r.get(vals, true)
}
// A profile and variant under which the field reaches the output. A
// profile may render $CANARY itself, so the field counts as reached only
// when a second canary, given to the field alone, shows up.
c2 := "cnrz" + c[4:]
var at attempt
var ref, prefix, lastErr string
found, hasPrefix := false, false
for _, a := range attempts {
at = a
out, err := render(a, c)
if err != nil {
return nil, err
}
if out.rc == 0 && containsFold(out.out, c) {
out2, err := render(a, c2)
if err != nil {
return nil, err
}
if out2.rc == 0 && containsFold(out2.out, c2) {
ref, found = out.out, true
break
}
}
if out.rc != 0 && lastErr == "" {
lastErr = firstError(out.err)
}
}
hasEnum := truthy(s.node["enum"])
if !found && s.kind == "value" && !hasEnum {
// A typed field (quantity, cron, URL) refuses a bare canary. Use a
// plausible value as the reference and append each payload to it.
// The field counts as reached when changing the value moves it in the
// output, counted as whole words: charts that generate secrets render
// differently every time.
name := ""
for i := len(s.path) - 1; i >= 0; i-- {
if s.path[i].kind == 'p' {
name = s.path[i].name
break
}
}
g := pyStr(guess(name, s.node))
alt := bumpDigit(g)
if alt == g {
alt = g + "a"
}
for _, a := range attempts {
at = a
out, err := render(a, g)
if err != nil {
return nil, err
}
if out.rc != 0 {
continue
}
out2, err := render(a, alt)
if err != nil {
return nil, err
}
if out2.rc == 0 && bounded(out.out, g) > bounded(out2.out, g) && bounded(out2.out, alt) > bounded(out.out, alt) {
ref, prefix, found, hasPrefix = out.out, g, true, true
break
}
}
}
if !found {
if hasEnum {
res.Status = "enum"
} else {
res.Status = "unreached"
if lastErr != "" {
res.Notes = append(res.Notes, lastErr)
}
}
return res, nil
}
refDocs, err := decodeStream(ref)
if err != nil {
res.Status = "ref-fail"
res.Notes = append(res.Notes, "reference does not decode: "+err.Error())
return res, nil
}
reference := prepare(refDocs, c)
if hasPrefix {
res.Notes = append(res.Notes, "typed; payloads appended to "+repr(prefix))
}
type fuzzCase struct {
id, value string
keyValue *string
}
var cases []fuzzCase
for _, p := range payloads {
cases = append(cases, fuzzCase{p.id, strings.ReplaceAll(p.value, "{c}", c), nil})
}
if s.kind == "key" {
for _, p := range keyPayloads {
kv := strings.ReplaceAll(p.value, "{c}", c)
cases = append(cases, fuzzCase{p.id, p.key, &kv})
}
}
for _, fc := range cases {
value := fc.value
if hasPrefix {
value = prefix + value[len(c):]
}
vals, err := f.values(at.base, at.variant, value, fc.keyValue)
if err != nil {
return nil, err
}
// Each payload render is new; only its reference is worth caching.
out, err := ch.render(vals, false)
if err != nil {
return nil, err
}
schemaOK := true
if out.rc != 0 && classifyError(out.err) == "schema" {
schemaOK = false
if out, err = ch.render(vals, true); err != nil {
return nil, err
}
}
var got []accepted
if out.rc != 0 {
if classifyError(out.err) != "yaml" {
continue // a template guard refused it, or an unrelated failure
}
src := "?"
if m := yamlParseErrorOn.FindStringSubmatch(out.err); m != nil {
src = m[1]
}
got = append(got, accepted{finding{"yaml-break", src, firstError(out.err)}, schemaOK})
} else {
pDocs, derr := decodeStream(out.out)
doc := false
for _, fd := range compare(f.memo, reference, pDocs, derr, out.out, c) {
got = append(got, accepted{fd, schemaOK})
doc = doc || fd.typ == "doc-injection"
}
if !doc && derr == nil {
more, err := f.secondOrder(refDocs, pDocs, schemaOK)
if err != nil {
return nil, err
}
got = append(got, more...)
}
}
for _, fd := range got {
schema := "accepted"
if !fd.accepted {
schema = "rejected"
}
res.Findings = append(res.Findings, findingJSON{fc.id, schema, fd.typ, fd.source, fd.detail})
}
}
var acc []findingJSON
for _, fd := range res.Findings {
if fd.Schema == "accepted" {
acc = append(acc, fd)
}
}
res.Status = "safe"
switch {
case anyProven(acc):
res.Status = "injectable"
case len(acc) > 0:
res.Status = "breakable"
case len(res.Findings) > 0:
res.Status = "latent"
}
return res, nil
}
func anyProven(fs []findingJSON) bool {
for _, f := range fs {
if proven[f.Type] {
return true
}
}
return false
}
// bumpDigit changes the first digit of s, so a typed value stays valid but
// differs.
func bumpDigit(s string) string {
for i := 0; i < len(s); i++ {
if '0' <= s[i] && s[i] <= '9' {
return s[:i] + strconv.Itoa((int(s[i]-'0')+1)%10) + s[i+1:]
}
}
return s
}
// secondOrder is the findings in the charts that in-tree HelmReleases of the
// render install, rendered from the values the release hands on.
func (f *fuzzer) secondOrder(refDocs, pDocs []doc, acc bool) ([]accepted, error) {
var found []accepted
base := map[int]release{}
for _, rel := range releases(refDocs, f.arts) {
base[rel.index] = rel
}
for _, rel := range releases(pDocs, f.arts) {
b, ok := base[rel.index]
if !ok {
continue
}
if j, err := json.Marshal(rel.values); err != nil || !containsFold(string(j), f.c) {
continue
}
tag := "via " + rel.name + " -> " + rel.chart
if rel.remote {
tag += " (tenant cluster)"
}
key := rel.chart + "\x00" + rel.release + "\x00" + rel.namespace
sub, ok := f.subs[key]
if !ok {
sub = newRenderCache(f.sub(rel.chart, rel.release, rel.namespace))
f.subs[key] = sub
}
bout, err := sub.get(b.values, true)
if err != nil {
return nil, err
}
if bout.rc != 0 {
continue // the installed chart does not render from the reference values
}
pout, err := sub.get(rel.values, false)
if err != nil {
return nil, err
}
subAcc := acc
if pout.rc != 0 && classifyError(pout.err) == "schema" {
subAcc = false
if pout, err = sub.get(rel.values, true); err != nil {
return nil, err
}
}
if pout.rc != 0 {
if classifyError(pout.err) == "yaml" {
found = append(found, accepted{finding{"yaml-break", tag + ": ?", firstError(pout.err)}, subAcc})
}
continue
}
ref, ok := f.refs[bout.out]
if !ok {
docs, err := decodeStream(bout.out)
if err == nil {
ref = prepare(docs, f.c)
}
f.refs[bout.out] = ref
}
if ref == nil {
continue
}
pd, derr := decodeStream(pout.out)
for _, fd := range compare(f.memo, ref, pd, derr, pout.out, f.c) {
found = append(found, accepted{finding{fd.typ, tag + ": " + fd.source, fd.detail}, subAcc})
}
}
return found, nil
}