Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/install/installer/pkg/config/validation.go
2499 views
1
// Copyright (c) 2021 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package config
6
7
import (
8
"encoding/json"
9
"fmt"
10
"io"
11
"strings"
12
13
"github.com/go-playground/validator/v10"
14
)
15
16
type ValidationResult struct {
17
Valid bool `json:"valid"`
18
Warnings []string `json:"warn,omitempty"`
19
Fatal []string `json:"fatal,omitempty"`
20
}
21
22
func Validate(version ConfigVersion, cfg interface{}) (r *ValidationResult, err error) {
23
defer func() {
24
if r != nil {
25
r.Valid = len(r.Fatal) == 0
26
}
27
}()
28
29
validate := validator.New()
30
err = version.LoadValidationFuncs(validate)
31
if err != nil {
32
return nil, err
33
}
34
35
var res ValidationResult
36
37
warnings, conflicts := version.CheckDeprecated(cfg)
38
39
for k, v := range warnings {
40
res.Warnings = append(res.Warnings, fmt.Sprintf("Deprecated config parameter: %s=%v", k, v))
41
}
42
res.Fatal = append(res.Fatal, conflicts...)
43
44
err = validate.Struct(cfg)
45
if err != nil {
46
validationErrors := err.(validator.ValidationErrors)
47
48
if len(validationErrors) > 0 {
49
for _, v := range validationErrors {
50
switch v.Tag() {
51
case "required":
52
res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' is required", v.Namespace()))
53
case "required_if", "required_unless", "required_with":
54
tag := strings.Replace(v.Tag(), "_", " ", -1)
55
res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' is %s '%s'", v.Namespace(), tag, v.Param()))
56
case "startswith":
57
res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' must start with '%s'", v.Namespace(), v.Param()))
58
case "block_new_users_passlist":
59
res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' failed. If 'Enabled = true', there must be at least one fully-qualified domain name in the passlist", v.Namespace()))
60
default:
61
// General error message
62
res.Fatal = append(res.Fatal, fmt.Sprintf("Field '%s' failed %s validation", v.Namespace(), v.Tag()))
63
}
64
}
65
return &res, nil
66
}
67
}
68
69
return &res, nil
70
}
71
72
// Marshal marshals this result to JSON
73
func (r *ValidationResult) Marshal(w io.Writer) {
74
enc := json.NewEncoder(w)
75
enc.SetIndent("", " ")
76
enc.Encode(r)
77
}
78
79