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>
This commit is contained in:
Myasnikov Daniil committed 2026-12-03 10:03:22 +00:00
1 parent 4b8eaffa53
commit fb00301f0b
31 files changed
+3562 -3

No files matched your search

+12 -3
View File
@@ -1,4 +1,4 @@
.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check rd-consumption-check migrations-target-check test test-controllers test-controllers-envtest test-backport-batch preflight
.PHONY: manifests assets prepare-env prepare-env-container unit-tests helm-unit-tests bats-unit-tests bats-unit-files-check bats-posix-compat-tests print-bats-unit-files print-bats-posix-compat-files print-bats-jobs rd-presets-check rd-consumption-check migrations-target-check values-injection-check test test-controllers test-controllers-envtest test-backport-batch preflight
include hack/common-envs.mk
@@ -129,7 +129,7 @@ test:
make -C packages/core/testing apply
make -C packages/core/testing e2e
unit-tests: helm-unit-tests bats-unit-tests bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check rd-consumption-check test-check-readiness migrations-target-check
unit-tests: helm-unit-tests bats-unit-tests bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check rd-consumption-check test-check-readiness migrations-target-check values-injection-check
helm-unit-tests:
hack/helm-unit-tests.sh
@@ -151,6 +151,15 @@ rd-consumption-check:
migrations-target-check:
hack/check-migrations-target.sh
# Render every chart in packages/apps and packages/extra with generated values
# in each field its schema allows, and fail when one changes the structure of
# the output rather than only its content. Fields multi-line by design are
# listed in hack/testdata/values-injection/allowlist.txt. The check is a module
# of its own under hack/values-injection; go-module-tests runs its unit tests.
values-injection-check:
go -C hack/values-injection build -o $(CURDIR)/_out/bin/values-injection .
_out/bin/values-injection
# ./internal/... runs in test-controllers; ./test/... and cmd/backport-batch
# run in targets of their own.
go-unit-tests:
@@ -305,7 +314,7 @@ bats-posix-compat-tests:
# own too; hack/unit-lane-no-cluster.bats fails when one is missing.
NO_CLUSTER_TARGETS := unit-tests test-controllers helm-unit-tests bats-unit-tests \
bats-posix-compat-tests go-unit-tests go-module-tests rd-presets-check rd-consumption-check \
test-check-readiness test-backport-batch migrations-target-check
test-check-readiness test-backport-batch migrations-target-check values-injection-check
$(NO_CLUSTER_TARGETS): export KUBECONFIG := /dev/null
$(NO_CLUSTER_TARGETS): export KUBERNETES_SERVICE_HOST :=
+1
View File
@@ -145,6 +145,7 @@ Markdown follows these markdownlint rules: every code fence names a language (`t
- An unquoted numeric value (`name: 123`) reaches a template as a number: `len` on it aborts the render with `len of type float64` (`int64` for a value given with `--set`) before any `fail` message is reached, and `if not $v` treats `0` as unset. For fields validated as text that permit numeric inputs, reject missing or null values with `kindIs "invalid"`, then coerce with `printf "%v"` and check emptiness with `eq $v ""`. Coercing null first produces the non-empty string `<nil>`.
- For integer fields, keep string inputs on their lexical validation path. Validate numeric inputs for type, integrality and bounds before conversion, then format the validated integer in decimal. Generic `printf "%v"` can emit exponent notation for a float (`4200000000` becomes `4.2e+09`), so it is not integer normalization.
- For nested values, validate or normalize each parent map before reading its children; checking only the leaf cannot prevent a nil-pointer error from a missing or null parent.
- A chart value never reaches YAML, a script or an embedded config unescaped. Write a string into YAML with `quote`, not bare and not with `toJson`, so it stays one scalar; hand data to a hook script in an environment variable it reads as `"$VAR"`, so the script text is static; validate what reaches an embedded config, or a chart that renders it unquoted or through `tpl`, against what that target accepts; write a map or list from values with `cozy-lib.yaml.toYaml`, which fails where `toYaml` would render nothing. `make values-injection-check` (`hack/values-injection`) enforces this; a field multi-line by design goes in `hack/testdata/values-injection/allowlist.txt` with its reason.
**No `lookup` that copies another object into the render.** A `lookup` reads cluster state at render time, and nothing re-renders the HelmRelease when that state changes, so whatever it copied into the output (a bucket name, an endpoint, a CA, a list of StorageClasses) stays stale until something unrelated upgrades the release. Lookups of this kind already in the charts have caused failures, and several have since been moved to values, so they are not precedent: do not add one of this kind unless a maintainer has authorized that specific one.
+6
View File
@@ -0,0 +1,6 @@
# Fields whose value is multi-line by design, one per line:
# <chart dir> <field> <reason>
# A field listed here may be breakable: the check reports it and does not fail.
# Injectable fails the check all the same, and so does an entry that no
# breakable field matches any more.
packages/apps/vm-instance cloudInit cloud-init user data is a multi-line document written whole, stored quoted as the userdata of the cloud-init Secret
+3
View File
@@ -0,0 +1,3 @@
profiles:
# machines[0].*: a machine renders its DHCP settings once per MAC address, so it needs at least one
- machines: [{hostname: machine1, mac: ["d6:fa:af:52:25:93"]}]
+3
View File
@@ -0,0 +1,3 @@
profiles:
# nodeGroups.*: supplied groups must include one ingress-nginx group that can scale to a node
- nodeGroups: {ingress: {minReplicas: 0, maxReplicas: 1, roles: [ingress-nginx]}}
+24
View File
@@ -0,0 +1,24 @@
profiles:
# Each provider's credentials block renders only when provider names it.
# The blocks are free-form objects in the schema, so only their default keys
# (accessKeyId, apiToken, ...) reach the output, never an arbitrary key.
# cloudflare.*: apiToken
- {provider: cloudflare}
# cloudflare.*: apiKey and apiEmail, which render only as a pair and only without apiToken
- {provider: cloudflare, cloudflare: {apiKey: key, apiEmail: dns@example.org}}
# aws.*: accessKeyId, secretAccessKey, region, zoneType
- {provider: aws}
# azure.*: tenantId, subscriptionId, resourceGroup, aadClientId, aadClientSecret
- {provider: azure}
# google.*: project, serviceAccountKey
- {provider: google}
# digitalocean.*: token
- {provider: digitalocean}
# linode.*: token
- {provider: linode}
# ovh.*: endpoint, applicationKey, applicationSecret, consumerKey
- {provider: ovh}
# exoscale.*: apiKey, apiSecret
- {provider: exoscale}
# godaddy.*: apiKey, apiSecret
- {provider: godaddy}
+5
View File
@@ -0,0 +1,5 @@
profiles:
# gatewayClassName: a tenant may select only a class the operator lists in gateway.tenantSelectableClasses
- _cluster: {gateway-tenant-classes: "$CANARY"}
# tlsPassthroughServices[0]: passthrough listeners render only on the publishing tenant, with the gateway on, for services it exposes
- _cluster: {expose-ingress: tenant-test, gateway-enabled: "true", expose-services: "$CANARY"}
+10
View File
@@ -0,0 +1,10 @@
profiles:
# kubelet.*ReservedCpu: an explicit reservation of a whole core needs a node large enough to hold it
- resources: {cpu: 8, memory: 16Gi}
# proxmox.*: the proxmox substrate needs a template, a bridge and DNS servers; a target storage needs a full clone
- substrate: proxmox
proxmox:
templateTags: [talos-v1.13.12]
full: true
network: {bridge: vmbr0}
dnsServers: [192.0.2.53]
+22
View File
@@ -0,0 +1,22 @@
profiles:
# addons.hami.*: HAMi runs on top of the GPU operator
- addons: {gpuOperator: {enabled: true}}
# addons.ouroboros.*: ouroboros fixes hairpin NAT for the tenant ingress-nginx
- addons: {ingressNginx: {enabled: true}}
# addons.verticalPodAutoscaler.*: the VPA is installed with the monitoring agents
- addons: {monitoringAgents: {enabled: true}}
# controlPlane.apiServer.extraVolumeMounts[0].*: a mount must name a volume declared in extraVolumes
- controlPlane:
apiServer:
extraVolumes: [{name: authn, configMap: {name: authn}}]
extraVolumeMounts: [{name: authn, mountPath: /etc/kubernetes/authn}]
# proxmox.*: the proxmox substrate with the settings its templates require
- substrate: proxmox
proxmox:
dnsServers: ["10.0.0.1"]
allowedNodes: ["pve1"]
ipv4Config: {addresses: ["10.0.0.10-10.0.0.20"], gateway: "10.0.0.1", prefix: 24}
ccm: {credentialsSecretName: pve}
csi: {credentialsSecretName: pve, storageClasses: [{name: fast, storage: local-lvm}]}
# oidc.customConfig.*, oidc.users[*]: a tenant-supplied issuer
- oidc: {mode: CustomConfig, customConfig: {secretRef: {name: authn}}}
+4
View File
@@ -0,0 +1,4 @@
profiles:
# users.<key>: a user renders only when a database role names it;
# fuzzkey is the key the fuzzer gives a map entry it creates
- databases: {db1: {roles: {admin: ["$CANARY", fuzzkey]}}}
+5
View File
@@ -0,0 +1,5 @@
profiles:
# seal.secretName, seal.keyId: the static seal needs both
- seal: {type: static, secretName: unseal-key, keyId: key-1}
# seal.previousSecretName, seal.previousKeyId: an n-1 key rotation of the static seal sets both, distinct from the current pair
- seal: {type: static, secretName: unseal-key, keyId: key-1, previousSecretName: unseal-key-old, previousKeyId: key-0}
+4
View File
@@ -0,0 +1,4 @@
profiles:
# bootstrap.*: a recovery from a legacy S3 backup needs inline S3 credentials and a source cluster name
- backup: {s3AccessKey: access, s3SecretKey: secret}
bootstrap: {enabled: true, oldName: source}
+3
View File
@@ -0,0 +1,3 @@
profiles:
# maxmemory: a gigabyte-sized maxmemory must fit in 90% of the pod's memory request
- resources: {cpu: 1, memory: 4Gi}
+3
View File
@@ -0,0 +1,3 @@
profiles:
# volume.zones.*: zones only render with the MultiZone topology, which needs no more replicas than zones
- {topology: MultiZone, replicationFactor: 1}
+3
View File
@@ -0,0 +1,3 @@
profiles:
# whitelist[0]: the HTTP/HTTPS frontends render the client whitelist only with whitelistHTTP on
- {whitelistHTTP: true, whitelist: [10.0.0.0/8]}
+3
View File
@@ -0,0 +1,3 @@
profiles:
# gatewayClass: read only when the tenant owns its Gateway
- {gateway: true}
+1
View File
@@ -0,0 +1 @@
/values-injection
+493
View File
@@ -0,0 +1,493 @@
package main
import (
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
)
// Finding types that prove an injection: a token the payload carries shows
// up as structure of its own.
var proven = map[string]bool{"doc-injection": true, "yaml-inject": true, "shell-injection": true,
"heredoc-inject": true, "embedded-inject": true, "tpl-eval": true, "namespace": true}
var shells = map[string]bool{"sh": true, "bash": true, "ash": true, "dash": true}
type finding struct {
typ string
source string
detail string
}
// A path into a decoded document is kept two ways: its elements, a string
// key or an int index, for reports, and a prefix-free encoding of them, for
// set and map keys.
func keyElem(k string) string { return "s" + strconv.Itoa(len(k)) + ":" + k }
func indexElem(i int) string { return "i" + strconv.Itoa(i) + ";" }
func joinPath(path []any) string {
parts := make([]string, len(path))
for i, e := range path {
parts[i] = fmt.Sprint(e)
}
return strings.Join(parts, ".")
}
// normKey is <X> for the payload's own token, <C> for a key carrying the
// canary, with what precedes it kept.
func normKey(k, c string) string {
lk := lower(k)
i := strings.Index(lk, c)
if i < 0 {
return k
}
if strings.HasPrefix(lk[i:], c+"x") {
return k[:i] + "<X>"
}
return k[:i] + "<C>"
}
func isMarked(k string) bool {
return strings.HasSuffix(k, "<X>") || strings.HasSuffix(k, "<C>")
}
// shapeEntry is one leaf of a document's shape: where a value is and its type,
// or an empty map or list.
type shapeEntry struct {
path []any
typ string
marked bool
}
// walkShape calls emit for every entry of obj's shape, keyed by path and type.
// path is reused between calls; emit copies it if it keeps it.
func walkShape(obj any, c, prefix string, path []any, marked bool, emit func(key string, e shapeEntry)) {
switch x := obj.(type) {
case map[string]any:
if len(x) == 0 {
emit(prefix+"t{}", shapeEntry{path, "{}", marked})
}
for _, k := range sortedKeys(x) {
nk := normKey(k, c)
walkShape(x[k], c, prefix+keyElem(nk), append(path, nk), marked || isMarked(nk), emit)
}
case []any:
if len(x) == 0 {
emit(prefix+"t[]", shapeEntry{path, "[]", marked})
}
for i, v := range x {
walkShape(v, c, prefix+indexElem(i), append(path, i), marked, emit)
}
default:
t := typeName(obj)
emit(prefix+"t"+t, shapeEntry{path, t, marked})
}
}
func shape(obj any, c string) map[string]struct{} {
out := map[string]struct{}{}
walkShape(obj, c, "", nil, false, func(key string, _ shapeEntry) { out[key] = struct{}{} })
return out
}
// added is the shape of obj that base lacks.
func added(obj any, c string, base map[string]struct{}) []shapeEntry {
seen := map[string]bool{}
var out []shapeEntry
walkShape(obj, c, "", nil, false, func(key string, e shapeEntry) {
if _, ok := base[key]; ok || seen[key] {
return
}
seen[key] = true
e.path = append([]any(nil), e.path...)
out = append(out, e)
})
return out
}
func tupleRepr(path []any) string {
parts := make([]string, len(path))
for i, e := range path {
if s, ok := e.(string); ok {
parts[i] = repr(s)
} else {
parts[i] = fmt.Sprint(e)
}
}
if len(parts) == 1 {
return "(" + parts[0] + ",)"
}
return "(" + strings.Join(parts, ", ") + ")"
}
// describe lists up to four entries, ordered as the first version of this
// check ordered them: by the Python text of (path, type).
func describe(entries []shapeEntry) string {
type keyed struct {
key string
e shapeEntry
}
sorted := make([]keyed, len(entries))
for i, e := range entries {
sorted[i] = keyed{"(" + tupleRepr(e.path) + ", " + repr(e.typ) + ")", e}
}
sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].key < sorted[j].key })
var parts []string
for _, k := range sorted[:min(4, len(sorted))] {
parts = append(parts, "+"+joinPath(k.e.path)+":"+k.e.typ)
}
return strings.Join(parts, ", ")
}
// pathEntry is a string at a path of a document, in the order a walk meets
// it; a later string at the same path replaces the value, not the position.
type pathEntry struct {
key string
path []any
val string
}
type orderedPaths struct {
index map[string]int
list []pathEntry
}
func (o *orderedPaths) set(key string, path []any, val string) {
if o.index == nil {
o.index = map[string]int{}
}
if i, ok := o.index[key]; ok {
o.list[i].val = val
if o.list[i].path == nil && path != nil {
o.list[i].path = append([]any(nil), path...)
}
return
}
o.index[key] = len(o.list)
if path != nil {
path = append([]any(nil), path...)
}
o.list = append(o.list, pathEntry{key, path, val})
}
func (o *orderedPaths) get(key string) (string, bool) {
i, ok := o.index[key]
if !ok {
return "", false
}
return o.list[i].val, true
}
// leaves is every string of obj, keyed by its path with keys normalized. A
// leaf keeps its path only when the canary is in its value: no other is
// reported.
func leaves(obj any, c string) *orderedPaths {
out := &orderedPaths{}
var walk func(v any, prefix string, path []any)
walk = func(v any, prefix string, path []any) {
switch x := v.(type) {
case map[string]any:
for _, k := range sortedKeys(x) {
nk := normKey(k, c)
walk(x[k], prefix+keyElem(nk), append(path, nk))
}
case []any:
for i, e := range x {
walk(e, prefix+indexElem(i), append(path, i))
}
case string:
if containsFold(x, c) {
out.set(prefix, path, x)
} else {
out.set(prefix, nil, x)
}
}
}
walk(obj, "", nil)
return out
}
func basename(p string) string {
return p[strings.LastIndexByte(p, '/')+1:]
}
func isShellFlag(s string) bool {
if len(s) < 2 || s[0] != '-' {
return false
}
c := false
for i := 1; i < len(s); i++ {
if s[i] < 'a' || s[i] > 'z' {
return false
}
c = c || s[i] == 'c'
}
return c
}
// findScripts is every shell script of obj by its path, keys as they are:
// the argument of `sh [-opts] -c`, the value of a *.sh key, a string that
// starts with a shell shebang.
func findScripts(obj any) *orderedPaths {
out := &orderedPaths{}
var walk func(v any, prefix string, path []any)
walk = func(v any, prefix string, path []any) {
switch x := v.(type) {
case map[string]any:
cmd, _ := x["command"].([]any)
args, _ := x["args"].([]any)
argv := append(append([]any(nil), cmd...), args...)
for i, a := range argv {
if s, ok := a.(string); !ok || !shells[basename(s)] {
continue
}
for j := i + 1; j < min(i+5, len(argv)-1); j++ {
flag, ok := argv[j].(string)
script, ok2 := argv[j+1].(string)
if !ok || !ok2 || !isShellFlag(flag) {
continue
}
k := j + 1
if k < len(cmd) {
out.set(prefix+keyElem("command")+indexElem(k), append(path, "command", k), script)
} else {
out.set(prefix+keyElem("args")+indexElem(k-len(cmd)), append(path, "args", k-len(cmd)), script)
}
break
}
}
for _, k := range sortedKeys(x) {
if s, ok := x[k].(string); ok && strings.HasSuffix(k, ".sh") {
out.set(prefix+keyElem(k), append(path, k), s)
}
walk(x[k], prefix+keyElem(k), append(path, k))
}
case []any:
for i, e := range x {
walk(e, prefix+indexElem(i), append(path, i))
}
case string:
first, _, _ := strings.Cut(x, "\n")
if strings.HasPrefix(x, "#!") && strings.Contains(first, "sh") {
out.set(prefix, path, x)
}
}
}
walk(obj, "", nil)
return out
}
// memo caches what strings decode to, for a slot whose reference values are
// decoded once per payload.
type memo map[string]any
func (m memo) structured(text string) any {
if v, ok := m[text]; ok {
return v
}
v := structured(text)
m[text] = v
return v
}
// embedded is the finding type for a string that carries YAML or JSON, if
// any, and whether the reference string is structured at all.
func embedded(m memo, bv, pv, c, kind string) (string, bool) {
bs := m.structured(bv)
if bs == nil {
return "", false
}
ps := m.structured(pv)
if ps == nil {
return kind + "-break", true
}
for _, e := range added(ps, c, shape(bs, c)) {
if e.marked {
return kind + "-inject", true
}
}
return "", true
}
// refDoc is a document of a reference render with what every payload render
// is compared against, worked out once.
type refDoc struct {
doc
id string
shape map[string]struct{}
scripts *orderedPaths
leaves *orderedPaths
}
type reference struct {
docs []refDoc
ids []string
}
func prepare(docs []doc, c string) *reference {
ref := &reference{}
for _, d := range docs {
id, _ := ident(d.obj)
ref.docs = append(ref.docs, refDoc{d, id, shape(d.obj, c), findScripts(d.obj), leaves(d.obj, c)})
ref.ids = append(ref.ids, id)
}
return ref
}
func ident(v any) (key, display string) {
if m, ok := v.(map[string]any); ok {
av, kd := pyRepr(m["apiVersion"]), pyRepr(m["kind"])
return "d" + av + "\x00" + kd, "(" + av + ", " + kd + ")"
}
t := typeName(v)
return "t" + t, t
}
func count(ids []string, id string) int {
n := 0
for _, x := range ids {
if x == id {
n++
}
}
return n
}
// compare is the findings of a payload render that succeeded, against the
// reference: pDocs and err are what decoding pOut gave.
func compare(m memo, ref *reference, pDocs []doc, err error, pOut, c string) []finding {
var findings []finding
if err != nil {
return []finding{{"yaml-break", "?", truncate(err.Error(), 200)}}
}
if marker := c + "tpleval"; strings.Contains(pOut, marker) {
src := "?"
for _, d := range pDocs {
if j, err := json.Marshal(d.obj); err == nil && strings.Contains(string(j), marker) {
src = d.source
break
}
}
line := ""
for _, l := range splitLines(pOut) {
if strings.Contains(l, marker) {
line = l
break
}
}
findings = append(findings, finding{"tpl-eval", src, truncate(strip(line), 160)})
}
pIDs := make([]string, len(pDocs))
pShown := make([]string, len(pDocs))
for i, d := range pDocs {
pIDs[i], pShown[i] = ident(d.obj)
}
if strings.Join(pIDs, "\x01") != strings.Join(ref.ids, "\x01") || len(pIDs) != len(ref.ids) {
var extra []string
for i, id := range pIDs {
if count(pIDs, id) > count(ref.ids, id) {
extra = append(extra, pDocs[i].source+" "+pShown[i])
}
}
src := "?"
if len(extra) > 0 {
src, _, _ = strings.Cut(extra[0], " ")
} else if len(pDocs) > 0 {
src = pDocs[0].source
}
detail := fmt.Sprintf("%d -> %d documents; ", len(ref.ids), len(pIDs)) + strings.Join(extra[:min(2, len(extra))], "; ")
return append(findings, finding{"doc-injection", src, detail})
}
for i, b := range ref.docs {
pd := pDocs[i].obj
src := b.source
kind := ""
if pm, ok := pd.(map[string]any); ok {
if k, has := pm["kind"]; has {
kind = pyStr(k)
}
if ns, ok := asMap(pm["metadata"])["namespace"].(string); ok && containsFold(ns, c) {
findings = append(findings, finding{"namespace", src, kind + " namespace " + repr(ns)})
}
}
add := added(pd, c, b.shape)
var inj []shapeEntry
for _, e := range add {
if e.marked {
inj = append(inj, e)
}
}
if len(inj) > 0 {
findings = append(findings, finding{"yaml-inject", src, kind + " " + describe(inj)})
continue
}
if len(add) > 0 {
findings = append(findings, finding{"yaml-shape", src, kind + " " + describe(add)})
continue
}
pScripts := findScripts(pd)
for _, ps := range pScripts.list {
btext, ok := b.scripts.get(ps.key)
if !ok || !containsFold(ps.val, c) {
continue
}
where := joinPath(ps.path)
bp := parseScript(btext)
if !bp.ok {
continue
}
pp := parseScript(ps.val)
if !pp.ok {
findings = append(findings, finding{"shell-break", src, where})
continue
}
if pp.skeleton != bp.skeleton {
findings = append(findings, finding{"shell-injection", src, where})
continue
}
for h := 0; h < min(len(bp.heredocs), len(pp.heredocs)); h++ {
bh, ph := bp.heredocs[h], pp.heredocs[h]
if !containsFold(ph, c) {
continue
}
typ, isStruct := embedded(m, bh, ph, c, "heredoc")
if typ != "" {
findings = append(findings, finding{strings.ReplaceAll(typ, "heredoc-break", "heredoc-newline"), src, where})
} else if !isStruct && strings.Count(ph, "\n") > strings.Count(bh, "\n") {
findings = append(findings, finding{"heredoc-newline", src, where})
}
}
if nl := "\n" + c + "x"; strings.Contains(ps.val, nl) && !strings.Contains(btext, nl) {
findings = append(findings, finding{"script-newline", src, where})
}
}
for _, pl := range leaves(pd, c).list {
bv, ok := b.leaves.get(pl.key)
if !ok || !containsFold(pl.val, c) {
continue
}
if _, isScript := pScripts.index[pl.key]; isScript {
continue
}
where := joinPath(pl.path)
typ, isStruct := embedded(m, bv, pl.val, c, "embedded")
switch {
case typ != "":
findings = append(findings, finding{typ, src, where})
case isStruct || !strings.Contains(bv, "\n"):
case strings.Count(pl.val, "\n") > strings.Count(bv, "\n") || strings.Count(pl.val, "\r") > strings.Count(bv, "\r"):
findings = append(findings, finding{"embedded-newline", src, where})
case strings.Contains(pl.val, c+"\""+c+"x") || strings.Contains(pl.val, c+"'"+c+"x"):
findings = append(findings, finding{"embedded-quote", src, where})
}
}
}
return findings
}
+203
View File
@@ -0,0 +1,203 @@
package main
import (
"reflect"
"strings"
"testing"
)
const c = "cnry123abc"
func TestNormKey(t *testing.T) {
for _, tc := range []struct{ in, want string }{
{"plain", "plain"},
{c, "<C>"},
{c + "x", "<X>"},
{"pre-" + c + "-tail", "pre-<C>"},
{"pre-" + strings.ToUpper(c) + "X: y", "pre-<X>"},
{"pre-" + c[:5], "pre-" + c[:5]},
} {
if got := normKey(tc.in, c); got != tc.want {
t.Errorf("normKey(%q) = %q, want %q", tc.in, got, tc.want)
}
}
}
func types(entries []shapeEntry) []string {
var out []string
for _, e := range entries {
out = append(out, joinPath(e.path)+":"+e.typ)
}
return out
}
func TestAddedShape(t *testing.T) {
base := map[string]any{"data": map[string]any{"v": c, "n": float64(1)}}
for _, tc := range []struct {
name string
payload any
want []string
marked bool
}{
{"same shape, other text", map[string]any{"data": map[string]any{"v": c + " other", "n": float64(2)}}, nil, false},
{"the payload's own key", map[string]any{"data": map[string]any{"v": c, "n": float64(1), c + "x": true}}, []string{"data.<X>:bool"}, true},
{"a key carrying the canary", map[string]any{"data": map[string]any{"v": c, "n": float64(1), "k" + c: "y"}}, []string{"data.k<C>:str"}, true},
{"a value turned into a number", map[string]any{"data": map[string]any{"v": float64(7), "n": float64(1)}}, []string{"data.v:int"}, false},
{"an int turned into a float", map[string]any{"data": map[string]any{"v": c, "n": 1.5}}, []string{"data.n:float"}, false},
{"a value turned into a map", map[string]any{"data": map[string]any{"v": map[string]any{}, "n": float64(1)}}, []string{"data.v:{}"}, false},
} {
t.Run(tc.name, func(t *testing.T) {
got := added(tc.payload, c, shape(base, c))
if !reflect.DeepEqual(types(got), tc.want) {
t.Fatalf("added = %v, want %v", types(got), tc.want)
}
marked := false
for _, e := range got {
marked = marked || e.marked
}
if marked != tc.marked {
t.Fatalf("marked = %v, want %v", marked, tc.marked)
}
})
}
}
func TestDescribeOrdersAsPythonReprAndKeepsFour(t *testing.T) {
entries := []shapeEntry{
{path: []any{"b"}, typ: "str"},
{path: []any{"a", 1}, typ: "str"},
{path: []any{"a", 0}, typ: "str"},
{path: []any{"c"}, typ: "str"},
{path: []any{"a"}, typ: "{}"},
}
// By repr, "(('a', 0)" sorts before "(('a',)": a space before a parenthesis.
want := "+a.0:str, +a.1:str, +a:{}, +b:str"
if got := describe(entries); got != want {
t.Fatalf("describe = %q, want %q", got, want)
}
}
func TestShellSkeleton(t *testing.T) {
base := parseScript("set -e\necho " + c + " >/tmp/out\n")
if !base.ok {
t.Fatal("the reference script does not parse")
}
same := parseScript("set -e\necho " + c + "-other-text >/tmp/out\n")
if !same.ok || same.skeleton != base.skeleton {
t.Fatal("a change of literal text changed the skeleton")
}
for _, injected := range []string{
"set -e\necho " + c + "$(true " + c + "x) >/tmp/out\n",
"set -e\necho " + c + "`true " + c + "x` >/tmp/out\n",
"set -e\necho " + c + ";true " + c + "x; >/tmp/out\n",
"set -e\necho " + c + " " + c + "x >/tmp/out\n",
} {
p := parseScript(injected)
if !p.ok {
t.Fatalf("%q does not parse", injected)
}
if p.skeleton == base.skeleton {
t.Errorf("%q has the skeleton of the reference", injected)
}
}
if parseScript("echo \"" + c + "\n").ok {
t.Error("an unterminated quote parsed")
}
}
func TestHeredocs(t *testing.T) {
p := parseScript("cat <<EOF >/tmp/a\nkey: " + c + "\nother: $(date)\nEOF\ncat <<EOF\nEOF\ncat <<'Q'\nq: 1\nQ\n")
if !p.ok {
t.Fatal("the script does not parse")
}
// The empty heredoc has no body to compare and is not listed.
want := []string{"key: " + c + "\nother: X\n", "q: 1\n"}
if !reflect.DeepEqual(p.heredocs, want) {
t.Fatalf("heredocs = %q, want %q", p.heredocs, want)
}
}
// configMap is a manifest of one ConfigMap with data.
func configMap(data map[string]any) map[string]any {
return map[string]any{"apiVersion": "v1", "kind": "ConfigMap",
"metadata": map[string]any{"name": "probe"}, "data": data}
}
func findingTypes(fs []finding) []string {
var out []string
for _, f := range fs {
out = append(out, f.typ)
}
return out
}
func compareObjects(t *testing.T, b, p any) []string {
t.Helper()
ref := prepare([]doc{{"t.yaml", b}}, c)
return findingTypes(compare(memo{}, ref, []doc{{"t.yaml", p}}, nil, "", c))
}
func TestCompare(t *testing.T) {
podWith := func(script string) map[string]any {
return map[string]any{"apiVersion": "v1", "kind": "Pod", "metadata": map[string]any{"name": "p"},
"spec": map[string]any{"containers": []any{map[string]any{
"name": "c", "command": []any{"/bin/sh", "-ec", script}}}}}
}
heredoc := func(body string) string { return "cat <<EOF >/etc/conf.yaml\n" + body + "\nEOF\n" }
for _, tc := range []struct {
name string
b, p any
want []string
}{
{"same", configMap(map[string]any{"v": c}), configMap(map[string]any{"v": c}), nil},
{"key injected", configMap(map[string]any{"v": c}), configMap(map[string]any{"v": c, c + "x": "y"}), []string{"yaml-inject"}},
{"type changed", configMap(map[string]any{"v": c}), configMap(map[string]any{"v": true}), []string{"yaml-shape"}},
{"namespace chosen",
map[string]any{"apiVersion": "v1", "kind": "ConfigMap", "metadata": map[string]any{"name": "probe", "namespace": "tenant-test"}},
map[string]any{"apiVersion": "v1", "kind": "ConfigMap", "metadata": map[string]any{"name": "probe", "namespace": c}},
[]string{"namespace"}},
{"shell word added", podWith("echo " + c), podWith("echo " + c + " " + c + "x"), []string{"shell-injection"}},
{"shell broken", podWith("echo " + c), podWith("echo " + c + "\""), []string{"shell-break"}},
{"script under a .sh key", configMap(map[string]any{"run.sh": "echo " + c}), configMap(map[string]any{"run.sh": "echo " + c + ";true " + c + "x;"}), []string{"shell-injection"}},
{"script with a shebang", configMap(map[string]any{"entry": "#!/bin/bash\necho " + c}), configMap(map[string]any{"entry": "#!/bin/bash\necho " + c + "$(true " + c + "x)"}), []string{"shell-injection"}},
{"sh -c in args", map[string]any{"command": []any{"/bin/bash"}, "args": []any{"-c", "echo " + c}}, map[string]any{"command": []any{"/bin/bash"}, "args": []any{"-c", "echo " + c + " " + c + "x"}}, []string{"shell-injection"}},
{"newline into a script", podWith("echo '" + c + "'"), podWith("echo '" + c + "\n" + c + "x: y'"), []string{"script-newline"}},
{"heredoc key added", podWith(heredoc("a: " + c)), podWith(heredoc("a: " + c + "\n" + c + "x: y")), []string{"heredoc-inject", "script-newline"}},
{"heredoc line added", podWith(heredoc("a = " + c)), podWith(heredoc("a = " + c + "\n" + c + "x")), []string{"heredoc-newline", "script-newline"}},
{"embedded YAML key", configMap(map[string]any{"conf": "a: " + c + "\n"}), configMap(map[string]any{"conf": "a: " + c + "\n" + c + "x: y\n"}), []string{"embedded-inject"}},
{"embedded JSON key", configMap(map[string]any{"conf": `{"a": "` + c + `"}`}), configMap(map[string]any{"conf": `{"a": "` + c + `", "` + c + `x": "y"}`}), []string{"embedded-inject"}},
{"embedded JSON broken", configMap(map[string]any{"conf": `{"a": "` + c + `"}`}), configMap(map[string]any{"conf": `{"a": "` + c + `"` + c + `x"}`}), []string{"embedded-break"}},
{"embedded line", configMap(map[string]any{"conf": "[main]\na = " + c + "\n"}), configMap(map[string]any{"conf": "[main]\na = " + c + "\n" + c + "x\n"}), []string{"embedded-newline"}},
{"embedded quote", configMap(map[string]any{"conf": "[main]\na = \"" + c + "\"\n"}), configMap(map[string]any{"conf": "[main]\na = \"" + c + "\"" + c + "x\"\n"}), []string{"embedded-quote"}},
} {
t.Run(tc.name, func(t *testing.T) {
if got := compareObjects(t, tc.b, tc.p); !reflect.DeepEqual(got, tc.want) {
t.Fatalf("findings = %v, want %v", got, tc.want)
}
})
}
}
func TestCompareDocuments(t *testing.T) {
ref := prepare([]doc{{"a.yaml", configMap(map[string]any{"v": c})}}, c)
extra := []doc{{"a.yaml", configMap(map[string]any{"v": c})}, {"a.yaml", configMap(map[string]any{"v": c + "x"})}}
got := compare(memo{}, ref, extra, nil, "", c)
if len(got) != 1 || got[0].typ != "doc-injection" || got[0].detail != "1 -> 2 documents; a.yaml ('v1', 'ConfigMap'); a.yaml ('v1', 'ConfigMap')" {
t.Fatalf("findings = %+v", got)
}
out := "data:\n v: " + c + `{{print "` + c + `tp" "leval"}}` + "\n"
got = compare(memo{}, ref, []doc{{"a.yaml", configMap(map[string]any{"v": c + c + "tpleval"})}}, nil, "x: "+c+"tpleval", c)
if len(got) != 1 || got[0].typ != "tpl-eval" || got[0].source != "a.yaml" {
t.Fatalf("an evaluated template was not reported: %+v", got)
}
if got := compare(memo{}, ref, []doc{{"a.yaml", configMap(map[string]any{"v": out})}}, nil, out, c); len(got) != 0 {
t.Fatalf("a template rendered as text was reported: %+v", got)
}
_, err := decodeStream("a: [" + c)
got = compare(memo{}, ref, nil, err, "", c)
if len(got) != 1 || got[0].typ != "yaml-break" {
t.Fatalf("a render that does not decode was not yaml-break: %+v", got)
}
}
+178
View File
@@ -0,0 +1,178 @@
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"
}
+143
View File
@@ -0,0 +1,143 @@
package main
import (
"encoding/json"
"reflect"
"testing"
)
// The Kubernetes client reads U+0085 as a line break in a plain scalar, so a
// value carrying one adds a key. A parser that disagrees, as PyYAML does on
// U+0085 and U+2028, would call the same render safe.
func TestNELBreaksAPlainScalar(t *testing.T) {
docs, err := decodeStream("data:\n v: " + c + "\u0085" + c + "x: y\n")
if err != nil {
t.Fatal(err)
}
// The break ends the indented value, so the key lands at the top.
if _, ok := asMap(docs[0].obj)[c+"x"]; !ok {
t.Fatalf("U+0085 did not start a key: %v", docs[0].obj)
}
}
// helm reads --values as YAML. A raw U+0085 inside a quoted string is a line
// break there and folds into a space, so the payload would not reach the
// chart as written.
func TestEncodeValuesEscapesNonASCII(t *testing.T) {
in := map[string]any{"v": c + "\u0085\u2028\u00e9\U0001F600<&>", "n": json.Number("1.0"), "i": 2}
blob, err := encodeValues(in)
if err != nil {
t.Fatal(err)
}
for _, r := range string(blob) {
if r >= 0x80 {
t.Fatalf("non-ASCII %U left raw in %s", r, blob)
}
}
if want := `{"i":2,"n":1.0,"v":"` + c + `\u0085\u2028\u00e9\U0001f600<&>"}`; string(blob) != want {
t.Fatalf("encodeValues = %s, want %s", blob, want)
}
back, _, err := decodeYAML(string(blob))
if err != nil {
t.Fatal(err)
}
if got := asMap(back)["v"]; got != in["v"] {
t.Fatalf("the values did not read back as written: %q", got)
}
raw, _, err := decodeYAML(`{"v": "a` + "\u0085" + `b"}`)
if err != nil {
t.Fatal(err)
}
if asMap(raw)["v"] == "a\u0085b" {
t.Fatal("a raw U+0085 survived a quoted scalar, so escaping it guards nothing")
}
}
func TestDecodeStreamSources(t *testing.T) {
text := "---\n# Source: a/templates/one.yaml\nkind: A\n---\n# Source: a/templates/empty.yaml\n---\n# Source: a/templates/two.yaml\nkind: B\n"
docs, err := decodeStream(text)
if err != nil {
t.Fatal(err)
}
var got []string
for _, d := range docs {
got = append(got, d.source+"="+asMap(d.obj)["kind"].(string))
}
if want := []string{"a/templates/one.yaml=A", "a/templates/two.yaml=B"}; !reflect.DeepEqual(got, want) {
t.Fatalf("documents = %v, want %v", got, want)
}
if _, err := decodeStream("kind: A\n---\nkind: [B\n"); err == nil {
t.Fatal("a stream with a document that does not decode decoded")
}
}
func TestStructured(t *testing.T) {
for _, tc := range []struct {
in string
want bool
}{
{"a: 1\nb: 2\n", true},
{"[1, 2]", true},
{` {"a": 1} `, true},
{`{"a": 1} trailing`, false},
{"plain text", false},
{"a: 1\n---\nb: 2\n", false},
{"", false},
{"\u0085", false},
} {
if got := structured(tc.in) != nil; got != tc.want {
t.Errorf("structured(%q) = %v, want %v", tc.in, got, tc.want)
}
}
}
func TestTypeName(t *testing.T) {
for _, tc := range []struct {
in any
want string
}{
{float64(1), "int"}, {1.5, "float"}, {1e21, "float"}, {json.Number("1"), "int"},
{json.Number("1.0"), "float"}, {"s", "str"}, {nil, "NoneType"}, {true, "bool"},
} {
if got := typeName(tc.in); got != tc.want {
t.Errorf("typeName(%#v) = %q, want %q", tc.in, got, tc.want)
}
}
}
func TestSplitLines(t *testing.T) {
got := splitLines("a\r\nb\u0085c\u2028d\re\n")
if want := []string{"a", "b", "c", "d", "e"}; !reflect.DeepEqual(got, want) {
t.Fatalf("splitLines = %q, want %q", got, want)
}
}
func TestRepr(t *testing.T) {
for _, tc := range []struct{ in, want string }{
{"plain", `'plain'`},
{"it's", `"it's"`},
{`it's "x"`, `'it\'s "x"'`},
{"a\nb\u0085\u2028\u00e9", "'a\\nb\\x85\\u2028\u00e9'"},
} {
if got := repr(tc.in); got != tc.want {
t.Errorf("repr(%q) = %s, want %s", tc.in, got, tc.want)
}
}
}
func TestBounded(t *testing.T) {
for _, tc := range []struct {
text, word string
want int
}{
{"size: 1Gi", "1Gi", 1},
{"size: 11Gi 1Gi-x 1Gib", "1Gi", 1},
{"1Gi,1Gi 1Gi", "1Gi", 3},
{"x1Gi", "1Gi", 0},
} {
if got := bounded(tc.text, tc.word); got != tc.want {
t.Errorf("bounded(%q, %q) = %d, want %d", tc.text, tc.word, got, tc.want)
}
}
}
+408
View File
@@ -0,0 +1,408 @@
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
}
+285
View File
@@ -0,0 +1,285 @@
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)
}
+10
View File
@@ -0,0 +1,10 @@
module github.com/cozystack/cozystack/hack/values-injection
go 1.27.2
require (
mvdan.cc/sh/v3 v3.10.0
sigs.k8s.io/yaml v1.6.0
)
require go.yaml.in/yaml/v2 v2.4.4 // indirect
+18
View File
@@ -0,0 +1,18 @@
github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE=
go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI=
mvdan.cc/sh/v3 v3.10.0 h1:v9z7N1DLZ7owyLM/SXZQkBSXcwr2IGMm2LY2pmhVXj4=
mvdan.cc/sh/v3 v3.10.0/go.mod h1:z/mSSVyLFGZzqb3ZIKojjyqIx/xbmz/UHdCSv9HmqXY=
sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs=
sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4=
+513
View File
@@ -0,0 +1,513 @@
// 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
}
+315
View File
@@ -0,0 +1,315 @@
package main
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
const (
fixturePath = "hack/testdata/render-fixtures/configured.yaml"
namespace = "tenant-test"
)
type chartConfig struct {
release string
namespace string
args []string
values map[string]any
}
// chartConfigs is the render contract per chart, mirroring
// hack/check-render-matrix.sh. The two lookup-gated charts are sized by
// resources instead of a cluster instancetype.
var chartConfigs = map[string]chartConfig{
"postgres": {args: []string{"--api-versions", "keda.sh/v1alpha1"}},
"kubernetes": {args: []string{"--api-versions", "sdn.cozystack.io/v1alpha1/VPC"}},
"tenant": {release: "tenant-sub", args: []string{"--api-versions", "v1.edp.epam.com/v1"}},
"kubernetes-nodes": {
release: "kubernetes-nodes-render-check",
args: []string{"--set-string", "cluster=render", "--api-versions", "sdn.cozystack.io/v1alpha1/VPC"},
values: map[string]any{"instanceType": "", "resources": map[string]any{"cpu": 2, "memory": "4Gi"}},
},
"vm-instance": {
values: map[string]any{"instanceType": "", "instanceProfile": "",
"resources": map[string]any{"cpu": 1, "sockets": 1, "memory": "1Gi"}},
},
"external-dns": {values: map[string]any{"provider": "inmemory"}},
"bootbox": {namespace: "tenant-root"},
}
type renderResult struct {
rc int
out string
err string
}
type renderer struct {
dir string
name string
release string
namespace string
args []string
base map[string]any
fixture string
tmp string
}
func newRenderer(root, chart, tmp, release, ns string) *renderer {
dir := chart
if !filepath.IsAbs(dir) {
dir = filepath.Join(root, chart)
}
name := filepath.Base(dir)
conf := chartConfigs[name]
if release == "" {
release = conf.release
}
if release == "" {
// A tenant module refuses any release name but its own.
release = name + "-render-check"
if filepath.Base(filepath.Dir(dir)) == "extra" {
release = name
}
}
if ns == "" {
ns = conf.namespace
}
if ns == "" {
ns = namespace
}
fixture := filepath.Join(root, fixturePath)
if _, err := os.Stat(fixture); err != nil {
fixture = fixturePath
}
base := conf.values
if base == nil {
base = map[string]any{}
}
return &renderer{dir: dir, name: name, release: release, namespace: ns, args: conf.args, base: base,
fixture: fixture, tmp: tmp}
}
// render runs helm template with values over the chart's own and the fixture.
// An error means helm could not be run at all, not that the chart failed.
func (r *renderer) render(values map[string]any, skipSchema bool) (renderResult, error) {
blob, err := encodeValues(merge(r.base, values))
if err != nil {
return renderResult{}, err
}
vf, err := os.CreateTemp(r.tmp, r.name+"-*.json")
if err != nil {
return renderResult{}, err
}
defer os.Remove(vf.Name())
if _, err := vf.Write(blob); err != nil {
vf.Close()
return renderResult{}, err
}
if err := vf.Close(); err != nil {
return renderResult{}, err
}
args := []string{"template", r.release, r.dir, "--namespace", r.namespace}
args = append(args, r.args...)
args = append(args, "--values", r.fixture, "--values", vf.Name())
if skipSchema {
args = append(args, "--skip-schema-validation")
}
cmd := exec.Command("helm", args...)
var stdout, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &stdout, &stderr
rc := 0
if err := cmd.Run(); err != nil {
var exit *exec.ExitError
if !errors.As(err, &exit) {
return renderResult{}, fmt.Errorf("helm: %w", err)
}
rc = exit.ExitCode()
if rc == 0 {
rc = -1
}
}
var kept []string
for _, l := range splitLines(stderr.String()) {
if !strings.HasPrefix(l, "level=INFO") {
kept = append(kept, l)
}
}
return renderResult{rc: rc, out: stdout.String(), err: strings.Join(kept, "\n")}, nil
}
// renderFunc renders a chart with values over its own; an error means the
// renderer could not run at all, not that the chart failed.
type renderFunc func(values map[string]any, skipSchema bool) (renderResult, error)
// renderCache remembers renders, for a field that tries the same values under
// several attempts, or a chart a HelmRelease installs that is rendered from
// the same reference values for every payload. Charts that generate secrets
// render differently every time, so a reference is rendered once.
type renderCache struct {
render renderFunc
seen map[string]renderResult
}
func newRenderCache(r renderFunc) *renderCache {
return &renderCache{r, map[string]renderResult{}}
}
func (c *renderCache) get(values map[string]any, skipSchema bool) (renderResult, error) {
blob, err := encodeValues(values)
if err != nil {
return renderResult{}, err
}
key := fmt.Sprintf("%t:%s", skipSchema, blob)
if res, ok := c.seen[key]; ok {
return res, nil
}
res, err := c.render(values, skipSchema)
if err != nil {
return res, err
}
c.seen[key] = res
return res, nil
}
func firstError(err string) string {
var lines []string
for _, l := range splitLines(err) {
if strip(l) != "" {
lines = append(lines, l)
}
}
for _, l := range lines {
if strings.HasPrefix(l, "Error:") {
return truncate(l, 240)
}
}
if len(lines) > 0 {
return truncate(lines[0], 240)
}
return "render failed"
}
var yamlErrors = []string{"YAML parse error", "error converting YAML to JSON", "unable to parse YAML",
"yaml: line", "mapping values are not allowed", "did not find expected"}
func classifyError(err string) string {
if strings.Contains(err, "don't meet the specifications of the schema") {
return "schema"
}
for _, s := range yamlErrors {
if strings.Contains(err, s) {
return "yaml"
}
}
if strings.Contains(err, "execution error at") {
return "template"
}
return "other"
}
var yamlParseErrorOn = regexp.MustCompile(`YAML parse error on ([^:]+)`)
// artifacts maps an ExternalArtifact name to its chart dir, from the
// platform's PackageSources.
func artifacts(root string) (map[string]string, error) {
out := map[string]string{}
files, err := filepath.Glob(filepath.Join(root, "packages/core/platform/sources/*.yaml"))
if err != nil {
return nil, err
}
for _, f := range files {
text, err := os.ReadFile(f)
if err != nil {
return nil, err
}
docs, err := decodeStream(string(text))
if err != nil {
return nil, fmt.Errorf("%s: %w", f, err)
}
for _, d := range docs {
obj, ok := d.obj.(map[string]any)
if !ok || obj["kind"] != "PackageSource" {
continue
}
base := strings.ReplaceAll(pyStr(asMap(obj["metadata"])["name"]), ".", "-")
variants, _ := asMap(obj["spec"])["variants"].([]any)
for _, v := range variants {
vm := asMap(v)
comps, _ := vm["components"].([]any)
for _, comp := range comps {
cm := asMap(comp)
out[fmt.Sprintf("%s-%s-%s", base, pyStr(vm["name"]), pyStr(cm["name"]))] = "packages/" + pyStr(cm["path"])
}
}
}
}
return out, nil
}
// release is a HelmRelease of a render that installs an in-tree chart.
type release struct {
index int
name string
chart string
release string
namespace string
values map[string]any
remote bool // applied through a kubeConfig into the tenant's own cluster
}
func or(vals ...any) any {
for _, v := range vals {
if truthy(v) {
return v
}
}
return vals[len(vals)-1]
}
func releases(docs []doc, arts map[string]string) []release {
var out []release
for i, d := range docs {
obj, ok := d.obj.(map[string]any)
if !ok || obj["kind"] != "HelmRelease" {
continue
}
spec := asMap(obj["spec"])
ref := asMap(spec["chartRef"])
chart := ""
if ref["kind"] == "ExternalArtifact" {
if name, ok := ref["name"].(string); ok {
chart = arts[name]
}
}
values, ok := spec["values"].(map[string]any)
if chart == "" || !ok {
continue
}
meta := asMap(obj["metadata"])
name, hasName := meta["name"]
if !hasName {
name = "?"
}
relName, hasName := meta["name"]
if !hasName {
relName = "x"
}
_, remote := spec["kubeConfig"]
out = append(out, release{
index: i,
name: pyStr(name),
chart: chart,
release: pyStr(or(spec["releaseName"], relName)),
namespace: pyStr(or(spec["targetNamespace"], meta["namespace"], namespace)),
values: values,
remote: remote,
})
}
return out
}
+468
View File
@@ -0,0 +1,468 @@
package main
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
// step is one hop of a schema path: a named property ('p'), the entry of a
// free-form map ('m'), or an array element ('i').
type step struct {
kind byte
name string
}
type schemaPath []step
func (p schemaPath) with(s step) schemaPath {
out := make(schemaPath, len(p), len(p)+1)
copy(out, p)
return append(out, s)
}
func (p schemaPath) key() string {
var b strings.Builder
for _, s := range p {
b.WriteByte(s.kind)
if s.kind == 'p' {
b.WriteString(strconv.Itoa(len(s.name)))
b.WriteByte(':')
b.WriteString(s.name)
}
}
return b.String()
}
// slot is a string a tenant can set: a value, or the keys of a free-form map.
type slot struct {
path schemaPath
kind string // "value" or "key"
node map[string]any
}
func truthy(v any) bool {
switch x := v.(type) {
case nil:
return false
case bool:
return x
case string:
return x != ""
case int:
return x != 0
case float64:
return x != 0
case json.Number:
f, err := x.Float64()
return err != nil || f != 0
case []any:
return len(x) > 0
case map[string]any:
return len(x) > 0
}
return true
}
func asMap(v any) map[string]any {
if m, ok := v.(map[string]any); ok {
return m
}
return map[string]any{}
}
func typesOf(node map[string]any) map[string]bool {
t := node["type"]
if list, ok := t.([]any); ok {
out := map[string]bool{}
for _, e := range list {
out[pyStr(e)] = true
}
return out
}
if truthy(t) {
return map[string]bool{pyStr(t): true}
}
if truthy(node["x-kubernetes-int-or-string"]) {
return map[string]bool{"int-or-string": true}
}
_, hasProps := node["properties"]
_, hasAP := node["additionalProperties"]
if hasProps || hasAP {
return map[string]bool{"object": true}
}
return map[string]bool{}
}
// freeForm is the value schema of an object whose keys the schema does not
// name; ok is false for any other node.
func freeForm(node map[string]any) (map[string]any, bool) {
if !typesOf(node)["object"] {
return nil, false
}
ap, has := node["additionalProperties"]
if m, ok := ap.(map[string]any); ok {
return m, true
}
if ap == true || ((!has || ap == nil) && !truthy(node["properties"])) {
return map[string]any{}, true
}
return nil, false
}
func alternatives(node map[string]any) []map[string]any {
var out []map[string]any
for _, k := range []string{"oneOf", "anyOf", "allOf"} {
list, _ := node[k].([]any)
for _, alt := range list {
if m, ok := alt.(map[string]any); ok {
out = append(out, m)
}
}
}
return out
}
// slots calls yield for every string a tenant can set below node.
func slots(node any, path schemaPath, depth int, yield func(slot)) {
m, ok := node.(map[string]any)
if !ok || depth > 12 {
return
}
t := typesOf(m)
if t["string"] || t["int-or-string"] || (len(t) == 0 && !anyNonEmpty(alternatives(m))) {
yield(slot{path, "value", m})
}
props := asMap(m["properties"])
for _, name := range sortedKeys(props) {
slots(props[name], path.with(step{'p', name}), depth+1, yield)
}
ap, isFree := freeForm(m)
if def, ok := m["default"].(map[string]any); isFree && ok {
// A free-form block whose default names its keys (a provider's
// credentials): those keys are what the template reads.
for _, name := range sortedKeys(def) {
switch def[name].(type) {
case map[string]any, []any:
continue
}
if _, named := props[name]; !named {
slots(map[string]any{"type": "string"}, path.with(step{'p', name}), depth+1, yield)
}
}
}
if isFree {
yield(slot{path, "key", ap})
if len(ap) > 0 {
slots(ap, path.with(step{'m', ""}), depth+1, yield)
} else {
yield(slot{path.with(step{'m', ""}), "value", map[string]any{}})
}
}
if items, ok := m["items"].(map[string]any); ok && t["array"] {
slots(items, path.with(step{'i', ""}), depth+1, yield)
}
for _, alt := range alternatives(m) {
slots(alt, path, depth+1, yield)
}
}
func anyNonEmpty(alts []map[string]any) bool {
for _, a := range alts {
if len(a) > 0 {
return true
}
}
return false
}
func dotted(path schemaPath, kind string) string {
out := ""
for _, s := range path {
switch s.kind {
case 'p':
if out != "" {
out += "."
}
out += s.name
case 'm':
out += ".*"
default:
out += "[0]"
}
}
if kind == "key" {
if out != "" {
out += ".<key>"
} else {
out = "<key>"
}
}
if out == "" {
return "<root>"
}
return out
}
var exactGuesses = map[string]string{
"address": "10.0.0.1", "gateway": "10.0.0.1", "ip": "10.0.0.1", "netmask": "255.255.255.0",
"mac": "00:00:5e:00:53:01", "annotationprefix": "dns1.example.org/",
}
var partialGuesses = []struct {
parts []string
value string
}{
{[]string{"dnsserver", "nameserver", "timeserver"}, "10.0.0.1"},
{[]string{"whitelist", "allowlist", "cidr", "subnet", "sourcerange"}, "10.0.0.0/8"},
{[]string{"serveraddress"}, "http://vmselect.tenant-test.svc:8481"},
{[]string{"version"}, "v1.10.3"},
{[]string{"schedule"}, "0 2 * * *"},
{[]string{"memory", "size", "storage", "quantity"}, "1Gi"},
{[]string{"cpu"}, "1"},
{[]string{"url", "endpoint", "server"}, "https://s3.example.org"},
{[]string{"path", "destination"}, "s3://bucket/path/"},
{[]string{"time"}, "2026-01-01T00:00:00Z"},
{[]string{"host", "domain"}, "app.example.org"},
}
// guess is a plausible value for a field, so the chart's own checks accept it.
func guess(name string, node map[string]any) any {
if enum, ok := node["enum"].([]any); ok && len(enum) > 0 {
return enum[0]
}
if def, ok := node["default"].(string); ok && def != "" {
return def
}
n := strings.ToLower(name)
if v, ok := exactGuesses[n]; ok {
return v
}
for _, g := range partialGuesses {
for _, p := range g.parts {
if strings.Contains(n, p) {
return g.value
}
}
}
if typesOf(node)["int-or-string"] {
return "1"
}
return "fill"
}
// sample is a minimal instance of a schema, for an object created from scratch.
func sample(node any, depth int, name string) any {
m, ok := node.(map[string]any)
if !ok || depth > 8 {
return "fill"
}
if def, has := m["default"]; has {
return deepCopy(def)
}
if enum, ok := m["enum"].([]any); ok && len(enum) > 0 {
return deepCopy(enum[0])
}
t := typesOf(m)
switch {
case t["object"]:
props := asMap(m["properties"])
out := map[string]any{}
required, _ := m["required"].([]any)
for _, r := range required {
rs := pyStr(r)
sub, ok := props[rs]
if !ok {
sub = map[string]any{}
}
out[rs] = sample(sub, depth+1, rs)
}
return out
case t["array"]:
return []any{}
case t["boolean"]:
return false
case t["integer"] || t["number"]:
return 1
}
return guess(name, m)
}
// build is values that put leaf at path, or key as a key of the map at path.
// Variant 1 also sets `enabled: true` on every object along the path, and
// variant 2 also fills the empty strings beside it below the top level.
func build(node any, path schemaPath, leaf any, key *string, variant int, fresh bool, depth int, keyValue *string) any {
m := asMap(node)
if len(path) == 0 {
if key != nil {
if keyValue != nil {
return map[string]any{*key: *keyValue}
}
if ap, _ := freeForm(m); len(ap) > 0 {
return map[string]any{*key: sample(ap, 0, "")}
}
return map[string]any{*key: "fill"}
}
return leaf
}
s, rest := path[0], path[1:]
switch s.kind {
case 'p':
var obj map[string]any
if fresh {
obj, _ = sample(m, 0, "").(map[string]any)
}
if obj == nil {
obj = map[string]any{}
}
props := asMap(m["properties"])
if variant >= 1 && typesOf(asMap(props["enabled"]))["boolean"] {
obj["enabled"] = true
}
if variant >= 2 && depth > 0 {
for _, name := range sortedKeys(props) {
sub, ok := props[name].(map[string]any)
if name == s.name || !ok {
continue
}
if typesOf(sub)["string"] && !truthy(sub["enum"]) && !truthy(sub["default"]) {
obj[name] = guess(name, sub)
}
}
}
sub, ok := props[s.name]
if !ok {
sub = map[string]any{}
}
obj[s.name] = build(sub, rest, leaf, key, variant, fresh, depth+1, keyValue)
return obj
case 'm':
ap, _ := freeForm(m)
return map[string]any{"fuzzkey": build(ap, rest, leaf, key, variant, true, depth+1, keyValue)}
}
items := m["items"]
if !truthy(items) {
items = map[string]any{}
}
return []any{build(items, rest, leaf, key, variant, true, depth+1, keyValue)}
}
// put sets the field at path in values that build made, after a merge over
// it.
func put(values any, path schemaPath, leaf any) error {
node := values
for i, s := range path {
last := i == len(path)-1
switch s.kind {
case 'i':
list, ok := node.([]any)
if !ok || len(list) == 0 {
return fmt.Errorf("%s: no list to put into", dotted(path[:i+1], "value"))
}
if last {
list[0] = leaf
} else {
node = list[0]
}
default:
name := s.name
if s.kind == 'm' {
name = "fuzzkey"
}
obj, ok := node.(map[string]any)
if !ok {
return fmt.Errorf("%s: no map to put into", dotted(path[:i+1], "value"))
}
if last {
obj[name] = leaf
} else {
node = obj[name]
}
}
}
return nil
}
func substitute(v any, c string) any {
switch x := v.(type) {
case map[string]any:
out := make(map[string]any, len(x))
for k, e := range x {
out[strings.ReplaceAll(k, "$CANARY", c)] = substitute(e, c)
}
return out
case []any:
out := make([]any, len(x))
for i, e := range x {
out[i] = substitute(e, c)
}
return out
case string:
return strings.ReplaceAll(x, "$CANARY", c)
}
return v
}
func deepCopy(v any) any {
switch x := v.(type) {
case map[string]any:
out := make(map[string]any, len(x))
for k, e := range x {
out[k] = deepCopy(e)
}
return out
case []any:
out := make([]any, len(x))
for i, e := range x {
out[i] = deepCopy(e)
}
return out
}
return v
}
func container(v any) string {
switch v.(type) {
case map[string]any:
return "map"
case []any:
return "list"
}
return ""
}
// merge is b over a. Lists merge element by element, so a profile can
// complete an array element the fuzzer creates.
func merge(a, b any) any {
if al, ok := a.([]any); ok {
if bl, ok := b.([]any); ok {
n := min(len(al), len(bl))
out := make([]any, 0, max(len(al), len(bl)))
for i := 0; i < n; i++ {
if k := container(al[i]); k != "" && k == container(bl[i]) {
out = append(out, merge(al[i], bl[i]))
} else {
out = append(out, deepCopy(bl[i]))
}
}
tail := al[n:]
if len(bl) > len(al) {
tail = bl[n:]
}
for _, e := range tail {
out = append(out, deepCopy(e))
}
return out
}
}
out := asMap(deepCopy(a))
for k, v := range asMap(b) {
if kind := container(v); kind != "" && kind == container(out[k]) {
out[k] = merge(out[k], v)
} else {
out[k] = deepCopy(v)
}
}
return out
}
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"bytes"
"encoding/json"
"strings"
"sync"
"mvdan.cc/sh/v3/syntax"
"mvdan.cc/sh/v3/syntax/typedjson"
)
// parsedScript is what the comparison needs of a shell script: its parse
// tree without positions and literal text, and the text of each heredoc with
// every expansion in it written as X. ok is false when it does not parse.
type parsedScript struct {
ok bool
skeleton string
heredocs []string
}
var parsedScripts sync.Map // script text -> *parsedScript
// parseScript parses a script as `shfmt -ln bash --to-json` does: bash,
// comments kept, the tree in shfmt's typed JSON.
func parseScript(script string) *parsedScript {
if v, ok := parsedScripts.Load(script); ok {
return v.(*parsedScript)
}
res := &parsedScript{}
parser := syntax.NewParser(syntax.KeepComments(true), syntax.Variant(syntax.LangBash))
if f, err := parser.Parse(strings.NewReader(script), ""); err == nil {
var buf bytes.Buffer
var tree any
if typedjson.Encode(&buf, f) == nil && json.Unmarshal(buf.Bytes(), &tree) == nil {
if sk, err := json.Marshal(skeleton(tree)); err == nil {
res.ok = true
res.skeleton = string(sk)
res.heredocs = heredocs(f)
}
}
}
v, _ := parsedScripts.LoadOrStore(script, res)
return v.(*parsedScript)
}
// skeleton drops every Value and every position from the typed JSON tree, so
// two scripts compare equal when only their literal text differs.
func skeleton(n any) any {
switch x := n.(type) {
case map[string]any:
out := make(map[string]any, len(x))
for k, v := range x {
if k == "Value" || isPos(v) {
continue
}
out[k] = skeleton(v)
}
return out
case []any:
out := make([]any, len(x))
for i, v := range x {
out[i] = skeleton(v)
}
return out
}
return n
}
func isPos(v any) bool {
m, ok := v.(map[string]any)
if !ok {
return false
}
_, offset := m["Offset"]
_, line := m["Line"]
return offset && line
}
// heredocs is the body of every heredoc, in the order a walk of the tree
// meets them, with each part that is not literal text written as X. A heredoc
// with an empty body has no word at all.
func heredocs(f *syntax.File) []string {
var out []string
syntax.Walk(f, func(n syntax.Node) bool {
r, ok := n.(*syntax.Redirect)
if !ok || r.Hdoc == nil {
return true
}
var b strings.Builder
for _, p := range r.Hdoc.Parts {
if lit, ok := p.(*syntax.Lit); ok {
b.WriteString(lit.Value)
} else {
b.WriteString("X")
}
}
out = append(out, b.String())
return true
})
return out
}
+203
View File
@@ -0,0 +1,203 @@
package main
import (
"fmt"
"math"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// This check began as a Python script, and its reports, notes and finding
// details are kept identical to that script's, so a report from either can be
// diffed against the other. The helpers below carry the Python semantics where
// they decide a verdict or a reported string: line splitting on every Unicode
// line boundary, whitespace that includes the ASCII separators
// U+001C..U+001F, and repr() quoting.
// isSpace is Python's str.isspace for one rune.
func isSpace(r rune) bool {
return unicode.IsSpace(r) || (r >= 0x1c && r <= 0x1f)
}
func strip(s string) string {
return strings.TrimFunc(s, isSpace)
}
// splitLines is Python's str.splitlines: it also ends a line at \v, \f,
// U+001C..U+001E, U+0085, U+2028 and U+2029, and takes \r\n as one break.
func splitLines(s string) []string {
var out []string
start := 0
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
switch r {
case '\n', '\v', '\f', 0x1c, 0x1d, 0x1e, 0x85, 0x2028, 0x2029:
out = append(out, s[start:i])
i += size
start = i
case '\r':
out = append(out, s[start:i])
i += size
if i < len(s) && s[i] == '\n' {
i++
}
start = i
default:
i += size
}
}
if start < len(s) {
out = append(out, s[start:])
}
return out
}
// truncate keeps the first n characters, as s[:n] does on a Python str.
func truncate(s string, n int) string {
i := 0
for j := range s {
if i == n {
return s[:j]
}
i++
}
return s
}
// lower lowercases ASCII only. Every canary is ASCII, and no other rune
// lowercases to one of its characters, so a match is the same as Python's
// str.lower() finds, while byte offsets stay valid in the original string.
func lower(s string) string {
for i := 0; i < len(s); i++ {
if 'A' <= s[i] && s[i] <= 'Z' {
b := []byte(s)
for j := i; j < len(b); j++ {
if 'A' <= b[j] && b[j] <= 'Z' {
b[j] += 'a' - 'A'
}
}
return string(b)
}
}
return s
}
func containsFold(s, c string) bool {
return strings.Contains(lower(s), c)
}
// repr is Python's repr() of a string.
func repr(s string) string {
quote := byte('\'')
if strings.IndexByte(s, '\'') >= 0 && strings.IndexByte(s, '"') < 0 {
quote = '"'
}
var b strings.Builder
b.WriteByte(quote)
for _, r := range s {
switch {
case r == rune(quote) || r == '\\':
b.WriteByte('\\')
b.WriteRune(r)
case r == '\t':
b.WriteString(`\t`)
case r == '\n':
b.WriteString(`\n`)
case r == '\r':
b.WriteString(`\r`)
case r < ' ' || r == 0x7f:
fmt.Fprintf(&b, `\x%02x`, r)
case r < 0x7f || unicode.IsPrint(r):
b.WriteRune(r)
case r <= 0xff:
fmt.Fprintf(&b, `\x%02x`, r)
case r <= 0xffff:
fmt.Fprintf(&b, `\u%04x`, r)
default:
fmt.Fprintf(&b, `\U%08x`, r)
}
}
b.WriteByte(quote)
return b.String()
}
// isInt tells whether a number decoded from a manifest was an int to the
// Python script. Manifests reached it through Go's JSON encoder, which writes
// an integral float64 below 1e21 without a fraction or an exponent.
func isInt(f float64) bool {
return f == math.Trunc(f) && math.Abs(f) < 1e21
}
// pyStr is str() of a decoded JSON value, for the few that reach a report.
func pyStr(v any) string {
if s, ok := v.(string); ok {
return s
}
return pyRepr(v)
}
// pyRepr is repr() of a decoded JSON value.
func pyRepr(v any) string {
switch x := v.(type) {
case nil:
return "None"
case string:
return repr(x)
case bool:
if x {
return "True"
}
return "False"
case int:
return strconv.Itoa(x)
case float64:
if isInt(x) {
return strconv.FormatFloat(x, 'f', -1, 64)
}
return strconv.FormatFloat(x, 'g', -1, 64)
case fmt.Stringer:
return x.String()
case []any:
parts := make([]string, len(x))
for i, e := range x {
parts[i] = pyRepr(e)
}
return "[" + strings.Join(parts, ", ") + "]"
case map[string]any:
keys := sortedKeys(x)
parts := make([]string, len(keys))
for i, k := range keys {
parts[i] = repr(k) + ": " + pyRepr(x[k])
}
return "{" + strings.Join(parts, ", ") + "}"
}
return fmt.Sprint(v)
}
// bounded counts the occurrences of word not touching an ASCII letter or
// digit on either side, as re.findall with lookarounds does.
func bounded(text, word string) int {
alnum := func(b byte) bool {
return 'a' <= b && b <= 'z' || 'A' <= b && b <= 'Z' || '0' <= b && b <= '9'
}
n := 0
for i := 0; ; {
j := strings.Index(text[i:], word)
if j < 0 {
return n
}
j += i
end := j + len(word)
if (j == 0 || !alnum(text[j-1])) && (end == len(text) || !alnum(text[end])) {
n++
i = end
} else {
i = j + 1
}
if i > len(text) {
return n
}
}
}
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env bats
# hack/values-injection on charts built for the purpose: a value rendered raw,
# the same value quoted, and a quoted value that carries its line breaks into
# an embedded config, which is what a field multi-line by design looks like.
# Pinned here: what fails the check, what does not, and what the allowlist
# can and cannot excuse. The comparison itself is covered by the Go tests
# beside the check.
#
# Needs helm and go. Run from the repo root through `make bats-unit-tests`.
load test_helper
# Build once per file: the tests run in parallel under `bats -j`.
setup_file() {
go -C hack/values-injection build -o "$BATS_FILE_TMPDIR/values-injection" .
}
# make_chart <root> <name> <line rendering .Values.v>
make_chart() {
dir="$1/packages/apps/$2"
mkdir -p "$dir/templates"
printf 'apiVersion: v2\nname: %s\nversion: 0.0.0\n' "$2" > "$dir/Chart.yaml"
printf 'v: x\n' > "$dir/values.yaml"
printf '{"type": "object", "properties": {"v": {"type": "string", "default": "x"}}}\n' > "$dir/values.schema.json"
printf 'apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: probe\ndata:\n %s\n' "$3" > "$dir/templates/configmap.yaml"
}
# check <root> <allowlist> [chart dir…]: sets rc and out.
check() {
root=$1 allow=$2
shift 2
rc=0
out=$("$BATS_FILE_TMPDIR/values-injection" --root "$root" --allowlist "$allow" "$@" 2>&1) || rc=$?
}
@test "a value rendered raw is injectable and fails the check, the same value quoted passes" {
tmp=$(mktemp -d)
make_chart "$tmp" raw 'v: {{ .Values.v }}'
make_chart "$tmp" quoted 'v: {{ .Values.v | quote }}'
: > "$tmp/allow"
check "$tmp" "$tmp/allow" packages/apps/raw
if [ "$rc" -ne 1 ]; then
echo "FAIL: the check exited $rc on a value rendered raw"
printf '%s\n' "$out"
false
fi
if ! printf '%s\n' "$out" | grep -q '^INJECTABLE packages/apps/raw: v$'; then
echo "FAIL: the raw value was not reported injectable"
printf '%s\n' "$out"
false
fi
check "$tmp" "$tmp/allow" packages/apps/quoted
if [ "$rc" -ne 0 ]; then
echo "FAIL: the check exited $rc on a quoted value"
printf '%s\n' "$out"
false
fi
if ! printf '%s\n' "$out" | grep -qx 'fields: safe=1'; then
echo "FAIL: the quoted value was not counted safe"
printf '%s\n' "$out"
false
fi
rm -rf "$tmp"
}
@test "a multi-line value passes only when listed, and a listed field that is not breakable fails" {
tmp=$(mktemp -d)
make_chart "$tmp" multiline 'conf: {{ printf "[main]\na = %s\n" .Values.v | quote }}'
make_chart "$tmp" quoted 'v: {{ .Values.v | quote }}'
: > "$tmp/none"
check "$tmp" "$tmp/none" packages/apps/multiline
if [ "$rc" -ne 1 ] || ! printf '%s\n' "$out" | grep -q '^BREAKABLE packages/apps/multiline: v$'; then
echo "FAIL: an unlisted multi-line value did not fail the check as breakable (exit $rc)"
printf '%s\n' "$out"
false
fi
printf '# reason required\npackages/apps/multiline v an embedded config written whole\n' > "$tmp/allow"
check "$tmp" "$tmp/allow" packages/apps/multiline
if [ "$rc" -ne 0 ] || ! printf '%s\n' "$out" | grep -q '^ALLOWED packages/apps/multiline: v (an embedded config written whole)$'; then
echo "FAIL: a listed multi-line value was not allowed (exit $rc)"
printf '%s\n' "$out"
false
fi
printf 'packages/apps/multiline v an embedded config written whole\npackages/apps/quoted v once multi-line\n' > "$tmp/allow"
check "$tmp" "$tmp/allow" packages/apps/multiline packages/apps/quoted
if [ "$rc" -ne 1 ] || ! printf '%s\n' "$out" | grep -q 'STALE .*packages/apps/quoted v is safe, not breakable$'; then
echo "FAIL: an entry for a field that is safe did not fail the check (exit $rc)"
printf '%s\n' "$out"
false
fi
rm -rf "$tmp"
}
@test "the allowlist does not excuse an injectable field" {
tmp=$(mktemp -d)
make_chart "$tmp" raw 'v: {{ .Values.v }}'
printf 'packages/apps/raw v listed by mistake\n' > "$tmp/allow"
check "$tmp" "$tmp/allow" packages/apps/raw
if [ "$rc" -ne 1 ] || ! printf '%s\n' "$out" | grep -q '^INJECTABLE packages/apps/raw: v$'; then
echo "FAIL: a listed injectable field did not fail the check (exit $rc)"
printf '%s\n' "$out"
false
fi
rm -rf "$tmp"
}