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

286 lines
11 KiB
Go

package main
import (
"bytes"
"encoding/json"
"os"
"regexp"
"sort"
"strconv"
"strings"
"testing"
)
// fakeChart renders a ConfigMap whose data lines body writes from the values,
// as helm template would print it; a message from body fails the render, as a
// template guard does.
func fakeChart(body func(v map[string]any) (string, string)) renderFunc {
return func(values map[string]any, _ bool) (renderResult, error) {
data, fail := body(values)
if fail != "" {
return renderResult{rc: 1, err: "Error: execution error at (t/templates/cm.yaml:1:1): " + fail}, nil
}
return renderResult{out: "---\n# Source: t/templates/cm.yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n name: probe\ndata:\n" + data}, nil
}
}
func schemaOf(t *testing.T, text string) map[string]any {
t.Helper()
var s map[string]any
d := json.NewDecoder(strings.NewReader(text))
d.UseNumber()
if err := d.Decode(&s); err != nil {
t.Fatal(err)
}
return s
}
// fuzzAll fuzzes every field of a fake chart and returns each result by field.
func fuzzAll(t *testing.T, ch *chart) map[string]*result {
t.Helper()
ch.name, ch.path = "t", "packages/apps/t"
if ch.profiles == nil {
ch.profiles = []map[string]any{{}}
}
out := map[string]*result{}
slots(ch.schema, nil, 0, func(s slot) {
res, err := fuzzSlot(ch, s)
if err != nil {
t.Fatal(err)
}
out[res.Slot] = res
})
return out
}
func str(v any) string {
s, _ := v.(string)
return s
}
func findingSet(r *result) []string {
seen := map[string]bool{}
for _, f := range r.Findings {
seen[f.Schema+" "+f.Type] = true
}
var out []string
for k := range seen {
out = append(out, k)
}
sort.Strings(out)
return out
}
// A field behind `enabled` is reached on the variant that sets it, and a
// value written raw is injectable where the same value quoted is safe.
func TestFuzzReachesAGatedField(t *testing.T) {
schema := schemaOf(t, `{"type": "object", "properties": {"a": {"type": "object", "properties": {
"enabled": {"type": "boolean"}, "raw": {"type": "string"}, "quoted": {"type": "string"}}}}}`)
res := fuzzAll(t, &chart{schema: schema, render: fakeChart(func(v map[string]any) (string, string) {
a := asMap(v["a"])
if a["enabled"] != true {
return " off: \"1\"\n", ""
}
return " raw: " + str(a["raw"]) + "\n quoted: " + strconv.Quote(str(a["quoted"])) + "\n", ""
})})
if got := res["a.raw"].Status; got != "injectable" {
t.Errorf("a.raw is %s, want injectable; findings %v", got, findingSet(res["a.raw"]))
}
if got := res["a.quoted"].Status; got != "safe" {
t.Errorf("a.quoted is %s, want safe; findings %v", got, findingSet(res["a.quoted"]))
}
}
// A profile may render $CANARY itself. The field counts as reached only when
// the second canary, given to the field alone, shows up, so a field the
// template never reads stays unreached rather than safe.
func TestFuzzDoesNotTakeAProfileCanaryForTheField(t *testing.T) {
schema := schemaOf(t, `{"type": "object", "properties": {"p": {"type": "string"}, "unread": {"type": "string"}}}`)
res := fuzzAll(t, &chart{schema: schema, profiles: []map[string]any{{}, {"p": "$CANARY"}},
render: fakeChart(func(v map[string]any) (string, string) {
return " p: " + strconv.Quote(str(v["p"])) + "\n", ""
})})
if got := res["unread"].Status; got != "unreached" {
t.Errorf("unread is %s, want unreached", got)
}
if got := res["p"].Status; got != "safe" {
t.Errorf("p is %s, want safe", got)
}
}
// A typed field refuses a bare canary. It is reached with a plausible value
// that moves in the output when it changes, and each payload is appended to
// that value.
func TestFuzzReachesATypedField(t *testing.T) {
quantity := regexp.MustCompile(`^[0-9]+Gi`)
schema := schemaOf(t, `{"type": "object", "properties": {"size": {"type": "string"}, "mode": {"type": "string", "enum": ["a", "b"]}}}`)
res := fuzzAll(t, &chart{schema: schema, render: fakeChart(func(v map[string]any) (string, string) {
size := str(v["size"])
if size == "" {
size = "1Gi"
}
if !quantity.MatchString(size) {
return "", "size must be a quantity"
}
return " size: " + size + "\n mode: a\n", ""
})})
r := res["size"]
if r.Status != "injectable" || len(r.Notes) != 1 || r.Notes[0] != "typed; payloads appended to '1Gi'" {
t.Errorf("size is %s with notes %q, want injectable through '1Gi'", r.Status, r.Notes)
}
if got := res["mode"].Status; got != "enum" {
t.Errorf("mode is %s, want enum", got)
}
}
// A free-form map's keys are fuzzed as well as its values.
func TestFuzzMapKeys(t *testing.T) {
schema := schemaOf(t, `{"type": "object", "properties": {"labels": {"type": "object", "additionalProperties": {"type": "string"}}}}`)
res := fuzzAll(t, &chart{schema: schema, render: fakeChart(func(v map[string]any) (string, string) {
var b strings.Builder
labels := asMap(v["labels"])
for _, k := range sortedKeys(labels) {
b.WriteString(" owner: " + k + "\n value: " + strconv.Quote(str(labels[k])) + "\n")
}
return b.String(), ""
})})
if got := res["labels.<key>"].Status; got != "injectable" {
t.Errorf("labels.<key> is %s, want injectable", got)
}
if got := res["labels.*"].Status; got != "safe" {
t.Errorf("labels.* is %s, want safe", got)
}
}
// A key is also tried as $tplYaml, which a chart downstream renders through
// tpl: a key that is quoted everywhere is still injectable when one key name
// makes the chart evaluate its value.
func TestFuzzTriesTemplateKeys(t *testing.T) {
printCall := regexp.MustCompile(`\{\{print "([^"]*)" "([^"]*)"\}\}`)
schema := schemaOf(t, `{"type": "object", "properties": {"config": {"type": "object", "additionalProperties": {"type": "string"}}}}`)
res := fuzzAll(t, &chart{schema: schema, render: fakeChart(func(v map[string]any) (string, string) {
var b strings.Builder
config := asMap(v["config"])
for _, k := range sortedKeys(config) {
val := str(config[k])
if k == "$tplYaml" {
val = printCall.ReplaceAllString(val, "$1$2")
}
b.WriteString(" " + strconv.Quote(k) + ": " + strconv.Quote(val) + "\n")
}
return b.String(), ""
})})
r := res["config.<key>"]
if r.Status != "injectable" {
t.Fatalf("config.<key> is %s, want injectable; findings %v", r.Status, findingSet(r))
}
evaluated := false
for _, f := range r.Findings {
if f.Type == "tpl-eval" {
evaluated = true
if f.Payload != "tplyaml" {
t.Errorf("payload %s was evaluated: %+v", f.Payload, f)
}
}
}
if !evaluated {
t.Errorf("the $tplYaml key was not evaluated: %v", findingSet(r))
}
}
// A value handed on in a HelmRelease is followed into the in-tree chart the
// release installs, where it is written raw.
func TestFuzzFollowsHelmReleases(t *testing.T) {
schema := schemaOf(t, `{"type": "object", "properties": {"v": {"type": "string"}}}`)
release := func(values map[string]any, _ bool) (renderResult, error) {
return renderResult{out: "---\n# Source: t/templates/hr.yaml\napiVersion: helm.toolkit.fluxcd.io/v2\nkind: HelmRelease\n" +
"metadata:\n name: inner\n namespace: tenant-test\nspec:\n chartRef:\n kind: ExternalArtifact\n name: inner-art\n" +
" values:\n v: " + strconv.Quote(str(values["v"])) + "\n"}, nil
}
var subChart string
res := fuzzAll(t, &chart{schema: schema, render: release, arts: map[string]string{"inner-art": "packages/system/inner"},
sub: func(chart, rel, ns string) renderFunc {
subChart = chart + " " + rel + " " + ns
return fakeChart(func(v map[string]any) (string, string) { return " v: " + str(v["v"]) + "\n", "" })
}})
r := res["v"]
if r.Status != "injectable" {
t.Fatalf("v is %s, want injectable through the release", r.Status)
}
if subChart != "packages/system/inner inner tenant-test" {
t.Errorf("the installed chart was rendered as %q", subChart)
}
for _, f := range r.Findings {
if !strings.HasPrefix(f.Source, "via inner -> packages/system/inner: ") {
t.Errorf("finding %+v is not marked as found through the release", f)
}
}
}
func TestReportAllowlist(t *testing.T) {
results := func(statuses ...string) []*result {
var out []*result
for i, s := range statuses {
out = append(out, &result{Chart: "packages/apps/x", Slot: "f" + strconv.Itoa(i), Status: s,
Findings: []findingJSON{}, Notes: []string{}})
}
return out
}
allow := map[allowKey]string{{"packages/apps/x", "f0"}: "multi-line by design"}
for _, tc := range []struct {
name string
statuses []string
charts []string
rc int
line string
}{
{"a listed breakable field is allowed", []string{"breakable"}, []string{"packages/apps/x"}, 0, "ALLOWED packages/apps/x: f0 (multi-line by design)"},
{"a listed injectable field still fails", []string{"injectable"}, []string{"packages/apps/x"}, 1, "INJECTABLE packages/apps/x: f0"},
{"a listed safe field is stale", []string{"safe"}, []string{"packages/apps/x"}, 1, "STALE allow.txt: packages/apps/x f0 is safe, not breakable"},
{"a listed field that is gone is stale", []string{}, []string{"packages/apps/x"}, 1, "STALE allow.txt: packages/apps/x f0 is not a field, not breakable"},
{"a chart the run did not render cannot tell", []string{}, []string{"packages/apps/y"}, 0, "fields: "},
{"an unlisted breakable field fails", []string{"breakable", "breakable"}, []string{"packages/apps/x"}, 1, "BREAKABLE packages/apps/x: f1"},
{"ref-fail fails", []string{"breakable", "ref-fail"}, []string{"packages/apps/x"}, 1, "REF-FAIL packages/apps/x: f1"},
{"latent passes", []string{"breakable", "latent"}, []string{"packages/apps/x"}, 0, "LATENT packages/apps/x: f1"},
} {
t.Run(tc.name, func(t *testing.T) {
var out bytes.Buffer
rc := report(&options{allowlist: "allow.txt"}, results(tc.statuses...), tc.charts, allow, &out, &out)
if rc != tc.rc {
t.Errorf("rc = %d, want %d", rc, tc.rc)
}
if !strings.Contains(out.String(), tc.line+"\n") {
t.Errorf("no line %q in\n%s", tc.line, out.String())
}
})
}
}
func TestLoadAllowlist(t *testing.T) {
dir := t.TempDir()
path := dir + "/allow.txt"
if err := writeFile(path, "# comment\n\n packages/apps/a cloudInit written whole \n"); err != nil {
t.Fatal(err)
}
got, err := loadAllowlist(path)
if err != nil {
t.Fatal(err)
}
if reason := got[allowKey{"packages/apps/a", "cloudInit"}]; reason != "written whole" || len(got) != 1 {
t.Fatalf("allowlist = %v", got)
}
if err := writeFile(path, "packages/apps/a cloudInit\n"); err != nil {
t.Fatal(err)
}
if _, err := loadAllowlist(path); err == nil || !strings.Contains(err.Error(), "allow.txt:1: expected <chart dir> <field> <reason>") {
t.Fatalf("an entry without a reason was accepted: %v", err)
}
if got, err := loadAllowlist(dir + "/missing.txt"); err != nil || len(got) != 0 {
t.Fatalf("a missing allowlist is %v, %v", got, err)
}
}
func writeFile(path, text string) error {
return os.WriteFile(path, []byte(text), 0o644)
}