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

514 lines
15 KiB
Go

// Command values-injection finds chart inputs that reach the rendered output
// unescaped.
//
// An Application's spec becomes the values of a chart under packages/apps or
// packages/extra. For every string field and every free-form map key the
// chart's values.schema.json allows, it renders the chart once with a canary
// value and once per test payload, then compares the two renders.
//
// Findings that prove an injection, because a token the payload carries shows
// up as structure of its own:
//
// doc-injection the payload added or removed a Kubernetes object
// yaml-inject the payload added a key or element to an object
// shell-injection the payload changed the parse tree of a shell script
// heredoc-inject the payload added a key to YAML a script feeds a heredoc
// embedded-inject the payload added a key to YAML or JSON held in a string
// tpl-eval the payload was evaluated as a Go template
// namespace the payload chose the namespace of an object
//
// Findings that show a value is not escaped, without a change of structure:
//
// yaml-break the payload made the rendered manifest unparsable
// yaml-shape the payload changed a value's type or dropped content
// shell-break the payload made a shell script unparsable
// script-newline the payload's newline reached a script raw
// heredoc-newline the payload added a line to a heredoc
// embedded-break the payload made YAML or JSON held in a string unparsable
// embedded-newline the payload added a line to an embedded config file
// embedded-quote a raw quote reached an embedded config file
//
// Each payload is rendered with schema validation on, as an install does.
// When the schema rejects it, it is rendered again with validation off, so a
// sink that only a schema pattern guards is told apart from one safe on its
// own:
//
// injectable the schema accepts a payload that proves an injection
// breakable the schema accepts a payload that is not escaped
// allowed breakable, in a field the allowlist names as multi-line
// latent findings exist, but only with schema validation off
// safe no payload produced a finding
// unreached the canary never appeared in the rendered output
// enum a closed set of values the canary is not part of
// ref-fail the chart does not render on its defaults
//
// A chart that installs another in-tree chart through a HelmRelease hands the
// tenant's value on in spec.values. Such a release is rendered too, from the
// chart its ExternalArtifact names in packages/core/platform/sources, and its
// findings carry "via <release> -> <chart>"; "(tenant cluster)" marks a
// release applied through a kubeConfig into the tenant's own cluster.
//
// A field gated behind other settings is reached through a profile: a list of
// values in hack/testdata/values-injection/<chart>.yaml under `profiles:`,
// each merged under the fuzzed field in turn, with $CANARY replaced by the
// canary.
//
// A field whose value is multi-line by design is listed, with the reason, in
// hack/testdata/values-injection/allowlist.txt. It may be breakable, reported
// as allowed; injectable fails the check all the same.
//
// Charts are rendered by the helm on PATH. Manifests, and YAML embedded in
// them, are decoded with sigs.k8s.io/yaml, the parser the Kubernetes client
// uses; scripts are parsed with mvdan.cc/sh, the parser of shfmt, as bash.
//
// Exit status is 1 when a field is injectable, breakable and not allowed, or
// ref-fail, or when an allowlist entry matches no breakable field of a chart
// the run rendered, and 2 when the check cannot run. `make
// values-injection-check`, part of `make unit-tests`, runs it over every
// chart.
//
// Usage, from the repository root, which the profiles, the allowlist and the
// render fixture are read from:
//
// go -C hack/values-injection build -o "$PWD/_out/bin/values-injection" .
// _out/bin/values-injection [--root DIR] [--json OUT] [--jobs N]
// [--allowlist FILE] [-v] [chart-dir ...]
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
)
const profilesDir = "hack/testdata/values-injection"
func main() {
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}
type options struct {
root string
json string
jobs int
allowlist string
verbose bool
charts []string
}
func parseFlags(args []string, stderr io.Writer) (*options, error) {
o := &options{}
fs := flag.NewFlagSet("values-injection", flag.ContinueOnError)
fs.SetOutput(stderr)
fs.StringVar(&o.root, "root", ".", "repository tree whose charts to render")
fs.StringVar(&o.json, "json", "", "write every field's result to this file")
fs.IntVar(&o.jobs, "jobs", runtime.NumCPU(), "fields to fuzz at once")
fs.StringVar(&o.allowlist, "allowlist", filepath.Join(profilesDir, "allowlist.txt"), "fields breakable by design")
fs.BoolVar(&o.verbose, "verbose", false, "also list safe and unreached fields")
fs.BoolVar(&o.verbose, "v", false, "shorthand for --verbose")
fs.Usage = func() {
fmt.Fprintln(stderr, "usage: values-injection [--root DIR] [--json OUT] [--jobs N] [--allowlist FILE] [-v] [chart-dir ...]")
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
return nil, err
}
if o.jobs < 1 {
return nil, fmt.Errorf("--jobs must be at least 1, got %d", o.jobs)
}
o.allowlist = filepath.Clean(o.allowlist)
o.charts = fs.Args()
return o, nil
}
type allowKey struct{ chart, slot string }
// loadAllowlist reads lines of `<chart dir> <field> <reason>`.
func loadAllowlist(path string) (map[allowKey]string, error) {
out := map[allowKey]string{}
text, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return out, nil
}
if err != nil {
return nil, err
}
for n, line := range splitLines(string(text)) {
line = strip(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
parts := splitFields(line, 3)
if len(parts) < 3 {
return nil, fmt.Errorf("%s:%d: expected <chart dir> <field> <reason>", path, n+1)
}
out[allowKey{parts[0], parts[1]}] = parts[2]
}
return out, nil
}
// splitFields is Python's str.split(None, n-1): at most n fields, the last
// one the rest of the line.
func splitFields(s string, n int) []string {
var out []string
for {
s = strings.TrimLeftFunc(s, isSpace)
if s == "" {
return out
}
if len(out) == n-1 {
return append(out, s)
}
i := strings.IndexFunc(s, isSpace)
if i < 0 {
return append(out, s)
}
out = append(out, s[:i])
s = s[i:]
}
}
func loadProfiles(name string) ([]map[string]any, error) {
out := []map[string]any{{}}
path := filepath.Join(profilesDir, name+".yaml")
text, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return out, nil
}
if err != nil {
return nil, err
}
docs, err := decodeStream(string(text))
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if len(docs) == 0 {
return out, nil
}
list, _ := asMap(docs[0].obj)["profiles"].([]any)
for i, p := range list {
m, ok := p.(map[string]any)
if !ok {
return nil, fmt.Errorf("%s: profile %d is not a map", path, i)
}
out = append(out, m)
}
return out, nil
}
// listCharts is every chart under packages/apps and packages/extra that has a
// values schema.
func listCharts(root string) ([]string, error) {
var out []string
for _, pat := range []string{"packages/apps/*/values.schema.json", "packages/extra/*/values.schema.json"} {
files, err := filepath.Glob(filepath.Join(root, pat))
if err != nil {
return nil, err
}
for _, f := range files {
rel, err := filepath.Rel(root, filepath.Dir(f))
if err != nil {
return nil, err
}
out = append(out, rel)
}
}
sort.Strings(out)
return out, nil
}
// pool runs fn on every index below n, jobs at a time, and returns the first
// error.
func pool(n, jobs int, fn func(i int) error) error {
var (
wg sync.WaitGroup
mu sync.Mutex
first error
)
next := make(chan int)
for w := 0; w < min(jobs, n); w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range next {
if err := fn(i); err != nil {
mu.Lock()
if first == nil {
first = err
}
mu.Unlock()
}
}
}()
}
for i := 0; i < n; i++ {
next <- i
}
close(next)
wg.Wait()
return first
}
func run(args []string, stdout, stderr io.Writer) int {
o, err := parseFlags(args, stderr)
if errors.Is(err, flag.ErrHelp) {
return 0
}
if err != nil {
fmt.Fprintln(stderr, "values-injection:", err)
return 2
}
allowed, err := loadAllowlist(o.allowlist)
if err != nil {
fmt.Fprintln(stderr, "values-injection:", err)
return 2
}
results, charts, err := check(o)
if err != nil {
fmt.Fprintln(stderr, "values-injection:", err)
return 2
}
return report(o, results, charts, allowed, stdout, stderr)
}
// check fuzzes every field of the charts, and returns the results with the
// list of charts asked for.
func check(o *options) ([]*result, []string, error) {
// Without its profiles a gated field would quietly go unreached.
if _, err := os.Stat(profilesDir); err != nil {
return nil, nil, fmt.Errorf("%w: run from the repository root", err)
}
root, err := filepath.Abs(o.root)
if err != nil {
return nil, nil, err
}
charts := o.charts
if len(charts) == 0 {
if charts, err = listCharts(root); err != nil {
return nil, nil, err
}
}
for i, c := range charts {
charts[i] = filepath.Clean(c)
}
tmp, err := os.MkdirTemp("", "values-injection-")
if err != nil {
return nil, nil, err
}
defer os.RemoveAll(tmp)
arts := map[string]string{}
if _, err := os.Stat(filepath.Join(root, "packages/core/platform/sources")); err == nil {
if arts, err = artifacts(root); err != nil {
return nil, nil, err
}
}
// Each chart renders on its defaults first: one that does not is
// reported whole, and its fields are not fuzzed.
prepared := make([]*chart, len(charts))
chartResults := make([]*result, len(charts))
err = pool(len(charts), o.jobs, func(i int) error {
schemaFile := filepath.Join(root, charts[i], "values.schema.json")
text, err := os.ReadFile(schemaFile)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
var schema map[string]any
d := json.NewDecoder(bytes.NewReader(text))
d.UseNumber()
if err := d.Decode(&schema); err != nil {
return fmt.Errorf("%s: %w", schemaFile, err)
}
r := newRenderer(root, charts[i], tmp, "", "")
profiles, err := loadProfiles(r.name)
if err != nil {
return err
}
res, err := r.render(map[string]any{}, false)
if err != nil {
return err
}
if res.rc != 0 {
chartResults[i] = &result{Chart: charts[i], Slot: "<chart>", Kind: "-", Status: "ref-fail",
Findings: []findingJSON{}, Notes: []string{firstError(res.err)}}
return nil
}
prepared[i] = &chart{name: r.name, path: charts[i], render: r.render, schema: schema,
profiles: profiles, arts: arts, sub: func(chart, release, ns string) renderFunc {
return newRenderer(root, chart, tmp, release, ns).render
}}
return nil
})
if err != nil {
return nil, nil, err
}
type task struct {
chart *chart
slot slot
}
var tasks []task
var results []*result
for i, ch := range prepared {
if chartResults[i] != nil {
results = append(results, chartResults[i])
}
if ch == nil {
continue
}
seen := map[string]bool{}
slots(ch.schema, nil, 0, func(s slot) {
key := s.kind + "\x00" + s.path.key()
if !seen[key] {
seen[key] = true
tasks = append(tasks, task{ch, s})
}
})
}
fieldResults := make([]*result, len(tasks))
err = pool(len(tasks), o.jobs, func(i int) error {
res, err := fuzzSlot(tasks[i].chart, tasks[i].slot)
if err != nil {
return fmt.Errorf("%s %s: %w", tasks[i].chart.path, dotted(tasks[i].slot.path, tasks[i].slot.kind), err)
}
fieldResults[i] = res
return nil
})
if err != nil {
return nil, nil, err
}
results = append(results, fieldResults...)
sort.SliceStable(results, func(i, j int) bool {
if results[i].Chart != results[j].Chart {
return results[i].Chart < results[j].Chart
}
return results[i].Slot < results[j].Slot
})
return results, charts, nil
}
var reported = map[string]bool{"injectable": true, "breakable": true, "latent": true, "ref-fail": true, "allowed": true}
func report(o *options, results []*result, charts []string, allowed map[allowKey]string, stdout, stderr io.Writer) int {
// A field multi-line by design may be breakable, never injectable.
for _, res := range results {
if reason, ok := allowed[allowKey{res.Chart, res.Slot}]; ok && res.Status == "breakable" {
res.Status = "allowed"
res.Notes = append(res.Notes, reason)
}
}
if o.json != "" {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(results); err != nil {
fmt.Fprintln(stderr, "values-injection:", err)
return 2
}
if err := os.WriteFile(o.json, bytes.TrimSuffix(buf.Bytes(), []byte("\n")), 0o644); err != nil {
fmt.Fprintln(stderr, "values-injection:", err)
return 2
}
}
counts := map[string]int{}
for _, res := range results {
counts[res.Status]++
if !reported[res.Status] && !o.verbose {
continue
}
notes := ""
if len(res.Notes) > 0 {
notes = " (" + strings.Join(res.Notes, "; ") + ")"
}
fmt.Fprintf(stdout, "%-10s %s: %s%s\n", strings.ToUpper(res.Status), res.Chart, res.Slot, notes)
type group struct{ schema, typ, source, detail string }
var order []group
pids := map[group][]string{}
for _, f := range res.Findings {
g := group{f.Schema, f.Type, f.Source, f.Detail}
if _, ok := pids[g]; !ok {
order = append(order, g)
}
pids[g] = append(pids[g], f.Payload)
}
sort.Slice(order, func(i, j int) bool {
a, b := order[i], order[j]
if a.schema != b.schema {
return a.schema < b.schema
}
if a.typ != b.typ {
return a.typ < b.typ
}
if a.source != b.source {
return a.source < b.source
}
return a.detail < b.detail
})
for _, g := range order {
fmt.Fprintf(stdout, " %-16s [%s] %s %s %s\n", g.typ, g.schema, strings.Join(pids[g], ","), g.source, g.detail)
}
}
var statuses []string
for s := range counts {
statuses = append(statuses, s)
}
sort.Strings(statuses)
parts := make([]string, len(statuses))
for i, s := range statuses {
parts[i] = fmt.Sprintf("%s=%d", s, counts[s])
}
fmt.Fprintln(stdout, "\nfields: "+strings.Join(parts, ", "))
// An entry no field needs any more fails too, so the list cannot outlive
// what it excuses. Only charts this run rendered can tell.
status := map[allowKey]string{}
for _, res := range results {
status[allowKey{res.Chart, res.Slot}] = res.Status
}
rendered := map[string]bool{}
for _, c := range charts {
rendered[c] = true
}
var stale []allowKey
for k := range allowed {
if st := status[k]; rendered[k.chart] && st != "allowed" && st != "injectable" {
stale = append(stale, k)
}
}
sort.Slice(stale, func(i, j int) bool {
if stale[i].chart != stale[j].chart {
return stale[i].chart < stale[j].chart
}
return stale[i].slot < stale[j].slot
})
for _, k := range stale {
st, ok := status[k]
if !ok {
st = "not a field"
}
fmt.Fprintf(stdout, "STALE %s: %s %s is %s, not breakable\n", o.allowlist, k.chart, k.slot, st)
}
failed := counts["injectable"] + counts["breakable"] + counts["ref-fail"] + len(stale)
if failed > 0 {
fmt.Fprintf(stdout, "values-injection: %d finding(s); quote YAML strings, pass script data in env vars, "+
"validate what reaches an embedded config, or list a field multi-line by design in %s\n", failed, o.allowlist)
return 1
}
return 0
}