summaryrefslogtreecommitdiff
path: root/config/validation.go
blob: 3359211abd4fe03b321baee7e22bfdda49456391 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package config

import (
	"bytes"
	"context"
	"fmt"
	"path"
	"reflect"
	"regexp"
	"strings"
	"text/template"

	"github.com/docker/distribution/reference"
	"gopkg.in/go-playground/validator.v9"
)

var (
	// See Debian Policy
	//  https://www.debian.org/doc/debian-policy/#s-f-source
	//  https://www.debian.org/doc/debian-policy/#s-f-version
	debianPackageName   = `[a-z0-9][a-z0-9+.-]+`
	debianVersionSpec   = `(?:[0-9]+:)?[0-9]+[a-zA-Z0-9\.\+\-~]*`
	debianReleaseName   = `[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9]+)?`
	debianPackageRegexp = regexp.MustCompile(fmt.Sprintf(
		`^%s(?:=%s|/%s)?$`, debianPackageName, debianVersionSpec, debianReleaseName))

	// See IEEE Std 1003.1-2008 (http://pubs.opengroup.org/onlinepubs/9699919799/)
	environmentVariableRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]+$`)

	// Pattern for valid variant names
	variantNameRegexp = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9\-\.]+[a-zA-Z0-9]$`)

	humanizedErrors = map[string]string{
		"abspath":       `{{.Field}}: "{{.Value}}" is not a valid absolute non-root path`,
		"baseimage":     `{{.Field}}: "{{.Value}}" is not a valid base image reference`,
		"debianpackage": `{{.Field}}: "{{.Value}}" is not a valid Debian package name`,
		"envvars":       `{{.Field}}: contains invalid environment variable names`,
		"nodeenv":       `{{.Field}}: "{{.Value}}" is not a valid Node environment name`,
		"required":      `{{.Field}}: is required`,
		"username":      `{{.Field}}: "{{.Value}}" is not a valid user name`,
		"variantref":    `{{.Field}}: references an unknown variant "{{.Value}}"`,
		"variants":      `{{.Field}}: contains a bad variant name`,
	}

	validatorAliases = map[string]string{
		"nodeenv":  "alphanum",
		"username": "hostname,ne=root",
	}

	validatorFuncs = map[string]validator.FuncCtx{
		"abspath":       isAbsNonRootPath,
		"baseimage":     isBaseImage,
		"debianpackage": isDebianPackage,
		"envvars":       isEnvironmentVariables,
		"isfalse":       isFalse,
		"istrue":        isTrue,
		"variantref":    isVariantReference,
		"variants":      hasVariantNames,
	}
)

type ctxKey uint8

const rootCfgCtx ctxKey = iota

// NewValidator returns a validator instance for which our custom aliases and
// functions are registered.
//
func NewValidator() *validator.Validate {
	validate := validator.New()

	validate.RegisterTagNameFunc(resolveYAMLTagName)

	for name, tags := range validatorAliases {
		validate.RegisterAlias(name, tags)
	}

	for name, f := range validatorFuncs {
		validate.RegisterValidationCtx(name, f)
	}

	return validate
}

// Validate runs all validations defined for config fields against the given
// Config value. If the returned error is not nil, it will contain a
// user-friendly message describing all invalid field values.
//
func Validate(config Config) error {
	validate := NewValidator()

	ctx := context.WithValue(context.Background(), rootCfgCtx, config)

	return validate.StructCtx(ctx, config)
}

// HumanizeValidationError transforms the given validator.ValidationErrors
// into messages more likely to be understood by human beings.
//
func HumanizeValidationError(err error) string {
	var message bytes.Buffer

	if err == nil {
		return ""
	} else if !IsValidationError(err) {
		return err.Error()
	}

	templates := map[string]*template.Template{}

	for name, tmplString := range humanizedErrors {
		if tmpl, err := template.New(name).Parse(tmplString); err == nil {
			templates[name] = tmpl
		}
	}

	for _, ferr := range err.(validator.ValidationErrors) {
		if tmpl, ok := templates[ferr.Tag()]; ok {
			tmpl.Execute(&message, ferr)
		} else if trueErr, ok := err.(error); ok {
			message.WriteString(trueErr.Error())
		}

		message.WriteString("\n")
	}

	return strings.TrimSpace(message.String())
}

// IsValidationError tests whether the given error is a
// validator.ValidationErrors and can be safely iterated over as such.
//
func IsValidationError(err error) bool {
	if err == nil {
		return false
	} else if _, ok := err.(*validator.InvalidValidationError); ok {
		return false
	} else if _, ok := err.(validator.ValidationErrors); ok {
		return true
	}

	return false
}

func hasVariantNames(_ context.Context, fl validator.FieldLevel) bool {
	for _, name := range fl.Field().MapKeys() {
		if !variantNameRegexp.MatchString(name.String()) {
			return false
		}
	}

	return true
}

func isAbsNonRootPath(_ context.Context, fl validator.FieldLevel) bool {
	value := fl.Field().String()

	return path.IsAbs(value) && path.Base(path.Clean(value)) != "/"
}

func isBaseImage(_ context.Context, fl validator.FieldLevel) bool {
	value := fl.Field().String()

	return reference.ReferenceRegexp.MatchString(value)
}

func isDebianPackage(_ context.Context, fl validator.FieldLevel) bool {
	value := fl.Field().String()

	return debianPackageRegexp.MatchString(value)
}

func isEnvironmentVariables(_ context.Context, fl validator.FieldLevel) bool {
	for _, key := range fl.Field().MapKeys() {
		if !environmentVariableRegexp.MatchString(key.String()) {
			return false
		}
	}

	return true
}

func isFalse(_ context.Context, fl validator.FieldLevel) bool {
	val, ok := fl.Field().Interface().(bool)

	return ok && val == false
}

func isTrue(_ context.Context, fl validator.FieldLevel) bool {
	val, ok := fl.Field().Interface().(bool)

	return ok && val == true
}

func isVariantReference(ctx context.Context, fl validator.FieldLevel) bool {
	cfg := ctx.Value(rootCfgCtx).(Config)
	ref := fl.Field().String()

	for name := range cfg.Variants {
		if name == ref {
			return true
		}
	}

	return false
}

func resolveYAMLTagName(field reflect.StructField) string {
	return strings.SplitN(field.Tag.Get("yaml"), ",", 2)[0]
}