Skip to content

Commit

Permalink
Validate the var names before substitution
Browse files Browse the repository at this point in the history
Signed-off-by: Stefan Prodan <stefan.prodan@gmail.com>
  • Loading branch information
stefanprodan committed Feb 27, 2021
1 parent f2c986a commit cb72a77
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
4 changes: 2 additions & 2 deletions controllers/kustomization_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ var _ = Describe("KustomizationReconciler", func() {
Validation: "client",
Force: false,
PostBuild: &kustomizev1.PostBuild{
Substitute: map[string]string{"region": "eu-central-1"},
Substitute: map[string]string{"_Region": "eu-central-1"},
SubstituteFrom: []kustomizev1.SubstituteReference{
{
Kind: "ConfigMap",
Expand Down Expand Up @@ -274,7 +274,7 @@ metadata:
namespace: test
labels:
environment: ${env:=dev}
region: "${region}"
region: "${_Region}"
zone: "${zone}"
`,
},
Expand Down
12 changes: 12 additions & 0 deletions controllers/kustomization_varsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package controllers
import (
"context"
"fmt"
"regexp"
"strings"

"github.com/drone/envsubst"
Expand All @@ -15,6 +16,10 @@ import (
kustomizev1 "github.com/fluxcd/kustomize-controller/api/v1beta1"
)

// varsubRegex is the regular expression used to validate
// the var names before substitution
const varsubRegex = "^[_[:alpha:]][_[:alpha:][:digit:]]*$"

// substituteVariables replaces the vars with their values in the specified resource.
// If a resource is labeled or annotated with
// 'kustomize.toolkit.fluxcd.io/substitute: disabled' the substitution is skipped.
Expand Down Expand Up @@ -68,6 +73,13 @@ func substituteVariables(

// run bash variable substitutions
if len(vars) > 0 {
r, _ := regexp.Compile(varsubRegex)
for v := range vars {
if !r.MatchString(v) {
return nil, fmt.Errorf("'%s' var name is invalid, must match '%s'", v, varsubRegex)
}
}

output, err := envsubst.Eval(string(resData), func(s string) string {
return vars[s]
})
Expand Down
4 changes: 4 additions & 0 deletions docs/spec/v1beta1/kustomization.md
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,10 @@ for [bash string replacement functions](https://github.com/drone/envsubst) e.g.:
- `${var:position:length}`
- `${var/substring/replacement}`

Note that the name of a variable can contain only alphanumeric and underscore characters.
The controller validates the var names using this regular expression:
`^[_[:alpha:]][_[:alpha:][:digit:]]*$`.

Assuming you have manifests with the following variables:

```yaml
Expand Down

0 comments on commit cb72a77

Please sign in to comment.